diff --git a/mozilla/modules/security/freenav/MANIFEST b/mozilla/modules/security/freenav/MANIFEST deleted file mode 100644 index 97e9a6e4a2d..00000000000 --- a/mozilla/modules/security/freenav/MANIFEST +++ /dev/null @@ -1,19 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -base64.h -cert.h -preenc.h -seccomon.h -secerr.h -sechash.h -secnav.h -secrng.h -secstubn.h -secstubs.h -secstubt.h -ssl.h -sslerr.h -zig.h -rosetta.h diff --git a/mozilla/modules/security/freenav/Makefile.in b/mozilla/modules/security/freenav/Makefile.in deleted file mode 100644 index b14bd3df764..00000000000 --- a/mozilla/modules/security/freenav/Makefile.in +++ /dev/null @@ -1,60 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = security -LIBRARY_NAME = secfree - -REQUIRES = js img layer util - -CSRCS = \ - secport.c \ - navstubs.c \ - $(NULL) - -EXPORTS = \ - base64.h \ - cert.h \ - preenc.h \ - seccomon.h \ - secerr.h \ - sechash.h \ - secnav.h \ - secrng.h \ - secstubn.h \ - secstubs.h \ - secstubt.h \ - ssl.h \ - sslerr.h \ - zig.h \ - rosetta.h \ - $(NULL) - -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/modules/security/freenav/base64.h b/mozilla/modules/security/freenav/base64.h deleted file mode 100644 index 87ec74a8037..00000000000 --- a/mozilla/modules/security/freenav/base64.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "seccomon.h" diff --git a/mozilla/modules/security/freenav/cert.h b/mozilla/modules/security/freenav/cert.h deleted file mode 100644 index 3cab6d74802..00000000000 --- a/mozilla/modules/security/freenav/cert.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "seccomon.h" diff --git a/mozilla/modules/security/freenav/macbuild/NoSecurity.mcp b/mozilla/modules/security/freenav/macbuild/NoSecurity.mcp deleted file mode 100644 index f5b37cace3d..00000000000 Binary files a/mozilla/modules/security/freenav/macbuild/NoSecurity.mcp and /dev/null differ diff --git a/mozilla/modules/security/freenav/macbuild/Security.Prefix b/mozilla/modules/security/freenav/macbuild/Security.Prefix deleted file mode 100644 index d600ba15280..00000000000 --- a/mozilla/modules/security/freenav/macbuild/Security.Prefix +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -// -// Security.Prefix -// -// Global prefix file for the non-debug Security project. -// -// - - -#include "SecurityConfig.h" \ No newline at end of file diff --git a/mozilla/modules/security/freenav/macbuild/SecurityConfig.h b/mozilla/modules/security/freenav/macbuild/SecurityConfig.h deleted file mode 100644 index 28cae1bdfa8..00000000000 --- a/mozilla/modules/security/freenav/macbuild/SecurityConfig.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -// we have to do this here because ConditionalMacros.h will be included from -// within OpenTptInternet.h and will stupidly define these to 1 if they -// have not been previously defined. The new PowerPlant (CWPro1) requires that -// this be set to 0. (pinkerton) - -#error "Don't use me" - -#define OLDROUTINENAMES 0 -#ifndef OLDROUTINELOCATIONS - #define OLDROUTINELOCATIONS 0 -#endif - -#define XP_MAC 1 -#define _PR_NO_PREEMPT 1 -#define _NO_FAST_STRING_INLINES_ 1 - -// Need to define NETSCAPE so that Nelson's Java SSL API bits compile. -#ifndef NETSCAPE -#define NETSCAPE 1 -#endif - -// Need to define MOZILLA_CLIENT since, well, we're the client-side library. -#ifndef MOZILLA_CLIENT -#define MOZILLA_CLIENT 1 -#endif - -// OpenTransport.h has changed to not include the error messages we need from -// it unless this is defined. Why? dunnno...(pinkerton) -#define OTUNIXERRORS 1 - -// Brutal hack: Make sure only one copy of macsock.h is included. -//#define macksocket_h___ - -#include "IDE_Options.h" - -/* Make sure that "macintosh" is defined. */ -#ifndef macintosh -#define macintosh 1 -#endif diff --git a/mozilla/modules/security/freenav/makefile.win b/mozilla/modules/security/freenav/makefile.win deleted file mode 100644 index 837bc955aa0..00000000000 --- a/mozilla/modules/security/freenav/makefile.win +++ /dev/null @@ -1,99 +0,0 @@ - -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -!if "$(MOZ_BITS)" == "16" -!ifndef MOZ_DEBUG -OPTIMIZER=-Os -UDEBUG -DNDEBUG -!endif -!endif - -#//------------------------------------------------------------------------ -#// -#// Specify the depth of the current directory relative to the -#// root of NS -#// -#//------------------------------------------------------------------------ -DEPTH= ..\..\.. - -!ifndef MAKE_OBJ_TYPE -MAKE_OBJ_TYPE=EXE -!endif - -#//------------------------------------------------------------------------ -#// -#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...) -#// -#//------------------------------------------------------------------------ -LIBNAME=secfreenav$(MOZ_BITS) -PDBFILE=$(LIBNAME).pdb - -LINCS = \ -!if "$(MOZ_BITS)" != "16" - -I$(PUBLIC)\security \ - -I$(PUBLIC)\liblayer \ - -I$(PUBLIC)\dbm \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\img \ -!endif - -I$(DEPTH)\include - -#//------------------------------------------------------------------------ -#// -#// Define the files necessary to build the target (ie. OBJS) -#// -#//------------------------------------------------------------------------ -OBJS= \ - .\$(OBJDIR)\secport.obj \ - .\$(OBJDIR)\navstubs.obj \ - $(NULL) - -#//------------------------------------------------------------------------ -#// -#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...) -#// (these must be defined before the common makefiles are included) -#// -#//------------------------------------------------------------------------ -LIBRARY = .\$(OBJDIR)\$(LIBNAME).lib - -#//------------------------------------------------------------------------ -#// -#// install headers -#// -#//------------------------------------------------------------------------ -INSTALL_DIR=$(XPDIST)\include -INSTALL_FILE_LIST=base64.h cert.h preenc.h seccomon.h secerr.h sechash.h secnav.h secrng.h secstubn.h secstubs.h secstubt.h ssl.h sslerr.h zig.h secprefs.rc rosetta.h - -#//------------------------------------------------------------------------ -#// -#// Include the common makefile rules -#// -#//------------------------------------------------------------------------ -include <$(DEPTH)/config/rules.mak> - -CFLAGS = $(CFLAGS) -DMOZILLA_CLIENT - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -export:: INSTALL_FILES - -install:: install diff --git a/mozilla/modules/security/freenav/navstubs.c b/mozilla/modules/security/freenav/navstubs.c deleted file mode 100644 index 16914a0a14e..00000000000 --- a/mozilla/modules/security/freenav/navstubs.c +++ /dev/null @@ -1,734 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "secnav.h" -#include "libmocha.h" -#include "prlink.h" -#include "prinrval.h" - -void SSL_DataPending() {} - - -int -SSL_SetSockPeerID(PRFileDesc *fd, char *peerID) -{ - return(0); -} - -void -SECNAV_Posting(PRFileDesc *fd) -{ - return; -} - -void -SECNAV_HTTPHead(PRFileDesc *fd) -{ - return; -} - -void -SECNAV_RegisterNetlibMimeConverters() -{ - return; -} - -char * -SECNAV_MungeString(const char *unmunged_string) -{ - return(NULL); -} - -char * -SECNAV_UnMungeString(const char *munged_string) -{ - return(NULL); -} - -PRBool -SECNAV_GenKeyFromChoice(void *proto_win, LO_Element *form, - char *choiceString, char *challenge, - char *typeString, char *pqgString, - char **pValue, PRBool *pDone) -{ - return(PR_FALSE); -} - - -char ** -SECNAV_GetKeyChoiceList(char *type, char *pqgString) -{ - return(NULL); -} - -PRBool -SECNAV_SecurityDialog(MWContext *context, int state) -{ - return (state == SD_INSECURE_POST_FROM_INSECURE_DOC); -} - -JSObject * -lm_DefinePkcs11(MochaDecoder *decoder) -{ - return((JSObject *)1); -} - -JSObject * -lm_DefineCrypto(MochaDecoder *decoder) -{ - return((JSObject *)1); -} - -void -NET_InitCertLdapProtocol(void) -{ -} - - -CERTCertificate * -CERT_DupCertificate(CERTCertificate *cert) -{ - return(NULL); -} - -void -CERT_DestroyCertificate(CERTCertificate *cert) -{ - return; -} - -CERTCertificate * -CERT_NewTempCertificate (CERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER) -{ - return(NULL); -} - -CERTCertDBHandle * -CERT_GetDefaultCertDB(void) -{ - return(NULL); -} - -CERTCertificate * -CERT_DecodeCertFromPackage(char *certbuf, int certlen) -{ - return(NULL); -} - -char * -CERT_HTMLCertInfo(CERTCertificate *cert, PRBool showImages, PRBool showIssuer) -{ - return(NULL); -} - -PRBool -CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2) -{ - return(PR_FALSE); -} - -const char * -SECNAV_GetPolicyNameString(void) -{ - return(NULL); -} - -int -SECNAV_InitConfigObject(void) -{ - return(0); -} - -int -SECNAV_RunInitialSecConfig(void) -{ - return(0); -} - -void -SECNAV_EarlyInit(void) -{ - return; -} - -void -SECNAV_Init(void) -{ - return; -} - -void -SECNAV_Shutdown(void) -{ - return; -} - -void -SECNAV_SecurityAdvisor(void *proto_win, URL_Struct *url) -{ - return; -} - -char * -SECNAV_MakeCertButtonString(CERTCertificate *cert) -{ - return(NULL); -} - -int -SECNAV_SecURLData(char *which, NET_StreamClass *stream, MWContext *cx) -{ - return(-1); -} - -char * -SECNAV_SecURLContentType(char *which) -{ - return(NULL); -} - -int -SECNAV_SecHandleSecurityAdvisorURL(MWContext *cx, const char *which) -{ - return(-1); -} - -void -SECNAV_HandleInternalSecURL(URL_Struct *url, MWContext *cx) -{ - return; -} - -PRBool -SSL_IsDomestic(void) -{ - return(PR_FALSE); -} - -SECStatus -SECNAV_ComputeFortezzaProxyChallengeResponse(MWContext *context, - char *asciiChallenge, - char **signature_out, - char **clientRan_out, - char **certChain_out) -{ - return(SECFailure); -} - - -char * -SECNAV_PrettySecurityStatus(int level, unsigned char *status) -{ - return(NULL); -} - -char * -SECNAV_SecurityVersion(PRBool longForm) -{ - return("N"); -} - -char * -SECNAV_SSLCapabilities(void) -{ - return(NULL); -} - -unsigned char * -SECNAV_SSLSocketStatus(PRFileDesc *fd, int *return_security_level) -{ - return(NULL); -} - -unsigned char * -SECNAV_CopySSLSocketStatus(unsigned char *status) -{ - return(NULL); -} - - -unsigned int -SECNAV_SSLSocketStatusLength(unsigned char *status) -{ - return(0); -} - -char * -SECNAV_SSLSocketCertString(unsigned char *status) -{ - return(NULL); -} - -PRBool -SECNAV_CompareCertsForRedirection(unsigned char *status1, - unsigned char *status2) -{ - return(PR_FALSE); -} - -CERTCertificate * -SECNAV_CertFromSSLSocketStatus(unsigned char *status) -{ - return(NULL); -} - -SECStatus -RNG_RNGInit(void) -{ - return(SECSuccess); -} - -/* - * probably need to provide something here - */ -SECStatus -RNG_GenerateGlobalRandomBytes(void *dest, size_t len) -{ - /* This is a temporary implementation to avoid */ - /* the cache filename horkage. This needs to have a more */ - /* secure/free implementation here - Gagan */ - - char* output=dest; - size_t i; - srand((unsigned int) PR_IntervalToMilliseconds(PR_IntervalNow())); - for (i=0;iprotocol = HTTP_TYPE_URL; -#define HG42469 -#define HG87376 -#define HG76363 -#define HG83667 -#define HG00484 -#define HG88000 -#define HG50027 -#define HG72762 -#define HG16262 -#define HG72661 -#define HG13227 -#define HG65256 -#define HG33234 -#define HG22658 -#define HG28266 -#define HG00729 -#define HG60283 -#define HG60207 -#define HG42440 -#define HG20026 -#define HG02977 -#define HG02726 -#define HG98276 -#define HG72999 -#define HG73943 -#define HG92762 -#define HG92755 -#define HG98229 -#define HG98265 -#define HG93653 -#define HG82762 -#define HG82621 -#define HG22960 -#define HG92827 -#define HG02087 -#define HG82126 -#define HG62212 FALSE, FALSE -#define HG91611 FALSE, FALSE -#define HG81762 FALSE, FALSE -#define HG76255 FALSE, FALSE -#define HG22987 -#define HG22296 FALSE, FALSE -#define HG22867 -#define HG32145 -#define HG09990 FALSE, FALSE -#define HG89520 -#define HG02192 FALSE, FALSE -#define HG82821 -#define HG82224 -#define HG22821 -#define HG03067 "msg.h" -#define HG23277 -#define HG92923 -#define HG82220 -#define HG22067 -#define HG98330 -#define HG98373 -#define HG22860 -#define HG02700 "NIKI" -#define HG99877 "prefapi.h" -#define HG02902 "msgsend.h" -#define HG98214 "rosetta.h" -#define HG72621 -#define HG10828 -#define HG82727 -#define HG26763 -#define HG26250 -#define HG26251 -#define HG26252 SECFailure; -#define HG26253 FALSE -#define HG26237 -#define HG26748 -#define HG98476 -#define HG83764 -#define HG83744 -#define HG83476 -#define HG84777 -#define HG27398 -#define HG83263 -#define HG22730 -#define HG74640 -#define HG87365 -#define HG73632 -#define HG29383 -#define HG25262 -#define HG17993 -#define HG72294 -#define HG21522 -#define HG03937 -#define HG21632 -#define HG22220 -#define HG38932 -#define HG83330 -#define HG20476 -#define HG87358 -#define HG93765 -#define HG92743 Bool dummy, -#define HG83665 -#define HG98376 FALSE, -#define HG92362 -#define HG26300 -#define HG27229 "rosetta.h" -#define HG27230 FALSE, -#define HG27326 "mkutils.h" -#define HG32828 -#define HG26363 "msgnet.h" -#define HG26227 -#define HG27327 FALSE -#define HG38373 FALSE -#define HG72524 -#define HG73654 FALSE -#define HG87263 FALSE -#define HG83733 FALSE -#define HG32830 FALSE -#define HG29237 -#define HG87373 "net.h" -#define HG73226 -#define HG38731 -#define HG87272 MK_LDAP_TITLE -#define HG73272 MK_LDAP_TITLE -#define HG73211 -#define HG83363 -#define HG26557 -#define HG27328 -#define HG23833 -#define HG28330 -#define HG10299 "gui.h" -#define HG10300 FALSE, -#define HG82332 -#define HG32949 -#define HG38737 -#define HG29239 -#define HG28287 -#define HG22999 FALSE, -#define HG93230 -#define HG29399 -#define HG20900 -#define HG23929 "mktcp.h" -#define HG82300 -#define HG21899 -#define HG19088 -#define HG10877 -#define HG23298 -#define HG29898 -#define HG22201 -#define HG38738 FALSE, -#define HG02873 FALSE, -#define HG92892 -#define HG92871 -#define HG82772 -#define HG03903 -#define HG82773 FALSE -#define HG22087 FALSE -#define HG22088 -#define HG22089 FALSE -#define HG21092 -#define HG09309 -#define HG29802 0 -#define HG93882 -#define HG93898 -#define HG93288 -#define HG21090 -#define HG20092 -#define HG29398 -#define HG83273 -#define HG09438 "mkpop3.h" -#define HG09439 FALSE, -#define HG23535 "mktcp.h" -#define HG27655 -#define HG83763 -#define HG35353 -#define HG38763 "mime.h" -#define HG83777 -#define HG35632 -#define HG83773 -#define HG83787 -#define HG73678 -#define HG84378 -#define HG84772 -#define HG99875 XP_STRDUP -#define HG99876 XP_STRDUP -#define HG99879 XP_STRDUP -#define HG99880 -#define HG99881 -#define HG99882 -#define HG53784 -#define HG78478 -#define HG89984 -#define HG54689 -#define HG55451 -#define HG36459 -#define HG75442 -#define HG59731 -#define HG56898 -#define HG78111 FALSE - -/* WINDOWS FRONT END */ - - -#define HG37279 -#define HG83788 -#define HG82387 -#define HG89327 -#define HG27635 -#define HG83722 -#define HG06197 -#define HG32564 -#define HG73537 -#define HG21675 -#define HG72866 FALSE; -#define HG27861 -#define HG73221 FALSE -#define HG73723 -#define HG28751 FALSE; -#define HG28972 -#define HG29172 -#define HG98271 -#define HG27851 -#define HG98261 -#define HG28768 -#define HG28728 -#define HG26723 -#define HG29792 -#define HG38729 -#define HG81325 -#define HG87322 -#define HG28218 -#define HG76528 -#define HG27625 -#define HG72521 -#define HG87282 -#define HG28762 -#define HG92611 -#define HG11173 -#define HG21215 -#define HG21326 -#define HG22121 -#define HG28363 -#define HG26545 -#define HG12421 -#define HG17231 -#define HG26576 int idx = -1; -#define HG26522 -#define HG87236 return; -#define HG17236 return; -#define HG87211 -#define HG26722 -#define HG27811 -#define HG27129 -#define HG21198 FALSE, FALSE -#define HG26726 -#define HG21892 FALSE, FALSE -#define HG28118 -#define HG26262 -#define HG79266 -#define HG72611 -#define HG72625 -#define HG47991 -#define HG27367 -#define HG72671 -#define HG72729 ss = XP_STRDUP(XP_GetString(XFE_SECURITY_DISABLED)); -#define HG78268 -#define HG78261 -#define HG12675 -#define HG87163 -#define HG78262 -#define HG87268 -#define HG78265 -#define HG87627 -#define HG72721 -#define HG13267 -#define HG87262 -#define HG71265 -#define HG72587 -#define HG87271 -#define HG21989 -#define HG12976 -#define HG87265 -#define HG78272 -#define HG87921 -#define HG72881 -#define HG87111 -#define HG27632 -#define HG87782 -#define HG37211 -#define HG11326 -#define HG72819 -#define HG71199 -#define HG18159 -#define HG28688 -#define HG82160 -#define HG92799 -#define HG28190 -#define HG87291 -#define HG17211 -#define HG01019 -#define HG01283 -#define HG98269 -#define HG91001 -#define HG92179 -#define HG92769 -#define HG98268 -#define HG82688 -#define HG32179 -#define HG82687 -#define HG78277 -#define HG91268 -#define HG10219 -#define HG01092 -#define HG72711 -#define HG78281 -#define HG18181 -#define HG82981 -#define HG87288 -#define HG82111 FALSE -#define HG92828 -#define HG12821 -#define HG12111 -#define HG82128 -#define HG81210 -#define HG03833 -#define HG12928 -#define HG00298 -#define HG02920 -#define HG02092 -#define HG28999 -#define HG09219 -#define HG89219 -#define HG82198 -#define HG20303 FALSE -#define HG02023 FALSE -#define HG39875 -#define HG07326 -#define HG82883 -#define HG20388 -#define HG72988 FALSE -#define HG17272 -#define HG00288 -#define HG82992 -#define HG28732 -#define HG20931 -#define HG29322 -#define HG29281 -#define HG20363 -#define HG98200 -#define HG71611 -#define HG11111 -#define HG21933 -#define HG28921 -#define HG82872 NULL, NULL -#define HG72723 -#define HG20192 -#define HG20198 -#define HG35220 -#define HG82811 -#define HG97291 -#define HG12922 -#define HG28182 -#define HG12832 -#define HG20938 -#define HG71710 -#define HG11299 -#define HG10291 -#define HG01922 -#define HG10287 -#define HG10297 -#define HG81272 -#define HG02621 -#define HG19282 -#define HG92727 -#define HG82719 -#define HG21817 -#define HG81761 -#define HG12172 -#define HG10282 -#define HG29081 -#define HG21182 -#define HG02030 -#define HG93649 -#define HG18966 -#define HG27311 -#define HG89217 -#define HG82167 -#define HG21761 -#define HG10280 -#define HG19271 -#define HG10977 -#define HG19711 -#define HG19189 -#define HG71676 -#define HG71851 -#define HG78266 -#define HG18177 -#define HG18760 -#define HG71661 -#define HG90177 -#define HG79299 -#define HG21897 m_port_text -#define HG17661 m_port_text -#define HG18261 -#define HG19877 -#define HG19871 -#define HG19773 -#define HG18162 -#define HG13181 -#define HG14871 FALSE -#define HG19861 FALSE -#define HG21511 -#define HG19721 -#define HG19511 -#define HG17271 -#define HG18671 -#define HG19616 -#define HG19879 -#define HG17922 -#define HG98219 SetDlgItemInt(IDC_EDIT_PORT_NO, LDAP_PORT); -#define HG92710 -#define HG27626 -#define HG28981 -#define HG72186 -#define HG92672 -#define HG90271 -#define HG92177 -#define HG98216 -#define HG91761 SetDlgItemInt(IDC_EDIT_PORT_NO, LDAP_PORT); - -#define HG51387 -#define HG51388 -#define HG51389 - -#define HG43287 -#define HG43288 - - -#define HG91827 -#define HG92380 -#define HG28336 -#define HG02070 -#define HG62519 - - -#define HG09842 FALSE -#define HG09843 FALSE -#define HG09844 FALSE -#define HG09845 f[0] = 0; - -#define HG09846 \ - PR_Init("mimefilt", 24, 1, 0); \ - RNG_RNGInit(); \ - -#define HG09847 -#define HG09848 "usage: %s [ URL [ -fancy | -no-fancy | -html | -raw | -outline ]]\n" -#define HG09849 -#define HG09850 -#define HG09851 -#define HG09852 -#define HG09853 -#define HG09854 -#define HG09855 -#define HG09856 -#define HG09857 -#define HG09858 -#define HG09859 -#define HG09860 -#define HG09861 -#define HG09862 -#define HG09863 -#define HG09864 -#define HG09865 -#define HG09866 -#define HG09867 -#define HG09868 - -#define HG09869 \ - /* If we're supposed to write this object, but aren't supposed to convert */ \ - /* it to HTML, simply pass it through unaltered. (But, if we're supposed */ \ - /* to ******* ... uh, do something else.) */ \ - /* */ \ - if (obj->output_p && \ - obj->options && \ - !obj->options->write_html_p && \ - obj->options->output_fn) \ - return MimeObject_write(obj, line, length, TRUE); \ - - -#define HG09870 -#define HG09871 - -#define HG09872 status = MimeHeaders_write_raw_headers(msg->hdrs, obj->options, 0); -#define HG09873 altform_p = (msg && msg->hdrs); - -#define HG43771 -#define HG56232 0 -#define HG78388 -#define HG80200 -#define HG88918 -#define HG89321 -#define HG82921 -#define HG82991 -#define HG89202 middle_key = 0; -#define HG82001 "%s%s" -#define HG28974 -#define HG87988 -#define HG43290 -#define HG89332 0 -#define HG09878 - - - -/* begin mail/news netlib */ -#define HG37838 - -#define HG64967 \ - XP_Bool m_syncX1; - -#define HG20039 \ - m_syncX1 = FALSE; - -#define HG65202 - -#define HG46644 - -#define HG38728 - -#define HG09874 -#define HG56327 -#define HG78485 - -#define HG22334 \ - url = PR_smprintf("repl-ldap://%s%s:%d/%s", auth ? auth : "", \ - server->serverName, server->port, \ - server->searchBase); \ - -#define HG40923 -#define HG75778 -#define HG17482 XP_STRDUP -#define HG15296 XP_STRDUP - -#define HG47233 \ -"ssl.h" \ - -#define HG09893 \ -"secnav.h" - -#define HG64643 XP_STRDUP -#define HG63218 XP_STRDUP - -#define HG40855 \ -"ssl.h" \ - -#define HG07711 -#define HG25430 -#define HG43574 -#define HG43072 -#define HG51514 -#define HG28477 -#define HG42871 -#define HG25431 -#define HG55785 - -#define HG51966 \ - net_graceful_shutdown(con->csock, FALSE); \ - -#define HG72589 \ - urlScheme = "news:"; \ - -#define HG56946 \ - urlScheme = "news:"; \ - -#define HG43575 -#define HG05417 \ - defport = 0;\ - -#define HG05998 \ - port == NEWS_PORT \ - -#define HG45873 \ - *bValP = FALSE; \ - -#define HG66376 -#define HG78293 0 -#define HG01869 -#define HG51154 ce->URL_s->address -#define HG28465 NEWS_PORT -#define HG42817 FALSE -#define HG65321 cd->control_con->hostname -#define HG31966 "secnav.h" -#define HG31996 "ssl.h" -#define HG79357 "sslerr.h" -#define HG17322 -#define HG54697 IMAP4_PORT -#define HG72598 FALSE -#define HG94391 FALSE -#define HG65837 -#define HG17406 -#define HG32397 -#define HG26051 -#define HG03686 0 -#define HG47042 -#define HG41242 -#define HG53733 - -#define HG57771 \ - if (!password) return -1; \ - -#define HG12837 XP_STRDUP -#define HG04206 -#define HG68978 TRUE -#define HG09609 -#define HG56055 -#define HG10349 -#define HG40702 -#define HG30626 -#define HG16713 -#define HG92990 \ - if (CD_AUTH_LOGIN_METHOD) \ - { \ - CD_NEXT_STATE = SMTP_SEND_AUTH_LOGIN_USERNAME; \ - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_AUTH_LOGIN_RESPONSE; \ - } \ - else \ - { \ - CD_NEXT_STATE = SMTP_SEND_HELO_RESPONSE; \ - } \ - -#define HG18210 -#define HG76227 -#define HG79144 -#define HG26788 -#define HG77067 -#define HG15779 -#define HG06474 FALSE -#define HG70187 TRUE -#define HG50707 FALSE -#define HG27293 -#define HG68946 -#define HG11764 -#define HG18517 FALSE -#define HG74130 FALSE -#define HG38712 -#define HG12690 - -/* end mail/news netlib */ - - - - - - -#endif /* _ROSETTA_H_ */ - - - - diff --git a/mozilla/modules/security/freenav/seccomon.h b/mozilla/modules/security/freenav/seccomon.h deleted file mode 100644 index c233adf7e35..00000000000 --- a/mozilla/modules/security/freenav/seccomon.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef _SECCOMON_H_ -#define _SECCOMON_H_ - -#include -#include -#include -#include -#include "prmem.h" -#include "plarena.h" -#include "prtypes.h" -#include "prlog.h" -#include "plstr.h" -#include "prio.h" - -#if defined(XP_CPLUSPLUS) -# define SEC_BEGIN_PROTOS extern "C" { -# define SEC_END_PROTOS } -#else -# define SEC_BEGIN_PROTOS -# define SEC_END_PROTOS -#endif - -#include "secstubt.h" -#include "secstubs.h" - -#define PORT_Strlen(s) strlen(s) -#define PORT_Strcasecmp PL_strcasecmp -#define PORT_Memset memset -#define PORT_Strcmp strcmp -#define PORT_Assert PR_ASSERT -#define PORT_Memcpy memcpy -#define PORT_Strchr strchr - -SEC_BEGIN_PROTOS -void * -PORT_Alloc(size_t bytes); - -void * -PORT_Realloc(void *oldptr, size_t bytes); - -void * -PORT_ZAlloc(size_t bytes); - -void -PORT_Free(void *ptr); - -void -PORT_ZFree(void *ptr, size_t len); - -PRArenaPool * -PORT_NewArena(unsigned long chunksize); - -void * -PORT_ArenaAlloc(PRArenaPool *arena, size_t size); - -void * -PORT_ArenaZAlloc(PRArenaPool *arena, size_t size); - -void -PORT_FreeArena(PRArenaPool *arena, PRBool zero); - -void * -PORT_ArenaGrow(PRArenaPool *arena, void *ptr, size_t oldsize, size_t newsize); - -void * -PORT_ArenaMark(PRArenaPool *arena); - -void -PORT_ArenaRelease(PRArenaPool *arena, void *mark); -SEC_END_PROTOS - -#endif /* _SECCOMON_H_ */ diff --git a/mozilla/modules/security/freenav/secerr.h b/mozilla/modules/security/freenav/secerr.h deleted file mode 100644 index f88457aff79..00000000000 --- a/mozilla/modules/security/freenav/secerr.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef __SEC_ERR_H_ -#define __SEC_ERR_H_ - - -#ifdef XP_MAC -#define SEC_ERROR_BASE (-2000) -#else -#define SEC_ERROR_BASE (-0x2000) -#endif -#define SEC_ERROR_LIMIT (SEC_ERROR_BASE + 1000) - -#define IS_SEC_ERROR(code) \ - (((code) >= SEC_ERROR_BASE) && ((code) < SEC_ERROR_LIMIT)) - -#endif /* __SEC_ERR_H_ */ diff --git a/mozilla/modules/security/freenav/sechash.h b/mozilla/modules/security/freenav/sechash.h deleted file mode 100644 index 3cab6d74802..00000000000 --- a/mozilla/modules/security/freenav/sechash.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "seccomon.h" diff --git a/mozilla/modules/security/freenav/secnav.h b/mozilla/modules/security/freenav/secnav.h deleted file mode 100644 index 6a683570434..00000000000 --- a/mozilla/modules/security/freenav/secnav.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "seccomon.h" -#include "secstubn.h" diff --git a/mozilla/modules/security/freenav/secport.c b/mozilla/modules/security/freenav/secport.c deleted file mode 100644 index d11d047307c..00000000000 --- a/mozilla/modules/security/freenav/secport.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "seccomon.h" -#include "prmem.h" -#include "prerror.h" -#include "plarena.h" -#include "prlog.h" - -void * -PORT_Alloc(size_t bytes) -{ - void *rv; - - /* Always allocate a non-zero amount of bytes */ - rv = (void *)PR_Malloc(bytes ? bytes : 1); - return rv; -} - -void * -PORT_Realloc(void *oldptr, size_t bytes) -{ - void *rv; - - rv = (void *)PR_Realloc(oldptr, bytes); - return rv; -} - -void * -PORT_ZAlloc(size_t bytes) -{ - void *rv; - - /* Always allocate a non-zero amount of bytes */ - rv = (void *)PR_Calloc(1, bytes ? bytes : 1); - return rv; -} - -void -PORT_Free(void *ptr) -{ - if (ptr) { - PR_Free(ptr); - } -} - -void -PORT_ZFree(void *ptr, size_t len) -{ - if (ptr) { - memset(ptr, 0, len); - PR_Free(ptr); - } -} - -PRArenaPool * -PORT_NewArena(unsigned long chunksize) -{ - PRArenaPool *arena; - - arena = PORT_ZAlloc(sizeof(PRArenaPool)); - if ( arena != NULL ) { - PR_InitArenaPool(arena, "security", chunksize, sizeof(double)); - } - - return(arena); -} - -void * -PORT_ArenaAlloc(PRArenaPool *arena, size_t size) -{ - void *p; - - PR_ARENA_ALLOCATE(p, arena, size); - - return(p); -} - -void * -PORT_ArenaZAlloc(PRArenaPool *arena, size_t size) -{ - void *p; - - PR_ARENA_ALLOCATE(p, arena, size); - if (p == NULL) { - } else { - memset(p, 0, size); - } - - return(p); -} - -/* XXX - need to zeroize!! - jsw */ -void -PORT_FreeArena(PRArenaPool *arena, PRBool zero) -{ - PR_FinishArenaPool(arena); - PORT_Free(arena); -} - -void * -PORT_ArenaGrow(PRArenaPool *arena, void *ptr, size_t oldsize, size_t newsize) -{ - PR_ASSERT(newsize >= oldsize); - - PR_ARENA_GROW(ptr, arena, oldsize, ( newsize - oldsize ) ); - - return(ptr); -} - -void * -PORT_ArenaMark(PRArenaPool *arena) -{ - return PR_ARENA_MARK(arena); -} - -void -PORT_ArenaRelease(PRArenaPool *arena, void *mark) -{ - PR_ARENA_RELEASE(arena, mark); -} - diff --git a/mozilla/modules/security/freenav/secprefs.rc b/mozilla/modules/security/freenav/secprefs.rc deleted file mode 100644 index 8b137891791..00000000000 --- a/mozilla/modules/security/freenav/secprefs.rc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/mozilla/modules/security/freenav/secrng.h b/mozilla/modules/security/freenav/secrng.h deleted file mode 100644 index 3cab6d74802..00000000000 --- a/mozilla/modules/security/freenav/secrng.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "seccomon.h" diff --git a/mozilla/modules/security/freenav/secstubn.h b/mozilla/modules/security/freenav/secstubn.h deleted file mode 100644 index e9dd801f009..00000000000 --- a/mozilla/modules/security/freenav/secstubn.h +++ /dev/null @@ -1,254 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef _SECSTUBN_H_ -#define _SECSTUBN_H_ - -#include "xp.h" -#include "ntypes.h" -#include "net.h" - -typedef struct _digests DIGESTS; -typedef struct _zig ZIG; -typedef struct _zigcontext ZIG_Context; -typedef struct _peheader PEHeader; - -typedef struct SOBITEM_ { - char *pathname; - int type; - size_t size; - void *data; -} SOBITEM; - -typedef struct FINGERZIG_ { - size_t length; - void *key; - CERTCertificate *cert; -} FINGERZIG; - -#define ZIG_CB_SIGNAL 1 -#define ZIG_SIGN 10 -#define ZIG_F_GUESS 0 -#define ZIG_MF 2 -#define ZIG_ERR_PNF 12 - -/* certificate stuff */ - -#define ZIG_C_COMPANY 1 -#define ZIG_C_CA 2 -#define ZIG_C_SERIAL 3 -#define ZIG_C_EXPIRES 4 -#define ZIG_C_NICKNAME 5 -#define ZIG_C_FP 6 -#define ZIG_C_JAVA 100 - -SEC_BEGIN_PROTOS - -void -SECNAV_Posting(PRFileDesc *fd); - -void -SECNAV_HTTPHead(PRFileDesc *fd); - -void -SECNAV_RegisterNetlibMimeConverters(); - -char * -SECNAV_MungeString(const char *unmunged_string); - -char * -SECNAV_UnMungeString(const char *munged_string); - -PRBool -SECNAV_GenKeyFromChoice(void *proto_win, LO_Element *form, - char *choiceString, char *challenge, - char *typeString, char *pqgString, - char **pValue, PRBool *pDone); - -char ** -SECNAV_GetKeyChoiceList(char *type, char *pqgString); - -PRBool -SECNAV_SecurityDialog(MWContext *context, int state); - -void -NET_InitCertLdapProtocol(void); -const char * - -SECNAV_GetPolicyNameString(void); - -int -SECNAV_InitConfigObject(void); - -int -SECNAV_RunInitialSecConfig(void); - -void -SECNAV_EarlyInit(void); - -void -SECNAV_Init(void); - -void -SECNAV_Shutdown(void); - -void -SECNAV_SecurityAdvisor(void *proto_win, URL_Struct *url); - -char * -SECNAV_MakeCertButtonString(CERTCertificate *cert); - -int -SECNAV_SecURLData(char *which, NET_StreamClass *stream, MWContext *cx); - -char * -SECNAV_SecURLContentType(char *which); - -int -SECNAV_SecHandleSecurityAdvisorURL(MWContext *cx, const char *which); - -void -SECNAV_HandleInternalSecURL(URL_Struct *url, MWContext *cx); - -SECStatus -SECNAV_ComputeFortezzaProxyChallengeResponse(MWContext *context, - char *asciiChallenge, - char **signature_out, - char **clientRan_out, - char **certChain_out); - -char * -SECNAV_PrettySecurityStatus(int level, unsigned char *status); - -char * -SECNAV_SecurityVersion(PRBool longForm); - -char * -SECNAV_SSLCapabilities(void); - -unsigned char * -SECNAV_SSLSocketStatus(PRFileDesc *fd, int *return_security_level); - -unsigned char * -SECNAV_CopySSLSocketStatus(unsigned char *status); - -unsigned int -SECNAV_SSLSocketStatusLength(unsigned char *status); - -char * -SECNAV_SSLSocketCertString(unsigned char *status); - -PRBool -SECNAV_CompareCertsForRedirection(unsigned char *status1, - unsigned char *status2); - -CERTCertificate * -SECNAV_CertFromSSLSocketStatus(unsigned char *status); - - -DIGESTS *PR_CALLBACK -SOB_calculate_digest(void XP_HUGE *data, long length); - -int PR_CALLBACK -SOB_verify_digest(ZIG *siglist, const char *name, DIGESTS *dig); - -void PR_CALLBACK -SOB_destroy (ZIG *zig); - -char * -SOB_get_error (int status); - -ZIG_Context * -SOB_find(ZIG *zig, char *pattern, int type); - -int -SOB_find_next(ZIG_Context *ctx, SOBITEM **it); - -void -SOB_find_end(ZIG_Context *ctx); - -char * -SOB_get_url (ZIG *zig); - -ZIG * -SOB_new (void); - -int -SOB_set_callback (int type, ZIG *zig, - int (*fn) (int status, ZIG *zig, - const char *metafile, - char *pathname, char *errortext)); - -int PR_CALLBACK -SOB_cert_attribute(int attrib, ZIG *zig, long keylen, void *key, - void **result, unsigned long *length); - -int PR_CALLBACK -SOB_stash_cert(ZIG *zig, long keylen, void *key); - -int SOB_parse_manifest(char XP_HUGE *raw_manifest, long length, - const char *path, const char *url, ZIG *zig); - -void -SECNAV_signedAppletPrivileges(void *proto_win, char *javaPrin, - char *javaTarget, char *risk, PRBool isCert); - -void -SECNAV_signedAppletPrivilegesOnMozillaThread(void *proto_win, char *javaPrin, - char *javaTarget, char *risk, PRBool isCert); - -char * -SOB_JAR_list_certs (void); - -int -SOB_JAR_validate_archive (char *filename); - -void * -SOB_JAR_new_hash (int alg); - -void * -SOB_JAR_hash (int alg, void *cookie, int length, void *data); - -void * -SOB_JAR_end_hash (int alg, void *cookie); - -int -SOB_JAR_sign_archive (char *nickname, char *password, char *sf, char *outsig); - -int -SOB_set_context (ZIG *zig, MWContext *mw); - -int -SOB_pass_archive(int format, char *filename, const char *url, ZIG *zig); - -int -SOB_get_metainfo(ZIG *zig, char *name, char *header, void **info, - unsigned long *length); - -int -SOB_verified_extract(ZIG *zig, char *path, char *outpath); - -NET_StreamClass * -SECNAV_MakePreencryptedWriteStream(FO_Present_Types format_out, void *data, - URL_Struct *url, MWContext *window_id); - -SEC_END_PROTOS - -#endif /* _SECSTUBN_H_ */ diff --git a/mozilla/modules/security/freenav/secstubs.h b/mozilla/modules/security/freenav/secstubs.h deleted file mode 100644 index 5e5f75b1845..00000000000 --- a/mozilla/modules/security/freenav/secstubs.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef _SECSTUBS_H_ -#define _SECSTUBS_H_ - -SEC_BEGIN_PROTOS - -CERTCertificate * -CERT_DupCertificate(CERTCertificate *cert); - -void -CERT_DestroyCertificate(CERTCertificate *cert); - -CERTCertificate * -CERT_NewTempCertificate (CERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER); - -CERTCertDBHandle * -CERT_GetDefaultCertDB(void); - -CERTCertificate * -CERT_DecodeCertFromPackage(char *certbuf, int certlen); - -char * -CERT_HTMLCertInfo(CERTCertificate *cert, PRBool showImages, PRBool showIssuer); - -PRBool -CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2); - -unsigned long -SSL_SecurityCapabilities(void); - -int -SSL_SetSockPeerID(PRFileDesc *fd, char *peerID); - -int -SSL_SecurityStatus(PRFileDesc *fd, int *on, char **cipher, - int *keySize, int *secretKeySize, - char **issuer, char **subject); - -CERTCertificate * -SSL_PeerCertificate(PRFileDesc *fd); - -PRBool -SSL_IsDomestic(void); - -SECStatus -RNG_RNGInit(void); - -SECStatus -RNG_GenerateGlobalRandomBytes(void *dest, size_t len); - -size_t -RNG_GetNoise(void *buf, size_t maxbytes); - -void -RNG_SystemInfoForRNG(void); - -void RNG_FileForRNG(char *filename); - -SECStatus -RNG_RandomUpdate(void *data, size_t bytes); - -SECStatus -MD5_HashBuf(unsigned char *dest, const unsigned char *src, - uint32 src_length); - -MD5Context * -MD5_NewContext(void); - -void -MD5_DestroyContext(MD5Context *cx, PRBool freeit); - -void -MD5_Begin(MD5Context *cx); - -void -MD5_Update(MD5Context *cx, const unsigned char *input, unsigned int inputLen); - -void -MD5_End(MD5Context *cx, unsigned char *digest, - unsigned int *digestLen, unsigned int maxDigestLen); - -SECStatus -SHA1_HashBuf(unsigned char *dest, const unsigned char *src, uint32 src_length); - -SHA1Context * -SHA1_NewContext(void); - -void -SHA1_DestroyContext(SHA1Context *cx, PRBool freeit); - -void -SHA1_Begin(SHA1Context *cx); - -void -SHA1_Update(SHA1Context *cx, const unsigned char *input, unsigned int inputLen); - -void -SHA1_End(SHA1Context *cx, unsigned char *digest, - unsigned int *digestLen, unsigned int maxDigestLen); - -/* - * Generic hash api. In the future this should be the only public - * API. - */ - -extern unsigned int HASH_ResultLen(HASH_HashType type); - -extern unsigned int HASH_ResultLenContext(HASHContext *context); - -extern SECStatus HASH_HashBuf(HASH_HashType type, unsigned char *dest, - unsigned char *src, uint32 src_len); - -extern HASHContext *HASH_Create(HASH_HashType type); - -extern HASHContext *HASH_Clone(HASHContext *context); - -extern void HASH_Destroy(HASHContext *context); - -extern void HASH_Begin(HASHContext *context); - -extern void HASH_Update(HASHContext *context, const unsigned char *src, - unsigned int len); - -extern void HASH_End(HASHContext *context, unsigned char *result, - unsigned int *result_len, unsigned int max_result_len); - - -char * -BTOA_DataToAscii(const unsigned char *data, unsigned int len); - -unsigned char * -ATOB_AsciiToData(const char *string, unsigned int *lenp); - -SEC_END_PROTOS - -#endif /* _SECSTUBS_H_ */ diff --git a/mozilla/modules/security/freenav/secstubt.h b/mozilla/modules/security/freenav/secstubt.h deleted file mode 100644 index ef6069c8d7b..00000000000 --- a/mozilla/modules/security/freenav/secstubt.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef _SECSTUBT_H_ -#define _SECSTUBT_H_ - -typedef struct _item { - unsigned char *data; - unsigned long len; -} SECItem; - -struct CERTCertificateStr { - SECItem derCert; -}; - -typedef struct CERTCertificateStr CERTCertificate; -typedef struct _certdb CERTCertDBHandle; -typedef struct _md5context MD5Context; -typedef struct _sha1context SHA1Context; -typedef struct HASHContextStr HASHContext; - -#define MD5_LENGTH 16 -#define SHA1_LENGTH 20 - -typedef enum { - HASH_AlgNULL, - HASH_AlgMD2, - HASH_AlgMD5, - HASH_AlgSHA1, - HASH_AlgTOTAL -} HASH_HashType; - -typedef enum _SECStatus { - SECWouldBlock = -2, - SECFailure = -1, - SECSuccess = 0 -} SECStatus; - -#define SSL_SECURITY_STATUS_NOOPT -1 -#define SSL_SECURITY_STATUS_OFF 0 -#define SSL_SECURITY_STATUS_ON_HIGH 1 -#define SSL_SECURITY_STATUS_ON_LOW 2 -#define SSL_SECURITY_STATUS_FORTEZZA 3 - -#define SSL_SC_RSA 0x00000001L -#define SSL_SC_MD2 0x00000010L -#define SSL_SC_MD5 0x00000020L -#define SSL_SC_RC2_CBC 0x00001000L -#define SSL_SC_RC4 0x00002000L -#define SSL_SC_DES_CBC 0x00004000L -#define SSL_SC_DES_EDE3_CBC 0x00008000L -#define SSL_SC_IDEA_CBC 0x00010000L - -#endif /* _SECSTUBT_H_ */ diff --git a/mozilla/modules/security/freenav/ssl.h b/mozilla/modules/security/freenav/ssl.h deleted file mode 100644 index 3cab6d74802..00000000000 --- a/mozilla/modules/security/freenav/ssl.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "seccomon.h" diff --git a/mozilla/modules/security/freenav/sslerr.h b/mozilla/modules/security/freenav/sslerr.h deleted file mode 100644 index 0872f786c09..00000000000 --- a/mozilla/modules/security/freenav/sslerr.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef __SSL_ERR_H_ -#define __SSL_ERR_H_ - - -#ifdef XP_MAC -#define SSL_ERROR_BASE (-3000) -#else -#define SSL_ERROR_BASE (-0x3000) -#endif -#define SSL_ERROR_LIMIT (SSL_ERROR_BASE + 1000) - -#ifndef NO_SECURITY_ERROR_ENUM -typedef enum { - SSL_ERROR_BAD_CERTIFICATE = SSL_ERROR_BASE + 4 -} SSLErrorCodes; -#endif - -#define IS_SSL_ERROR(code) \ - (((code) >= SSL_ERROR_BASE) && ((code) < SSL_ERROR_LIMIT)) - -#endif /* __SSL_ERR_H_ */ diff --git a/mozilla/modules/security/freenav/zig.h b/mozilla/modules/security/freenav/zig.h deleted file mode 100644 index 6a683570434..00000000000 --- a/mozilla/modules/security/freenav/zig.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "seccomon.h" -#include "secstubn.h" diff --git a/mozilla/network/Makefile.in b/mozilla/network/Makefile.in deleted file mode 100644 index edef5b612d4..00000000000 --- a/mozilla/network/Makefile.in +++ /dev/null @@ -1,32 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = .. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -DIRS = cache client cnvts mimetype main protocol public module - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/MANIFEST b/mozilla/network/cache/MANIFEST deleted file mode 100644 index b6a0c6eb7a8..00000000000 --- a/mozilla/network/cache/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -extcache.h -netcache.h diff --git a/mozilla/network/cache/Makefile.in b/mozilla/network/cache/Makefile.in deleted file mode 100644 index ba5115f30e0..00000000000 --- a/mozilla/network/cache/Makefile.in +++ /dev/null @@ -1,46 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = netcache -LIBRARY_NAME = netcache - -REQUIRES = network dbm util pref js java fileurl security layer img jtools cache - -CSRCS = \ - cachedump.c \ - extcache.c \ - mkcache.c \ - mkextcac.c \ - mkmemcac.c \ - $(NULL) - -EXPORTS = netcache.h mkcache.h mkmemcac.h extcache.h -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/cachedump.c b/mozilla/network/cache/cachedump.c deleted file mode 100644 index 6e655576c47..00000000000 --- a/mozilla/network/cache/cachedump.c +++ /dev/null @@ -1,139 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* this little program will sequentially dump out - * every record in the database - */ -#include "mkcache.h" -#include "extcache.h" -#include "plstr.h" - -#include -#include -#include - -#ifdef _sgi -#include -#endif /* _sgi */ - -/* URL methods - */ -#define URL_GET_METHOD 0 -#define URL_POST_METHOD 1 -#define URL_HEAD_METHOD 2 - -static DB * -net_OpenExtCacheFatDB(char *filename) -{ - DB *rv; - HASHINFO hash_info = { - 16*1024, /* bucket size */ - 0, /* fill factor */ - 0, /* number of elements */ - 0, /* bytes to cache */ - 0, /* hash function */ - 0}; /* byte order */ - - - rv = dbopen(filename, - O_RDWR | O_CREAT, - 0644, - DB_HASH, - &hash_info); - - if(!rv) - { - printf("Could not open cache database: %s\n", filename); - exit(1); - } - - return(rv); -} - -int main(int argc, char **argv) -{ - net_CacheObject * cache_obj; - DB * ext_cache_database=0; - DBT key; - DBT data; - - memset(&cache_obj, 0, sizeof(net_CacheObject)); - - if(argc != 2) - { - printf("Usage:\n" - "%s database\n" - "\n" - "database: path and name of the database\n", argv[0]); - exit(1); - } - - /* open the cache database */ - ext_cache_database = net_OpenExtCacheFatDB(argv[1]); - - if(!ext_cache_database) - { - perror("Could not open cache database"); - exit(1); - } - - while(!(ext_cache_database->seq)(ext_cache_database, &key, &data, 0)) - { - - if(key.size == PL_strlen(EXT_CACHE_NAME_STRING) - && !PL_strcmp(key.data, EXT_CACHE_NAME_STRING)) - { - /* make sure it's a terminated string */ - if(((char *)data.data)[data.size-1] == '\0') - printf("\n\nDatabase Name: %s\n", (char*)data.data); - else - printf("\n\nDatabase Name is corrupted!\n"); - printf("\n--------------------------------------\n"); - continue; - } - - /* try and convert the db struct to a cache struct */ - cache_obj = net_DBDataToCacheStruct(&data); - - if(!cache_obj) - { - printf("Malformed database entry:\n"); - printf("key: "); - fwrite(key.data, 1, key.size, stdout); - printf("\ndata: "); - fwrite(data.data, 1, data.size, stdout); - printf("\n"); - printf("--------------------------------------\n"); - continue; - } - - /* the URL is 8 bytes into the key struct - */ - printf("URL: %s\n",(char*)key.data+8); - printf("file: %s\n", cache_obj->filename); - printf("is_relative_path: %s\n", cache_obj->is_relative_path ? "TRUE" : "FALSE"); - printf("content_type: %s\n", cache_obj->content_type); - printf("content_length: %d\n", cache_obj->content_length); - printf("last_modified: %s\n", ctime(&cache_obj->last_modified)); - printf("--------------------------------------\n"); - } -} - diff --git a/mozilla/network/cache/cacheutils.h b/mozilla/network/cache/cacheutils.h deleted file mode 100644 index d4feb646b43..00000000000 --- a/mozilla/network/cache/cacheutils.h +++ /dev/null @@ -1,21 +0,0 @@ - -#ifndef CACHEUTILS_H -#define CACHEUTILS_H - -/* Find an actively-loading cache file for URL_s in context, and copy the first - * nbytes of it to a new cache file. Return a cache converter stream by which - * the caller can append to the cloned cache file. - */ -extern NET_VoidStreamClass * -NET_CloneWysiwygCacheFile(MWContext *context, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href); - -/* Create a wysiwyg cache converter to a copy of the current entry for URL_s. - */ -extern NET_VoidStreamClass * -net_CloneWysiwygMemCacheEntry(MWContext *window_id, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href); - -#endif /* CACHEUTILS_H */ diff --git a/mozilla/network/cache/extcache.c b/mozilla/network/cache/extcache.c deleted file mode 100644 index 51af4eabbd9..00000000000 --- a/mozilla/network/cache/extcache.c +++ /dev/null @@ -1,861 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Please leave outside of ifdef for window precompiled headers */ -#include "mkcache.h" - -#ifdef MOZILLA_CLIENT -#include "mktrace.h" -#include "prmem.h" -#include "plstr.h" - -/* Publicly released Netscape cache access routines. - * - * These routines are shared between the netscape executable - * and the programs released as a cache developers kit. - * - * Created: Lou Montulli , July-95. - * Modifications/Addition: Gagan Saksena, 97 - */ - -#include "rosetta.h" - -#ifndef EXT_DB_ROUTINES -#include "secnav.h" -#include "sechash.h" -#endif - -#include "extcache.h" /* include this for everything */ - -#ifdef EXT_DB_ROUTINES - -#include -#include -#include - -typedef struct { - int32 len; - char *data; -} SECItem; - -#ifdef _sgi -#include -#endif /* _sgi */ - - -/* URL methods - */ - #define URL_GET_METHOD 0 - #define URL_POST_METHOD 1 - #define URL_HEAD_METHOD 2 - -#endif /* DB_STORE */ - - -MODULE_PRIVATE DBT * -net_CacheDBTDup(DBT *obj) -{ - DBT * rv = PR_NEW(DBT); - - if(!rv) - return(NULL); - - rv->size = obj->size; - rv->data = PR_Malloc(rv->size); - - if(!rv->data) - { - PR_Free(rv); - return(NULL); - } - - memcpy(rv->data, obj->data, rv->size); - - return(rv); - -} - -/* free the cache object - */ -MODULE_PRIVATE void net_freeCacheObj (net_CacheObject * cache_obj) -{ - - PR_FREEIF(cache_obj->address); - PR_FREEIF(cache_obj->post_data); - PR_FREEIF(cache_obj->post_headers); - PR_FREEIF(cache_obj->content_type); - PR_FREEIF(cache_obj->charset); - PR_FREEIF(cache_obj->content_encoding); - PR_FREEIF(cache_obj->page_services_url); - PR_FREEIF(cache_obj->filename); - -#ifndef EXT_DB_ROUTINES - PR_FREEIF(cache_obj->sec_info); -#endif - - PR_Free(cache_obj); -} - -/* returns true if this DBT looks like a valid - * entry. It looks at the checksum and the - * version number to see if it's valid - */ -#define MAX_VALID_DBT_SIZE 10000 - -MODULE_PRIVATE PRBool -net_IsValidCacheDBT(DBT *obj) -{ - char *cur_ptr, *max_ptr; - uint32 len; - - if(!obj || obj->size < 9 || obj->size > MAX_VALID_DBT_SIZE) - return(FALSE); - - cur_ptr = (char *)obj->data; - max_ptr = cur_ptr+obj->size; - - /* get the total size of the struct out of - * the first field to check it - */ - COPY_INT32(&len, cur_ptr); - cur_ptr += sizeof(int32); - - if(len != obj->size) - { - TRACEMSG(("Size going in is not the same as size coming out")); - return(FALSE); - } - - /* get the version number of the written structure - */ - if(cur_ptr > max_ptr) - return(FALSE); - COPY_INT32(&len, cur_ptr); - cur_ptr += sizeof(int32); - - if(len != CACHE_FORMAT_VERSION) - { - TRACEMSG(("Version of cache structure is wrong!: %d", len)); - return(FALSE); - } - - /* looks good to me... */ - return(TRUE); -} - - -/* takes a cache object and returns a malloc'd - * (void *) suitible for passing in as a database - * data storage object - */ -MODULE_PRIVATE DBT * -net_CacheStructToDBData(net_CacheObject * old_obj) -{ - int32 len; - char *cur_ptr; - void *new_obj; - int32 total_size; - DBT *rv; - - rv = PR_NEW(DBT); - - if(!rv) - return(NULL); - - total_size = sizeof(net_CacheObject); - -#define ADD_STRING_SIZE(string) \ -total_size += old_obj->string ? PL_strlen(old_obj->string)+1 : 0 - - ADD_STRING_SIZE(address); - total_size += old_obj->post_data_size+1; - ADD_STRING_SIZE(post_headers); - ADD_STRING_SIZE(content_type); - ADD_STRING_SIZE(content_encoding); - ADD_STRING_SIZE(charset); - ADD_STRING_SIZE(filename); - total_size += sizeof(uint32); /* size of secinfo */ - total_size += HG73653(old_obj->sec_info); - ADD_STRING_SIZE(page_services_url); - -#undef ADD_STRING_SIZE - - new_obj = PR_Malloc(total_size * sizeof(char)); - - if(!new_obj) - { - PR_Free(rv); - return NULL; - } - - memset(new_obj, 0, total_size * sizeof(char)); - - /* - * order is: - * int32 size of the entire structure; - * - * int32 version of the structure format (CACHE_FORMAT_VERSION) - * - * time_t last_modified; - * time_t last_accessed; - * time_t expires; - * uint32 content_length; - * XP_Bool is_netsite; - * - * time_t lock_date; - * - * char * filename; - * int32 filename_len; - * - * int32 HG52242; - * unsigned char * HG42320; - * - * int32 method; - * - * # don't store address, or post_data stuff - * # char * address; - * # uint32 post_data_size; - * # char * post_data; - * - * char * post_headers; - * char * content_type; - * char * content_encoding; - * char * charset; - * - * XP_Bool incomplete_file; - * uint32 total_content_length; - * - * char * page_services_url; - * - * string lengths all include null terminators - * all integer constants are stored as 4 bytes - * all booleans are stored as one byte - */ - - /* VERY VERY IMPORTANT. Whenever the - * format of the record structure changes - * you must verify that the byte positions - * in extcache.h are updated - */ - -#define STUFF_STRING(string) \ -{ \ - len = (old_obj->string ? PL_strlen(old_obj->string)+1 : 0); \ - COPY_INT32((void *)cur_ptr, &len); \ - cur_ptr = cur_ptr + sizeof(int32); \ - if(len) \ - memcpy((void *)cur_ptr, old_obj->string, len); \ - cur_ptr += len; \ -} - -#define STUFF_NUMBER(number) \ -{ \ - COPY_INT32((void *)cur_ptr, &old_obj->number); \ - cur_ptr = cur_ptr + sizeof(int32); \ -} - -#define STUFF_TIMET(number) \ -{ \ - COPY_INT32((void *)cur_ptr, &old_obj->number); \ - cur_ptr = cur_ptr + sizeof(time_t); \ -} - -#define STUFF_BOOL(bool_val) \ -{ \ - if(old_obj->bool_val) \ - ((char *)(cur_ptr))[0] = 1; \ - else \ - ((char *)(cur_ptr))[0] = 0; \ - cur_ptr = cur_ptr + sizeof(char); \ -} - - cur_ptr = (char *)new_obj; - - /* put the total size of the struct into - * the first field so that we have - * a cross check against corruption - */ - COPY_INT32((void *)cur_ptr, &total_size); - cur_ptr = cur_ptr + sizeof(int32); - - HG73209 - /* put the version number of the structure - * format that we are using - * By using a version string when writting - * we can support backwards compatibility - * in our reading code - * (use "len" as a temp variable) - */ - len = CACHE_FORMAT_VERSION; - COPY_INT32((void *)cur_ptr, &len); - cur_ptr = cur_ptr + sizeof(int32); - - STUFF_TIMET(last_modified); - STUFF_TIMET(last_accessed); - STUFF_TIMET(expires); - STUFF_NUMBER(content_length); - STUFF_BOOL(is_netsite); - - STUFF_TIMET(lock_date); - - STUFF_STRING(filename); - STUFF_NUMBER(filename_len); - - STUFF_BOOL(is_relative_path); - - STUFF_NUMBER(security_on); - -#ifndef EXT_DB_ROUTINES - HG42539 - /* save the security info */ - if ( old_obj->sec_info ) { - len = HG65293(old_obj->sec_info); - COPY_INT32((void *)cur_ptr, &len); - cur_ptr = cur_ptr + sizeof(int32); - - memcpy((void *)cur_ptr, old_obj->sec_info, len); - cur_ptr += len; - } else -#endif - { - len = 0; - COPY_INT32((void *)cur_ptr, &len); - cur_ptr = cur_ptr + sizeof(int32); - } - - STUFF_NUMBER(method); - -#ifdef STORE_ADDRESS_AND_POST_DATA - - STUFF_STRING(address); - STUFF_NUMBER(post_data_size); - - /* post_data - * this is special since it not necessarily a string - */ - if(old_obj->post_data_size) - { - memcpy(cur_ptr, old_obj->post_data, old_obj->post_data_size+1); - cur_ptr += old_obj->post_data_size+1; - } - -#endif /* STORE_ADDRESS_AND_POST_DATA */ - - STUFF_STRING(post_headers); - - STUFF_STRING(content_type); - STUFF_STRING(content_encoding); - STUFF_STRING(charset); - - STUFF_BOOL(incomplete_file); - STUFF_NUMBER(real_content_length); - - STUFF_STRING(page_services_url); - -#undef STUFF_STRING -#undef STUFF_NUMBER -#undef STUFF_BOOL - - rv->data = new_obj; - rv->size = total_size; - - return(rv); - -} - -/* takes a database storage object and returns a malloc'd - * cache data object. The cache object needs all of - * it's parts free'd. - * - * returns NULL on parse error - */ -MODULE_PRIVATE net_CacheObject * -net_DBDataToCacheStruct(DBT * db_obj) -{ - net_CacheObject * rv = PR_NEW(net_CacheObject); - char * cur_ptr; - char * max_ptr; - uint32 len; - int32 version; - - if(!rv) - return NULL; - - memset(rv, 0, sizeof(net_CacheObject)); - -/* if any strings are larger than this then - * there was a serious database error - */ -#define MAX_HUGE_STRING_SIZE 10000 - -#define RETRIEVE_STRING(string) \ -{ \ - if(cur_ptr > max_ptr) \ - { \ - net_freeCacheObj(rv); \ - return(NULL); \ - } \ - COPY_INT32(&len, cur_ptr); \ - cur_ptr += sizeof(int32); \ - if(len) \ - { \ - if(len > MAX_HUGE_STRING_SIZE) \ - { \ - net_freeCacheObj(rv); \ - return(NULL); \ - } \ - rv->string = (char*)PR_Malloc(len); \ - if(!rv->string) \ - { \ - net_freeCacheObj(rv); \ - return(NULL); \ - } \ - memcpy(rv->string, cur_ptr, len); \ - cur_ptr += len; \ - } \ -} - -#define RETRIEVE_NUMBER(number) \ -{ \ - if(cur_ptr > max_ptr) \ - return(rv); \ - COPY_INT32(&rv->number, cur_ptr); \ - cur_ptr += sizeof(int32); \ -} - -#define RETRIEVE_TIMET(number) \ -{ \ - if(cur_ptr > max_ptr) \ - return(rv); \ - COPY_INT32(&rv->number, cur_ptr); \ - cur_ptr += sizeof(time_t); \ -} - -#define RETRIEVE_BOOL(bool) \ -{ \ - if(cur_ptr > max_ptr) \ - return(rv); \ - if(((char *)(cur_ptr))[0]) \ - rv->bool = TRUE; \ - else \ - rv->bool = FALSE; \ - cur_ptr += sizeof(char); \ -} - - cur_ptr = (char *)db_obj->data; - - max_ptr = cur_ptr+db_obj->size; - - /* get the total size of the struct out of - * the first field to check it - */ - COPY_INT32(&len, cur_ptr); - cur_ptr += sizeof(int32); - - if(len != db_obj->size) - { - TRACEMSG(("Size going in is not the same as size coming out")); - PR_Free(rv); - return(NULL); - } - - /* get the version number of the written structure - */ - if(cur_ptr > max_ptr) - return(rv); - COPY_INT32(&version, cur_ptr); - cur_ptr += sizeof(int32); - - if(version != CACHE_FORMAT_VERSION) - { - TRACEMSG(("Version of cache structure is wrong!: %d", version)); - PR_Free(rv); - return(NULL); - } - - HG32839 - RETRIEVE_TIMET(last_modified); - RETRIEVE_TIMET(last_accessed); - RETRIEVE_TIMET(expires); - RETRIEVE_NUMBER(content_length); - RETRIEVE_BOOL(is_netsite); - - RETRIEVE_TIMET(lock_date); - - RETRIEVE_STRING(filename); - RETRIEVE_NUMBER(filename_len); - - RETRIEVE_BOOL(is_relative_path); - - HG72761 - - RETRIEVE_NUMBER(method); - -#ifdef STORE_ADDRESS_AND_POST_DATA - - RETRIEVE_STRING(address); - RETRIEVE_NUMBER(post_data_size); - - /* post_data - * this is special since it not necessarily a string - */ - if(rv->post_data_size) - { - rv->post_data = PR_Malloc(rv->post_data_size+1); - if(rv->post_data) - memcpy(rv->post_data, cur_ptr, rv->post_data_size+1); - cur_ptr += rv->post_data_size+1; - } - -#endif /* STORE_ADDRESS_AND_POST_DATA */ - - RETRIEVE_STRING(post_headers); - - RETRIEVE_STRING(content_type); - RETRIEVE_STRING(content_encoding); - RETRIEVE_STRING(charset); - - RETRIEVE_BOOL(incomplete_file); - RETRIEVE_NUMBER(real_content_length); - - RETRIEVE_STRING(page_services_url); -#undef RETRIEVE_STRING -#undef RETRIEVE_NUMBER -#undef RETRIEVE_BOOL - - return(rv); -} - -#if defined(DEBUG) && defined(UNIX) -int -cache_test_me() -{ - - net_CacheObject test; - net_CacheObject *rv; - int32 total_size; - DBT *db_obj; - - memset(&test, 0, sizeof(net_CacheObject)); - StrAllocCopy(test.address, "test1"); - db_obj = net_CacheStructToDBData(&test); - rv = net_DBDataToCacheStruct(db_obj); - printf("test1: %s\n", rv->address); - - memset(&test, 0, sizeof(net_CacheObject)); - StrAllocCopy(test.address, "test2"); - StrAllocCopy(test.charset, "test2"); - db_obj = net_CacheStructToDBData(&test); - rv = net_DBDataToCacheStruct(db_obj); - printf("test2: %s %s\n", rv->address, rv->charset); - - memset(&test, 0, sizeof(net_CacheObject)); - StrAllocCopy(test.address, "test3"); - StrAllocCopy(test.charset, "test3"); - test.content_length = 3 ; - test.method = 3 ; - test.is_netsite = 3 ; - db_obj = net_CacheStructToDBData(&test); - rv = net_DBDataToCacheStruct(db_obj); - printf("test3: %s %s %d %d %s\n", - rv->address, rv->charset, - rv->content_length, rv->method, - (rv->is_netsite == 3 ? "TRUE" : "FALSE")); - -} -#endif - -/* generates a key for use in the cache database - * from a CacheObject struct - * - * Key is based on the address and the post_data - * - * looks like: - * size checksum | size of address | ADDRESS | size of post data | POST DATA - */ -MODULE_PRIVATE DBT * -net_GenCacheDBKey(char *address, char *post_data, int32 post_data_size) -{ - DBT *rv = PR_NEW(DBT); - char *hash; - char *data_ptr; - int32 str_len; - int32 size; - -#define MD5_HASH_SIZE 16 /* always 16 due to md5 hash type */ - - if(!rv) - return(NULL); - - if(!address) - { - PR_ASSERT(0); - rv->size = 0; - return(rv); - } - - hash = PL_strchr(address, '#'); - - /* don't include '#' in a key */ - if(hash) - *hash = '\0'; - - str_len = PL_strlen(address)+1; - - size = sizeof(int32); /* for check sum */ - size += sizeof(int32); /* for size of address */ - size += str_len; /* for address string */ - size += sizeof(int32); /* for size of post_data */ - - HG42490 - - rv->size = size; - rv->data = PR_Malloc(size); - - if(!rv->data) - { - PR_Free(rv); - return NULL; - } - - data_ptr = (char *) rv->data; - - /* put in the checksum size */ - COPY_INT32(data_ptr, &size); - data_ptr = data_ptr + sizeof(int32); - HG83777 - - /* put in the size of the address string */ - COPY_INT32(data_ptr, &str_len); - data_ptr = data_ptr + sizeof(int32); - - /* put in the address string data */ - memcpy(data_ptr, address, str_len); - data_ptr = data_ptr + str_len; - - /* set the address back to it's original form */ - if(hash) - *hash = '#'; - - /* put in the size of the post data */ - HG73699 - { - COPY_INT32(data_ptr, &post_data_size); - data_ptr = data_ptr + sizeof(int32); - } - - return(rv); -} - -/* returns a static string that contains the - * URL->address of the key - * - * returns NULL on error - */ -MODULE_PRIVATE char * -net_GetAddressFromCacheKey(DBT *key) -{ - uint32 size; - char *data; - - /* check for minimum size */ - if(key->size < 10) - return(NULL); - HG72873 - - /* validate size checksum */ - data = (char *)key->data; - COPY_INT32(&size, data); - data += sizeof(int32); - - if(size != key->size) - return(NULL); - - /* get size of address string */ - COPY_INT32(&size, data); - data += sizeof(int32); - - /* make sure it's a valid c string */ - if(data[size] != '\0') - return(NULL); - - /* it's valid return it */ - return(data); -} - - -/* checks a date within a DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns 0 on error - */ -MODULE_PRIVATE time_t -net_GetTimeInCacheDBT(DBT *data, int byte_position) -{ - time_t date; - char *ptr = (char *)data->data; - - if(data->size < byte_position+sizeof(time_t)) - return(0); - - if(!net_IsValidCacheDBT(data)) - return(0); - - COPY_INT32(&date, ptr+byte_position); - - /* TRACEMSG(("Got date from cache DBT: %d", date)); */ - - return(date); - -} - -/* Sets a date within a DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns 0 on error - */ -MODULE_PRIVATE void -net_SetTimeInCacheDBT(DBT *data, int byte_position, time_t date) -{ - char *ptr = (char *)data->data; - - if(data->size < byte_position+sizeof(time_t)) - return; - - if(!net_IsValidCacheDBT(data)) - return; - - COPY_INT32(ptr+byte_position, &date); - - return; - -} - -/* Gets the filename within a cache DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns NULL on error - */ -#define MAX_FILE_SIZE 2048 -MODULE_PRIVATE char * -net_GetFilenameInCacheDBT(DBT *data) -{ - int32 size; - char *rv; - char *ptr = (char*)data->data; - - if(data->size < FILENAME_BYTE_POSITION) - return(NULL); - - if(!net_IsValidCacheDBT(data)) - return(0); - - COPY_INT32(&size, ptr+FILENAME_SIZE_BYTE_POSITION); - - if(data->size < FILENAME_BYTE_POSITION+size - || size > MAX_FILE_SIZE) - return(NULL); - - rv = (char *)PR_Malloc(size); - if(!rv) - return(NULL); - memcpy(rv, ptr+FILENAME_BYTE_POSITION, size); - - TRACEMSG(("Got filename: %s from DBT", rv)); - - return(rv); -} - -/* Gets a int32 within a DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns 0 on error - */ -MODULE_PRIVATE time_t -net_GetInt32InCacheDBT(DBT *data, int byte_position) -{ - int32 num; - char *ptr = (char *)data->data; - - if(!net_IsValidCacheDBT(data)) - return(0); - - if(data->size < byte_position+sizeof(time_t)) - return(0); - - COPY_INT32(&num, ptr+byte_position); - - /* TRACEMSG(("Got int32 from cache DBT: %d", num)); */ - - return(num); - -} - -MODULE_PRIVATE void -net_FreeCacheDBTdata(DBT *stuff) -{ - if(stuff) - { - PR_Free(stuff->data); - PR_Free(stuff); - } -} - -/* takes a database storage object and returns an un-malloc'd - * cache data object. The structure returned has pointers - * directly into the database memory and are only valid - * until the next call to any database function - * - * do not free anything returned by this structure - */ -MODULE_PRIVATE net_CacheObject * -net_Fast_DBDataToCacheStruct(DBT *obj) -{ - static net_CacheObject *rv=0; - - /* free any previous one */ - if(rv) - net_freeCacheObj(rv); - - rv = net_DBDataToCacheStruct(obj); - - return(rv); - -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cache/extcache.h b/mozilla/network/cache/extcache.h deleted file mode 100644 index a03ba313996..00000000000 --- a/mozilla/network/cache/extcache.h +++ /dev/null @@ -1,272 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef EXT_CACHE_H -#define EXT_CACHE_H - -#ifndef EXT_DB_ROUTINES -#include "mcom_db.h" -#endif - -#ifdef EXT_DB_ROUTINES -#define PRBool char -#define uint32 unsigned int -#define int32 int -#define PR_NEW(structure) ((structure *) malloc(sizeof(structure))) -#define PR_Malloc (void *) malloc -#define memcpy memcpy -#define memset memset -#define TRACEMSG(x) printf x -#define FREEIF(x) do { if(x) free(x); } while(0) -#define FREE free -#define PL_strlen strlen -#define PL_strchr strchr -#define PL_strcmp strcmp -#define PR_ASSERT assert -#define MODULE_PRIVATE -#define PRIVATE static -#define TRUE !0 -#define FALSE 0 - -#include -#include -#include -#endif - -#ifndef EXT_DB_ROUTINES - -#include "prtypes.h" /* for IS_LITTLE_ENDIAN / IS_BIG_ENDIAN */ - -#endif /* EXT_DB_ROUTINES */ - -#if !defined(IS_LITTLE_ENDIAN) && !defined(IS_BIG_ENDIAN) -ERROR! Must have a byte order -#endif - -#ifdef IS_LITTLE_ENDIAN -#define COPY_INT32(_a,_b) memcpy(_a, _b, sizeof(int32)); -#else -#define COPY_INT32(_a,_b) /* swap */ \ - do { \ - ((char *)(_a))[0] = ((char *)(_b))[3]; \ - ((char *)(_a))[1] = ((char *)(_b))[2]; \ - ((char *)(_a))[2] = ((char *)(_b))[1]; \ - ((char *)(_a))[3] = ((char *)(_b))[0]; \ - } while(0) -#endif - -#define EXT_CACHE_NAME_STRING "INT_ExternalCacheNameString" - -/* Internal WARNING!! Some slots of this structure - * are shared with URL_Struct and - * History_entry. If you add a slot, decide whether it needs to be shared - * as well. - */ -typedef struct _net_CacheObject { - time_t last_modified; - time_t last_accessed; - time_t expires; - PRBool is_netsite; - uint32 content_length; - - char * filename; /* cache file name */ - int32 filename_len; /* optimization */ - PRBool is_relative_path; /* is the path relative? */ - - /* Security information */ - int32 security_on; /* is security on? */ - unsigned char *sec_info; - - time_t lock_date; /* the file is locked if this - * is non-zero. The date - * represents the time the - * lock was put in place. - * Locks are only valid for - * one session - */ - - int32 method; - char * address; - uint32 post_data_size; - char * post_data; - char * post_headers; - char * content_type; - char * content_encoding; - char * charset; - - PRBool incomplete_file; /* means that the whole - * file is not there. - * This can only be true - * if the server supports byteranges - */ - uint32 real_content_length; /* the whole content length - * i.e. the server size of a truncated - * client file - */ - char * page_services_url; - char * etag; /* HTTP/1.1 Etag */ - -} net_CacheObject; - -/* this is the version number of the cache database entry. - * It should be incremented in integer ingrements up - * to MAXINT32 - */ -#define CACHE_FORMAT_VERSION 5 - -/* these defines specify the exact byte position - * of the first 4 elements in the DBT data struct - * Change these if you change the order of entry into - * the DBT - */ -#define LAST_MODIFIED_BYTE_POSITION \ - sizeof(int32)+sizeof(int32) -#define LAST_ACCESSED_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t) -#define EXPIRES_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t)+sizeof(time_t) -#define CONTENT_LENGTH_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t)+sizeof(time_t) \ - +sizeof(time_t) -#define IS_NETSITE_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t)+sizeof(time_t) \ - +sizeof(time_t)+sizeof(int32) - -#define LOCK_DATE_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t)+sizeof(time_t) \ - +sizeof(time_t)+sizeof(int32)+sizeof(char) - -#define FILENAME_SIZE_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t)+sizeof(time_t) \ - +sizeof(time_t)+sizeof(uint32)+sizeof(char)+sizeof(time_t) -#define FILENAME_BYTE_POSITION \ - sizeof(int32)+sizeof(int32)+sizeof(time_t)+sizeof(time_t) \ - +sizeof(time_t)+sizeof(uint32)+sizeof(char)+sizeof(time_t) \ - +sizeof(int32) - -/* generates a key for use in the cache database - * from a CacheObject struct - * - * Key is based on the address and the post_data - */ -extern DBT * -net_GenCacheDBKey(char *address, char *post_data, int32 post_data_size); - -/* returns a static string that contains the - * URL->address of the key - * - * returns NULL on error - */ -extern char * -net_GetAddressFromCacheKey(DBT *key); - - -/* allocs and copies a new DBT from an existing DBT - */ -extern DBT * net_CacheDBTDup(DBT *obj); - -/* free the cache object - */ -extern void net_freeCacheObj (net_CacheObject * cache_obj); - -/* takes a cache object and returns a malloc'd - * (void *) suitible for passing in as a database - * data storage object - */ -extern DBT * net_CacheStructToDBData(net_CacheObject * old_obj); - -/* takes a database storage object and returns a malloc'd - * cache data object. The cache object needs all of - * it's parts free'd. - * - * returns NULL on parse error - */ -extern net_CacheObject * net_DBDataToCacheStruct(DBT * db_obj); - -/* checks a date within a DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns 0 on error - */ -extern time_t net_GetTimeInCacheDBT(DBT *data, int byte_position); - -/* Sets a date within a DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns 0 on error - */ -extern void net_SetTimeInCacheDBT(DBT *data, int byte_position, time_t date); - -/* Gets the filename within a cache DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns NULL on error - */ -extern char * net_GetFilenameInCacheDBT(DBT *data); - -/* Gets a int32 within a DBT struct so - * that we don't have to convert it into a CacheObject - * - * This works because of the fixed length record format - * of the first part of the specific DBT format I'm - * using - * - * returns 0 on error - */ -extern time_t net_GetInt32InCacheDBT(DBT *data, int byte_position); - -/* free's a DBT struct - */ -extern void net_FreeCacheDBTdata(DBT *stuff); - -/* stores a cache object in the DBM database - */ -extern void net_ExtCacheStore(DB *database, net_CacheObject * obj); - -/* takes a database storage object and returns an un-malloc'd - * cache data object. The structure returned has pointers - * directly into the database memory and are only valid - * until the next call to any database function - * - * do not free anything returned by this structure - */ -extern net_CacheObject * net_Fast_DBDataToCacheStruct(DBT *obj); - -/* returns true if this DBT looks like a valid - * entry. It looks at the checksum and the - * version number to see if it's valid - */ -extern PRBool net_IsValidCacheDBT(DBT *obj); - -#endif /* EXT_CACHE_H */ diff --git a/mozilla/network/cache/makefile.win b/mozilla/network/cache/makefile.win deleted file mode 100644 index cf4d7de3077..00000000000 --- a/mozilla/network/cache/makefile.win +++ /dev/null @@ -1,113 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -DEPTH=..\.. -include <$(DEPTH)\config\config.mak> - -!ifdef NU_CACHE -DIRS=nu -!endif - -#------------------------------------------------------------------------ -# -# Makefile to build the cache LIB -# -#------------------------------------------------------------------------ - -#!ifdef MOZ_JAVA -#LOCAL_JMC_SUBDIR = . -#!endif - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\extcache.obj \ - .\$(OBJDIR)\mkcache.obj \ - .\$(OBJDIR)\mkextcac.obj \ - .\$(OBJDIR)\mkmemcac.obj \ - $(NULL) - - -CSRCS = \ - cachedump.c \ - extcache.c \ - mkcache.c \ - mkextcac.c \ - mkmemcac.c \ - $(NULL) - - -LIBRARY_NAME=netcache - -MODULE=netcache - -EXTRA_LIBS= - -!ifdef NU_CACHE -REQUIRES= network nspr2 cache -!else -REQUIRES= network nspr2 -!endif - -EXPORTS= netcache.h - -C_OBJS = \ - $(NULL) - - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\dbm \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\network \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\fileurl \ - -I$(XPDIST)\public\security \ -!ifdef NU_CACHE - -I$(XPDIST)\public\cache \ -!endif - -I$(XPDIST)\public\jtools -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/cache/mkcache.c b/mozilla/network/cache/mkcache.c deleted file mode 100644 index a5d3b7458cd..00000000000 --- a/mozilla/network/cache/mkcache.c +++ /dev/null @@ -1,3932 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* implements disk caching: See mkmemcac.c for memory cache - * - * Designed and originally implemented by Lou Montulli '94 - * Modifications/additions by Gagan Saksena '97 - */ - -#ifdef MOZILLA_CLIENT - -/* dbm code */ - -#include "mkcache.h" -#include "rosetta.h" -#include "extcache.h" -#include "mkgeturl.h" -#include "netutils.h" -#include "netcache.h" -#include "glhist.h" -#include "xp_hash.h" -#include "xp_mcom.h" -#include "client.h" -#include "mkstream.h" -#include HG65288 -#include "mcom_db.h" -#include "prclist.h" -#include "prmem.h" -#include "plstr.h" -#include "net_xp_file.h" - -#include "mkextcac.h" -#include "fileurl.h" -#include "mkmemcac.h" -#include "merrors.h" - -#ifdef NU_CACHE -#include "CacheStubs.h" -#endif - -#ifdef PROFILE -#pragma profile on -#endif - -#ifdef XP_OS2_NOT_YET -/*serious hack to put cache cleanup on another thread...*/ -extern int XP_LazyFileRemove(const char * name, XP_FileType type); -#else -#define XP_LazyFileRemove NET_XP_FileRemove -#endif - -/* For Mac */ -#include - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_CACHE_CLEANUP; -extern int MK_CACHE_CONTENT_LENGTH; -extern int MK_CACHE_REAL_CONTENT_LENGTH; -extern int MK_CACHE_CONTENT_TYPE; -extern int MK_CACHE_LOCAL_FILENAME; -extern int MK_CACHE_LAST_MODIFIED; -extern int MK_CACHE_EXPIRES; -extern int MK_CACHE_LAST_ACCESSED; -extern int MK_CACHE_CHARSET; -HG73891 -extern int MK_CACHE_USES_RELATIVE_PATH; -extern int MK_CACHE_FROM_NETSITE_SERVER; - -#define INTERNAL_NAME_PREFIX "INT_" -#define DISK_CACHE_SIZE_KEY_NAME "INT_DiskCacheSize" -#define DISK_CACHE_NUMBER_KEY_NAME "INT_DiskCacheNumber" -#define DISK_CACHE_NAME "Netscape Internal Disk Cache" - -#define CACHE_SYNC_RATE 30 - -typedef enum { - NEW_CACHE_STORE, - REFRESH_CACHE_STORE -} store_type_enum; - -PRIVATE DBT *net_DiskCacheSizeKey=0; -PRIVATE DBT *net_DiskCacheNumberKey=0; -PRIVATE DBT *net_DiskCacheNameKey=0; -PRIVATE uint32 net_DiskCacheSize=0; -PRIVATE uint32 net_NumberInDiskCache=0; -PRIVATE uint32 net_MaxDiskCacheSize=0; -PRIVATE uint32 net_cache_file_block_size=0; - -/* Saves the cache struct to the DB */ -extern void CACHE_SaveCacheInfoToDB(ExtCacheDBInfo *db_info); - -#ifdef NO_MEMORY_CACHE -PRIVATE uint32 net_MaxMemoryCacheSize=0; -#endif /* NO_MEMORY_CACHE */ - -/* trace variable for cache testing */ -MODULE_PRIVATE PRBool NET_CacheTraceOn = PR_FALSE; -HG76298 -PRIVATE DB * cache_database = 0; -/* PRIVATE XXX Mac CodeWarrior bug */ PRCList active_cache_data_objects - = PR_INIT_STATIC_CLIST(&active_cache_data_objects); - -typedef struct _CacheDataObject { - PRCList links; - XP_File fp; - NET_StreamClass *next_stream; - URL_Struct *URL_s; -#ifdef NU_CACHE - void* cache_object; -#else - net_CacheObject *cache_object; -#endif -} CacheDataObject; - -PRIVATE void net_RemoveAllDiskCacheObjects(void); - -HG87325 - -PUBLIC PRBool -NET_IsCacheTraceOn(void) -{ -#ifdef NU_CACHE - return CacheTrace_IsEnabled(); -#else - return NET_CacheTraceOn; -#endif -} - -/* return the size of the file on - * disk based on the block size - */ -PRIVATE -uint32 -net_calc_real_file_size(uint32 size) -{ - if(net_cache_file_block_size == 0) - return(size); - else /* round sizes up to the next block size */ - return(PR_ROUNDUP(size, net_cache_file_block_size)); -} - -PRIVATE void -net_GetDiskCacheSize(void) -{ - DBT data; - - if(!cache_database) - return; - - if(!net_DiskCacheSizeKey) - { - net_DiskCacheSizeKey = PR_NEW(DBT); - if(!net_DiskCacheSizeKey) - return; - - net_DiskCacheSizeKey->data = 0; - BlockAllocCopy(net_DiskCacheSizeKey->data, - DISK_CACHE_SIZE_KEY_NAME, - PL_strlen(DISK_CACHE_SIZE_KEY_NAME)); - net_DiskCacheSizeKey->size = PL_strlen(DISK_CACHE_SIZE_KEY_NAME); - } - - if(0 == (*cache_database->get)(cache_database, - net_DiskCacheSizeKey, - &data, - 0)) - { - if(data.size == sizeof(uint32)) - { - COPY_INT32(&net_DiskCacheSize, data.data); - } - else - { - net_DiskCacheSize = 0; - } - } - else - { - net_DiskCacheSize = 0; - } - - if(!net_DiskCacheNumberKey) - { - net_DiskCacheNumberKey = PR_NEW(DBT); - if(!net_DiskCacheNumberKey) - return; - - net_DiskCacheNumberKey->data = 0; - BlockAllocCopy(net_DiskCacheNumberKey->data, - DISK_CACHE_NUMBER_KEY_NAME, - PL_strlen(DISK_CACHE_NUMBER_KEY_NAME)); - net_DiskCacheNumberKey->size = PL_strlen(DISK_CACHE_NUMBER_KEY_NAME); - } - - if(0 == (*cache_database->get)(cache_database, - net_DiskCacheNumberKey, - &data, - 0)) - { - if(data.size == sizeof(uint32)) - { - COPY_INT32(&net_NumberInDiskCache, data.data); - } - else - { - net_NumberInDiskCache = 0; - } - } - else - { - net_NumberInDiskCache = 0; - } - HG63453 -} - - -PRIVATE int -net_OpenCacheFatDB(void) -{ - char* filename; - static XP_Bool have_tried_open=FALSE; - - if(!cache_database) - { - HASHINFO hash_info = { - 4 * 1024, - 0, - 0, -#ifdef WIN16 - 60 * 1024, -#else - 96 * 1024, -#endif - 0, - 0}; - filename = WH_FileName("", xpCacheFAT); - if (!filename) return 0; - - /* @@@ add .db to the end of the files - */ - cache_database = dbopen(filename, - O_RDWR | O_CREAT, - 0600, - DB_HASH, - &hash_info); - PR_Free(filename); - - if(!have_tried_open && !cache_database) - { - XP_StatStruct stat_entry; - - have_tried_open = TRUE; /* only do this once */ - - TRACEMSG(("Could not open cache database -- errno: %d", errno)); - - /* if the file is zero length remove it - */ - if(NET_XP_Stat("", &stat_entry, xpCacheFAT) != -1) - { - if(stat_entry.st_size <= 0) - { - NET_XP_FileRemove("", xpCacheFAT); - } - else - { - XP_File fp; -#define BUFF_SIZE 1024 - char buffer[BUFF_SIZE]; - - /* open the file and look for - * the old magic cookie. If it's - * there delete the file - */ - fp = NET_XP_FileOpen("", xpCacheFAT, XP_FILE_READ); - - if(fp) - { - NET_XP_FileReadLine(buffer, BUFF_SIZE, fp); - - NET_XP_FileClose(fp); - - if(PL_strstr(buffer, - "Cache-file-allocation-table-format")) - NET_XP_FileRemove("", xpCacheFAT); - - } - } - } - - - /* try it again */ - filename = WH_FileName("", xpCacheFAT); - if (filename) { - cache_database = dbopen(filename, - O_RDWR | O_CREAT, - 0600, - DB_HASH, - 0); - PR_Free(filename); - } - else - cache_database = NULL; - } - - HG98471 - if(cache_database) - { - if(-1 == (*cache_database->sync)(cache_database, 0)) - { - TRACEMSG(("Error syncing cache database")); - - /* close the database */ - (*cache_database->close)(cache_database); - cache_database = 0; - } - - net_GetDiskCacheSize(); - } - -#ifndef XP_PC - /* if we don't know the standard block size yet - * get it now - */ - if(!net_cache_file_block_size) - { - XP_StatStruct stat_entry; - - if(NET_XP_Stat("", &stat_entry, xpCacheFAT) != -1) -#ifdef HAVE_ST_BLKSIZE - net_cache_file_block_size = stat_entry.st_blksize; -#else - net_cache_file_block_size = stat_entry.st_size; -#endif - } -#endif - } - - /* return non-zero if the cache_database pointer is - * non-zero - */ - return((int) cache_database); - -} - -#if defined(DEBUG) && defined(UNIX) -int -cache_test_me() -{ - - net_CacheObject test; - net_CacheObject *rv; - int32 total_size; - DBT *db_obj; - - memset(&test, 0, sizeof(net_CacheObject)); - StrAllocCopy(test.address, "test1"); - db_obj = net_CacheStructToDBData(&test); - rv = net_DBDataToCacheStruct(db_obj); - printf("test1: %s\n", rv->address); - - memset(&test, 0, sizeof(net_CacheObject)); - StrAllocCopy(test.address, "test2"); - StrAllocCopy(test.charset, "test2"); - db_obj = net_CacheStructToDBData(&test); - rv = net_DBDataToCacheStruct(db_obj); - printf("test2: %s %s\n", rv->address, rv->charset); - - memset(&test, 0, sizeof(net_CacheObject)); - StrAllocCopy(test.address, "test3"); - StrAllocCopy(test.charset, "test3"); - test.content_length = 3 ; - test.method = 3 ; - test.is_netsite = 3 ; - db_obj = net_CacheStructToDBData(&test); - rv = net_DBDataToCacheStruct(db_obj); - printf("test3: %s %s %d %d %s\n", - rv->address, rv->charset, - rv->content_length, rv->method, - (rv->is_netsite == 3 ? "TRUE" : "FALSE")); - -} -#endif - -PRIVATE void -net_StoreDiskCacheSize(void) -{ - DBT data; - uint32 tmp_num; - - if(!cache_database) - return; - - if(!net_DiskCacheSizeKey) - { - net_DiskCacheSizeKey = PR_NEW(DBT); - if(!net_DiskCacheSizeKey) - return; - - net_DiskCacheSizeKey->data = 0; - BlockAllocCopy(net_DiskCacheSizeKey->data, - DISK_CACHE_SIZE_KEY_NAME, - PL_strlen((char *)DISK_CACHE_SIZE_KEY_NAME)); - net_DiskCacheSizeKey->size = PL_strlen(DISK_CACHE_SIZE_KEY_NAME); - } - - if(!net_DiskCacheNumberKey) - { - net_DiskCacheNumberKey = PR_NEW(DBT); - if(!net_DiskCacheNumberKey) - return; - - net_DiskCacheNumberKey->data = 0; - BlockAllocCopy(net_DiskCacheNumberKey->data, - DISK_CACHE_NUMBER_KEY_NAME, - PL_strlen((char *)DISK_CACHE_NUMBER_KEY_NAME)); - net_DiskCacheNumberKey->size = PL_strlen(DISK_CACHE_NUMBER_KEY_NAME); - } - - if(!net_DiskCacheNameKey) - { - /* set the name of the cache so that - * if it is read as an external cache - * we will know what created it - */ - net_DiskCacheNameKey = PR_NEW(DBT); - if(!net_DiskCacheNameKey) - return; - - net_DiskCacheNameKey->data = 0; - BlockAllocCopy(net_DiskCacheNameKey->data, - EXT_CACHE_NAME_STRING, - PL_strlen((char *)EXT_CACHE_NAME_STRING)); - net_DiskCacheNameKey->size = PL_strlen(EXT_CACHE_NAME_STRING); - } - - data.size = sizeof(uint32); - COPY_INT32(&tmp_num, &net_DiskCacheSize); - data.data = &tmp_num; - - (*cache_database->put)(cache_database, net_DiskCacheSizeKey, &data, 0); - - data.size = sizeof(uint32); - COPY_INT32(&tmp_num, &net_NumberInDiskCache); - data.data = &tmp_num; - - (*cache_database->put)(cache_database, net_DiskCacheNumberKey, &data, 0); - - data.size = PL_strlen(DISK_CACHE_NAME)+1; - data.data = DISK_CACHE_NAME; - HG52897 - (*cache_database->put)(cache_database, net_DiskCacheNameKey, &data, 0); - -} - -/* returns TRUE if the object gets stored - * FALSE if not - */ -PRIVATE XP_Bool -net_CacheStore(net_CacheObject * obj, - URL_Struct * URL_s, - XP_Bool accept_partial_files, - store_type_enum store_type) -#ifdef NU_CACHE -{ - /* Shouldn't be getting called */ - PR_ASSERT(0); - if (!obj || !URL_s || !URL_s->address) - return FALSE; - - if (URL_s->server_date - && URL_s->server_date < obj->last_modified) - { - /* the last modified date is after the current date - * as given by the server. We shoudn't cache this - * object - */ - obj->last_modified = 0; - URL_s->last_modified = 0; - - /* URL_s is now updated from META tags etc. so re-read this information */ - } - return TRUE; -} -#else -{ - DBT *data, *key; - int status; - static cache_sync_count = 0; - XP_StatStruct stat_entry; - - /* larubbio */ - XP_Bool SARCache = FALSE; - XP_FileType fileType; - DB *local_cache_database = NULL; - - /* larubbio fix to allow 197 SAR cache adds without modifying - * the navigator cache (too much) - */ - if ( URL_s != NULL && URL_s->SARCache != NULL ) - { - SARCache = TRUE; - fileType = xpSARCache; - local_cache_database = URL_s->SARCache->database; - } - else - { - fileType = xpCache; - local_cache_database = cache_database; - } - - if(!local_cache_database) - { - /* delete the file since we wont remember it - */ -#ifdef XP_OS2 - XP_LazyFileRemove(obj->filename, fileType); -#else - NET_XP_FileRemove(obj->filename, fileType); -#endif - - return FALSE; - } - - if(URL_s - && URL_s->server_date - && URL_s->server_date < obj->last_modified) - { - /* the last modified date is after the current date - * as given by the server. We shoudn't cache this - * object - */ - - TRACEMSG(("Found file dated into the future. " - "Zeroing the last modified date")); - obj->last_modified = 0; - URL_s->last_modified = 0; - } - - if(store_type == NEW_CACHE_STORE) - { - if(URL_s && URL_s->dont_cache) - { - /* delete the file since we wont remember it - */ -#ifdef XP_OS2 - XP_LazyFileRemove(obj->filename, fileType); -#else - NET_XP_FileRemove(obj->filename, fileType); -#endif - return FALSE; - } - else if(NET_XP_Stat(obj->filename, &stat_entry, fileType) != -1) - { - if(stat_entry.st_size == 0) - { - /* don't cache any zero length files - */ -#ifdef XP_OS2 - XP_LazyFileRemove(obj->filename, fileType); -#else - NET_XP_FileRemove(obj->filename, fileType); -#endif - return FALSE; - } - - if(obj->content_length <= 0) - { - /* fill this in for consistancy */ - obj->real_content_length = stat_entry.st_size; - obj->content_length = stat_entry.st_size; - } - else if(accept_partial_files - && obj->content_length > (uint32) stat_entry.st_size) - { - obj->real_content_length = obj->content_length; - obj->content_length = (uint32) stat_entry.st_size; - obj->incomplete_file = TRUE; - } - else - { - /* stat the file to verify the content_length - * if the content_length is positive and does not - * match the size of the cache file, handle it somehow - */ - if(obj->content_length != (uint32) stat_entry.st_size) - { - /* this is a case of a server or network - * error. Assume that the file is corrupted, - * Display it as it was for history navigation - * but do a complete reload any time the server - * is contacted - * kill the last modified date to disable IMS - */ - obj->last_modified = 0; - if(URL_s) - URL_s->last_modified = 0; - TRACEMSG(("\n\n!!!!!!!! Content length of cache file not equal" - " To the content transfer length: %d - %d !!!!!!!\n", - obj->content_length, stat_entry.st_size)); - } - - /* fill this in for consistancy */ - - obj->real_content_length - = obj->content_length - = stat_entry.st_size; - } - - /* must be set now */ - PR_ASSERT(obj->content_length); - - } - else - { - /* delete the file since we wont remember it - */ -#ifdef XP_OS2 - XP_LazyFileRemove(obj->filename, fileType); -#else - NET_XP_FileRemove(obj->filename, fileType); -#endif - return FALSE; - } - - /* refresh these entries in case meta changes them */ - if(URL_s) - { - obj->expires = URL_s->expires; - obj->last_modified = URL_s->last_modified; - StrAllocCopy(obj->charset, URL_s->charset); - } - } - else if(store_type == REFRESH_CACHE_STORE) - { - /* OK */ - } - else - { - PR_ASSERT(0); - } - - /* update the last accessed time - */ - obj->last_accessed = time(NULL); /* current time */ - - /* these must be true or else the partial cache logic is screwed */ - PR_ASSERT(obj->content_length == obj->real_content_length - || obj->incomplete_file); - - /* create key */ - key = net_GenCacheDBKey(obj->address, obj->post_data, obj->post_data_size); - - /* create new dbt data object */ - data = net_CacheStructToDBData(obj); - HG73870 - if(!key || !data) - { - TRACEMSG(("Failed to get key or data: malloc error probably")); - /* delete the file since we wont remember it - */ -#ifdef XP_OS2 - XP_LazyFileRemove(obj->filename, fileType); -#else - NET_XP_FileRemove(obj->filename, fileType); -#endif - return FALSE; - } - - if(store_type == NEW_CACHE_STORE) - status = (*local_cache_database->put)(local_cache_database, - key, - data, - R_NOOVERWRITE); - else /* overwrite by default */ - status = (*local_cache_database->put)(local_cache_database, key, data, 0); - - if(status > 0) - { - DBT old_data; - - TRACEMSG(("Duplicate cache object found")); - - /* get the duplicate out of the database */ - status = (*local_cache_database->get)(local_cache_database, key, &old_data, 0); - - /* we should always get a success here - * or at least a DB error. - */ - assert(status < 1); - - if(status == 0) - { - /* found it */ - - /* delete the previous object from the database - */ - /* remove the old file */ - char * filename = net_GetFilenameInCacheDBT((DBT *)&old_data); - if(filename) - { -#ifdef XP_OS2 - XP_LazyFileRemove(filename, fileType); -#else - NET_XP_FileRemove(filename, fileType); -#endif - PR_Free(filename); - } - - /* larubbio file size checks for SARCache */ - if ( SARCache ) - { - /* subtract the size of the file being removed */ - URL_s->SARCache->DiskCacheSize -= net_calc_real_file_size( - net_GetInt32InCacheDBT(&old_data, - CONTENT_LENGTH_BYTE_POSITION)); - URL_s->SARCache->NumberInDiskCache--; - } - else - { - /* subtract the size of the file being removed */ - net_DiskCacheSize -= net_calc_real_file_size( - net_GetInt32InCacheDBT(&old_data, - CONTENT_LENGTH_BYTE_POSITION)); - net_NumberInDiskCache--; - } - - /* put the new data in over the old data */ - status = (*local_cache_database->put)(local_cache_database, key, data, 0); - } - } - - - if(status < 0) - { - char * filename = net_GetFilenameInCacheDBT((DBT *)&data); - - TRACEMSG(("cache update failed due to database error")); - - /* remove the old file */ - if(filename) - { -#ifdef XP_OS2 - XP_LazyFileRemove(filename, fileType); -#else - NET_XP_FileRemove(filename, fileType); -#endif - PR_Free(filename); - } - - if ( !SARCache ) { - /* close the database */ - (*local_cache_database->close)(local_cache_database); - - cache_database = 0; - } - else - CACHE_CloseCache(URL_s->SARCache); - - local_cache_database = 0; - } - - if (store_type == NEW_CACHE_STORE) - { - if ( !SARCache ) - { - /* add the size of the new file - * size_on_disk can be in error, use content_length - * when missized - */ - net_DiskCacheSize += net_calc_real_file_size(obj->content_length); - net_NumberInDiskCache++; - - if (++cache_sync_count >= CACHE_SYNC_RATE) - { - - /* sync the database everytime to guarentee - * consistancy - */ - if(local_cache_database && -1 == (*local_cache_database->sync)(local_cache_database, 0)) - { - TRACEMSG(("Error syncing cache database")); - - /* close the database */ - (*local_cache_database->close)(local_cache_database); - cache_database = 0; - local_cache_database = 0; - } - - cache_sync_count = 0; - - } - } - else - { - /* larubbio */ - /* add the size of the new file - * size_on_disk can be in error, use content_length - * when missized - */ - URL_s->SARCache->DiskCacheSize += net_calc_real_file_size(obj->content_length); - URL_s->SARCache->NumberInDiskCache++; - - if(URL_s->SARCache->DiskCacheSize > URL_s->SARCache->MaxSize && -1 != URL_s->SARCache->MaxSize ) - { - TRACEMSG(("MaxSize exceeded!!!")); - /* delete the file since we wont remember it - */ - NET_XP_FileRemove(obj->filename, fileType); - - URL_s->SARCache->DiskCacheSize -= net_calc_real_file_size(obj->content_length); - URL_s->SARCache->NumberInDiskCache--; - - return FALSE; - } - - /* sync the database every time to guarentee - * consistancy - */ - if(local_cache_database && -1 == (*local_cache_database->sync)(local_cache_database, 0)) - { - TRACEMSG(("Error syncing cache database")); - - /* close the database */ - (*local_cache_database->close)(local_cache_database); - CACHE_CloseCache(URL_s->SARCache); - local_cache_database = 0; - } - else - { - /* This is inefficent to do each time, but it keeps us in synch, and this is for - offline browsing, which is not a performance intensive task */ - CACHE_SaveCacheInfoToDB(URL_s->SARCache); - } - } - } - - net_FreeCacheDBTdata(key); - net_FreeCacheDBTdata(data); - - return TRUE; - -} -#endif /* NU_CACHE */ - -/* Public accesor function for Netcaster */ -PUBLIC PRBool -NET_CacheStore(net_CacheObject * obj, - URL_Struct * URL_s, - PRBool accept_partial_files) -{ - return net_CacheStore(obj, URL_s, accept_partial_files, NEW_CACHE_STORE); -} - -/* Accessor functions for cache database used by cache browser */ -PUBLIC int -NET_FirstCacheObject(DBT *key, DBT *data) -{ - return (*cache_database->seq)(cache_database, key, data, R_FIRST); -} - -/* Accessor functions for cache database used by cache browser */ -PUBLIC int -NET_NextCacheObject(DBT *key, DBT *data) -{ - return (*cache_database->seq)(cache_database, key, data, R_NEXT); -} - -/* Accessor functions for cache database used by cache browser */ -PUBLIC int32 -NET_GetMaxDiskCacheSize() -{ - return net_MaxDiskCacheSize; -} - -/**************************************************************** - * General cache routines needed by lots of stuff - */ - -typedef struct _DatePlusDBT { - DBT * dbt; - time_t date; -} DatePlusDBT; - -/* removes the specified number of objects from the - * cache taking care to remove only the oldest objects. - */ -PUBLIC int32 -NET_RemoveDiskCacheObjects(uint32 remove_num) -{ -#define CORRUPT_ENTRY_ARRAY_SIZE 50 - uint32 corrupt_entry_count = 0; - DatePlusDBT *old_array; - DBT *corrupt_entry_array[CORRUPT_ENTRY_ARRAY_SIZE]; - uint32 total_cl=0; - uint32 total_number=0; - time_t date, lock_date; - time_t last_modified_date = (time_t) 0; - uint32 i,j; - char *filename; - char *url_address; - DBT data; - DBT key; - - HG74380 - /* - * This optimization is not valid for the case of URLs that normally - * would not be cached because their size exceeds the cache size, but - * will be cached anyway because the must_cache flag of the URL is set. - * For these URLs, the condition below would be true (since we're - * trying to remove as many files as possible to make room for the - * too-big file), which would cause all files to be removed but also - * the cache database to be closed and deleted. With the database - * gone, net_CacheStore will fail, so even though the large file was - * saved correctly it won't be used. (See bug #11327.) - */ -#if 0 - if(remove_num >= net_NumberInDiskCache) - { - net_RemoveAllDiskCacheObjects(); - return(net_DiskCacheSize); - } -#endif - - if(!cache_database) - return(net_DiskCacheSize); - - old_array = (DatePlusDBT *)PR_Malloc(sizeof(DatePlusDBT) * remove_num); - - if(!old_array) - return(net_DiskCacheSize); - - memset(old_array, 0, sizeof(DatePlusDBT) * remove_num); - - /* We need to delete the oldest items in the database. - * Sequentailly go throught the DB and remove - * the oldest items - */ - - if(0 != (*cache_database->seq)(cache_database, &key, &data, R_FIRST)) - return(net_DiskCacheSize); - total_cl += net_calc_real_file_size(net_GetInt32InCacheDBT(&data, - CONTENT_LENGTH_BYTE_POSITION)); - total_number++; - - /* Only add the first item to the old_array if the number to remove - is greater than zero, otherwise we're writing where we shouldn't be */ - if(remove_num > 0) - { - old_array[0].dbt = net_CacheDBTDup(&key); - old_array[0].date = net_GetTimeInCacheDBT(&data, - LAST_ACCESSED_BYTE_POSITION); - } - - while(0 == (*cache_database->seq)(cache_database, &key, &data, R_NEXT)) - { - date = net_GetTimeInCacheDBT(&data, LAST_ACCESSED_BYTE_POSITION); - - if(date) - last_modified_date = net_GetTimeInCacheDBT(&data, - LAST_MODIFIED_BYTE_POSITION); - - /* there are other items beside FAT entries in here - * but they don't have a date - */ - if(!date) - { - /* this could be a corrupt entry */ - if(!net_IsValidCacheDBT(&data)) - { - if((key.size < 4 || PL_strncmp((char*)key.data, - INTERNAL_NAME_PREFIX, - 4)) - && corrupt_entry_count < CORRUPT_ENTRY_ARRAY_SIZE) - { - - /* store invalid cache entries in an array - * for later deletion - */ - corrupt_entry_array[corrupt_entry_count++] = - net_CacheDBTDup(&key); - TRACEMSG(("Found %d corrupted cache entries", - corrupt_entry_count)); - } - - } - } - else - { - url_address = net_GetAddressFromCacheKey(&key); - - if(!last_modified_date - || (url_address && PL_strncasecmp(url_address, "http",4))) - { - /* this is not a http URL or it has no last modified date. - * Delete it preferentially - * if it's older than the current session - */ - if(NET_StartupTime > date) - { - /* set the date really low so it automatically - * gets deleted - */ - date = 1; - } - } - - total_cl += net_calc_real_file_size(net_GetInt32InCacheDBT(&data, - CONTENT_LENGTH_BYTE_POSITION)); - total_number++; - - lock_date = net_GetTimeInCacheDBT(&data, LOCK_DATE_BYTE_POSITION); - - /* honor locks issued during this session */ - TRACEMSG(("cache: comparing lock date %ld to startup time %ld\n", - lock_date, NET_StartupTime)); - if(lock_date > NET_StartupTime) - continue; - else if(lock_date) - net_SetTimeInCacheDBT(&data, - LOCK_DATE_BYTE_POSITION, - 0); /* current time */ - - for(i=0; i < remove_num; i++) - { - if(date < old_array[i].date || !old_array[i].date) - { - /* free the oldest one so it - * doesn't get lost as it is pushed off - * the stack - */ - if(old_array[remove_num-1].dbt) - net_FreeCacheDBTdata(old_array[remove_num-1].dbt); - - /* shift all the entries down */ - for(j=remove_num-1; j > i; j--) - { - old_array[j].dbt = old_array[j-1].dbt; - old_array[j].date = old_array[j-1].date; - } - - old_array[i].date = date; - old_array[i].dbt = net_CacheDBTDup(&key); - - break; - } - } - } - } - -#ifdef XP_UNIX - /* assert(total_cl == net_DiskCacheSize); */ -#endif - net_DiskCacheSize = total_cl; - -#ifdef XP_UNIX - /* assert(total_number == net_NumberInDiskCache); */ -#endif - net_NumberInDiskCache = total_number; - - /* now old1 old2 and old3 should contain the oldest - * keys in the database. Delete them all. - */ - for(i=0; i < remove_num; i++) - { - DBT *db_obj = old_array[i].dbt; - - if(db_obj) - { - if(0 == (*cache_database->get)(cache_database, db_obj, &data, 0)) - { - lock_date = net_GetTimeInCacheDBT(&data, LOCK_DATE_BYTE_POSITION); - - /* honor locks issued during this session */ - TRACEMSG(("cache: comparing (2) lock date %ld to startup time %ld\n", - lock_date, NET_StartupTime)); - if(lock_date > NET_StartupTime) - { - TRACEMSG(("cache: saved your ass again, bud!")); - continue; - } - - filename = net_GetFilenameInCacheDBT(&data); - if(filename) - { - TRACEMSG(("Removing file: %s due to disk" - " cache size overflow",filename)); -#ifdef XP_OS2 - XP_LazyFileRemove(filename, xpCache); -#else - NET_XP_FileRemove(filename, xpCache); -#endif - PR_Free(filename); - } - net_DiskCacheSize -= net_calc_real_file_size( - net_GetInt32InCacheDBT(&data, - CONTENT_LENGTH_BYTE_POSITION)); - net_NumberInDiskCache--; - (*cache_database->del)(cache_database, db_obj, 0); - } - - net_FreeCacheDBTdata(db_obj); - } - } - - /* remove any invalid cache intries - */ - for(i=0; i < corrupt_entry_count; i++) - { - DBT *newkey = corrupt_entry_array[i]; - if(newkey && -1 == (*cache_database->del)(cache_database, newkey, 0)) - { - TRACEMSG(("Ack, error trying to delete corrupt entry, aborting",i)); - break; - } - - TRACEMSG(("Deleting %d corrupted cache entries",i)); - net_FreeCacheDBTdata(newkey); - } - - /* don't need the stale array any more */ - PR_Free(old_array); - - /* sync the database - */ - net_StoreDiskCacheSize(); - - if(-1 == (*cache_database->sync)(cache_database, 0)) - { - TRACEMSG(("Error syncing cache database")); - - /* close the database */ - (*cache_database->close)(cache_database); - cache_database = 0; - } - - return(net_DiskCacheSize); -} - -PRIVATE void -net_ReduceDiskCacheTo(MWContext *window_id, uint32 size, int recurse_count) -{ - uint32 avg, reduce, remove_num; - - if(net_DiskCacheSize < size - || !net_NumberInDiskCache - || recurse_count >= 5) - return; - - TRACEMSG(("net_ReduceDiskCacheTo: Current size: %d " - "Desired Size: %d Number: %d", - net_DiskCacheSize, - size, - net_NumberInDiskCache)); - - /* compute the avarage size of the - * contents of the disk cache - */ - if(net_NumberInDiskCache < 1) - avg = 0; - else - avg = net_DiskCacheSize/net_NumberInDiskCache; - - /* compute the amount that we need to shrink - * the disk cache - */ - reduce = net_DiskCacheSize - size; - - /* add 10% of the total disk cache size - * to the reduce number to reduce - * the number of times that we need to - * do this operation - */ - reduce += net_DiskCacheSize/10; - - /* compute the number of objects to remove - */ - if(avg < 1) - remove_num = 1; - else - remove_num = reduce/avg; - - if(remove_num < 1) - remove_num = 1; - - if(window_id) - { - char buffer[256]; - sprintf(buffer, XP_GetString( XP_CACHE_CLEANUP ), remove_num); - NET_Progress(window_id, buffer); - } - - NET_RemoveDiskCacheObjects(remove_num); - - /* make sure we removed enough - */ - if(net_DiskCacheSize > size) - net_ReduceDiskCacheTo(window_id, size, ++recurse_count); - - return; -} - -#ifdef NO_MEMORY_CACHE - -/* set the size of the Memory cache. - * Set it to 0 if you want cacheing turned off - * completely - */ -PUBLIC void -NET_SetMemoryCacheSize(int32 new_size) -{ - - net_MaxMemoryCacheSize=new_size; - IL_ReduceImageCacheSizeTo(new_size); - return; -} - -PUBLIC int32 -NET_GetMaxMemoryCacheSize() -{ - return net_MaxMemoryCacheSize; -} - -/* remove the last memory cache object if one exists - * returns the total size of the memory cache in bytes - * after performing the operation - */ -PUBLIC int32 -NET_RemoveLastMemoryCacheObject() -{ - /* and remove something from the image cache */ - return IL_ShrinkCache(); - - /* XXX now the mac arithmetic is wrong */ - return(0); -} - -/* returns the number of bytes currently in use by the Memory cache - */ -PUBLIC int32 -NET_GetMemoryCacheSize() -{ - return(0); -} - -/* stub functions for memory cache that are no - * longer needed - */ -MODULE_PRIVATE int -NET_MemoryCacheLoad (ActiveEntry * cur_entry) -{ - return(-1); -} - -MODULE_PRIVATE int -NET_ProcessMemoryCache (ActiveEntry * cur_entry) -{ - return(-1); -} - -MODULE_PRIVATE int -NET_InterruptMemoryCache (ActiveEntry * cur_entry) -{ - return(-1); -} - -#endif /* MEMORY_CACHE */ - -/* set the size of the Disk cache. - * Set it to 0 if you want cacheing turned off - * completely - */ -PUBLIC void -NET_SetDiskCacheSize(int32 new_size) -{ - if(new_size < 0) - new_size = 0; -#ifdef NU_CACHE - DiskModule_SetSize(new_size); -#else - - net_MaxDiskCacheSize = new_size; - - /* open it if it's not open already */ - if(net_MaxDiskCacheSize > 0) - { - net_OpenCacheFatDB(); - net_ReduceDiskCacheTo(NULL, (uint32) new_size, 0); - } - else - { - net_RemoveAllDiskCacheObjects(); - } -#endif /* NU_CACHE */ -} - -/* remove the last disk cache object if one exists - * returns the total size of the disk cache in bytes - * after performing the operation - */ -PUBLIC int32 -NET_RemoveLastDiskCacheObject(void) -{ - return(net_DiskCacheSize); -} - -PRIVATE void -net_RemoveAllDiskCacheObjects(void) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Should not be called */ -} -#else -{ - char * filename; - DBT data; - DBT key; - - if(!cache_database) - return; - - if(0 != (*cache_database->seq)(cache_database, &key, &data, R_FIRST)) - return; - - do - { - filename = net_GetFilenameInCacheDBT(&data); - if(filename) - { - TRACEMSG(("Removing file: %s due to disk" - " cache size remove",filename)); -#ifdef XP_OS2 - XP_LazyFileRemove(filename, xpCache); -#else - NET_XP_FileRemove(filename, xpCache); -#endif - PR_Free(filename); - } - /* We don't acctually need to do the - * del since we will del the database - */ - /* (*cache_database->del)(cache_database, &key, 0); */ - } - while(0 == (*cache_database->seq)(cache_database, &key, &data, R_NEXT)); - - net_DiskCacheSize = 0; - net_NumberInDiskCache = 0; - - if(-1 == (*cache_database->close)(cache_database)) - { - TRACEMSG(("Error closing cache database")); - } - - cache_database = 0; - - /* remove the database */ - NET_XP_FileRemove("", xpCacheFAT); -} -#endif /* NU_CACHE */ - -/* returns the number of bytes currently in use by the Disk cache - */ -PUBLIC int32 -NET_GetDiskCacheSize() -{ - return(net_DiskCacheSize); -} - - -/****************************************************************** - * Cache Stream input routines - */ - -/* is the stream ready for writing? - */ -PRIVATE unsigned int net_CacheWriteReady (NET_StreamClass *stream) -{ - CacheDataObject *obj=stream->data_object; - if(obj->next_stream) - return((*obj->next_stream->is_write_ready)(obj->next_stream)); - else - return(MAX_WRITE_READY); -} - -/* stream write function - */ -PRIVATE int net_CacheWrite (NET_StreamClass *stream, CONST char* buffer, int32 len) -#ifdef NU_CACHE -{ - CacheDataObject* obj = stream->data_object; - if (obj && obj->cache_object) - { - if (!CacheObject_Write(obj->cache_object, buffer, len)) - { - if (obj->URL_s) - obj->URL_s->dont_cache = TRUE; - - /* CacheObject_MarkForDeletion(); TODO*/ - } - - /* Write for next stream */ - if (obj->next_stream) - { - int status = 0; - PR_ASSERT(buffer && (len >= 0)); - status = (*obj->next_stream->put_block) - (obj->next_stream, buffer, len); - - /* abort */ - if(status < 0) - return(status); - } - } - return(1); -} -#else -{ - CacheDataObject *obj=stream->data_object; - TRACEMSG(("net_CacheWrite called with %ld buffer size", len)); - - if(obj->fp) - { - /* increase the global cache size counter - */ - if(NET_XP_FileWrite((char *) buffer, len, obj->fp) < len) - { - TRACEMSG(("Error writing to cache file")); - NET_XP_FileClose(obj->fp); -#ifdef XP_OS2 - XP_LazyFileRemove(obj->cache_object->filename, xpCache); -#else - NET_XP_FileRemove(obj->cache_object->filename, xpCache); -#endif - if(obj->URL_s) - obj->URL_s->dont_cache = TRUE; - obj->fp = 0; - } - - } - - if(obj->next_stream) - { - int status=0; - - assert (buffer); - assert (len > -1); - status = (*obj->next_stream->put_block) - (obj->next_stream, buffer, len); - - /* abort */ - if(status < 0) - return(status); - } - - return(1); -} -#endif /* NU_CACHE */ - -/* complete the stream -*/ -PRIVATE void net_CacheComplete (NET_StreamClass *stream) -#ifdef NU_CACHE -{ - CacheDataObject* obj = stream->data_object; - PR_ASSERT(obj && obj->cache_object); - - /*Add it to the module and mark it as completed */ - CacheObject_Synch(obj->cache_object); - CacheObject_SetIsCompleted(obj->cache_object, TRUE); - - /* Plugins can use this file */ - /* If object is in memory GetFilename will return null so this is ok */ - if (obj->URL_s && CacheObject_GetFilename(obj->cache_object)) - { - StrAllocCopy(obj->URL_s->cache_file, CacheObject_GetFilename(obj->cache_object)); - } - - /* Complete the next stream */ - if (obj->next_stream) - { - (*obj->next_stream->complete)(obj->next_stream); - PR_Free(obj->next_stream); - } - - /* Do the things I don't as yet understand or have time to */ - PR_REMOVE_LINK(&obj->links); - PR_Free(obj); -} -#else -{ - CacheDataObject *obj=stream->data_object; - /* close the cache file - */ - if(obj->fp) - NET_XP_FileClose(obj->fp); - - assert(obj->cache_object); - - /* add it to the database */ - if(net_CacheStore(obj->cache_object, - obj->URL_s, - FALSE, - NEW_CACHE_STORE)) - { - /* set the cache_file in the url struct so that Plugins can - * use it... - */ - if(obj->URL_s) - StrAllocCopy(obj->URL_s->cache_file, obj->cache_object->filename); - } - - /* complete the next stream - */ - if(obj->next_stream) - { - (*obj->next_stream->complete)(obj->next_stream); - PR_Free(obj->next_stream); - } - - net_freeCacheObj(obj->cache_object); - PR_REMOVE_LINK(&obj->links); - PR_Free(obj); - - return; -} -#endif /* NU_CACHE */ - -/* Abort the stream - * - */ -PRIVATE void net_CacheAbort (NET_StreamClass *stream, int status) -#ifdef NU_CACHE -{ - CacheDataObject* obj = stream->data_object; - PR_ASSERT(obj); - PR_ASSERT(obj->cache_object); - - /* abort the next stream */ - if(obj->next_stream) - { - (*obj->next_stream->abort)(obj->next_stream, status); - PR_Free(obj->next_stream); - } - - /* This will take care of open files and other cleanup activity - plus will also mark the object as partial. TODO - Gagan */ - /* CacheObject_Abort(obj->cache_object); */ - /* Call CacheObject_Synch() if something was written */ - /* CacheObject_Destroy(obj->cache_object); */ - - PR_REMOVE_LINK(&obj->links); - PR_Free(obj); -} -#else -{ - - CacheDataObject *obj=stream->data_object; - PR_ASSERT(obj); - PR_ASSERT(obj->cache_object); - - /* abort the next stream - */ - if(obj->next_stream) - { - (*obj->next_stream->abort)(obj->next_stream, status); - PR_Free(obj->next_stream); - } - - /* fp might be null if we had a file write error */ - if(obj->fp) - { - NET_XP_FileClose(obj->fp); - - /* do this test in here since the file must be - * alright for us to use this - * - * test to see if we were user interrupted and if - * the server support byteranges. If so, store - * the partial object since we will request it - * with a partial byterange later - * - * Also, we can't do partial caching unless we know - * the content_length - */ - if(obj->URL_s - && obj->URL_s->content_length - && (obj->URL_s->server_can_do_byteranges || obj->URL_s->server_can_do_restart) - && !obj->URL_s->dont_cache) - { - - /* store the partial file */ - if(obj->URL_s->real_content_length > 0) - obj->cache_object->content_length = obj->URL_s->real_content_length; - net_CacheStore(obj->cache_object, - obj->URL_s, - TRUE, - NEW_CACHE_STORE); - - } - else if(status == MK_INTERRUPTED - && obj->URL_s->content_length - && !PL_strcasecmp(obj->URL_s->content_type, TEXT_HTML)) - { - /* temporarly cache interrupted HTML pages for history navigation */ - obj->URL_s->last_modified = 0; - net_CacheStore(obj->cache_object, - obj->URL_s, - FALSE, - NEW_CACHE_STORE); - - } - else - { -#ifdef XP_OS2 - XP_LazyFileRemove(obj->cache_object->filename, xpCache); -#else - NET_XP_FileRemove(obj->cache_object->filename, xpCache); -#endif - } - } - - net_freeCacheObj(obj->cache_object); - PR_REMOVE_LINK(&obj->links); - PR_Free(obj); - - return; -} -#endif - - -#ifdef XP_UNIX -extern char **fe_encoding_extensions; /* gag! */ -#endif - -/* setup the stream - */ -MODULE_PRIVATE NET_StreamClass * -NET_CacheConverter (FO_Present_Types format_out, - void *converter_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - CacheDataObject * data_object=0; -#ifdef NU_CACHE - void* cache_object=0; -#else - net_CacheObject * cache_object=0; -#endif /* NU_CACHE */ - NET_StreamClass * stream=0; - char *filename=0, *new_filename=0; - char *org_content_type = 0; - XP_Bool do_disk_cache=FALSE; - XP_Bool want_to_cache=FALSE; - XP_File fp=0; - NET_StreamClass * next_stream=0; - - /* XXX brendan will #define this hack after 3.0 ships! */ - XP_Bool dont_hold_URL_s = (converter_obj != NULL); - - TRACEMSG(("Setting up cache stream. Have URL: %s\n", URL_s->address)); - - FE_EnableClicking(window_id); - -#ifdef MOZILLA_CLIENT - /* add this new url to the Global history since we must be getting it now - */ - if (NET_URL_Type(URL_s->address) != WYSIWYG_TYPE_URL && URL_s->SARCache == NULL) - GH_UpdateGlobalHistory(URL_s); -#endif /* MOZILLA_CLIENT */ - - StrAllocCopy(org_content_type, URL_s->content_type); - if(!org_content_type) - return(NULL); - - if(format_out != FO_CACHE_ONLY) - { - format_out = CLEAR_CACHE_BIT(format_out); - next_stream = NET_StreamBuilder(format_out, URL_s, window_id); - if(!next_stream) - { - PR_FREEIF(org_content_type); - return(NULL); - } - } - - /* set the content type back the way it should be - * this is because some streams muck with it and - * dont set it back and we need it intact - */ - PR_Free(URL_s->content_type); - URL_s->content_type = org_content_type; - org_content_type = 0; - - /* do we want to cache this object? - */ - if(URL_s->server_can_do_restart) URL_s->must_cache = TRUE; - - - TRACEMSG(("cache: URL_s->must_cache is %s", URL_s->must_cache ? "TRUE" : "FALSE")); - - if(URL_s->must_cache /* overrides all the rest of these tests */ - || (CLEAR_CACHE_BIT(format_out) == FO_INTERNAL_IMAGE - || format_out == FO_CACHE_ONLY - || !PL_strncasecmp(URL_s->content_type, "IMAGE", 5) - || !PL_strncasecmp(URL_s->content_type, "TEXT", 4) - || !PL_strncasecmp(URL_s->content_type, "MESSAGE", 7) - || !PL_strcasecmp(URL_s->content_type, APPLICATION_HTTP_INDEX) - || !PL_strcasecmp(URL_s->content_type, APPLICATION_JAVAARCHIVE) - || ( (URL_s->content_length>0) && ((uint32) URL_s->content_length < (net_MaxDiskCacheSize/4)) ) - ) - ) - { - /* set a flag to say that we want to cache */ - want_to_cache = TRUE; - } - else - { - /* bypass the whole cache mechanism - */ - if(format_out != FO_CACHE_ONLY) - { - format_out = CLEAR_CACHE_BIT(format_out); - return(next_stream); - } - return NULL; - } - - /* set a flag if we should disk cache it based - * on whether the cache setting is non-zero and - * the cache database is open - */ - - HG52980 - TRACEMSG(("cache: want_to_cache is %s", want_to_cache ? "TRUE" : "FALSE")); - - if(want_to_cache - && (HG73896 - PL_strncasecmp(URL_s->address, "https:", 6)) - && !URL_s->dont_cache -#ifdef NU_CACHE - && (DiskModule_GetSize() > 0 || URL_s->must_cache) -#else - && (net_MaxDiskCacheSize > 0 || URL_s->must_cache) - && net_OpenCacheFatDB() /* make sure database is open */ -#endif /* NU_CACHE */ - && PL_strncasecmp(URL_s->address, "news:", 5) /* not news: */ - HG73684 - && PL_strncasecmp(URL_s->address, "mailbox://", 10)) /* not IMAP */ - do_disk_cache = TRUE; - - /* Special case for StreamAsFile plugins: */ - if (URL_s->must_cache /* this only set by plugin code ? */ - && ((PL_strncasecmp(URL_s->address, "news:", 5)==0) /* is news */ - HG83903 - || !PL_strncasecmp(URL_s->address, "mailbox://", 10))) /* is imap */ - do_disk_cache = TRUE; - -#ifdef NU_CACHE - cache_object = CacheObject_Create(URL_s->address); - if (!cache_object) - return 0; - do_disk_cache = TRUE; /* Testing remove later */ - CacheObject_SetModule(cache_object, (PRInt16) (do_disk_cache ? DISK_MODULE_ID : MEM_MODULE_ID)); - CacheObject_SetExpires(cache_object, URL_s->expires); - CacheObject_SetEtag(cache_object, URL_s->etag); - CacheObject_SetLastModified(cache_object, URL_s->last_modified); - CacheObject_SetContentLength(cache_object, URL_s->content_length); - CacheObject_SetContentType(cache_object, URL_s->content_type); - CacheObject_SetCharset(cache_object, URL_s->charset); - CacheObject_SetContentEncoding(cache_object, URL_s->content_encoding); - CacheObject_SetPageServicesURL(cache_object, URL_s->page_services_url); - /* This filename discovery thing takes place every time! - * So optimize this in nu code, TODO - */ - /* BEGIN BAD CODE */ - filename = WH_TempName(xpCache, "cache"); - - if (filename) - { - /* Put an appropriate suffix on the tmp cache file */ - if (URL_s->address) /* Why are we doing this? */ - { - - char *tail = NULL; - char *suffix; - char *allocSuffix; /* in case we have to allocate a suffix */ - char *end; - char *junk; - char old_char = 0; - - suffix = allocSuffix = NULL; - - if (URL_s->content_name){ - suffix = (URL_s->content_name ? PL_strrchr (URL_s->content_name, '.') : 0); - } - else if ((URL_s->address) && - (!PL_strncasecmp(URL_s->address, "mailbox:", 8) - || !PL_strncasecmp(URL_s->address, "news:", 5) - HG65294) - && (URL_s->content_type) && (*(URL_s->content_type))) - { - /* - Gag. If we're a mailbox URL and can't figure out the content name, - but have a content type, ask the type registry for a suitable suffix. - (This allows us to set up Java and audio cache files so that those - subsystems will actually work with the cache files. Ick.) - */ - char *regSuffix = NET_cinfo_find_ext(URL_s->content_type); - if (regSuffix) - { - suffix = PR_smprintf(".%s", regSuffix); - allocSuffix = suffix; /* we allocated it here, we delete it below */ - } - } - - if (!suffix) - { - tail = PL_strrchr (URL_s->address, '/'); - suffix = (tail ? PL_strrchr (tail, '.') : 0); - } - end = suffix + (suffix ? PL_strlen (suffix) : 0); - junk=0; - -#ifdef XP_UNIX - /* Gag. foo.html.gz --> cacheXXXXX.html, not cacheXXXXX.gz. */ - if (suffix && fe_encoding_extensions) - { - int i = 0; - while (fe_encoding_extensions [i]) - { - if (!PL_strcmp (suffix, fe_encoding_extensions [i])) - { - end = suffix; - suffix--; - while (suffix > tail && *suffix != '.') - suffix--; - if (*suffix != '.') - suffix = 0; - break; - } - i++; - } - } -#endif - - /* Avoid "cache2F1F6AD102169F0.sources&maxhits=10" */ - if (suffix) - { - junk = suffix + 1; - while (isalnum (*junk)) - junk++; - old_char = *junk; - *junk = 0; - } - - -#ifdef XP_PC - /* Remove any suffix that the temp filename currently has - */ - strtok(filename, "."); -#endif - - if (suffix && (end - suffix) < 20) - { - /* make sure it is terminated... */ - if(!junk) - { - junk = end; - old_char = *junk; - *junk = 0; - } - StrAllocCopy(new_filename, filename); -#ifdef XP_PC - /* the comment */ - /* say 16 bit */ - /* 32 bit Win */ - /* goes thru */ - /* here, so do */ - /* the same for*/ - /* OS2 */ - /* make all suffixes be UPPERCASE for win16 - * since the operating system will make - * them so and we need to know the exact - * name for hashing and comparison purposes - */ - if(1) - { - char *new_suffix = PL_strdup(suffix); - if(new_suffix) - { - char *cp = new_suffix; - int i; - /* limit it to 4 chars. - * a dot and three letters - */ - for(i=0; *cp && i < 4; i++) - { - *cp = NET_TO_UPPER(*cp); - cp++; - } - *cp = '\0'; /* make sure it's terminated */ - StrAllocCat(new_filename, new_suffix); - PR_Free(new_suffix); - } - } -#else - StrAllocCat(new_filename, suffix); -#endif - } - else - { - StrAllocCopy(new_filename, filename); - } - - - if(junk) - *junk = old_char; - - if (allocSuffix) - PR_Free(allocSuffix); - } - PR_Free(filename); - } - /* END BAD CODE */ - CacheObject_SetFilename(cache_object, new_filename); - /* TODO check for return from SetFilename */ - - /* I am still not convinced that PostData should be - persistent but here it is for keeping it sake. Once - FE/History takes this, this should be ripped off.*/ - if (URL_s->post_data) - { - CacheObject_SetPostData(cache_object, URL_s->post_data, URL_s->post_data_size); - } - - data_object = PR_NEW(CacheDataObject); - if (!data_object) - { - CacheObject_Destroy(cache_object); - return NULL; - } - - /* init the object */ - memset(data_object, 0, sizeof(CacheDataObject)); - - /* assign the cache object to the stream data object - */ - data_object->cache_object = cache_object; - - /* save the URL struct since we will - * need to use some data from it later - * XXX if converter_obj is non-null it is a flag telling us not - * XXX to hold a pointer to the URL struct. - */ - if (dont_hold_URL_s == FALSE) - data_object->URL_s = URL_s; - data_object->fp = 0 /* fp */; /* TODO -Gagan */ - - stream = PR_NEW(NET_StreamClass); - if (!stream) - { - CacheObject_Destroy(cache_object); - PR_Free(data_object); - return NULL; - } - - stream->name = "Nu Cache Stream"; - stream->complete = (MKStreamCompleteFunc) net_CacheComplete; - stream->abort = (MKStreamAbortFunc) net_CacheAbort; - stream->put_block = (MKStreamWriteFunc) net_CacheWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_CacheWriteReady; - stream->data_object = data_object; /* document info object */ - stream->window_id = window_id; - - if (format_out != FO_CACHE_ONLY) - data_object->next_stream = next_stream; - - PR_APPEND_LINK(&data_object->links, &active_cache_data_objects); /* verify */ - - return stream; - -#else /* NU_CACHE */ - /* malloc and init all the necessary structs - * do_disk_cache will be set false on error - */ - if(do_disk_cache) - { - - TRACEMSG(("Object has not been cached before")); - - cache_object = PR_NEW(net_CacheObject); - if (!cache_object) - { - return(NULL); - } - - /* assign and init the cache object */ - memset(cache_object, 0, sizeof(net_CacheObject)); - - /* copy the contents of the URL structure - */ - StrAllocCopy(cache_object->address, URL_s->address); - cache_object->method = URL_s->method; - if(URL_s->post_data) - { - cache_object->post_data_size = URL_s->post_data_size; - StrAllocCopy(cache_object->post_data, URL_s->post_data); - StrAllocCopy(cache_object->post_headers, URL_s->post_headers); - } - - /* add expiration stuff from URL structure - */ - cache_object->expires = URL_s->expires; - cache_object->last_modified = URL_s->last_modified; - - cache_object->content_length = URL_s->content_length; - cache_object->real_content_length = URL_s->content_length; - cache_object->is_netsite = URL_s->is_netsite; - - StrAllocCopy(cache_object->content_type, URL_s->content_type); - StrAllocCopy(cache_object->charset, URL_s->charset); - StrAllocCopy(cache_object->content_encoding, URL_s->content_encoding); - - HG32138 - StrAllocCopy(cache_object->page_services_url, URL_s->page_services_url); - - /* we always use relative paths in the main disk cache - */ - cache_object->is_relative_path = TRUE; - - /* open a file for the cache - larubbio added SARCache check it's late in 4.0 cycle, and I don't want to have - any impact on the other platforms - - */ - filename = WH_TempName( -#ifdef XP_UNIX - (NULL != URL_s->SARCache) ? xpSARCache : -#endif - xpCache, "cache"); - - if (filename) - { - /* Put an appropriate suffix on the tmp cache file */ - if (cache_object->address) - { - - char *tail = NULL; - char *suffix; - char *allocSuffix; /* in case we have to allocate a suffix */ - char *end; - char *junk; - char old_char = 0; - - suffix = allocSuffix = NULL; - - if (URL_s->content_name){ - suffix = (URL_s->content_name ? PL_strrchr (URL_s->content_name, '.') : 0); - } - else if ((URL_s->address) && - (!PL_strncasecmp(URL_s->address, "mailbox:", 8) - || !PL_strncasecmp(URL_s->address, "news:", 5) - HG65294) - && (URL_s->content_type) && (*(URL_s->content_type))) - { - /* - Gag. If we're a mailbox URL and can't figure out the content name, - but have a content type, ask the type registry for a suitable suffix. - (This allows us to set up Java and audio cache files so that those - subsystems will actually work with the cache files. Ick.) - */ - char *regSuffix = NET_cinfo_find_ext(URL_s->content_type); - if (regSuffix) - { - suffix = PR_smprintf(".%s", regSuffix); - allocSuffix = suffix; /* we allocated it here, we delete it below */ - } - } - - if (!suffix) - { - tail = PL_strrchr (cache_object->address, '/'); - suffix = (tail ? PL_strrchr (tail, '.') : 0); - } - end = suffix + (suffix ? PL_strlen (suffix) : 0); - junk=0; - -#ifdef XP_UNIX - /* Gag. foo.html.gz --> cacheXXXXX.html, not cacheXXXXX.gz. */ - if (suffix && fe_encoding_extensions) - { - int i = 0; - while (fe_encoding_extensions [i]) - { - if (!PL_strcmp (suffix, fe_encoding_extensions [i])) - { - end = suffix; - suffix--; - while (suffix > tail && *suffix != '.') - suffix--; - if (*suffix != '.') - suffix = 0; - break; - } - i++; - } - } -#endif - - /* Avoid "cache2F1F6AD102169F0.sources&maxhits=10" */ - if (suffix) - { - junk = suffix + 1; - while (isalnum (*junk)) - junk++; - old_char = *junk; - *junk = 0; - } - - -#ifdef XP_PC - /* Remove any suffix that the temp filename currently has - */ - strtok(filename, "."); -#endif - - if (suffix && (end - suffix) < 20) - { - /* make sure it is terminated... */ - if(!junk) - { - junk = end; - old_char = *junk; - *junk = 0; - } - StrAllocCopy(new_filename, filename); -#ifdef XP_PC - /* the comment */ - /* say 16 bit */ - /* 32 bit Win */ - /* goes thru */ - /* here, so do */ - /* the same for*/ - /* OS2 */ - /* make all suffixes be UPPERCASE for win16 - * since the operating system will make - * them so and we need to know the exact - * name for hashing and comparison purposes - */ - if(1) - { - char *new_suffix = PL_strdup(suffix); - if(new_suffix) - { - char *cp = new_suffix; - int i; - /* limit it to 4 chars. - * a dot and three letters - */ - for(i=0; *cp && i < 4; i++) - { - *cp = NET_TO_UPPER(*cp); - cp++; - } - *cp = '\0'; /* make sure it's terminated */ - StrAllocCat(new_filename, new_suffix); - PR_Free(new_suffix); - } - } -#else - StrAllocCat(new_filename, suffix); -#endif - } - else - { - StrAllocCopy(new_filename, filename); - } - - - if(junk) - *junk = old_char; - - if (allocSuffix) - PR_Free(allocSuffix); - } - PR_Free(filename); - } - - if(new_filename) - { - /* larubbio added 197 SAR cache checks */ - if ( URL_s->SARCache == NULL ) - fp = NET_XP_FileOpen(new_filename, xpCache, XP_FILE_WRITE_BIN); - else - fp = NET_XP_FileOpen(new_filename, xpSARCache, XP_FILE_WRITE_BIN); - } - - if(!fp) - { - net_freeCacheObj(cache_object); - cache_object = 0; - do_disk_cache = FALSE; - PR_FREEIF(new_filename); - } - else - { - cache_object->filename = new_filename; - - /* cap the total size of the cache - */ - - /* larubbio disk cache size checks for SARCache - * Also, don't reduce the cache size yet for "must_cache" - * objects, since in the download-restart case the object - * will be deleted most of the time before it ever gets - * counted in the cache. Objects that do get put into - * the cache will self correct at the next call to - * ReduceDiskCacheTo() - */ - if(net_DiskCacheSize+URL_s->content_length > net_MaxDiskCacheSize - && URL_s->SARCache == NULL - && !URL_s->must_cache) - { - int32 new_size = net_MaxDiskCacheSize - URL_s->content_length; - if(new_size < 0) - new_size = 0; - net_ReduceDiskCacheTo(window_id, (uint32)new_size, 0); - } - } - } - - /* if we get this far and do_disk_cache is true - * then we want cache and all the setup succeeded. - */ - if(do_disk_cache) - { - TRACEMSG(("Caching this URL!!!!")); - - data_object = PR_NEW(CacheDataObject); - if (!data_object) - { - NET_XP_FileClose(fp); - return(NULL); - } - - stream = PR_NEW(NET_StreamClass); - if(!stream) - { - NET_XP_FileClose(fp); - PR_Free(data_object); - return(NULL); - } - - /* init the object */ - memset(data_object, 0, sizeof(CacheDataObject)); - - /* assign the cache object to the stream data object - */ - data_object->cache_object = cache_object; - - /* save the URL struct since we will - * need to use some data from it later - * XXX if converter_obj is non-null it is a flag telling us not - * XXX to hold a pointer to the URL struct. - */ - if (dont_hold_URL_s == FALSE) - data_object->URL_s = URL_s; - data_object->fp = fp; - - TRACEMSG(("Returning stream from NET_CacheConverter\n")); - - stream->name = "Cache stream"; - stream->complete = (MKStreamCompleteFunc) net_CacheComplete; - stream->abort = (MKStreamAbortFunc) net_CacheAbort; - stream->put_block = (MKStreamWriteFunc) net_CacheWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_CacheWriteReady; - stream->data_object = data_object; /* document info object */ - stream->window_id = window_id; - - if(format_out != FO_CACHE_ONLY) - data_object->next_stream = next_stream; - - PR_APPEND_LINK(&data_object->links, &active_cache_data_objects); - return stream; - } - else - { - - TRACEMSG(("NOT Disk Caching this URL")); - - if(want_to_cache) - { - net_MemCacheConverterObject mem_conv_obj; - - mem_conv_obj.next_stream = next_stream; - mem_conv_obj.dont_hold_URL_s = dont_hold_URL_s; - return(NET_MemCacheConverter(format_out, - &mem_conv_obj, - URL_s, - window_id)); - } - - /* bypass the whole cache mechanism - */ - if(format_out != FO_CACHE_ONLY) - { - format_out = CLEAR_CACHE_BIT(format_out); - - return(next_stream); - } - - } -#endif /* NU_CACHE */ - return(NULL); -} - -/*************************************************************************** - * Cache object manipulation stuff - */ - -/* locks or unlocks a cache file. The - * cache lock is only good for a single - * session - */ -PUBLIC XP_Bool -NET_ChangeCacheFileLock(URL_Struct *URL_s, XP_Bool set) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Shouldn't be getting called */ - return TRUE; -} -#else -{ - int status; - DBT data; - DBT * key; - DBT * new_data=0; - net_CacheObject *found_cache_obj; - - /* lock or unlock the memory cache too */ - NET_ChangeMemCacheLock(URL_s, set); - - if(!cache_database) - return(FALSE); - - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - status = (*cache_database->get)(cache_database, key, &data, 0); - - if(status != 0) - { - TRACEMSG(("Key not found in database")); - net_FreeCacheDBTdata(key); - return(FALSE); - } - - found_cache_obj = net_Fast_DBDataToCacheStruct(&data); - - if(!found_cache_obj) - { - TRACEMSG(("mkcache: Corrupted db entry")); - return(FALSE); - } - - if(set) - found_cache_obj->lock_date = time(NULL); - else - found_cache_obj->lock_date = 0; - - /* create new dbt data object */ - new_data = net_CacheStructToDBData(found_cache_obj); - - if(new_data) - status = (*cache_database->put)(cache_database, key, new_data, 0); - - return(status == 0); -} -#endif - -MODULE_PRIVATE void NET_RefreshCacheFileExpiration(URL_Struct * URL_s) -#ifdef NU_CACHE -{ - void* cache_object; - - /* only update if the server status is 304 - * The other cases involve a new cache object - * and all the info will automatically get updated - */ - if (URL_s->server_status != 304) - { - return; - } - - cache_object = CacheManager_GetObject(URL_s->address); - if (cache_object) - { - CacheObject_SetLastModified(cache_object, URL_s->last_modified); - CacheObject_SetExpires(cache_object, URL_s->expires); - } -} -#else -{ - net_CacheObject *found_cache_obj; - int status; - DBT *key; - DBT data; - - if(!cache_database) - { - TRACEMSG(("Cache database not open")); - return; - } - - /* only update if the server status is 304 - * The other cases involve a new cache object - * and all the info will automatically get updated - */ - if(URL_s->server_status != 304) - return; - - /* gen a key */ - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - /* look up the key */ - status = (*cache_database->get)(cache_database, key, &data, 0); - - /* don't need the key anymore */ - net_FreeCacheDBTdata(key); - - if(status != 0) - return; - - /* turn the cache DB object into a cache object */ - found_cache_obj = net_Fast_DBDataToCacheStruct(&data); - - if(!found_cache_obj) - return; - - /* stick the address and post data in there - * since this stuff is ususally in the Key - */ - StrAllocCopy(found_cache_obj->address, URL_s->address); - if(URL_s->post_data_size) - { - found_cache_obj->post_data_size = URL_s->post_data_size; - BlockAllocCopy(found_cache_obj->post_data, - URL_s->post_data, - URL_s->post_data_size); - } - - /* this will update the last modified time */ - net_CacheStore(found_cache_obj, - NULL, - FALSE, - REFRESH_CACHE_STORE); - - return; - -} -#endif /* NU_CACHE */ - -/* returns TRUE if the url is in the disk cache - */ -PUBLIC XP_Bool -NET_IsURLInDiskCache(URL_Struct *URL_s) -{ - DBT *key; - DBT data; - int status; -#ifdef NU_CACHE - PR_ASSERT(0); /* Don't call this! Use DiskModule_Contains(URL_s->address);*/ - return FALSE; -#endif - - if(!cache_database) - { - TRACEMSG(("Cache database not open")); - return(0); - } - - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - status = (*cache_database->get)(cache_database, key, &data, 0); - - net_FreeCacheDBTdata(key); - - if(status == 0) - return(TRUE); - else - return(FALSE); -} - -/* remove a URL from the cache - */ -MODULE_PRIVATE void -NET_RemoveURLFromCache(URL_Struct *URL_s) -#ifdef NU_CACHE -{ - if (!URL_s || !URL_s->address) - return; - - CacheManager_Remove(URL_s->address); -} -#else -{ - - int status; - DBT data; - DBT *key; - - /* larubbio */ - XP_Bool SARCache = FALSE; - XP_FileType fileType; - DB *local_cache_database = NULL; - - /* larubbio fix to allow 197 SAR cache adds without modifying - * the navigator cache (too much) - */ - if ( URL_s != NULL && URL_s->SARCache != NULL ) - { - SARCache = TRUE; - fileType = xpSARCache; - local_cache_database = URL_s->SARCache->database; - } - else - { - fileType = xpCache; - local_cache_database = cache_database; - } - - - NET_RemoveURLFromMemCache(URL_s); - - if(!local_cache_database) - return; - - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - if(!key) - return; - - status = (*local_cache_database->get)(local_cache_database, key, &data, 0); - - if(status == 0) - { - char * filename = net_GetFilenameInCacheDBT(&data); - - if(filename) - { -#ifdef XP_OS2 - XP_LazyFileRemove(filename, fileType); -#else - NET_XP_FileRemove(filename, fileType); -#endif - PR_Free(filename); - } - - (*local_cache_database->del)(local_cache_database, key, 0); - - if ( SARCache ) - { - /* subtract the size of the file being removed */ - URL_s->SARCache->DiskCacheSize -= net_calc_real_file_size( - net_GetInt32InCacheDBT(&data, - CONTENT_LENGTH_BYTE_POSITION)); - URL_s->SARCache->NumberInDiskCache--; - } - else - { - net_DiskCacheSize -= net_calc_real_file_size( - net_GetInt32InCacheDBT(&data, - CONTENT_LENGTH_BYTE_POSITION)); - net_NumberInDiskCache--; - } - } - - net_FreeCacheDBTdata(key); -} -#endif /* NU_CACHE */ - -/* return TRUE if the URL is in the cache and - * is a partial cache file - */ -MODULE_PRIVATE PRBool -NET_IsPartialCacheFile(URL_Struct *URL_s) -#ifdef NU_CACHE -{ - if (!URL_s || !URL_s->address) - return PR_FALSE; - /* Todo change this to just getObject, if null then... - Gagan */ - if (CacheManager_Contains(URL_s->address)) - { - return CacheObject_IsPartial(CacheManager_GetObject(URL_s->address)); - } - return PR_FALSE; -} -#else -{ - net_CacheObject *found_cache_obj; - int status; - DBT *key; - DBT data; - - if(!cache_database) - { - TRACEMSG(("Cache database not open")); - return(0); - } - - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - status = (*cache_database->get)(cache_database, key, &data, 0); - - net_FreeCacheDBTdata(key); - - if(status != 0) - return(0); - - found_cache_obj = net_Fast_DBDataToCacheStruct(&data); - - if(found_cache_obj) - return(found_cache_obj->incomplete_file); - else - return(0); -} -#endif /* NU_CACHE */ - -PUBLIC int -NET_FindURLInCache(URL_Struct * URL_s, MWContext *ctxt) -#ifdef NU_CACHE -{ - - if (!URL_s || !URL_s->address) - return 0; - - /* zero the last modified date so that we don't - * screw up the If-modified-since header by - * having it in even when the document isn't - * cached. - */ - URL_s->last_modified = 0; - - if (!CacheManager_Contains(URL_s->address)) - return 0; - else - { - /* mkabout.c relies on updating the URL_struct with the found info */ - void* pObject = CacheManager_GetObject(URL_s->address); - /* Copy all the stuff from CacheObject to URL_struct */ - if (pObject) - { - URL_s->expires = CacheObject_GetExpires(pObject); - URL_s->last_modified = CacheObject_GetLastModified(pObject); - StrAllocCopy(URL_s->charset, CacheObject_GetCharset(pObject)); - StrAllocCopy(URL_s->content_encoding, CacheObject_GetContentEncoding(pObject)); - if (!URL_s->preset_content_type) - { - StrAllocCopy(URL_s->content_type, CacheObject_GetContentType(pObject)); - } - /* StrAllocCopy(URL_s->page_services_url, CacheObject_GetPageServicesURL() */ - - /* Only set these for HTTP URLs otherwise the content-length will mess up files that - * dont return it and are different. - */ - if(!PL_strncasecmp(URL_s->address, "http", 4) || !PL_strncasecmp(URL_s->address, "ftp", 3)) - { - URL_s->content_length = CacheObject_GetContentLength(pObject); - URL_s->real_content_length = CacheObject_GetSize(pObject); - /* If no Content-Length: header was supplied */ - if ((0 == URL_s->content_length) && (URL_s->real_content_length>0)) - URL_s->content_length = URL_s->real_content_length; - } - - URL_s->cache_object = pObject; - - return NU_CACHE_TYPE_URL; - } - else - return 0; - } -} -#else -{ - net_CacheObject *found_cache_obj; - XP_StatStruct stat_entry; - int status; - char *byterange; - char byterange_char = 0; - DBT *key; - DBT data; - TRACEMSG(("Checking for URL in cache")); - - /* zero the last modified date so that we don't - * screw up the If-modified-since header by - * having it in even when the document isn't - * cached. - */ - URL_s->last_modified = 0; - - if(!cache_database) - { - TRACEMSG(("Cache database not open")); - - /* can't find it here. Let's look - * in the memory and external caches - */ - status = NET_FindURLInMemCache(URL_s, ctxt); - - if(status) - return(status); - else - return(NET_FindURLInExtCache(URL_s, ctxt)); - } - - byterange = PL_strcasestr(URL_s->address, ";bytes="); - - /* this might be a cached imap url. Ignore the mime - part when going back for attachments, otherwise we'll - reload the attachment from the server */ - if (!byterange) - byterange = PL_strcasestr(URL_s->address, "&part="); - - if(byterange) - { - byterange_char = *byterange; - *byterange = '\0'; - } - - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - - if(byterange) - *byterange = byterange_char; - - status = (*cache_database->get)(cache_database, key, &data, 0); - - - /* try it again with the byterange stuff - */ - if(status != 0 && byterange) - { - net_FreeCacheDBTdata(key); - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - status = (*cache_database->get)(cache_database, key, &data, 0); - } - - /* If the file doesn't have an extension try adding - * a slash to the end and look for it again. - * this will catch the most common redirect cases - */ - if(status != 0) - { - char *slash; - - slash = PL_strrchr(URL_s->address, '/'); - if(slash && !PL_strchr(slash, '.') && *(slash+1) != '\0') - { - /* no extension. Add the slash and - * look for it in the database - */ - StrAllocCat(URL_s->address, "/"); - net_FreeCacheDBTdata(key); - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - status = (*cache_database->get)(cache_database, key, &data, 0); - - if(status != 0) - { - /* adding the slash didn't work, get rid of it - */ - URL_s->address[PL_strlen(URL_s->address)-1] = '\0'; - } - else - { - URL_s->address_modified = TRUE; - } - } - } - - /* If the java Cache api is requesting this file, and it was found in the - * navigator cache, remove it from that cache so it can be recached in the proper archive cache - */ - if( (0 == status) && (NULL != URL_s->SARCache) ) - { - found_cache_obj = net_Fast_DBDataToCacheStruct(&data); - - if(!found_cache_obj) - { - TRACEMSG(("mkcache: Corrupted db entry")); - return(0); - } - - /* remove the object from the cache - */ - NET_XP_FileRemove(found_cache_obj->filename, xpCache); - - if(cache_database) - status = (*cache_database->del)(cache_database, key, 0); - - /* remove the size of that file from the running total */ - net_DiskCacheSize -= net_calc_real_file_size( - found_cache_obj->content_length); - - status = -1; - } - - - if(status != 0) - { - TRACEMSG(("Key not found in database")); - net_FreeCacheDBTdata(key); - - /* can't find it here. Let's look - * in the memory and external caches - */ - status = NET_FindURLInMemCache(URL_s, ctxt); - - if(status) - return(status); - else - return(NET_FindURLInExtCache(URL_s, ctxt)); - } - - found_cache_obj = net_Fast_DBDataToCacheStruct(&data); - - if(!found_cache_obj) - { - TRACEMSG(("mkcache: Corrupted db entry")); - return(0); - } - - TRACEMSG(("mkcache: found URL in cache!")); - - /* pretend we don't have the object cached if we are looking - * for a byterange URL and the object is only partially - * cached - */ - if(byterange && found_cache_obj->incomplete_file) - { - return(0); - } - - /* make sure the file still exists - */ - if(NET_XP_Stat(found_cache_obj->filename, &stat_entry, xpCache) == -1) - { - /* file does not exist!! - * remove the entry - */ - TRACEMSG(("Error! Cache file missing")); - - if(cache_database) - status = (*cache_database->del)(cache_database, key, 0); - - /* remove the size of that file from the running total */ - net_DiskCacheSize -= net_calc_real_file_size( - found_cache_obj->content_length); - -#ifdef DEBUG - if(status != 0) - TRACEMSG(("Error deleting bad file from cache")); -#endif /* DEBUG */ - - net_FreeCacheDBTdata(key); - - return(0); - - } - - /* - * if the last accessed date is before the startup date set the - * expiration date really low so that the URL is forced to be rechecked - * again. We don't just not return the URL as being in the - * cache because we want to use "If-modified-since" - * - * This works correctly because mkhttp will zero the - * expires field. - * - * if it's not an http url then just delete the entry - * since we can't do an If-modified-since - * - * NOTE: use the use_local_copy flag as a signal not to - * do the "once per session" check since it is possible - * that the cache is read only, also use history_num - * since we shouldn't reload on history navigation or resize - */ - if(!URL_s->use_local_copy) - { - if(found_cache_obj->last_accessed < NET_StartupTime - && NET_CacheUseMethod != CU_NEVER_CHECK -#ifdef MOZ_OFFLINE - && !NET_IsOffline() -#endif /* MOZ_OFFLINE */ - ) /* *X* check for is offline */ - { - if(!PL_strncasecmp(URL_s->address, "http", 4)) - { - URL_s->expires = 1; - -#if 0 - /* this is ifdeffed because of the following bug: - * If you update now, there is still the possibility - * of putting this URL on the wait queue. If that - * happens, when the URL gets pulled off the wait queue - * it will be called with NET_GetURL again and come - * here again. Since we already updated it wont - * get set expired again. So instead I will update - * the URL when I get a 304 in NET_RefreshCacheFileExpiration - */ - /* stick the address and post data in there - * since this stuff is in the Key - */ - StrAllocCopy(found_cache_obj->address, URL_s->address); - if(URL_s->post_data_size) - { - found_cache_obj->post_data_size = URL_s->post_data_size; - BlockAllocCopy(found_cache_obj->post_data, - URL_s->post_data, - URL_s->post_data_size); - } - - /* this will update the last accessed time - */ - net_CacheStore(found_cache_obj, - NULL, - FALSE, - REFRESH_CACHE_STORE); -#endif - } - else - { - /* remove the object from the cache - */ -#ifdef XP_OS2 - XP_LazyFileRemove(found_cache_obj->filename, xpCache); -#else - NET_XP_FileRemove(found_cache_obj->filename, xpCache); -#endif - /* remove the size of that file from the running total */ - net_DiskCacheSize -= net_calc_real_file_size( - found_cache_obj->content_length); - - status = (*cache_database->del)(cache_database, key, 0); -#ifdef DEBUG - if(status != 0) - TRACEMSG(("Error deleting expired file from cache")); -#endif /* DEBUG */ - - net_FreeCacheDBTdata(key); - - return(0); - } - } - else - { - /* otherwise use the normal expires date */ - URL_s->expires = found_cache_obj->expires; - } - } - else - { - URL_s->expires = 0; /* prevent looping */ - } - - /* we don't need the key anymore */ - net_FreeCacheDBTdata(key); - - /* copy in the cache file name - */ - StrAllocCopy(URL_s->cache_file, found_cache_obj->filename); - - /* copy the contents of the URL struct so that the content type - * and other stuff gets recorded - */ - if(!URL_s->preset_content_type) - StrAllocCopy(URL_s->content_type, found_cache_obj->content_type); - StrAllocCopy(URL_s->charset, found_cache_obj->charset); - StrAllocCopy(URL_s->content_encoding, found_cache_obj->content_encoding); - - StrAllocCopy(URL_s->page_services_url, found_cache_obj->page_services_url); - - /* only set these for HTTP url's - * otherwise the content-length will mess up files that don't - * return a content-length and are different - */ - if(!PL_strncasecmp(URL_s->address, "http", 4) || !PL_strncasecmp(URL_s->address, "ftp", 3)) - { - URL_s->content_length = found_cache_obj->content_length; - URL_s->real_content_length = found_cache_obj->real_content_length; - - if(URL_s->content_length != URL_s->real_content_length - && !found_cache_obj->incomplete_file) - { - /* TODO later- switch back to a PR_ASSERT(0) */ - if (1) - { - char *buf = 0; - StrAllocCopy(buf,"Possible Gromit vs. Mozilla cache corruption!\nDid you forget to clean your cache?\nIf you see this error AFTER cleaning your cache then call me- Gagan(x2187)"); - FE_Alert(ctxt, buf); - PR_Free(buf); - } - - URL_s->real_content_length = 0; - URL_s->content_length = 0; - - /* content type indicates a partial cache file but - * the incomplete file flag is not set. Something - * went wrong. - */ - return(0); /* return not found */ - } - } - - URL_s->last_modified = found_cache_obj->last_modified; - URL_s->is_netsite = found_cache_obj->is_netsite; - - HG83267 - - TRACEMSG(("Cached copy is valid. returning method")); - - TRACEMSG(("Using Disk Copy")); - - return(FILE_CACHE_TYPE_URL); -} -#endif - - -/* read the Cache File allocation table. - */ -PUBLIC void -NET_ReadCacheFAT(char * cachefatfile, XP_Bool stat_files) -{ -#ifdef NU_CACHE - PR_ASSERT(0); /* Shouldn't be getting called */ -#endif - if(net_MaxDiskCacheSize > 0) - net_OpenCacheFatDB(); - - return; -} - -PUBLIC void -NET_CacheInit(void) -{ -#ifdef NU_CACHE - Cache_Init(); -#else - NET_ReadCacheFAT("", TRUE); -#endif /* NU_CACHE */ -} - -/* unload the disk cache FAT list to disk - * - * set final_call to true if this is the last call to - * this function before cleaning up the cache and shutting down. - * - * Front ends should never set final_call to TRUE, this will - * be done by the cache cleanup code when the netlib is being - * shutdown. - */ -PUBLIC void -NET_WriteCacheFAT(char *filename, XP_Bool final_call) -{ -#ifdef NU_CACHE - PR_ASSERT(0); -#endif - net_StoreDiskCacheSize(); - - if(!cache_database) - return; - - if(-1 == (*cache_database->sync)(cache_database, 0)) - { - TRACEMSG(("Error syncing cache database")); - /* close the database */ - (*cache_database->close)(cache_database); - cache_database = 0; - } - - return; -} - -MODULE_PRIVATE void -NET_CleanupCache (void) -{ -#ifdef NU_CACHE - Cache_Shutdown(); -#else - net_StoreDiskCacheSize(); - - if(!cache_database) - return; - - if(-1 == (*cache_database->close)(cache_database)) - { - TRACEMSG(("Error closing cache database")); - } - - cache_database = 0; - - CACHE_CloseAllOpenSARCache(); -#endif -} - -/* returns the number of files currently in the - * disk cache - */ -PUBLIC uint32 -NET_NumberOfFilesInDiskCache() -{ -#ifdef NU_CACHE - return DiskModule_Entries(); -#else - return(net_NumberInDiskCache); -#endif -} - -static int -net_cache_strcmp (const void *a, const void *b) -{ - return PL_strcmp ((const char *) a, (const char *) b); -} - - -/* this function recurses through all directories in - * the cache directory and stuffs all the files into - * the hash table. Any directory names below the - * root cache directory should have their relative path - * names prepended to them - * - * returns 0 on success, -1 on failure - */ -PRIVATE int -net_cache_recursive_file_finder(XP_HashList *hash_table, - const char *prefix, - char *cur_dir, - char *base_dir, - char *buffer) -{ - PRDir *dir_ptr; - PRDirEntry *dir_entry; - int base_len; - int prefix_len, d_len, status; - char *dir_prefix=0; - const char *d_name; - XP_Bool add_dir_prefix=TRUE; - - /* compute the difference between base_dir and - * cur_dir. The difference should be prepended - * to the front of filenames - */ - base_len = PL_strlen(base_dir); - StrAllocCopy(dir_prefix, cur_dir+base_len); - - if(!dir_prefix) - return(-1); - - - if(*dir_prefix == '\0') - add_dir_prefix = FALSE; - else if(dir_prefix[PL_strlen(dir_prefix)-1] == '/') - dir_prefix[PL_strlen(dir_prefix)-1] = '\0'; - - if(!(dir_ptr = PR_OpenDir (cur_dir))) - { - PR_Free(dir_prefix); - return(-1); - } - - /* add all the files on disk to a hash table - */ - prefix_len = PL_strlen(prefix); - while((dir_entry = PR_ReadDir(dir_ptr, PR_SKIP_BOTH)) != 0) - { - /* only do comparison and delete if the prefix - * is the same - */ - d_name = dir_entry->name; - d_len = PL_strlen(d_name); - status = 0; - if(PL_strncmp(d_name, prefix, prefix_len)) - { -#if 0 - XP_StatStruct stat_entry; -#endif - - /* This directory didn't begin with the cache prefix, so it - *should* be a directory. But if it's not, then it's some - random junk that somehow got into the cache directory. - - Rather than stat'ing it first and then recursing, we will - simply assume it's a directory, recurse, and call XP_OpenDir - on it. If it's not a directory this will fail, and we will - ignore it. - */ - -#ifdef XP_UNIX - /* Unix-specific speed hack: only recursively descend directories - if they have names which consist of exactly two hex digits. - Because of the behavior of xp_file.c on Unix, anything else is - either not a directory, or not a directory which we use. - */ - if (! (d_len == 2 && - ((d_name[0] >= '0' && d_name[0] <= '9') || - (d_name[0] >= 'A' && d_name[0] <= 'F')) && - ((d_name[1] >= '0' && d_name[1] <= '9') || - (d_name[1] >= 'A' && d_name[1] <= 'F')))) - continue; -#endif /* !XP_UNIX */ - - if(add_dir_prefix) - { - sprintf(buffer, "%.250s/%.250s", dir_prefix, d_name); - } - - if(status != -1) - { - char *new_dir=0; - StrAllocCopy(new_dir, cur_dir); - if(cur_dir[PL_strlen(cur_dir)-1] != '/') - StrAllocCat(new_dir, "/"); - StrAllocCat(new_dir, d_name); - net_cache_recursive_file_finder(hash_table, - prefix, - new_dir, - base_dir, - buffer); - PR_Free(new_dir); - } - continue; - } - - if(add_dir_prefix) - { - sprintf(buffer, "%.250s/%.250s", dir_prefix, d_name); - XP_HashListAddObject(hash_table, PL_strdup(buffer)); - } - else - { - XP_HashListAddObject(hash_table, PL_strdup(d_name)); - } - - } - - PR_Free(dir_prefix); - - PR_CloseDir(dir_ptr); - return 0; -} -/* cleans up the cache directory by listing every - * file and deleting the ones it doesn't know about - * that begin with the cacheing prefix - */ -PUBLIC int -NET_CleanupCacheDirectory(char * dir_name, const char * prefix) -{ -#define REMOVE_LIST_SIZE 1000 - DBT *remove_list[REMOVE_LIST_SIZE]; - char *filename, *d_name; - XP_HashList *hash_table; - DBT key, data; - int status; - char buffer[512]; - uint32 num_files; - int i; - int number_in_remove_list=0; -#ifdef NU_CACHE - /* PR_ASSERT(0); Shouldn't be getting called */ - return 0; -#endif -#ifdef XP_MAC - - /* make sure the size of the cache is as we want it - */ - if(net_MaxDiskCacheSize == 0) - net_RemoveAllDiskCacheObjects(); - else - net_ReduceDiskCacheTo(NULL, net_MaxDiskCacheSize, 0); - - if(!dir_name) - dir_name = ""; - - /* optimization for cleanup. - * - * If the number of files on disk is within a couple - * of the number of files that we know about then - * skip the cache directory cleanup - */ - num_files = XP_FileNumberOfFilesInDirectory(dir_name, xpCache); - if(num_files-3 <= net_NumberInDiskCache) - return(0); -#endif - - if(!cache_database) - return(-1); - - TRACEMSG(("cleaning up cache directory of unknown cache files")); - - hash_table = XP_HashListNew(1597, XP_StringHash, net_cache_strcmp); - - if(!hash_table) - return(-1); - - /* find all the files in the cache directory - */ - if(net_cache_recursive_file_finder(hash_table, - prefix, - dir_name, - dir_name, - buffer)) - return(-1); - - /* init the count of all the files in the database */ - num_files = 0; - - /* now run through the disk cache FAT and remove - * any matches from the hash table - */ - status = (*cache_database->seq)(cache_database, &key, &data, R_FIRST); - - while(status == 0) - { - filename = net_GetFilenameInCacheDBT(&data); - if(filename) - { - time_t last_modified_date = net_GetTimeInCacheDBT(&data, - LAST_MODIFIED_BYTE_POSITION); - - if(!last_modified_date) - { - /* if there is no last_modified date then - * it doesn't do us much good to keep the - * data since it can't be compared and used - * in a future session. Put the file in a remove list - * - * Don't do this if the check mode is NEVER - * - */ - if(NET_CacheUseMethod != CU_NEVER_CHECK - && number_in_remove_list < REMOVE_LIST_SIZE) - remove_list[number_in_remove_list++] = - net_CacheDBTDup(&key); - } - else - { - num_files++; /* keep a count of all the files in the database */ - - d_name = (char*) XP_HashListRemoveObject(hash_table, filename); - if(d_name) - { - PR_Free(d_name); - } - } - PR_Free(filename); - } - else - { - /* could not grab the filename from - * the DBT. See if this is a valid - * entry - */ - if(!net_IsValidCacheDBT(&data) - && (key.size < 4 || PL_strncmp((char*)key.data, - INTERNAL_NAME_PREFIX, - 4)) - && number_in_remove_list < REMOVE_LIST_SIZE) - { - remove_list[number_in_remove_list++] = net_CacheDBTDup(&key); - } - } - - status = (*cache_database->seq)(cache_database, &key, &data, R_NEXT); - } - - /* any files left in the hash table are not in the - * cache FAT, so delete them - * - * @@@@ Manipulate the hash table directly - */ - { - int list_count; - XP_List *list_ptr; - - for(list_count=0; list_count < hash_table->size; list_count++) - { - list_ptr = hash_table->list[list_count]; - if(list_ptr) - { - while((filename = - (char *) XP_ListRemoveTopObject(list_ptr)) != 0) - { -#ifdef XP_OS2 - XP_LazyFileRemove(filename, xpCache); -#else - NET_XP_FileRemove(filename, xpCache); -#endif - TRACEMSG(("Unknown cache file %s found! -- deleteing...", - filename)); - PR_Free(filename); - } - XP_ListDestroy(list_ptr); /* free the list */ - } - } - - XP_HashListDestroy(hash_table); - } - - /* remove the entries that are no longer needed or - * are corrupt - * - * Note that we don't need to remove the files since - * they will already have been removed from the code - * above - */ - TRACEMSG(("Deleting %d unneeded cache entries",number_in_remove_list)); - for(i=0; i < number_in_remove_list; i++) - { - DBT *newkey = remove_list[i]; - if(-1 == (*cache_database->del)(cache_database, newkey, 0)) - { - TRACEMSG(("Ack, error trying to delete corrupt entry, aborting",i)); break; - } - - net_FreeCacheDBTdata(newkey); - } - - /* if the number of files that we counted in the database - * does not agree with the number we think it should be - * reset the number we think it should be with the actual - * number - */ - if(net_NumberInDiskCache != num_files) - { - TRACEMSG(("Reseting number of files in cache to: %d", num_files)); - net_NumberInDiskCache = num_files; - net_StoreDiskCacheSize(); /* this will store the number of files */ - } - return(0); -} - -/* removes all cache files from the cache directory - * and deletes the cache FAT - */ -PUBLIC int -NET_DestroyCacheDirectory(char * dir_name, char * prefix) -{ -#ifdef NU_CACHE - PR_ASSERT(0); /* Shouldn't be getting called */ -#endif - net_RemoveAllDiskCacheObjects(); - NET_CleanupCacheDirectory(dir_name, prefix); - - (*cache_database->close)(cache_database); - cache_database = 0; - - net_DiskCacheSize=0; - net_NumberInDiskCache=0; - - return NET_XP_FileRemove("", xpCacheFAT); -} - -/* create an HTML stream and push a bunch of HTML about - * the cache - */ -MODULE_PRIVATE void -NET_DisplayCacheInfoAsHTML(ActiveEntry * cur_entry) -#ifdef NU_CACHE -{ - NET_StreamClass *stream; - char buffer[1024]; - - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, - cur_entry->window_id); - - if(!stream) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - return; - } - - CacheManager_InfoAsHTML(buffer); - - cur_entry->status = (*stream->put_block)(stream, buffer,PL_strlen(buffer)); - - if(cur_entry->status < 0) - (*stream->abort)(stream, cur_entry->status); - else - (*stream->complete)(stream); -} -#else -{ - char *buffer = (char*)PR_Malloc(2048); - char *address; - char *escaped; - NET_StreamClass * stream; - net_CacheObject * cache_obj; - DBT key, data; - XP_Bool long_form = FALSE; - int i; - - if(!buffer) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - return; - } - - if(PL_strcasestr(cur_entry->URL_s->address, "?long")) - long_form = TRUE; - else if(PL_strcasestr(cur_entry->URL_s->address, "?traceon")) - NET_CacheTraceOn = TRUE; - else if(PL_strcasestr(cur_entry->URL_s->address, "?traceoff")) - NET_CacheTraceOn = FALSE; - - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, - cur_entry->window_id); - - if(!stream) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - PR_Free(buffer); - return; - } - - - /* define a macro to push a string up the stream - * and handle errors - */ -#define PUT_PART(part) \ -cur_entry->status = (*stream->put_block)(stream, \ - part ? part : "Unknown", \ - part ? PL_strlen(part) : 7); \ -if(cur_entry->status < 0) \ - goto END; - - sprintf(buffer, -"Information about the Netscape disk cache\n" -"

Disk Cache statistics

\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"
Maximum size:%ld
Current size:%ld
Number of files in cache:%ld
Average cache file size:%ld
\n" -"
", -net_MaxDiskCacheSize, -net_DiskCacheSize, -net_NumberInDiskCache, -net_NumberInDiskCache ? net_DiskCacheSize/net_NumberInDiskCache : 0); - - PUT_PART(buffer); - - if(!cache_database) - { - PL_strcpy(buffer, "The cache database is currently closed"); - PUT_PART(buffer); - goto END; - } - - if(0 != (*cache_database->seq)(cache_database, &key, &data, R_FIRST)) - return; - - /* define some macros to help us output HTML tables - */ -#if 0 - -#define TABLE_TOP(arg1) \ - sprintf(buffer, \ -"%s\n" \ -"", arg1); \ -PUT_PART(buffer); - -#define TABLE_BOTTOM \ - sprintf(buffer, \ -""); \ -PUT_PART(buffer); - -#else - -#define TABLE_TOP(arg1) \ - PL_strcpy(buffer, ""); \ - for(i=PL_strlen(arg1); i < 16; i++) \ - PL_strcat(buffer, " "); \ - PL_strcat(buffer, arg1); \ - PL_strcat(buffer, " "); \ - PUT_PART(buffer); - -#define TABLE_BOTTOM \ - PL_strcpy(buffer, "
\n"); \ - PUT_PART(buffer); - -#endif - - do - { - - cache_obj = net_Fast_DBDataToCacheStruct(&data); - - if(!cache_obj) - { - if(!net_IsValidCacheDBT(&data) - && (key.size < 4 || PL_strncmp((char*)key.data, - INTERNAL_NAME_PREFIX, - 4))) - { - - PL_strcpy(buffer, "

Corrupted or misversioned cache entry

" - "This entry will be deleted automatically " - "in the future." - "
"); - PUT_PART(buffer); - } - } - else - { -#if 0 - /* begin a table for this entry */ - PL_strcpy(buffer, ""); - PUT_PART(buffer); -#endif - - /* put the URL out there */ - /* the URL is 8 bytes into the key struct - */ - address = (char *)key.data+8; - - TABLE_TOP("URL:"); - PL_strcpy(buffer, ""); - PUT_PART(buffer); - escaped = NET_EscapeHTML(address); - PUT_PART(escaped); - PR_Free(escaped); - PL_strcpy(buffer, ""); - PUT_PART(buffer); - TABLE_BOTTOM; - - TABLE_TOP( XP_GetString(MK_CACHE_CONTENT_LENGTH) ); - sprintf(buffer, "%lu", cache_obj->content_length); - PUT_PART(buffer); - TABLE_BOTTOM; - - if(cache_obj->content_length != cache_obj->real_content_length) - { - TABLE_TOP( XP_GetString(MK_CACHE_REAL_CONTENT_LENGTH) ); - sprintf(buffer, "%lu", cache_obj->real_content_length); - PUT_PART(buffer); - TABLE_BOTTOM; - } - - TABLE_TOP( XP_GetString(MK_CACHE_CONTENT_TYPE) ); - PUT_PART(cache_obj->content_type); - TABLE_BOTTOM; - - TABLE_TOP( XP_GetString(MK_CACHE_LOCAL_FILENAME) ); - PUT_PART(cache_obj->filename); - TABLE_BOTTOM; - - TABLE_TOP( XP_GetString(MK_CACHE_LAST_MODIFIED) ); - if(cache_obj->last_modified) - { - PUT_PART(ctime(&cache_obj->last_modified)); - } - else - { - PL_strcpy(buffer, "No date sent"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - - TABLE_TOP( XP_GetString(MK_CACHE_EXPIRES) ); - if(cache_obj->expires) - { - PUT_PART(ctime(&cache_obj->expires)); - } - else - { - PL_strcpy(buffer, "No expiration date sent"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - - if(long_form) - { - TABLE_TOP( XP_GetString(MK_CACHE_LAST_ACCESSED) ); - PUT_PART(ctime(&cache_obj->last_accessed)); - TABLE_BOTTOM; - - TABLE_TOP( XP_GetString(MK_CACHE_CHARSET) ); - if(cache_obj->charset) - { - PUT_PART(cache_obj->charset); - } - else - { - PL_strcpy(buffer, "iso-8859-1 (default)"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - - HG63287 - - TABLE_TOP( XP_GetString(MK_CACHE_USES_RELATIVE_PATH) ); - sprintf(buffer, "%s", cache_obj->is_relative_path ? - "TRUE" : "FALSE"); - PUT_PART(buffer); - TABLE_BOTTOM; - - TABLE_TOP( XP_GetString(MK_CACHE_FROM_NETSITE_SERVER) ); - sprintf(buffer, "%s", cache_obj->is_netsite ? - "TRUE" : "FALSE"); - PUT_PART(buffer); - TABLE_BOTTOM; - - TABLE_TOP( "Lock date:" ); - if(cache_obj->lock_date) - { - PUT_PART(ctime(&cache_obj->lock_date)); - } - else - { - PL_strcpy(buffer, "Not locked"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - } - - -#if 0 - /* end the table for this entry */ - PL_strcpy(buffer, "

"); - PUT_PART(buffer); -#else - PL_strcpy(buffer, "\n

\n"); - PUT_PART(buffer); -#endif - } - - - } - while(0 == (*cache_database->seq)(cache_database, &key, &data, R_NEXT)); - -END: - PR_Free(buffer); - if(cur_entry->status < 0) - (*stream->abort)(stream, cur_entry->status); - else - (*stream->complete)(stream); - - return; -} -#endif /* NU_CACHE */ - -#define SANE_BUFLEN 1024 - -#include "libmocha.h" - -NET_StreamClass * -NET_CloneWysiwygCacheFile(MWContext *window_id, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href) -#ifdef NU_CACHE -{ - /*PR_ASSERT(0);*/ /* I hate GOTOs == Lou's programming */ - return NULL; -} -#else -{ - char *filename; - PRCList *link; - CacheDataObject *data_object; - NET_StreamClass *stream; - XP_File fromfp; - int32 buflen, len; - char *buf; - int url_type = NET_URL_Type(URL_s->address); - XP_FileType mode = xpCache; - - if (url_type == MAILBOX_TYPE_URL || - url_type == IMAP_TYPE_URL || - url_type == POP3_TYPE_URL) - return NULL; - - filename = URL_s->cache_file; - if (!filename) - { - /* not hitting the cache -- check whether we're filling it */ - for (link = active_cache_data_objects.next; - link != &active_cache_data_objects; - link = link->next) - { - data_object = (CacheDataObject *)link; - if (data_object->URL_s == URL_s) - { - XP_FileFlush(data_object->fp); - filename = data_object->cache_object->filename; - goto found; - } - } - - /* try memory cache and local filesystem */ - stream = net_CloneWysiwygMemCacheEntry(window_id, URL_s, nbytes, - wysiwyg_url, base_href); - if (stream) - return stream; - return net_CloneWysiwygLocalFile(window_id, URL_s, nbytes, - wysiwyg_url, base_href); - } - else - { - /* - * If this is a local file URL_s->cache_file will have been - * set by the code in mkfile.c so that the stream is treated - * like a disk-cache stream. But, in this case, we care that - * they are different and need to preserve the fact that its - * a local file URL - */ - if(NET_IsLocalFileURL(URL_s->address)) - mode = xpURL; - } - -found: - fromfp = NET_XP_FileOpen(filename, mode, XP_FILE_READ_BIN); - if (!fromfp) - return NULL; - stream = LM_WysiwygCacheConverter(window_id, URL_s, wysiwyg_url, - base_href); - if (!stream) - { - NET_XP_FileClose(fromfp); - return 0; - } - buflen = stream->is_write_ready(stream); - if (buflen > SANE_BUFLEN) - buflen = SANE_BUFLEN; - buf = (char *)PR_Malloc(buflen * sizeof(char)); - if (!buf) - { - NET_XP_FileClose(fromfp); - return 0; - } - while (nbytes != 0) - { - len = buflen; - if ((uint32)len > nbytes) - len = (int32)nbytes; - len = NET_XP_FileRead(buf, len, fromfp); - if (len <= 0) - break; - if (stream->put_block(stream, buf, len) < 0) - break; - nbytes -= len; - } - PR_Free(buf); - NET_XP_FileClose(fromfp); - if (nbytes != 0) - { - /* NB: Our caller must clear top_state->mocha_write_stream. */ - stream->abort(stream, MK_UNABLE_TO_CONVERT); - PR_Free(stream); - return 0; - } - return stream; -} -#endif - -#ifdef NU_CACHE -PUBLIC PRBool -NET_IsURLInCache(const URL_Struct *URL_s) -{ - return CacheManager_Contains(URL_s->address); -} -#endif - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cache/mkcache.h b/mozilla/network/cache/mkcache.h deleted file mode 100644 index 94654f6a6a2..00000000000 --- a/mozilla/network/cache/mkcache.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKCACHE_H -#define MKCACHE_H - -#include "xp.h" - -#ifndef EXT_CACHE_H -#include "extcache.h" -#endif - -#ifndef NU_CACHE -/* trace variable for cache testing */ -extern PRBool NET_CacheTraceOn; -#endif /* This is handled by CacheTrace_Enable() and CacheTrace_IsEnabled() in the NU world */ - -PR_BEGIN_EXTERN_C -#ifndef NU_CACHE -/* public accessor function for netcaster */ -extern PRBool NET_CacheStore(net_CacheObject *cacheObject, URL_Struct *url_s, PRBool accept_partial_files); -#endif /* NU_CACHE */ - -PUBLIC int NET_FirstCacheObject(DBT *key, DBT *data); -PUBLIC int NET_NextCacheObject(DBT *key, DBT *data); -PUBLIC int32 NET_GetMaxDiskCacheSize(); - -PR_END_EXTERN_C - -#endif /* MKCACHE_H */ diff --git a/mozilla/network/cache/mkextcac.c b/mozilla/network/cache/mkextcac.c deleted file mode 100644 index 442d14e3ba5..00000000000 --- a/mozilla/network/cache/mkextcac.c +++ /dev/null @@ -1,1568 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* Created: Lou Montulli */ -/* Modifications/Additions: Gagan Saksena */ -/* Please leave outside of ifdef for windows precompiled headers. */ - -#ifdef MOZILLA_CLIENT - -#include "xp.h" -#include "mktrace.h" -#include "mkcache.h" -#include "glhist.h" -#include "xp_hash.h" -#include "xp_mcom.h" -#include "client.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "secnav.h" -#include "extcache.h" -#include "mkextcac.h" -#include "prmem.h" -#include "plstr.h" -#include "timing.h" -#include "net_xp_file.h" - -/* For 197 java hookup */ -#include "jri.h" - -#ifdef PROFILE -#pragma profile on -#endif - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_DATABASE_CANT_BE_VALIDATED_MISSING_NAME_ENTRY; -extern int XP_DB_SELECTED_DB_NAMED; -extern int XP_REQUEST_EXTERNAL_CACHE; - -PRIVATE XP_List * ext_cache_database_list = 0; -PRIVATE XP_Bool AtLeastOneOpenCache = FALSE; - - -/* ************************************ Defines ************************************** */ -#define SAR_CACHE_INFO_STRING "CACHE_ExternalSARCacheNameString" - -#define EXTCACHE 1 -#define SARCACHE 2 -#define SUCCESS 0 -#define FAILURE -1 -#define MIN_MAX_SIZE 1000 - -/* ************************************ Proto's ************************************** */ - -/* Modified existing functions to call these (read Cut n Paste with passed in args) */ -PRIVATE void cache_ReadCacheInfo(XP_File fp, XP_List **list_ptr, int type); -PRIVATE void cache_SaveCacheInfo(XP_File fp, XP_List *list_ptr, int type); -PRIVATE void cache_SaveSARCacheInfo(void); - -/* Newly written functions */ -PRIVATE int cache_PutSARCacheInfoIntoDB(ExtCacheDBInfo *db_info); -PRIVATE ExtCacheDBInfo * cache_GetSARCacheInfoFromDB(ExtCacheDBInfo *db_info); -MODULE_PRIVATE DBT * cache_ExtCacheDBInfoStructToDBData(ExtCacheDBInfo * old_obj); -MODULE_PRIVATE ExtCacheDBInfo * cache_DBDataToExtCacheDBInfoStruct(DBT * db_obj); -MODULE_PRIVATE void cache_freeExtCacheDBInfoObj (ExtCacheDBInfo * cache_obj); - -/* ************************************ Variables ************************************** */ -PRIVATE XP_List * SAR_cache_database_list = 0; -PRIVATE XP_Bool SARCacheIndexOpen = FALSE; - - -/* close an external cache - */ -PRIVATE void -net_CloseExtCacheFat(ExtCacheDBInfo *db_info) -{ - if(db_info->database) - { - (*db_info->database->close)(db_info->database); - db_info->database = 0; - } - -} - - -PRIVATE char * -net_GetExtCacheNameFromDB(ExtCacheDBInfo *db_info) -{ - DBT key; - DBT data; - - if(!db_info->database) - return NULL; - - key.data = EXT_CACHE_NAME_STRING; - key.size = PL_strlen(EXT_CACHE_NAME_STRING); - - if(0 == (*db_info->database->get)(db_info->database, &key, &data, 0)) - { - /* make sure it's a valid cstring */ - char *name = (char *)data.data; - if(name[data.size-1] == '\0') - return(PL_strdup(name)); - else - return(NULL); - } - - return(NULL); - -} - -/* read/open an External Cache File allocation table. - * - * Returns a True if successfully opened - * Returns False if not. - */ -PRIVATE XP_Bool -net_OpenExtCacheFat(MWContext *ctxt, ExtCacheDBInfo *db_info) -{ - char *slash; - char *db_name; - XP_Bool close_db=FALSE; - - if(!db_info->database) - { - /* @@@ add .db to the end of the files - */ - char* filename = WH_FilePlatformName(db_info->filename); - db_info->database = dbopen(filename, - O_RDONLY, - 0600, - DB_HASH, - 0); -#ifdef XP_PC -/* This is probably the last checkin into Akbar */ -/* What really needs to be fixed is that Warren's implementation */ -/* of WH_FilePlatformName needs to return a malloc'd string */ -/* Right now, on Mac & X, it does not. See xp_file.c */ - PR_FREEIF(filename); -#endif - if(!db_info->database) - return(FALSE); - else - AtLeastOneOpenCache = TRUE; - - StrAllocCopy(db_info->path, db_info->filename); - - /* figure out the path to the database */ -#ifdef XP_PC - slash = PL_strrchr(db_info->path, '\\'); -#elif defined(XP_MAC) - slash = PL_strrchr(db_info->path, '/'); -#else - slash = PL_strrchr(db_info->path, '/'); -#endif - - if(slash) - { - *(slash+1) = '\0'; - } - else - { - *db_info->path = '\0'; - } - - db_name = net_GetExtCacheNameFromDB(db_info); - - if(!db_name) - { - close_db = !FE_Confirm(ctxt, - XP_GetString( XP_DATABASE_CANT_BE_VALIDATED_MISSING_NAME_ENTRY ) ); - } - else if(PL_strcmp(db_name, db_info->name)) - { - char buffer[2048]; - - PR_snprintf(buffer, sizeof(buffer), - XP_GetString( XP_DB_SELECTED_DB_NAMED ), - db_name, db_info->name); - - close_db = !FE_Confirm(ctxt, buffer); - } - - if(close_db) - { - (*db_info->database->close)(db_info->database); - db_info->database = 0; - return(FALSE); - } - } - - return(TRUE); -} - - -PRIVATE void -net_SaveExtCacheInfo(void) -{ - XP_File fp; - XP_List *list_ptr; - - fp = NET_XP_FileOpen("", xpExtCacheIndex, XP_FILE_WRITE); - list_ptr = ext_cache_database_list; - - cache_SaveCacheInfo(fp, list_ptr, EXTCACHE); -} - -#define BUF_SIZE 2048 -PRIVATE void -net_ReadExtCacheInfo(void) -{ - XP_File fp; - - fp = NET_XP_FileOpen("", xpExtCacheIndex, XP_FILE_READ); - - cache_ReadCacheInfo(fp, &ext_cache_database_list, EXTCACHE); -} - -PRIVATE void -net_OpenExtCacheFATCallback(MWContext *ctxt, char * filename, void *closure) -{ - ExtCacheDBInfo *db_info = (ExtCacheDBInfo*)closure; - - if(!db_info || !filename) - return; - - StrAllocCopy(db_info->filename, filename); - - /* once we have the name try and open the - * cache fat - */ - if(net_OpenExtCacheFat(ctxt, db_info)) - { - AtLeastOneOpenCache = TRUE; - } - else - { - if(FE_Confirm(ctxt, "Unable to open External Cache. Try again?")) - { - /* try and open again */ - - FE_PromptForFileName (ctxt, /* context */ - db_info->name, /* prompt string */ - db_info->filename, /* default file/path */ - TRUE, /* file must exist */ - FALSE, /* directories allowed */ - net_OpenExtCacheFATCallback, /* callback */ - (void *)db_info); /* closure */ - - - return; /* don't save ExtCache info */ - } - } - - net_SaveExtCacheInfo(); -} - -PUBLIC void -NET_OpenExtCacheFAT(MWContext *ctxt, char * cache_name, char * instructions) -{ - ExtCacheDBInfo *db_info=0, *db_ptr; - XP_Bool done = FALSE; - XP_List *list_ptr; - - if(!ext_cache_database_list) - { - net_ReadExtCacheInfo(); - if(!ext_cache_database_list) - return; - } - - /* look up the name in a list and open the file - * if it's not open already - */ - list_ptr = ext_cache_database_list; - while((db_ptr = (ExtCacheDBInfo *)XP_ListNextObject(list_ptr)) != NULL) - { - if(db_ptr->name && !PL_strcmp(db_ptr->name, cache_name)) - { - db_info = db_ptr; - break; - } - } - - if(!db_info) - { - db_info = PR_NEW(ExtCacheDBInfo); - if(!db_info) - return; - memset(db_info, 0, sizeof(ExtCacheDBInfo)); - StrAllocCopy(db_info->name, cache_name); - - XP_ListAddObject(ext_cache_database_list, db_info); - } - else if(db_info->queried_this_session) - { - /* don't query or try and open again. - */ - return; - } - - if(db_info->filename) - { - done = net_OpenExtCacheFat(ctxt, db_info); - - if(done) - { - char buffer[1024]; - - PR_snprintf(buffer, sizeof(buffer), - "Now using external cache: %.900s", - db_info->name); - if(!FE_Confirm(ctxt, buffer)) - net_CloseExtCacheFat(db_info); - } - } - - /* If we don't have the correct filename, query the - * user for the name - */ - if(!done) - { - - if(instructions) - done = !FE_Confirm(ctxt, instructions); - else - done = !FE_Confirm(ctxt, XP_GetString( XP_REQUEST_EXTERNAL_CACHE ) ); - - if(!done) - FE_PromptForFileName (ctxt, /* context */ - db_info->name, /* prompt string */ - db_info->filename, /* default file/path */ - TRUE, /* file must exist */ - FALSE, /* directories allowed */ - net_OpenExtCacheFATCallback, /* callback */ - (void *)db_info); /* closure */ - } - - db_info->queried_this_session = TRUE; - - return; -} - -/* lookup routine - * - * builds a key and looks for it in - * the database. Returns an access - * method and sets a filename in the - * URL struct if found - */ -MODULE_PRIVATE int -NET_FindURLInExtCache(URL_Struct * URL_s, MWContext *ctxt) -{ - return CACHE_FindURLInCache(URL_s, ctxt); -} - -/* **************************************************************************************************************************** - * Exposed Navigator Cache Calls - * ****************************************************************************************************************************/ - -/* - * allows java to enumerate through all of the managed cache - */ -PUBLIC XP_List * -CACHE_GetManagedCacheList() -{ - XP_File fp; - - /* If the Cache Index is not open, we can not see if the cache is open now can we */ - if (!SARCacheIndexOpen) - { - fp = NET_XP_FileOpen("", xpSARCacheIndex, XP_FILE_READ); - - /* check to see if the open succeeds */ - if (fp) - { - cache_ReadCacheInfo(fp, &SAR_cache_database_list, SARCACHE); - SARCacheIndexOpen = TRUE; - } - else - return NULL; - } - - return SAR_cache_database_list; -} - - -MODULE_PRIVATE void -CACHE_CloseAllOpenSARCache() -{ - ExtCacheDBInfo * db_info; - XP_StatStruct stat_entry; - - if (!SARCacheIndexOpen) return; - - if (!SAR_cache_database_list) return; - - while(NULL != (db_info = (ExtCacheDBInfo *)XP_ListNextObject(SAR_cache_database_list))) - { - CACHE_CloseCache(db_info); - - if ( db_info->logFile ) - NET_XP_FileClose(db_info->logFile); - - /* stat the db file to see if it exists, if it doesn't remove it from */ - /* the archive.fat file to keep things consistent */ - if(db_info->filename && (NET_XP_Stat(db_info->filename, &stat_entry, xpSARCache) == -1) ) - { - /* file does not exist!! - * remove the entry - */ - TRACEMSG(("Error! Cache db file missing: %s", db_info->filename)); - - if ( NULL != SAR_cache_database_list->prev ) - SAR_cache_database_list = SAR_cache_database_list->prev; - - XP_ListRemoveObject(SAR_cache_database_list, db_info); - } - cache_freeExtCacheDBInfoObj(db_info); - } - - cache_SaveSARCacheInfo(); - - SAR_cache_database_list = 0; - SARCacheIndexOpen = FALSE; -} - -MODULE_PRIVATE void -CACHE_OpenAllSARCache() -{ - XP_File fp; - XP_List *tmpList; - ExtCacheDBInfo *db_info, - *tmpDB_info; - char * filename, /* The platform specific filename returned by WH_PlatformFileName */ - * tmpName; /* The filename returned by WH_FileName */ - - if (!SARCacheIndexOpen) - { - fp = NET_XP_FileOpen("", xpSARCacheIndex, XP_FILE_READ); - - /* check to see if the open succeeds */ - if (fp) - cache_ReadCacheInfo(fp, &SAR_cache_database_list, SARCACHE); - else - return; - } - - SARCacheIndexOpen = TRUE; - - if (!SAR_cache_database_list) return; - - tmpList = SAR_cache_database_list; - while(NULL != (db_info = (ExtCacheDBInfo *)XP_ListNextObject(tmpList))) - { - if ( !db_info->database ) - { - tmpName = WH_FileName(db_info->filename, xpSARCache); - filename = WH_FilePlatformName(tmpName); - - /* Open or create the db file they specified */ - db_info->database = dbopen(filename, - O_RDWR | O_CREAT, - 0600, - DB_HASH, - 0); - - /* check to see if the dbopen failed */ - if ( NULL == db_info->database ) - { - CACHE_CloseCache(db_info); - PR_FREEIF(db_info); - db_info = NULL; - } - - /* Do stuff to get the type, and name */ - tmpDB_info = cache_GetSARCacheInfoFromDB(db_info); - - if ( !tmpDB_info ) return; - - /* Since they can access this one, fill in the cache name value */ - db_info->DiskCacheSize = tmpDB_info->DiskCacheSize; - db_info->NumberInDiskCache = tmpDB_info->NumberInDiskCache; - db_info->MaxSize = tmpDB_info->MaxSize; - db_info->name = PL_strdup(tmpDB_info->name); - db_info->logFile = NULL; - - cache_freeExtCacheDBInfoObj(tmpDB_info); -#ifdef XP_PC - PR_FREEIF(filename); -#endif - } - } - -} - - -/* - * Closes the cache db - */ -PUBLIC int -CACHE_CloseCache(ExtCacheDBInfo *db) -{ - /* If there is no Cache Struct return */ - if (!db) return 0; - - /* If there is no db return */ - if (!db->database) return 0; - - if(-1 == (*db->database->close)(db->database)) - { - TRACEMSG(("Error closing cache database")); - - return 0; - } - - db->database = 0; - - return SUCCESS; -} - -/* - * Closes the cache db - */ -PUBLIC void -CACHE_UpdateCache(ExtCacheDBInfo *db) -{ - if ( db ) - cache_PutSARCacheInfoIntoDB(db); -} - - -/* - * Returns a handle to the desired persitent cache, - * It also adds this newly opened cache to the list - * of opened caches - */ -PUBLIC ExtCacheDBInfo * -CACHE_GetCache(ExtCacheDBInfo *db) -{ - XP_File fp; - char * filename, /* The platform specific filename returned by WH_PlatformFileName */ - * tmpName; /* The filename returned by WH_FileName */ - - ExtCacheDBInfo *db_info, - *tmpDB_info; - XP_Bool inIndex = FALSE, - add2Index = FALSE; - XP_List *tmpList; - uint32 maxSize; - - /* If there is no Cache Struct return */ - if (!db) return NULL; - -/* ************************************************************************************************** - This is a hack. It is a temp fix for bug 69098. The plan is to go with this for 4.0 and - do the right thing in 4.1 -************************************************************************************************** */ - if ( -1 == db->type ) { - tmpName = WH_FileName(db->filename, xpSARCache); -#ifndef XP_MAC - filename = WH_FilePlatformName(tmpName); -#else - filename = tmpName; -#endif - - /* Open or create the db file they specified */ - db->database = dbopen(filename, - O_RDWR | O_CREAT, - 0600, - DB_HASH, - 0); - return db; - } -/* ************************************************************************************************** - The above was a hack. -************************************************************************************************** */ - - - /* Set up the max size for the cache */ - if (db->MaxSize < 0) { - maxSize = NET_GetDiskCacheSize(); - - if (maxSize < MIN_MAX_SIZE) - maxSize = MIN_MAX_SIZE; - } - else { - maxSize = db->MaxSize; - } - - /* Kludge to prevent NULL writes to the Cache Index */ - if ( db->path == NULL || *(db->path) == '\0' || *(db->path) == ' ') - { - db->path = PL_strdup("\\"); - } - - /* If the Cache Index is not open, we can not see if the cache is open now can we */ - if (!SARCacheIndexOpen) - { - fp = NET_XP_FileOpen("", xpSARCacheIndex, XP_FILE_READ); - - /* check to see if the open succeeds */ - if (fp) - cache_ReadCacheInfo(fp, &SAR_cache_database_list, SARCACHE); - else - { - /* I guess the index isn't there, let's make a new one */ - SAR_cache_database_list = XP_ListNew(); - if(!SAR_cache_database_list) - return NULL; - - /* set the db_info values here since they will not be retrieved later */ - db_info = (ExtCacheDBInfo *)PR_Malloc(sizeof(ExtCacheDBInfo)); - db_info->name = PL_strdup(db->name); - db_info->filename = PL_strdup(db->filename); - db_info->path = PL_strdup(db->path); - db_info->queried_this_session = FALSE; - db_info->type = db->type; - db_info->database = NULL; - db_info->DiskCacheSize = 0; - db_info->NumberInDiskCache = 0; - db_info->MaxSize = maxSize; - db_info->logFile = NULL; - - add2Index = TRUE; - } - SARCacheIndexOpen = TRUE; - } - - if (!SAR_cache_database_list) return NULL; - - /* If I have to add it, I already know it's not there */ - if ( !add2Index ) - { - tmpList = SAR_cache_database_list; - while( NULL != (db_info = (ExtCacheDBInfo *)XP_ListNextObject(tmpList))) - { - if(!PL_strcmp(db->filename, db_info->filename) ) /* && !PL_strcmp(db->path, db_info->path) ) */ - { - inIndex = TRUE; - break; - } - } - } - - if (!inIndex && !add2Index) - { - /* We know nothing about this cache so add it */ - db_info = (ExtCacheDBInfo *)PR_Malloc(sizeof(ExtCacheDBInfo)); - db_info->name = PL_strdup(db->name); - db_info->filename = PL_strdup(db->filename); - db_info->path = PL_strdup(db->path); - db_info->queried_this_session = FALSE; - db_info->type = db->type; - db_info->database = NULL; - db_info->DiskCacheSize = 0; - db_info->NumberInDiskCache = 0; - db_info->MaxSize = maxSize; - db_info->logFile = NULL; - - add2Index = TRUE; - } - else - { - /* if it is already open I am going to return the handle to it, - if it is not open I will return NULL since we have a name conflict */ - if ((db_info!= NULL) && (db_info->database)) - { - /* Do the meager name check to see if they can access this cache */ - if ( PL_strcmp(db->name, db_info->name) ) - { - db_info = NULL; - } - - return db_info; - } - } - - tmpName = WH_FileName(db->filename, xpSARCache); -#ifndef XP_MAC - filename = WH_FilePlatformName(tmpName); -#else - filename = tmpName; -#endif - - if (!db_info) - return NULL ; - - /* Open or create the db file they specified */ - db_info->database = dbopen(filename, - O_RDWR | O_CREAT, - 0600, - DB_HASH, - 0); - - /* check to see if the dbopen failed */ - if ( NULL == db_info->database ) - { - CACHE_CloseCache(db_info); - PR_FREEIF(db_info); - - db_info = NULL; - - return NULL; - } - - /* Do stuff to get the type, and name */ - tmpDB_info = cache_GetSARCacheInfoFromDB(db_info); - - /* If tmpDB_info doesn't exist then this is a new cache */ - if ( !tmpDB_info ) - { - /* Since they can access this one, fill in the cache name value before it is saved */ - db_info->name = PL_strdup(db->name); - cache_PutSARCacheInfoIntoDB(db_info); - } - else - { - /* Do the meager name check to see if they can access this cache */ - if ( PL_strcmp(db->name, tmpDB_info->name) ) - { - CACHE_CloseCache(db_info); - PR_FREEIF(db_info); - - db_info = NULL; - } - else - { - /* Since they can access this one, fill in the cache name value */ - db_info->name = PL_strdup(db->name); - db_info->DiskCacheSize = tmpDB_info->DiskCacheSize; - db_info->NumberInDiskCache = tmpDB_info->NumberInDiskCache; - db_info->MaxSize = maxSize; - db_info->logFile = NULL; - } - - cache_freeExtCacheDBInfoObj(tmpDB_info); - } - - if ( add2Index ) - { - /* Since this is not in the index, add it */ - XP_ListAddObject(SAR_cache_database_list, db_info); - cache_SaveSARCacheInfo(); - } - - /* This might cause problems for FileName routins - PR_FREEIF(tmpName); - */ -#ifdef XP_PC - PR_FREEIF(filename); -#endif - - if (db_info != NULL) - db_info->type = db->type; - - /* free the struct they passed in, and have it point to the new - * struct we will be using. - */ - PR_FREEIF(db); - db = db_info; - - return db_info; -} - -PUBLIC XP_Bool -CACHE_Put(char *filename, URL_Struct *url_s) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Should not be getting called */ - return FALSE; -} -#else -{ - net_CacheObject *cacheObject = PR_NEW(net_CacheObject); - memset(cacheObject, 0, sizeof(net_CacheObject)); - - cacheObject->last_modified = url_s->last_modified; - cacheObject->content_length = url_s->content_length; - StrAllocCopy(cacheObject->filename, filename); - cacheObject->is_relative_path = TRUE; - StrAllocCopy(cacheObject->address, url_s->address); - StrAllocCopy(cacheObject->content_type, url_s->content_type); - - return NET_CacheStore(cacheObject, url_s, FALSE); -} -#endif /* NU_CACHE */ - -PUBLIC char * -CACHE_GetCachePath(char * name) -{ - char * tmpName, * filename; - - tmpName = WH_FileName(name, xpSARCache); - filename = WH_FilePlatformName(tmpName); - - return filename; -} - - -PUBLIC ExtCacheDBInfo * -CACHE_GetCacheStruct(char * path, char * filename, char * name) -{ - ExtCacheDBInfo * db_info; - XP_List *tmpList; - - tmpList = SAR_cache_database_list; - while( NULL != (db_info = (ExtCacheDBInfo *)XP_ListNextObject(tmpList))) - { - if(!PL_strcmp(path, db_info->path) && !PL_strcmp(filename, db_info->filename) && !PL_strcmp(name, db_info->name) ) - { - return db_info; - } - } - - return NULL; -} - -/* - * New Cache version to allow for different files, and cache lists - */ -PRIVATE void -cache_SaveCacheInfo(XP_File fp, XP_List *list_ptr, int type) -{ - ExtCacheDBInfo *db_info; - int32 len = 0; - - if(!list_ptr) - return; - - if(!fp) - return; - - len = NET_XP_FileWrite("# Netscape External Cache Index" LINEBREAK - "# This is a generated file! Do not edit." LINEBREAK - LINEBREAK, - -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - return; - } - - /* file format is: - * Filename database_name - */ - while((db_info = (ExtCacheDBInfo *)XP_ListNextObject(list_ptr)) != NULL) - { - - if( !db_info->filename && ( (type == EXTCACHE && !db_info->name) || (type == SARCACHE && !db_info->path) ) ) - continue; - - len = NET_XP_FileWrite(db_info->filename, -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - return; - } - NET_XP_FileWrite("\t", -1, fp); - - if ( type == EXTCACHE ) - NET_XP_FileWrite(db_info->name, -1, fp); - else - { - if ( db_info->path == NULL || *(db_info->path) == '\0' || *(db_info->path) == ' ') - { - NET_XP_FileWrite("\\", -1, fp); - } - else - { - NET_XP_FileWrite(db_info->path, -1, fp); - } - } - - len = NET_XP_FileWrite(LINEBREAK, -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - return; - } - } - - NET_XP_FileClose(fp); -} - -PRIVATE void -cache_SaveSARCacheInfo(void) -{ - XP_File fp; - XP_List *list_ptr; - - fp = NET_XP_FileOpen("", xpSARCacheIndex, XP_FILE_WRITE); - list_ptr = SAR_cache_database_list; - - cache_SaveCacheInfo(fp, list_ptr, SARCACHE); -} - -/* - * New Cache version to allow for different files, and cache lists - */ -PRIVATE void -cache_ReadCacheInfo(XP_File fp, XP_List **list_ptr, int type) -{ - ExtCacheDBInfo *new_db_info; - char buf[BUF_SIZE]; - char *name; - - if(!*list_ptr) - { - *list_ptr = XP_ListNew(); - if(!*list_ptr) - return; - } - - if(!fp) - return; - - /* file format is: - * Filename database_name - */ - while(NET_XP_FileReadLine(buf, BUF_SIZE-1, fp)) - { - if (*buf == 0 || *buf == '#' || *buf == CR || *buf == LF) - continue; - - /* remove /r and /n from the end of the line */ - XP_StripLine(buf); - - name = PL_strchr(buf, '\t'); - - if(!name) - continue; - - *name++ = '\0'; - - new_db_info = PR_NEW(ExtCacheDBInfo); - if(!new_db_info) - return; - - memset(new_db_info, 0, sizeof(ExtCacheDBInfo)); - - StrAllocCopy(new_db_info->filename, buf); - - if ( type == EXTCACHE ) - StrAllocCopy(new_db_info->name, name); - else - StrAllocCopy(new_db_info->path, name); - - XP_ListAddObject(*list_ptr, new_db_info); - } - - NET_XP_FileClose(fp); -} - -/* - * Delete the specified cache and all the files in it. - */ -PUBLIC int CACHE_EmptyCache(ExtCacheDBInfo *db) -{ - DBT data; - DBT key; - int ret; - char *filename; - -#ifdef DEBUG_francis - printf("CACHE_EmptyCache()\n"); -#endif - - ret = (*db->database->seq)(db->database, &key, &data, R_FIRST); - - if( 0 != ret ) - { -#ifdef DEBUG_francis - printf("CACHE_EmptyCache(): 0 != ret\n"); -#endif - - return 0; - } - - do - { - filename = net_GetFilenameInCacheDBT(&data); - if(filename) - { -#ifdef DEBUG_francis - printf("CACHE_EmptyCache(): removing %s\n",filename); -#endif - - TRACEMSG(("Removing file: %s due to disk" - " cache remove",filename)); - NET_XP_FileRemove(filename, xpSARCache); /* *X* What will happen if I pass this */ - PR_Free(filename); /* a relative path */ - } - } - while(0 == (*db->database->seq)(db->database, &key, &data, R_NEXT)); - - db->DiskCacheSize = 0; - db->NumberInDiskCache = 0; - -#ifdef DEBUG_francis - printf("CACHE_EmptyCache(): success\n"); -#endif - - - return SUCCESS; -} - -/* - * Delete the specified cache and all the files in it. - */ -PUBLIC int CACHE_RemoveCache(ExtCacheDBInfo *db) -{ - int ret = 0; - ExtCacheDBInfo *db_info; - XP_List *tmpList; - - /* See if the database is open */ - if (!db->database) return 0; - - CACHE_EmptyCache(db); - CACHE_CloseCache(db); - - /* Find the database object in my internal list */ - tmpList = SAR_cache_database_list; - while(NULL != (db_info = (ExtCacheDBInfo *)XP_ListNextObject(tmpList))) - { - if(!PL_strcmp(db->path, db_info->path) && !PL_strcmp(db->filename, db_info->filename)) break; - } - - /* Remove the cache from SAR_cache_database_list */ - if ( XP_ListRemoveObject(SAR_cache_database_list, db_info) ) - ret = NET_XP_FileRemove(db->filename, xpSARCache); - - /* This was released in the call to CACHE_CloseCache above */ - db_info->database = 0; - - cache_freeExtCacheDBInfoObj(db_info); - - cache_SaveSARCacheInfo(); - - return ret; -} - -MODULE_PRIVATE int -CACHE_FindURLInCache(URL_Struct *URL_s, MWContext *ctxt) -{ - DBT *key; - DBT data; - net_CacheObject *found_cache_obj; - ExtCacheDBInfo *db_ptr; - int status; - XP_StatStruct stat_entry; - char *filename=0; - XP_List *list_ptr; - - /* larubbio */ - XP_FileType fileType = (XP_FileType)0; - - TRACEMSG(("Checking for URL in external cache")); - - /* zero the last modified date so that we don't - * screw up the If-modified-since header by - * having it in even when the document isn't - * cached. - */ - URL_s->last_modified = 0; - - if(!AtLeastOneOpenCache && !SARCacheIndexOpen) - { - TRACEMSG(("No External Cache databases open")); - return(0); - } - - key = net_GenCacheDBKey(URL_s->address, - URL_s->post_data, - URL_s->post_data_size); - - status = 1; - - /* Search the external caches first */ - if (AtLeastOneOpenCache) - { - list_ptr = ext_cache_database_list; - while((db_ptr = (ExtCacheDBInfo *)XP_ListNextObject(list_ptr)) != NULL) - { - if(db_ptr->database) - { - TRACEMSG(("Searching databse: %s", db_ptr->name)); - status = (*db_ptr->database->get)(db_ptr->database, key, &data, 0); - if(status == 0) - { - fileType = xpExtCache; - break; - } - } - } - } - - /* Search the SAR caches next */ - if (SARCacheIndexOpen && status != 0) - { - list_ptr = SAR_cache_database_list; - while((db_ptr = (ExtCacheDBInfo *)XP_ListNextObject(list_ptr)) != NULL) - { - if(db_ptr->database) - { - TRACEMSG(("Searching databse: %s", db_ptr->name)); - status = (*db_ptr->database->get)(db_ptr->database, key, &data, 0); - if(status == 0) - { - time_t cur_time = time(NULL); - - /* - * larubbio: If were here, then the file must have - * been found in an external (CD or archive) cache. - * In order to prevent unnecessary network refresh, - * override the network check if the file has - * not already expired out of the cache and the call - * isnt being made from Java (so its not the Netcaster - * crawler). - */ - if( (NULL == URL_s->SARCache) && - ( (0 == URL_s->expires) || (cur_time < URL_s->expires) )) - URL_s->use_local_copy = 1; - - fileType = xpSARCache; - URL_s->SARCache = db_ptr; - break; - } - } - } - } - - if(status != 0) - { - TRACEMSG(("Key not found in any database")); - net_FreeCacheDBTdata(key); - return(0); - } - - found_cache_obj = net_Fast_DBDataToCacheStruct(&data); - - TRACEMSG(("mkextcache: found URL in cache!")); - - if(!found_cache_obj) - return(0); - - /* copy in the cache file name - */ - if(db_ptr->path -#if REAL_TIME /* use this for real */ - && found_cache_obj->is_relative_path -#endif - ) - { - if ( PL_strcmp(db_ptr->path, "\\" ) ) - StrAllocCopy(filename, db_ptr->path); - - StrAllocCat(filename, found_cache_obj->filename); - } - else - { - StrAllocCopy(filename, found_cache_obj->filename); - } - - /* make sure the file still exists - * Looks like the new cache is ok since xpExtCache tells NET_XP_Stat to use it's default - * settings, which is what we want so I won't touch it. - */ - if(NET_XP_Stat(filename, &stat_entry, fileType) == -1) - { - /* file does not exist!! - * remove the entry - */ - TRACEMSG(("Error! Cache file missing: %s", filename)); - - net_FreeCacheDBTdata(key); - - PR_Free(filename); - - return(0); - - } - - /* - * if the last accessed date is before the startup date set the - * expiration date really low so that the URL is forced to be rechecked - * again. We don't just not return the URL as being in the - * cache because we want to use "If-modified-since" - * - * This works correctly because mkhttp will zero the - * expires field. - * - * if it's not an http url then just delete the entry - * since we can't do an If-modified-since - */ - - /* since we can't set a last accessed time - * we can't do the once per session thing. - * Always assume EVERY TIME - * - * if(found_cache_obj->last_accessed < NET_StartupTime - * && NET_CacheUseMethod != CU_NEVER_CHECK) - */ - if(URL_s->use_local_copy || URL_s->history_num) - { - /* we already did an IMS get or it's coming out - * of the history. - * Set the expires to 0 so that we can now use the - * object - */ - URL_s->expires = 0; - } - - else if(NET_CacheUseMethod != CU_NEVER_CHECK) - { - if(!PL_strncasecmp(URL_s->address, "http", 4)) - { -#ifdef MOZ_OFFLINE - if ( NET_IsOffline() ) - { - time_t cur_time = time(NULL); - - if ( (0 == URL_s->expires) || (cur_time < URL_s->expires) ) - URL_s->use_local_copy = 1; - } -#endif /* MOZ_OFFLINE */ - } - else - { - /* object has expired and cant use IMS. Don't return it */ - - net_FreeCacheDBTdata(key); - PR_Free(filename); - - return(0); - } - } - else - { - /* otherwise use the normal expires date for CU_NEVER_CHECK */ - URL_s->expires = found_cache_obj->expires; - } - - /* won't need the key anymore */ - net_FreeCacheDBTdata(key); - - URL_s->cache_file = filename; - - /* copy the contents of the URL struct so that the content type - * and other stuff gets recorded - */ - StrAllocCopy(URL_s->content_type, found_cache_obj->content_type); - StrAllocCopy(URL_s->charset, found_cache_obj->charset); - StrAllocCopy(URL_s->content_encoding, found_cache_obj->content_encoding); - URL_s->content_length = found_cache_obj->content_length; - URL_s->real_content_length = found_cache_obj->real_content_length; - URL_s->last_modified = found_cache_obj->last_modified; - URL_s->is_netsite = found_cache_obj->is_netsite; - - /* copy security info */ - URL_s->security_on = found_cache_obj->security_on; - URL_s->sec_info = SECNAV_CopySSLSocketStatus(found_cache_obj->sec_info); - - TIMING_MESSAGE(("cache,%s,on disk", URL_s->address)); - TRACEMSG(("Cached copy is valid. returning method")); - - TRACEMSG(("Using Disk Copy")); - - URL_s->ext_cache_file = TRUE; - - return(FILE_CACHE_TYPE_URL); -} - - - /* free the cache object - */ -MODULE_PRIVATE void cache_freeExtCacheDBInfoObj (ExtCacheDBInfo * cache_obj) -{ - - PR_FREEIF(cache_obj->database); - PR_FREEIF(cache_obj->filename); - PR_FREEIF(cache_obj->path); - PR_FREEIF(cache_obj->name); - - PR_Free(cache_obj); -} - - -PRIVATE ExtCacheDBInfo * -cache_GetSARCacheInfoFromDB(ExtCacheDBInfo *db_info) -{ - DBT key; - DBT data; - - if(!db_info->database) - return NULL; - - key.data = SAR_CACHE_INFO_STRING; - key.size = PL_strlen(SAR_CACHE_INFO_STRING); - - if(0 == (*db_info->database->get)(db_info->database, &key, &data, 0)) - { - /* convert it to a struct */ - return cache_DBDataToExtCacheDBInfoStruct(&data); - } - - return(NULL); -} - -/* Flushes the DB's contents to disk */ -PUBLIC void -CACHE_FlushCache(ExtCacheDBInfo *db_info) -{ - (*db_info->database->sync)(db_info->database, 0); -} - -PUBLIC void -CACHE_SaveCacheInfoToDB(ExtCacheDBInfo *db_info) -{ - cache_PutSARCacheInfoIntoDB(db_info); -} - -PRIVATE int -cache_PutSARCacheInfoIntoDB(ExtCacheDBInfo *db_info) -{ - DBT key; - DBT * data; - - if(!db_info->database) - return 0; - - key.data = SAR_CACHE_INFO_STRING; - key.size = PL_strlen(SAR_CACHE_INFO_STRING); - - data = cache_ExtCacheDBInfoStructToDBData(db_info); - - if(0 == (*db_info->database->put)(db_info->database, &key, data, 0)) - { - /* Flush the db to disk */ - (*db_info->database->sync)(db_info->database, 0); - return(SUCCESS); - } - - return 0; -} - -/* takes a cache object and returns a malloc'd - * (void *) suitible for passing in as a database - * data storage object - */ -MODULE_PRIVATE DBT * -cache_ExtCacheDBInfoStructToDBData(ExtCacheDBInfo * old_obj) -{ - int32 len; - char *cur_ptr; - void *new_obj; - int32 total_size; - DBT *rv; - - rv = PR_NEW(DBT); - - if(!rv) - return(NULL); - - total_size = sizeof(ExtCacheDBInfo); - -#define ADD_STRING_SIZE(string) \ -total_size += old_obj->string ? PL_strlen(old_obj->string)+1 : 0 - - total_size += sizeof(NULL); - ADD_STRING_SIZE(filename); - ADD_STRING_SIZE(path); - ADD_STRING_SIZE(name); - total_size += sizeof(XP_Bool); - total_size += sizeof(uint32); - total_size += sizeof(uint32); - total_size += sizeof(uint32); - total_size += sizeof(uint32); - -#undef ADD_STRING_SIZE - - new_obj = PR_Malloc(total_size * sizeof(char)); - - if(!new_obj) - { - PR_Free(rv); - return NULL; - } - - memset(new_obj, 0, total_size * sizeof(char)); - /* VERY VERY IMPORTANT. Whenever the - * format of the record structure changes - * you must verify that the byte positions - * in extcache.h are updated - */ - -#define STUFF_STRING(string) \ -{ \ - len = (old_obj->string ? PL_strlen(old_obj->string)+1 : 0); \ - COPY_INT32((void *)cur_ptr, &len); \ - cur_ptr = cur_ptr + sizeof(int32); \ - if(len) \ - memcpy((void *)cur_ptr, old_obj->string, len); \ - cur_ptr += len; \ -} - -#define STUFF_NUMBER(number) \ -{ \ - COPY_INT32((void *)cur_ptr, &old_obj->number); \ - cur_ptr = cur_ptr + sizeof(int32); \ -} - -#define STUFF_BOOL(bool_val) \ -{ \ - if(old_obj->bool_val) \ - ((char *)(cur_ptr))[0] = 1; \ - else \ - ((char *)(cur_ptr))[0] = 0; \ - cur_ptr = cur_ptr + sizeof(char); \ -} - - cur_ptr = (char *)new_obj; - - /* put the total size of the struct into - * the first field so that we have - * a cross check against corruption - */ - COPY_INT32((void *)cur_ptr, &total_size); - cur_ptr = cur_ptr + sizeof(int32); - - STUFF_STRING(filename); - STUFF_STRING(path); - STUFF_STRING(name); - STUFF_BOOL(queried_this_session); - STUFF_NUMBER(type); - STUFF_NUMBER(DiskCacheSize); - STUFF_NUMBER(NumberInDiskCache); - STUFF_NUMBER(MaxSize); - -#undef STUFF_STRING -#undef STUFF_NUMBER -#undef STUFF_BOOL - - rv->data = new_obj; - rv->size = total_size; - - return(rv); -} - -/* takes a database storage object and returns a malloc'd - * cache data object. The cache object needs all of - * it's parts free'd. - * - * returns NULL on parse error - */ -MODULE_PRIVATE ExtCacheDBInfo * -cache_DBDataToExtCacheDBInfoStruct(DBT * db_obj) -{ - ExtCacheDBInfo * rv = PR_NEW(ExtCacheDBInfo); - char * cur_ptr; - char * max_ptr; - uint32 len; - - if(!rv) - return NULL; - - memset(rv, 0, sizeof(ExtCacheDBInfo)); - -/* if any strings are larger than this then - * there was a serious database error - */ -#define MAX_HUGE_STRING_SIZE 10000 - -#define RETRIEVE_STRING(string) \ -{ \ - if(cur_ptr > max_ptr) \ - { \ - cache_freeExtCacheDBInfoObj(rv); \ - return(NULL); \ - } \ - COPY_INT32(&len, cur_ptr); \ - cur_ptr += sizeof(int32); \ - if(len) \ - { \ - if(len > MAX_HUGE_STRING_SIZE) \ - { \ - cache_freeExtCacheDBInfoObj(rv); \ - return(NULL); \ - } \ - rv->string = (char*)PR_Malloc(len); \ - if(!rv->string) \ - { \ - cache_freeExtCacheDBInfoObj(rv); \ - return(NULL); \ - } \ - memcpy(rv->string, cur_ptr, len); \ - cur_ptr += len; \ - } \ -} - -#define RETRIEVE_NUMBER(number) \ -{ \ - if(cur_ptr > max_ptr) \ - return(rv); \ - COPY_INT32(&rv->number, cur_ptr); \ - cur_ptr += sizeof(int32); \ -} - -#define RETRIEVE_BOOL(bool) \ -{ \ - if(cur_ptr > max_ptr) \ - return(rv); \ - if(((char *)(cur_ptr))[0]) \ - rv->bool = TRUE; \ - else \ - rv->bool = FALSE; \ - cur_ptr += sizeof(char); \ -} - - cur_ptr = (char *)db_obj->data; - - max_ptr = cur_ptr+db_obj->size; - - /* get the total size of the struct out of - * the first field to check it - */ - COPY_INT32(&len, cur_ptr); - cur_ptr += sizeof(int32); - - if(len != db_obj->size) - { - TRACEMSG(("Size going in is not the same as size coming out")); - PR_Free(rv); - return(NULL); - } - - RETRIEVE_STRING(filename); - RETRIEVE_STRING(path); - RETRIEVE_STRING(name); - RETRIEVE_BOOL(queried_this_session); - RETRIEVE_NUMBER(type); - RETRIEVE_NUMBER(DiskCacheSize); - RETRIEVE_NUMBER(NumberInDiskCache); - RETRIEVE_NUMBER(MaxSize); - - return(rv); -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cache/mkextcac.h b/mozilla/network/cache/mkextcac.h deleted file mode 100644 index 6862ea9b59d..00000000000 --- a/mozilla/network/cache/mkextcac.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKEXTCACHE_H -#define MKEXTCACHE_H - -PUBLIC void NET_OpenExtCacheFAT(MWContext *ctxt, char * cache_name, char * instructions); -MODULE_PRIVATE int NET_FindURLInExtCache(URL_Struct * URL_s, MWContext *ctxt); -MODULE_PRIVATE void CACHE_CloseAllOpenSARCache(); -MODULE_PRIVATE void CACHE_OpenAllSARCache(); - -#endif /* MKEXTCACHE_H */ diff --git a/mozilla/network/cache/mkmemcac.c b/mozilla/network/cache/mkmemcac.c deleted file mode 100644 index bdd0c7adb6f..00000000000 --- a/mozilla/network/cache/mkmemcac.c +++ /dev/null @@ -1,2324 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* Module to do memory caching; storage and retreival - * very simple hash table based scheme. - * - * designed and originally implemented by Lou Montulli - * modifications/additions by Gagan Saksena - */ - -/* Please leave outside of ifdef for windows precompiled headers */ -#include "rosetta.h" -#include "xp.h" - -#ifdef MOZILLA_CLIENT - -#include "mkcache.h" -#include "mkselect.h" -#include "netutils.h" -#include "mktcp.h" -#include "glhist.h" -#include "xp_hash.h" -#include "xp_mcom.h" -#include "client.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "extcache.h" -#include "mkmemcac.h" -extern void IL_SetCacheSize(uint32 new_size); -#include "prclist.h" -#include "prmem.h" -#include "plstr.h" -#include "shist.h" -#include "secnav.h" -#include "timing.h" - -#ifdef NU_CACHE -#include "CacheStubs.h" -#endif - -/* exported error ints */ -extern int MK_OUT_OF_MEMORY; - -/* the size of the cache segment output size - */ -#define NET_MEM_CACHE_OUTPUT_SIZE 2048 - -/* MAX_MEMORY_ALLOC_SIZE is the size of the largest malloc - * used in this module - * - * the NET_Socket_Buffer can never be larger than the - * MAX_MEMORY_ALLOC_SIZE or this will fail - */ -#ifdef XP_WIN16 -#define MAX_MEMORY_ALLOC_SIZE 32767 /* MAXINT */ -#elif defined(XP_MAC) -#define MAX_MEMORY_ALLOC_SIZE 64*1024 -#else -#define MAX_MEMORY_ALLOC_SIZE (((unsigned) (~0) << 1) >> 1) /* MAXINT */ - -/* @@@@@@@@@ there is currently a limit on PR_Malloc to less than 32 K */ -#undef MAX_MEMORY_ALLOC_SIZE -#define MAX_MEMORY_ALLOC_SIZE 32767 /* MAXINT */ -#endif - -/* this is the minimum size of each of the memory segments used to hold - * the cache object in memory - */ -#ifdef XP_MAC -#define MEMORY_CACHE_SEGMENT_SIZE 64*1024 -#else -#define MEMORY_CACHE_SEGMENT_SIZE 2048 -#endif - -/* !!! structure is typedef'd to net_MemoryCacheObject - * in net.h - */ -struct _net_MemoryCacheObject { - XP_List *list; - net_CacheObject cache_obj; - int external_locks; /* locks set by other modules calling in */ - int mem_read_lock; /* the number of current readers */ - XP_Bool delete_me; /* set this to delete the object - * once all readers are done - */ - XP_Bool current_page_only; /* this is set when the document - * requested not to be cached. - * When set the document should - * only be served if it's a - * resize or print - */ - XP_Bool completed; /* whether or not we have completed the - * caching of this object. Initialized to - * false, then set to true once the - * complete function is called. - */ - XP_Bool aborted; /* whether or not we have aborted the - * caching of this object. - */ -}; - -/* structure to hold memory - * segments - */ -typedef struct _net_MemorySegment { - char *segment; - uint32 seg_size; - uint32 in_use; -} net_MemorySegment; - -/* the hash table pointer that holds all the memory cache - * objects for quick lookup - */ -PRIVATE XP_HashList * net_MemoryCacheHashList = 0; - -/* semaphore counter set when calling any of the list add functions - */ -PRIVATE int net_cache_adding_object=0; - -/* a list of all the documents currently in - * memory - * - * The net_MemoryCacheList is used as a delete queue - * and is ordered by last-accessed time. - */ -PRIVATE XP_List *net_MemoryCacheList=0; -PRIVATE uint32 net_MemoryCacheSize=0; -PRIVATE uint32 net_MaxMemoryCacheSize=0; - -/* this object is used by the MemCacheConverter. - * MemCacheConverter is a standard netlib stream and uses - * this structure to hold data between invokations of - * the write function and complete or abort. - */ -typedef struct _CacheDataObject { - PRCList links; - NET_StreamClass *next_stream; - net_MemoryCacheObject *memory_copy; - URL_Struct *URL_s; - uint32 computed_content_length; -} CacheDataObject; - -/* PRIVATE XXX Mac CodeWarrior bug */ PRCList mem_active_cache_data_objects - = PR_INIT_STATIC_CLIST(&mem_active_cache_data_objects); - -/* free a segmented memory copy of an object - * and the included net_cacheObject struct - */ -PRIVATE void -net_FreeMemoryCopy(net_MemoryCacheObject * mem_copy) -{ - net_MemorySegment * mem_seg; - - PR_ASSERT(mem_copy); - - if(!mem_copy) - return; - - /* If the stream was aborted while being written, and nobody is - * reading it, then it's ok to delete it now. That is, - * we don't need to check if we want to set delete_me - */ - if (!((mem_copy->mem_read_lock == 0) && mem_copy->aborted)) - { - /* if this object is currently being read or written DO NOT delete it. - * It will be deleted by another call to this function - * after it is finished being read. - */ - if (((mem_copy->mem_read_lock > 0) && mem_copy->completed) || - !mem_copy->completed) - { - TRACEMSG(("Seting delete_me flag on memory cache object")); - mem_copy->delete_me = TRUE; - - /* remove it from the hash list so it won't be found - * by NET_GetURLInMemCache - */ - XP_HashListRemoveObject(net_MemoryCacheHashList, mem_copy); - return; - } - } - - TRACEMSG(("Freeing memory cache copy")); - - /* free and delete the memory segment list - */ - while((mem_seg = (net_MemorySegment *)XP_ListRemoveTopObject(mem_copy->list)) != NULL) - { - /* reduce the global memory cache size - */ - net_MemoryCacheSize -= mem_seg->seg_size; - PR_Free(mem_seg->segment); - PR_Free(mem_seg); - } - - XP_ListDestroy(mem_copy->list); - - /* Remove it from the hash and delete lists, - * If the object isn't in these lists anymore - * the call will be ignored. - */ - XP_HashListRemoveObject(net_MemoryCacheHashList, mem_copy); - XP_ListRemoveObject(net_MemoryCacheList, mem_copy); - - PR_FREEIF(mem_copy->cache_obj.address); - PR_FREEIF(mem_copy->cache_obj.post_data); - PR_FREEIF(mem_copy->cache_obj.post_headers); - PR_FREEIF(mem_copy->cache_obj.content_type); - PR_FREEIF(mem_copy->cache_obj.charset); - PR_FREEIF(mem_copy->cache_obj.content_encoding); - - PR_Free(mem_copy); - -} - -/* removes the last mem object. Returns negative on error, - * otherwise returns the current size of the cache - */ -PRIVATE int32 -net_remove_last_memory_cache_object(void) -{ - net_MemoryCacheObject * mem_cache_obj; - - /* safty valve in case there are no list items - * or if we are in the process of adding an object - */ - if(net_cache_adding_object) - return -1; - - mem_cache_obj = (net_MemoryCacheObject *) - XP_ListRemoveEndObject(net_MemoryCacheList); - - if(!mem_cache_obj) - return -1; - - /* we can't remove it if we have external locks or if it's not completed - - * try removing another one - */ - if(mem_cache_obj->external_locks || !mem_cache_obj->completed) - { - int status = net_remove_last_memory_cache_object(); /* recurse */ - /* add the object back in */ - XP_ListAddObject(net_MemoryCacheList, mem_cache_obj); - return status; - } - - net_FreeMemoryCopy(mem_cache_obj); - - return((int32) net_MemoryCacheSize); -} - -/* this function free's objects to bring the cache size - * below the size passed in - */ -PRIVATE void -net_ReduceMemoryCacheTo(uint32 size) -{ - /* safty valve in case we are in the process of adding an object - */ - if(net_cache_adding_object) - return; - - while(net_MemoryCacheSize > size) - { - if(0 > net_remove_last_memory_cache_object()) - break; - } -} - -/* set the size of the Memory cache. - * Set it to 0 if you want cacheing turned off - * completely - */ -#define HTML_CACHE_MAX_BASE_SIZE 1024l*1024l -#define HTML_CACHE_VARIABLE_GROWTH .05 /* the percentage to add */ -PUBLIC void -NET_SetMemoryCacheSize(int32 new_size) -{ - int32 image_cache_size; - int32 html_cache_size; - - if(new_size <= 0) - { - IL_SetCacheSize(0); - net_ReduceMemoryCacheTo(0); - net_MaxMemoryCacheSize = 0; - return; - } - - /* the netlib mem cache is set to .3*new_size - * or 200K + .05 * new_size, whichever is less. - * and imagelb uses the rest - */ - if(new_size * .3 < HTML_CACHE_MAX_BASE_SIZE) - { - /* use .3 of new_size */ - html_cache_size = (int32) (.3 * new_size); - } - else - { - /* use HTML_CACHE_MAX_BASE_SIZE + .05*new_size */ - html_cache_size = HTML_CACHE_MAX_BASE_SIZE + - (int32)(HTML_CACHE_VARIABLE_GROWTH* - (new_size - HTML_CACHE_MAX_BASE_SIZE)); - } - - image_cache_size = new_size - html_cache_size; - - net_MaxMemoryCacheSize = html_cache_size; - - net_ReduceMemoryCacheTo((uint32) html_cache_size); - - /* set the image cache to be the rest - */ - IL_SetCacheSize(image_cache_size); - - return; -} - -/* Remove the last memory cache object if one exists - * Returns the total size of the memory cache in bytes - * after performing the operation - */ -PUBLIC int32 -NET_RemoveLastMemoryCacheObject() -{ - net_remove_last_memory_cache_object(); - - return(net_MemoryCacheSize); -} - -/* returns the number of bytes currently in use by the Memory cache - */ -PUBLIC int32 -NET_GetMemoryCacheSize() -{ - return(net_MemoryCacheSize); -} - -PUBLIC int32 -NET_GetMaxMemoryCacheSize() -{ - return net_MaxMemoryCacheSize; -} - -/* compare entries for the hashing functions - * - * return 0 if match or positive or negative on - * non match - */ -PRIVATE int net_CacheHashComp(net_MemoryCacheObject * obj1, - net_MemoryCacheObject * obj2) -{ - int result; - char *hash1; - char *hash2; - char *ques1=0; - char *ques2=0; - char *ques3=0; - char *ques4=0; - - if(obj1->cache_obj.method != obj2->cache_obj.method) - return(obj1->cache_obj.method - obj2->cache_obj.method); - - /* If this is a "news:" or "snews:" URL, then any search data in the URL - * (the stuff after '?') should be ignored for cache-comparison purposes, - * so that "news:MSGID" and "news:MSGID?headers=all" share the same cache - * file. - */ - if((NET_TO_UPPER(obj1->cache_obj.address[0]) == 'N' - || NET_TO_UPPER(obj1->cache_obj.address[0]) == 'S') - && NET_URL_Type(obj1->cache_obj.address) == NEWS_TYPE_URL) - { - ques1 = PL_strchr(obj1->cache_obj.address, '?'); - if(ques1) - *ques1 = '\0'; - } - - if((NET_TO_UPPER(obj2->cache_obj.address[0]) == 'N' - || NET_TO_UPPER(obj2->cache_obj.address[0]) == 'S') - && NET_URL_Type(obj2->cache_obj.address) == NEWS_TYPE_URL) - { - ques2 = PL_strchr(obj2->cache_obj.address, '?'); - if(ques2) - *ques2 = '\0'; - } - - - /* do the same for IMAP */ - if(!PL_strncasecmp(obj1->cache_obj.address,"mailbox://",10)) - { - ques3 = PL_strstr(obj1->cache_obj.address, "&part="); - if(ques3) - *ques3 = '\0'; - } - - if(!PL_strncasecmp(obj2->cache_obj.address,"mailbox://",10)) - { - ques4 = PL_strstr(obj2->cache_obj.address, "&part="); - if(ques4) - *ques4 = '\0'; - } - - - /* strip hash symbols because they - * really represent the same - * document - */ - hash1 = PL_strchr(obj1->cache_obj.address, '#'); - hash2 = PL_strchr(obj2->cache_obj.address, '#'); - - if(hash1) - *hash1 = '\0'; - if(hash2) - *hash2 = '\0'; - - result = PL_strcmp(obj1->cache_obj.address, obj2->cache_obj.address); - - /* set them back to previous values - */ - if(hash1) - *hash1 = '#'; - if(hash2) - *hash2 = '#'; - if(ques1) - *ques1 = '?'; - if(ques2) - *ques2 = '?'; - if(ques3) - *ques3 = '&'; - if(ques4) - *ques4 = '&'; - - - if(result != 0) - return(result); - - if(!obj1->cache_obj.post_data && !obj2->cache_obj.post_data) - return(0); /* match; no post data on either */ - - if(obj1->cache_obj.post_data && obj2->cache_obj.post_data) - { - result = PL_strcmp(obj1->cache_obj.post_data, - obj2->cache_obj.post_data); - return(result); - } - else - { /* one but not the other */ - if(obj1->cache_obj.post_data) - return(1); - else - return(-1); - } - - return(0); /* match with post data */ -} - -/* hashing function for url's - * - * This is some magic Jamie gave me... - */ -PRIVATE uint32 net_CacheHashFunc(net_MemoryCacheObject * obj1) -{ - unsigned const char *x; - uint32 h = 0; - uint32 g; - XP_Bool news_type_url = FALSE; - XP_Bool imap_type_url = FALSE; - - if(!obj1) - return 0; - - x = (unsigned const char *) obj1->cache_obj.address; - - /* figure out if it's a news type URL */ - if((NET_TO_UPPER(obj1->cache_obj.address[0]) == 'N' - || NET_TO_UPPER(obj1->cache_obj.address[0]) == 'S') - && NET_URL_Type(obj1->cache_obj.address) == NEWS_TYPE_URL) - news_type_url = TRUE; - /* figure out if it's an IMAP type URL */ - else if (NET_TO_UPPER(obj1->cache_obj.address[0]) == 'M' && - !PL_strncasecmp(obj1->cache_obj.address,"Mailbox://",10)) - imap_type_url = TRUE; - - /* modify the default String hash function - * to work with URL's - */ - assert(x); - - if (!x) return 0; - - /* ignore '#' data for all URL's. - * ignore '?' data for news URL's - * ignore '&' data for all IMAP URL's - */ - while (*x != 0 && *x != '#' && (!news_type_url || *x != '?') && - (!imap_type_url || *x != '&')) - { - h = (h << 4) + *x++; - if ((g = h & 0xf0000000) != 0) - h = (h ^ (g >> 24)) ^ g; - } - - return h; -} - -/****************************************************************** - * Cache Converter Stream input routines - */ - -/* is the stream ready for writing? - */ -PRIVATE unsigned int net_MemCacheWriteReady (NET_StreamClass *stream) -{ - CacheDataObject *obj=stream->data_object; - if(obj->next_stream) - return((*obj->next_stream->is_write_ready)(obj->next_stream)); - else - return(MAX_WRITE_READY); -} - -/* stream write function - * - * this function accepts a stream and writes the data - * into memory segments on a segment list. - */ -PRIVATE int net_MemCacheWrite (NET_StreamClass *stream, CONST char* buffer, int32 len) -{ - CacheDataObject *obj=stream->data_object; - TRACEMSG(("net_MemCacheWrite called with %ld buffer size", len)); - - /* if delete_me is set, we don't want to keep writing to the memcache stream. - */ - if(obj->memory_copy && !obj->memory_copy->delete_me) - { - net_MemorySegment * mem_seg; - char * cur_mem_seg_ptr; - - /* compute a content_length as we read data - * to use as a comparison and for URL's that - * don't send a content type - */ - obj->computed_content_length += len; - - /* we are always adding to the end one in the list so - * lets get it - */ - mem_seg = (net_MemorySegment *) - XP_ListGetEndObject(obj->memory_copy->list); - PR_ASSERT(mem_seg); - - if(mem_seg->in_use+len > mem_seg->seg_size) - { - /* we need a new segment - */ - net_MemorySegment * new_mem_seg = PR_NEW(net_MemorySegment); - uint32 size_left_in_old_buffer = mem_seg->seg_size - mem_seg->in_use; - uint32 size_for_new_buffer = len - size_left_in_old_buffer; - char * new_mem_seg_ptr; - - if(!new_mem_seg) - { - net_FreeMemoryCopy(obj->memory_copy); - obj->memory_copy = 0; - goto EndOfMemWrite; - } - - /* @@@ the socket buffer can never be larger - * than the MAX_MEMORY_ALLOC_SIZE - */ - if(size_for_new_buffer > MEMORY_CACHE_SEGMENT_SIZE) - { - new_mem_seg->segment = (char*)PR_Malloc(size_for_new_buffer); - new_mem_seg->seg_size = size_for_new_buffer; - } - else - { - new_mem_seg->segment = (char*)PR_Malloc( - MEMORY_CACHE_SEGMENT_SIZE); - new_mem_seg->seg_size = MEMORY_CACHE_SEGMENT_SIZE; - } - - if(!new_mem_seg->segment) - { - PR_Free(new_mem_seg); - net_FreeMemoryCopy(obj->memory_copy); - obj->memory_copy = 0; - goto EndOfMemWrite; - } - - /* increase the global cache size counter - */ - net_MemoryCacheSize += new_mem_seg->seg_size; - - TRACEMSG(("Cache size now: %d", net_MemoryCacheSize)); - - cur_mem_seg_ptr = mem_seg->segment; - new_mem_seg_ptr = new_mem_seg->segment; - - /* fill in what we can to the old buffer - */ - if(size_left_in_old_buffer) - { - memcpy(cur_mem_seg_ptr+mem_seg->in_use, - buffer, - (size_t) size_left_in_old_buffer); - mem_seg->in_use = mem_seg->seg_size; /* seg new size */ - } - - /* fill in the new buffer - */ - memcpy(new_mem_seg_ptr, - buffer+size_left_in_old_buffer, - (size_t) size_for_new_buffer); - new_mem_seg->in_use = size_for_new_buffer; - - net_cache_adding_object++; /* semaphore */ - XP_ListAddObjectToEnd(obj->memory_copy->list, new_mem_seg); - net_cache_adding_object--; /* semaphore */ - - TRACEMSG(("Adding %d to New memory segment %p", len, new_mem_seg)); - } - else - { - assert (mem_seg->segment); - cur_mem_seg_ptr = mem_seg->segment; - - /* fill in some more into the existing segment - */ - memcpy(cur_mem_seg_ptr + mem_seg->in_use, buffer, (size_t) len); - mem_seg->in_use += len; - - TRACEMSG(("Adding %d to existing memory segment %p", len, mem_seg)); - } - - } - -EndOfMemWrite: /* target of a goto from an error above */ - - if(obj->next_stream) - { - int status=0; - - PR_ASSERT (buffer); - PR_ASSERT (len > -1); - status = (*obj->next_stream->put_block) - (obj->next_stream, buffer, len); - - /* abort */ - if(status < 0) - return(status); - } - - return(1); -} - -/* complete the stream -*/ -PRIVATE void net_MemCacheComplete (NET_StreamClass *stream) -{ - CacheDataObject *obj=stream->data_object; - /* refresh these entries in case meta changes them */ - if(obj->URL_s && obj->memory_copy) - { - obj->memory_copy->cache_obj.expires = obj->URL_s->expires; - obj->memory_copy->cache_obj.last_modified = obj->URL_s->last_modified; - StrAllocCopy(obj->memory_copy->cache_obj.charset, obj->URL_s->charset); - } - - if (obj->memory_copy) - { - /* now it's completed */ - obj->memory_copy->completed = TRUE; - - /* if the object is zero size or - * if the computed size is different that a given content type, - * zero the last modified date so that it wont get reused - * on a recheck or reload - */ - if(!obj->computed_content_length - || (obj->memory_copy->cache_obj.content_length - && obj->memory_copy->cache_obj.content_length - != obj->computed_content_length - ) - ) - { - obj->memory_copy->cache_obj.last_modified = 0; - } - - /* override the given content_length with the correct - * content length - */ - obj->memory_copy->cache_obj.content_length = - obj->computed_content_length; - - /* set current time */ - obj->memory_copy->cache_obj.last_accessed = time(NULL); - } - - -/* loser: */ - /* complete the next stream - */ - if(obj->next_stream) - { - (*obj->next_stream->complete)(obj->next_stream); - PR_Free(obj->next_stream); - } - - /* finally, check to see if we want to delete this, after going - through all that work just to put it in here. */ - if(obj->memory_copy && - obj->memory_copy->delete_me && - (obj->memory_copy->mem_read_lock == 0)) - { - net_FreeMemoryCopy(obj->memory_copy); - } - - - /* don't need the data obj any more since this is the end - * of the stream... */ - PR_REMOVE_LINK(&obj->links); - PR_Free(obj); - - /* this is what keeps the cache from growing without end */ - net_ReduceMemoryCacheTo(net_MaxMemoryCacheSize); - - return; -} - -/* add the object into the cache, even if it hasn't been finished - getting cached. When it's finished, net_MemCacheComplete will - set the obj->memory_copy->comlpleted flag. -*/ -PRIVATE void net_MemCacheAddObjectToCache (CacheDataObject * obj) -{ - int status; - - /* if the hash table doesn't exist yet, initialize it now - */ - if(!net_MemoryCacheHashList) - { - - net_MemoryCacheHashList = XP_HashListNew(499, - (XP_HashingFunction) net_CacheHashFunc, - (XP_HashCompFunction) net_CacheHashComp); - if(!net_MemoryCacheHashList) - { - net_FreeMemoryCopy(obj->memory_copy); - goto loser; - return; - } - - } - - /* if the delete list doesn't exist yet, initialize it now - */ - if(!net_MemoryCacheList) - { - net_MemoryCacheList = XP_ListNew(); - if(!net_MemoryCacheList) - { - net_FreeMemoryCopy(obj->memory_copy); - goto loser; - return; - } - } - - /* memory copy could have been free'd and clear if an - * error occured in the write, so check to make sure - * it's still around. - */ - if(obj->memory_copy) - { - /* set the completed flag so that we know we're in - * the process of caching this object. - */ - obj->memory_copy->completed = FALSE; - obj->memory_copy->aborted = FALSE; - - /* if the document requested not to be cached, - * set the flag to only serve it for reloads and such - */ - if(obj->URL_s && obj->URL_s->dont_cache) - obj->memory_copy->current_page_only = TRUE; - - /* add the struct to the delete list */ - net_cache_adding_object++; /* semaphore */ - XP_ListAddObject(net_MemoryCacheList, obj->memory_copy); - net_cache_adding_object--; /* semaphore */ - - /* add the struct to the hash list */ - net_cache_adding_object++; /* semaphore */ - status = XP_HashListAddObject(net_MemoryCacheHashList, - obj->memory_copy); - net_cache_adding_object--; /* semaphore */ - - /* check for hash collision */ - if(status == XP_HASH_DUPLICATE_OBJECT) - { - net_MemoryCacheObject * tmp_obj; - - tmp_obj = (net_MemoryCacheObject *) - XP_HashListFindObject(net_MemoryCacheHashList, - obj->memory_copy); - - if ((tmp_obj->mem_read_lock == 0) && tmp_obj->completed) - { - /* If there is nobody currently reading or writing the - * duplicate hash entry, then free the old copy. - * This will remove it from the hash list, also. - */ - net_FreeMemoryCopy(tmp_obj); - - TRACEMSG(("Found duplicate object in cache. Removing old object")); - - /* re add the object - */ - net_cache_adding_object++; /* semaphore */ - XP_HashListAddObject(net_MemoryCacheHashList, - obj->memory_copy); - net_cache_adding_object--; /* semaphore */ - } - else - { - /* We can't cache this entry, the duplicate is - * currently being read or written. So delete this entry. - */ - net_FreeMemoryCopy(obj->memory_copy); - } - } - } - -loser: - - return; -} - -/* Abort the stream - * - */ -PRIVATE void net_MemCacheAbort (NET_StreamClass *stream, int status) -{ - CacheDataObject *obj=stream->data_object; - /* abort the next stream - */ - if(obj->next_stream) - { - (*obj->next_stream->abort)(obj->next_stream, status); - PR_Free(obj->next_stream); - } - - /* set the aborted flag so that the object will really be deleted - * if there are no read locks. */ - obj->memory_copy->aborted = TRUE; - net_FreeMemoryCopy(obj->memory_copy); - - PR_REMOVE_LINK(&obj->links); - PR_Free(obj); - - return; -} - -/* setup the stream - */ -MODULE_PRIVATE NET_StreamClass * -NET_MemCacheConverter (FO_Present_Types format_out, - void *converter_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - CacheDataObject * data_object=0; - NET_StreamClass * stream=0; - net_MemorySegment * mem_seg=0; - net_MemoryCacheObject *memory_copy=0; - net_MemCacheConverterObject *mem_conv_obj = converter_obj; - - TRACEMSG(("Setting up cache stream. Have URL: %s\n", URL_s->address)); - - TRACEMSG(("Setting up memory cache")); - - /* check to see if the object is larger than the - * size of the max memory cache - * - * skip the size check if the must_cache flag is set. - */ - if(!URL_s->must_cache && (uint32)URL_s->content_length >= net_MaxMemoryCacheSize) - goto malloc_failure; /* dont cache this URL */ - - /* set up the memory caching struct. - * - * malloc the segment first since it's the most likely malloc to fail - */ - mem_seg = PR_NEW(net_MemorySegment); - - if(!mem_seg) - return(NULL); - - mem_seg->in_use = 0; - - if(URL_s->content_length > 0) - { - /* use the content_length if we can since that would be - * the most efficient - */ - if(URL_s->content_length > MAX_MEMORY_ALLOC_SIZE) - { - mem_seg->segment = (char*)PR_Malloc(MAX_MEMORY_ALLOC_SIZE); - mem_seg->seg_size = MAX_MEMORY_ALLOC_SIZE; - } - else - { - /* add 10 just in case it's needed due to a bad content type :) */ - mem_seg->segment = (char*)PR_Malloc(URL_s->content_length+10); - mem_seg->seg_size = URL_s->content_length+10; - } - } - else - { - /* this is a case of no content length, use standard size segments */ - mem_seg->segment = (char*)PR_Malloc(MEMORY_CACHE_SEGMENT_SIZE); - mem_seg->seg_size = MEMORY_CACHE_SEGMENT_SIZE; - } - - if(!mem_seg->segment) - { - PR_Free(mem_seg); - goto malloc_failure; /* skip memory cacheing */ - } - - /* malloc the main cache holding structure */ - memory_copy = PR_NEW(net_MemoryCacheObject); - if(!memory_copy) - { - PR_Free(mem_seg); - PR_Free(mem_seg->segment); - goto malloc_failure; /* skip memory cacheing */ - } - memset(memory_copy, 0, sizeof(net_MemoryCacheObject)); - - memory_copy->list = XP_ListNew(); - if(!memory_copy->list) - { - PR_Free(mem_seg); - PR_Free(mem_seg->segment); - PR_Free(memory_copy); - goto malloc_failure; /* skip memory cacheing */ - } - - /* if we get this far add the object to the size count - * since if we fail anywhere below here it will get - * subtracted by net_FreeMemoryCopy(memory_copy); - */ - net_MemoryCacheSize += mem_seg->seg_size; - - /* add the segment malloced above to the segment list */ - net_cache_adding_object++; /* semaphore */ - XP_ListAddObject(memory_copy->list, mem_seg); - net_cache_adding_object--; /* semaphore */ - - StrAllocCopy(memory_copy->cache_obj.address, URL_s->address); - memory_copy->cache_obj.method = URL_s->method; - if(URL_s->post_data) - { - memory_copy->cache_obj.post_data_size = URL_s->post_data_size; - StrAllocCopy(memory_copy->cache_obj.post_data, URL_s->post_data); - StrAllocCopy(memory_copy->cache_obj.post_headers, URL_s->post_headers); - } - - memory_copy->cache_obj.expires = URL_s->expires; - memory_copy->cache_obj.last_modified = URL_s->last_modified; - - memory_copy->cache_obj.content_length = URL_s->content_length; - memory_copy->cache_obj.real_content_length = URL_s->content_length; - memory_copy->cache_obj.is_netsite = URL_s->is_netsite; - - StrAllocCopy(memory_copy->cache_obj.content_type, URL_s->content_type); - StrAllocCopy(memory_copy->cache_obj.charset, URL_s->charset); - StrAllocCopy(memory_copy->cache_obj.content_encoding, - URL_s->content_encoding); - - /* check for malloc failure on critical fields above */ - if(!memory_copy->cache_obj.address || !memory_copy->cache_obj.content_type) - { - net_FreeMemoryCopy(memory_copy); - goto malloc_failure; /* skip memory cacheing */ - } - - HG83363 - - /* build the stream object */ - stream = PR_NEW(NET_StreamClass); - if(!stream) - { - net_FreeMemoryCopy(memory_copy); - goto malloc_failure; /* skip memory cacheing */ - } - - /* this structure gets passed back into the write, complete - * and abort stream functions - */ - data_object = PR_NEW(CacheDataObject); - if (!data_object) - { - PR_Free(stream); - net_FreeMemoryCopy(memory_copy); - goto malloc_failure; /* skip memory cacheing */ - } - - /* init the object */ - memset(data_object, 0, sizeof(CacheDataObject)); - - /* assign the cache object to the stream data object - */ - data_object->memory_copy = memory_copy; - - if (mem_conv_obj->dont_hold_URL_s == FALSE) - data_object->URL_s = URL_s; - - TRACEMSG(("Returning stream from NET_CacheConverter\n")); - - stream->name = "Cache stream"; - stream->complete = (MKStreamCompleteFunc) net_MemCacheComplete; - stream->abort = (MKStreamAbortFunc) net_MemCacheAbort; - stream->put_block = (MKStreamWriteFunc) net_MemCacheWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_MemCacheWriteReady; - stream->data_object = data_object; /* document info object */ - stream->window_id = window_id; - - /* next stream is passed in by the caller but can be null */ - data_object->next_stream = mem_conv_obj->next_stream; - - PR_APPEND_LINK(&data_object->links, &mem_active_cache_data_objects); - - /* add the cache object to the hash list, but don't - * complete it yet - */ - net_MemCacheAddObjectToCache(data_object); - - return stream; - -malloc_failure: /* target of malloc failure */ - - TRACEMSG(("NOT Caching this URL")); - - /* bypass the whole cache mechanism - */ - if(format_out != FO_CACHE_ONLY) - { - format_out = CLEAR_CACHE_BIT(format_out); - return(mem_conv_obj->next_stream); - } - - return(NULL); -} - -PRIVATE net_MemoryCacheObject * -net_FindObjectInMemoryCache(URL_Struct *URL_s) -{ - net_MemoryCacheObject tmp_cache_obj, *return_obj; - - /* fill in the temporary cache object so we can - * use it for searching - */ - memset(&tmp_cache_obj, 0, sizeof(tmp_cache_obj)); - tmp_cache_obj.cache_obj.method = URL_s->method; - tmp_cache_obj.cache_obj.address = URL_s->address; - tmp_cache_obj.cache_obj.post_data = URL_s->post_data; - tmp_cache_obj.cache_obj.post_data_size = URL_s->post_data_size; - - return_obj = (net_MemoryCacheObject *) - XP_HashListFindObject(net_MemoryCacheHashList, &tmp_cache_obj); - if (return_obj) - return (return_obj); - else - { - /* try unescaping the URL address - MHTML parts are - escaped, and weren't getting picked up in the - cache */ - tmp_cache_obj.cache_obj.address = PL_strdup(URL_s->address); - if (tmp_cache_obj.cache_obj.address) - { - /* unescape it */ - NET_UnEscape(tmp_cache_obj.cache_obj.address); - if (tmp_cache_obj.cache_obj.address) - { - return_obj = (net_MemoryCacheObject *) - XP_HashListFindObject(net_MemoryCacheHashList, &tmp_cache_obj); - PR_Free(tmp_cache_obj.cache_obj.address); - } - } - return (return_obj); - } -} - -/* set or unset a lock on a memory cache object - */ -MODULE_PRIVATE void -NET_ChangeMemCacheLock(URL_Struct *URL_s, PRBool set) -{ - net_MemoryCacheObject * found_cache_obj; - - /* look up cache struct */ - found_cache_obj = net_FindObjectInMemoryCache(URL_s); - - if(found_cache_obj && found_cache_obj->completed) - { - PR_ASSERT(found_cache_obj->external_locks >= 0); - - if(set) - { - /* increment lock counter */ - found_cache_obj->external_locks++; - } - else - { - /* decrement lock counter */ - found_cache_obj->external_locks--; - -/* PR_ASSERT(found_cache_obj->external_locks >= 0); */ - - if(found_cache_obj->external_locks < 0) - found_cache_obj->external_locks = 0; - } - } -} - -/* remove a URL from the memory cache - */ -MODULE_PRIVATE void -NET_RemoveURLFromMemCache(URL_Struct *URL_s) -{ - net_MemoryCacheObject * found_cache_obj; - - found_cache_obj = net_FindObjectInMemoryCache(URL_s); - - if(found_cache_obj && - (found_cache_obj->mem_read_lock == 0) && - found_cache_obj->completed) - net_FreeMemoryCopy(found_cache_obj); -} - -/* Returns TRUE if the URL is currently in the - * memory cache and false otherwise. - */ -PUBLIC XP_Bool -NET_IsURLInMemCache(URL_Struct *URL_s) -{ - if(net_FindObjectInMemoryCache(URL_s)) - return(TRUE); - else - return(FALSE); -} - -/* this function looks up a URL in the hash table and - * returns MEMORY_CACHE_TYPE_URL if it's found and - * should be loaded via the memory cache. - * - * It also sets several entries in the passed in URL - * struct including "memory_copy" which is a pointer - * to the found net_MemoryCacheObject struct. - */ -MODULE_PRIVATE int -NET_FindURLInMemCache(URL_Struct * URL_s, MWContext *ctxt) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Should not be getting called. Also, compiler will warn of missing prototype */ - return 0; -} -#else -{ - net_MemoryCacheObject *found_cache_obj; - - TRACEMSG(("Checking for URL in cache")); - - if(!net_MemoryCacheHashList) - return(0); - - found_cache_obj = net_FindObjectInMemoryCache(URL_s); - - if(found_cache_obj) - { - TRACEMSG(("mkcache: found URL in memory cache!")); - - if(found_cache_obj->current_page_only) - { - History_entry * he = SHIST_GetCurrent(&ctxt->hist); - int hist_num; - - /* if the current_page_only flag is set - * then the page should only be - * served if it's the current document loaded - * (i.e. reloads) - * - * @@@ if !he then let it through, this allows the - * doc info window to work - */ - if(he) - { - hist_num = SHIST_GetIndex(&ctxt->hist, he); - - /* we can tell if the document being loaded is the - * same as the current document by looking up it's - * index in the history. If they don't match - * then it isn't the current document - */ - if(URL_s->history_num != hist_num) - return 0; - } - } - - /* set a pointer to the structure in the URL struct - */ - URL_s->memory_copy = found_cache_obj; - - /* copy the contents of the URL struct so that the content type - * and other stuff gets recorded - */ - StrAllocCopy(URL_s->content_type, - found_cache_obj->cache_obj.content_type); - StrAllocCopy(URL_s->charset, - found_cache_obj->cache_obj.charset); - StrAllocCopy(URL_s->content_encoding, - found_cache_obj->cache_obj.content_encoding); - URL_s->content_length = found_cache_obj->cache_obj.content_length; - URL_s->real_content_length = found_cache_obj->cache_obj.content_length; - URL_s->expires = found_cache_obj->cache_obj.expires; - URL_s->last_modified = found_cache_obj->cache_obj.last_modified; - URL_s->is_netsite = found_cache_obj->cache_obj.is_netsite; - - HG26557 - net_cache_adding_object++; /* semaphore */ - /* reorder objects so that the list is in last accessed order */ - XP_ListRemoveObject(net_MemoryCacheList, found_cache_obj); - XP_ListAddObject(net_MemoryCacheList, found_cache_obj); - net_cache_adding_object--; /* semaphore */ - - TIMING_MESSAGE(("cache,%s,in memory", URL_s->address)); - TRACEMSG(("Cached copy is valid. returning method")); - - return(MEMORY_CACHE_TYPE_URL); - } - - TRACEMSG(("URL not found in cache")); - - return(0); -} -#endif - -/***************************************************************** - * Memory cache output module routine - * - * This set of routines pushes the document in memory up a stream - * created by NET_StreamBuilder - */ - -/* used to hold data between invokations of ProcessNet - */ -typedef struct _MemCacheConData { - XP_List *cur_list_ptr; - uint32 bytes_written_in_segment; - NET_StreamClass *stream; -} MemCacheConData; - -#define CD_CUR_LIST_PTR connection_data->cur_list_ptr -#define CD_BYTES_WRITTEN_IN_SEGMENT connection_data->bytes_written_in_segment -#define CD_STREAM connection_data->stream - -#define CE_URL_S cur_entry->URL_s -#define CE_WINDOW_ID cur_entry->window_id -#define CE_FORMAT_OUT cur_entry->format_out -#define CE_STATUS cur_entry->status -#define CE_BYTES_RECEIVED cur_entry->bytes_received - -/* begin the load, This is called from NET_GetURL - */ -#ifdef OLD_MOZ_MAIL_NEWS -extern int -net_InitializeNewsFeData (ActiveEntry * cur_entry); -extern int -IMAP_InitializeImapFeData (ActiveEntry * cur_entry); -extern void -IMAP_URLFinished(URL_Struct *URL_s); -#endif /* OLD_MOZ_MAIL_NEWS */ - -PRIVATE int32 -net_MemoryCacheLoad (ActiveEntry * cur_entry) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Should not be getting called */ - return 0; -} -#else -{ - /* get memory for Connection Data */ - MemCacheConData * connection_data = PR_NEW(MemCacheConData); - net_MemorySegment * mem_seg; - uint32 chunk_size; - char *mem_seg_ptr; - char *first_buffer; - - TRACEMSG(("Entering NET_MemoryCacheLoad!\n")); - - if(!connection_data) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - CE_STATUS = MK_OUT_OF_MEMORY; - return (CE_STATUS); - } - - if (!CE_URL_S->memory_copy) - { - /* the memory_copy has been freed before fully - * making it into the cache. In other words, it's - * been aborted. Abort this load then, also. - * We should probably never hit this case, however. - * If we got here, it means we've just found this entry - * in the hash table, which means we have not deleted it - * and we have not set the delete_me flag. - */ - PR_ASSERT(FALSE); - CE_STATUS = MK_OBJECT_NOT_IN_CACHE; - return (CE_STATUS); - } - - cur_entry->protocol = MEMORY_CACHE_TYPE_URL; - cur_entry->memory_file = TRUE; - - /* point to the first list struct that contains data - */ - CD_CUR_LIST_PTR = CE_URL_S->memory_copy->list->next; - CD_BYTES_WRITTEN_IN_SEGMENT = 0; - - /* put a read lock on the data - */ - CE_URL_S->memory_copy->mem_read_lock++; - - cur_entry->con_data = connection_data; - - cur_entry->local_file = TRUE; - - cur_entry->socket = NULL; - - NET_SetCallNetlibAllTheTime(CE_WINDOW_ID, "mkmemcac"); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - - FE_EnableClicking(CE_WINDOW_ID); - -#ifdef OLD_MOZ_MAIL_NEWS - if (cur_entry->format_out == FO_PRESENT) - { - if (NET_URL_Type(cur_entry->URL_s->address) == NEWS_TYPE_URL) - { - /* #### DISGUSTING KLUDGE to make cacheing work for news articles. */ - cur_entry->status = net_InitializeNewsFeData (cur_entry); - if (cur_entry->status < 0) - { - /* #### what error message? */ - return cur_entry->status; - } - } - else if (!PL_strncmp(CE_URL_S->address, "Mailbox://", 10)) - { - /* #### DISGUSTING KLUDGE to make cacheing work for imap articles. */ - cur_entry->status = IMAP_InitializeImapFeData (cur_entry); - if (cur_entry->status < 0) - { - /* #### what error message? */ - return cur_entry->status; - } - } - } -#endif /* OLD_MOZ_MAIL_NEWS */ - - /* open the outgoing stream - */ - CD_STREAM = NET_StreamBuilder(CE_FORMAT_OUT, CE_URL_S, CE_WINDOW_ID); - if(!CD_STREAM) - { - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkmemcac"); - - PR_Free(connection_data); - - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - CE_STATUS = MK_UNABLE_TO_CONVERT; - return (CE_STATUS); - } - - if (!CE_URL_S->load_background) - FE_GraphProgressInit(CE_WINDOW_ID, CE_URL_S, CE_URL_S->content_length); - - /* process one chunk of the - * cache file so that - * layout can continue - * when images are in the cache - */ -#define FIRST_BUFF_SIZE 1024 - if (CE_URL_S->memory_copy->completed) - { - mem_seg = (net_MemorySegment *) CD_CUR_LIST_PTR->object; - - mem_seg_ptr = mem_seg->segment; - - chunk_size = MIN(FIRST_BUFF_SIZE, - mem_seg->in_use-CD_BYTES_WRITTEN_IN_SEGMENT); - - /* malloc this first buffer because we can't use - * the NET_SocketBuffer in calls from NET_GetURL - * because of reentrancy - */ - first_buffer = (char *) PR_Malloc(chunk_size); - - if(!first_buffer) - { - PR_Free(connection_data); - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - /* copy the segment because the parser will muck with it - */ - memcpy(first_buffer, - mem_seg_ptr+CD_BYTES_WRITTEN_IN_SEGMENT, - (size_t) chunk_size); - - CD_BYTES_WRITTEN_IN_SEGMENT += chunk_size; - - CE_STATUS = (*CD_STREAM->put_block)(CD_STREAM, - first_buffer, - chunk_size); - if(CE_STATUS < 0) - { - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkmemcac"); - - if (!CE_URL_S->load_background) - FE_GraphProgressDestroy(CE_WINDOW_ID, - CE_URL_S, - CE_URL_S->content_length, - CE_BYTES_RECEIVED); - - PR_Free(connection_data); - - return (CE_STATUS); - } - - CE_BYTES_RECEIVED += chunk_size; - - /* check to see if we need to advance the pointer yet. - * should hardly ever happen here since the first buffer - * is so small - */ - if(CD_BYTES_WRITTEN_IN_SEGMENT >= mem_seg->in_use) - { - CD_CUR_LIST_PTR = CD_CUR_LIST_PTR->next; - CD_BYTES_WRITTEN_IN_SEGMENT = 0; - } - - PR_Free(first_buffer); - } - else - { - CE_STATUS = 0; - } - - return(CE_STATUS); - -} -#endif /* NU_CACHE */ - -/* called repeatedly from NET_ProcessNet to push all the - * data up the stream - */ -PRIVATE int32 -net_ProcessMemoryCache (ActiveEntry * cur_entry) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Should not be getting called */ - return 0; -} -#else -{ - MemCacheConData * connection_data = (MemCacheConData *)cur_entry->con_data; - net_MemorySegment * mem_seg; - uint32 chunk_size; - uint32 buffer_size; - char *mem_seg_ptr; - - - if (!CE_URL_S->memory_copy) - { - /* the memory_copy has been freed before fully - * making it into the cache. In other words, it's - * been aborted. Abort this load then, also, - * since it's a concurrent load. - * We know that CE_URL_S->memory_copy will be NULL - * if it's been removed, because we have a read lock - * on the entry, and that will cause the delete_me - * flag to be set, rather than just deleting the - * object initially. We catch the delete_me flag - * here, and set CE_URL_S->memory_copy to NULL. - */ - CE_STATUS = MK_OBJECT_NOT_IN_CACHE; - return (CE_STATUS); - } - - - /* wait until the object has been fully inserted into - * the cache. - */ - if (!CE_URL_S->memory_copy->completed && - !(CE_URL_S->memory_copy->delete_me && - CE_URL_S->memory_copy->aborted)) - { - /* normal case - we are still waiting for it to complete */ - return 0; - } - - if(!CD_CUR_LIST_PTR || - (CE_URL_S->memory_copy->aborted && - CE_URL_S->memory_copy->delete_me)) - { - /* when CD_CUR_LIST_PTR turns NULL we are at the end - * of the document. Finish up the stream and exit. - * - * If the entry is aborted and the delete_me flag is set, - * the stream was aborted in the middle of being written. - * If we are here, then it's simultaneously being read also. - * So, finish up. - */ - - /* complete the stream - */ - (*CD_STREAM->complete)(CD_STREAM); - - /* free the stream - */ - PR_Free(CD_STREAM); - - /* remove the read lock - */ - CE_URL_S->memory_copy->mem_read_lock--; - - /* check to see if we should delete this memory cached object - * - * delete_me is set by FreeMemoryCacheObject when it tried - * to free it but couldn't because of read locks on the - * object - */ - if(CE_URL_S->memory_copy->delete_me && - CE_URL_S->memory_copy->mem_read_lock == 0) - { - net_FreeMemoryCopy(CE_URL_S->memory_copy); - CE_URL_S->memory_copy = 0; - } - - /* PR_Free the structs used by this protocol module - */ - PR_Free(connection_data); - - /* set the status to success */ - if (CE_URL_S->memory_copy && CE_URL_S->memory_copy->completed) - CE_STATUS = MK_DATA_LOADED; - else - CE_STATUS = MK_OBJECT_NOT_IN_CACHE; - - /* clear the CallNetlibAllTheTime if there are no - * other readers - */ - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkmemcac"); - - if (!CE_URL_S->load_background) - FE_GraphProgressDestroy(CE_WINDOW_ID, - CE_URL_S, - CE_URL_S->content_length, - CE_BYTES_RECEIVED); - -#ifdef OLD_MOZ_MAIL_NEWS - if (!PL_strncmp(CE_URL_S->address, "Mailbox://", 10)) - /* #### DISGUSTING KLUDGE to make cacheing work for imap articles. */ - IMAP_URLFinished(CE_URL_S); -#endif - /* Tell ProcessNet that we are all done */ - return(-1); - } - - /* CD_CUR_LIST_PTR is pointing to the most current - * memory segment list object - */ - mem_seg = (net_MemorySegment *) CD_CUR_LIST_PTR->object; - - TRACEMSG(("ProcessMemoryCache: printing segment %p",mem_seg)); - - mem_seg_ptr = mem_seg->segment; - - /* write out at least part of the buffer - */ - buffer_size = (*CD_STREAM->is_write_ready)(CD_STREAM); - buffer_size = MIN(buffer_size, (unsigned int) NET_Socket_Buffer_Size); - - /* make it ??? at the most - * when coming out of the cache - */ - buffer_size = MIN(buffer_size, NET_MEM_CACHE_OUTPUT_SIZE); - - chunk_size = MIN(buffer_size, mem_seg->in_use-CD_BYTES_WRITTEN_IN_SEGMENT); - - /* copy the segment because the parser will muck with it - */ - memcpy(NET_Socket_Buffer, - mem_seg_ptr+CD_BYTES_WRITTEN_IN_SEGMENT, - (size_t) chunk_size); - - /* remember how much of this segment we have written */ - CD_BYTES_WRITTEN_IN_SEGMENT += chunk_size; - - CE_STATUS = (*CD_STREAM->put_block)(CD_STREAM, - NET_Socket_Buffer, - chunk_size); - CE_BYTES_RECEIVED += chunk_size; - - /* check to see if we need to advance the pointer yet - */ - if(CD_BYTES_WRITTEN_IN_SEGMENT >= mem_seg->in_use) - { - CD_CUR_LIST_PTR = CD_CUR_LIST_PTR->next; - CD_BYTES_WRITTEN_IN_SEGMENT = 0; - } - - if (!CE_URL_S->load_background) - FE_GraphProgress(CE_WINDOW_ID, CE_URL_S, CE_BYTES_RECEIVED, - chunk_size, CE_URL_S->content_length); - - if(CE_STATUS < 0) - { - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkmemcac"); - - (*CD_STREAM->abort)(CD_STREAM, CE_STATUS); - } - - return(CE_STATUS); - -} -#endif /* NU_CACHE */ - -/* called by functions in mkgeturl to interrupt the loading of - * an object. (Usually a user interrupt) - */ -PRIVATE int32 -net_InterruptMemoryCache (ActiveEntry * cur_entry) -#ifdef NU_CACHE -{ - PR_ASSERT(0); /* Should not be getting called */ - return 0; -} -#else -{ - MemCacheConData * connection_data = (MemCacheConData *)cur_entry->con_data; - - /* abort and free the outgoing stream - */ - (*CD_STREAM->abort)(CD_STREAM, MK_INTERRUPTED); - PR_Free(CD_STREAM); - - if (!CE_URL_S->memory_copy) - { - /* the memory_copy has been freed before fully - * making it into the cache. In other words, it's - * been aborted. Abort this load then, also, - * since it's a concurrent load. - */ - CE_STATUS = MK_OBJECT_NOT_IN_CACHE; - return (CE_STATUS); - } - - /* remove the read lock - */ - CE_URL_S->memory_copy->mem_read_lock--; - - /* check to see if we should delete this memory cached object - */ - if(CE_URL_S->memory_copy->delete_me && - CE_URL_S->memory_copy->mem_read_lock == 0) - { - net_FreeMemoryCopy(CE_URL_S->memory_copy); - CE_URL_S->memory_copy = 0; - } - - /* PR_Free the structs - */ - PR_Free(connection_data); - CE_STATUS = MK_INTERRUPTED; - - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkmemcac"); - - return(CE_STATUS); -} -#endif - -/* create an HTML stream and push a bunch of HTML about - * the memory cache - */ -MODULE_PRIVATE void -NET_DisplayMemCacheInfoAsHTML(ActiveEntry * cur_entry) -{ - char *buffer = (char*)PR_Malloc(2048); - char *address; - char *escaped; - NET_StreamClass * stream; - net_CacheObject * cache_obj; - net_MemoryCacheObject * mem_cache_obj; - XP_Bool long_form = FALSE; - int32 number_in_memory_cache; - XP_List *list_ptr; - int i; - - if(!buffer) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - return; - } - - if(PL_strcasestr(cur_entry->URL_s->address, "?long")) - long_form = TRUE; - else if(PL_strcasestr(cur_entry->URL_s->address, "?traceon")) -#ifdef NU_CACHE - CacheTrace_Enable(TRUE); -#else - NET_CacheTraceOn = TRUE; -#endif - else if(PL_strcasestr(cur_entry->URL_s->address, "?traceoff")) -#ifdef NU_CACHE - CacheTrace_Enable(FALSE); -#else - NET_CacheTraceOn = FALSE; -#endif - - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, - cur_entry->window_id); - - if(!stream) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - PR_Free(buffer); - return; - } - - /* define a macro to push a string up the stream - * and handle errors - */ -#define PUT_PART(part) \ -cur_entry->status = (*stream->put_block)(stream, \ - part ? part : "Unknown", \ - part ? PL_strlen(part) : 7); \ -if(cur_entry->status < 0) \ - goto END; - - if(!net_MemoryCacheList) - { - PL_strcpy(buffer, "There are no objects in the memory cache"); - PUT_PART(buffer); - goto END; - } - - number_in_memory_cache = XP_ListCount(net_MemoryCacheList); - - /* add the header info */ - sprintf(buffer, -"Information about the Netscape memory cache\n" -"

Memory Cache statistics

\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"\n" -"
Maximum size:%ld
Current size:%ld
Number of files in cache:%ld
Average cache file size:%ld
\n" -"
", -net_MaxMemoryCacheSize, -net_MemoryCacheSize, -number_in_memory_cache, -number_in_memory_cache ? net_MemoryCacheSize/number_in_memory_cache : 0); - - PUT_PART(buffer); - - /* define some macros to help us output HTML tables - */ -#if 0 - -#define TABLE_TOP(arg1) \ - sprintf(buffer, \ -"%s\n" \ -"", arg1); \ -PUT_PART(buffer); - -#define TABLE_BOTTOM \ - sprintf(buffer, \ -""); \ -PUT_PART(buffer); - -#else - -#define TABLE_TOP(arg1) \ - PL_strcpy(buffer, ""); \ - for(i=PL_strlen(arg1); i < 16; i++) \ - PL_strcat(buffer, " "); \ - PL_strcat(buffer, arg1); \ - PL_strcat(buffer, " "); \ - PUT_PART(buffer); - -#define TABLE_BOTTOM \ - PL_strcpy(buffer, "
\n"); \ - PUT_PART(buffer); - -#endif - - list_ptr = net_MemoryCacheList; - - while((mem_cache_obj = (net_MemoryCacheObject *) XP_ListNextObject(list_ptr)) != NULL) - { - - cache_obj = &mem_cache_obj->cache_obj; - address = PL_strdup(mem_cache_obj->cache_obj.address); - - /* put the URL out there */ - TABLE_TOP("URL:"); - PL_strcpy(buffer, ""); - PUT_PART(buffer); - escaped = NET_EscapeHTML(address); - PUT_PART(escaped); - PR_Free(address); - PR_Free(escaped); - PL_strcpy(buffer, ""); - PUT_PART(buffer); - TABLE_BOTTOM; - - TABLE_TOP("Content Length:"); - sprintf(buffer, "%lu", cache_obj->content_length); - PUT_PART(buffer); - TABLE_BOTTOM; - - TABLE_TOP("Content type:"); - PUT_PART(cache_obj->content_type); - TABLE_BOTTOM; - - TABLE_TOP("Last Modified:"); - if(cache_obj->last_modified) - { - PUT_PART(ctime(&cache_obj->last_modified)); - } - else - { - PL_strcpy(buffer, "No date sent"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - - TABLE_TOP("Expires:"); - if(cache_obj->expires) - { - PUT_PART(ctime(&cache_obj->expires)); - } - else - { - PL_strcpy(buffer, "No expiration date sent"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - - TABLE_TOP("Last accessed:"); - PUT_PART(ctime(&cache_obj->last_accessed)); - TABLE_BOTTOM; - - TABLE_TOP("Character set:"); - if(cache_obj->charset) - { - PUT_PART(cache_obj->charset); - } - else - { - PL_strcpy(buffer, "iso-8859-1 (default)"); - PUT_PART(buffer); - } - TABLE_BOTTOM; - - HG27328 - - PL_strcpy(buffer, "\n

\n"); - PUT_PART(buffer); - - - } - -END: - PR_Free(buffer); - if(cur_entry->status < 0) - (*stream->abort)(stream, cur_entry->status); - else - (*stream->complete)(stream); - - return; -} - -/*Accessor for use by Cache Browser */ -PUBLIC net_CacheObject* -NET_FirstMemCacheObject(XP_List* list_ptr) -{ - if (net_MemoryCacheList) - { - list_ptr = net_MemoryCacheList; - return NET_NextMemCacheObject(list_ptr); - } - else - return 0; -} - -/*Accessor for use by Cache Browser */ -PUBLIC net_CacheObject* -NET_NextMemCacheObject(XP_List* list_ptr) -{ - if (list_ptr) - { - net_MemoryCacheObject * tmp = (net_MemoryCacheObject *) XP_ListNextObject(list_ptr); - if (tmp) - { - return &tmp->cache_obj; - } - } - return 0; -} - -#include "libmocha.h" - -NET_StreamClass * -net_CloneWysiwygMemCacheEntry(MWContext *window_id, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href) -#ifdef NU_CACHE -{ - PR_ASSERT(0); - return NULL; -} -#else -{ - net_MemoryCacheObject *memory_copy; - PRCList *link; - CacheDataObject *data_object; - NET_StreamClass *stream; - XP_List *list; - net_MemorySegment *seg; - uint32 len; - - if (!(memory_copy = URL_s->memory_copy)) - { - /* not hitting the cache -- check whether we're filling it */ - for (link = mem_active_cache_data_objects.next; - link != &mem_active_cache_data_objects; - link = link->next) - { - data_object = (CacheDataObject *)link; - if (data_object->URL_s == URL_s && - (memory_copy = data_object->memory_copy) != NULL) - { - goto found; - } - } - return NULL; - } - -found: - stream = LM_WysiwygCacheConverter(window_id, URL_s, - wysiwyg_url, base_href); - if (!stream) - return 0; - list = memory_copy->list; - while (nbytes != 0 && - (seg = (net_MemorySegment *) XP_ListNextObject(list)) != NULL) - { - len = seg->seg_size; - if (len > nbytes) - len = nbytes; - if (stream->put_block(stream, seg->segment, - (int32)len) < 0) - break; - nbytes -= len; - } - if (nbytes != 0) - { - /* NB: Our caller must clear top_state->mocha_write_stream. */ - stream->abort(stream, MK_UNABLE_TO_CONVERT); - PR_Free(stream); - return 0; - } - return stream; -} -#endif - -PRIVATE void -net_CleanupMemoryCacheProtocol(void) -{ -} - -PUBLIC void -NET_InitMemCacProtocol(void) /* no prototype when NU_CACHE */ -{ - static NET_ProtoImpl mem_cac_proto_impl; -#ifdef NU_CACHE - PR_ASSERT(0); - return; -#endif - mem_cac_proto_impl.init = net_MemoryCacheLoad; - mem_cac_proto_impl.process = net_ProcessMemoryCache; - mem_cac_proto_impl.interrupt = net_InterruptMemoryCache; - mem_cac_proto_impl.resume = NULL; - mem_cac_proto_impl.cleanup = net_CleanupMemoryCacheProtocol; - - NET_RegisterProtocolImplementation(&mem_cac_proto_impl, MEMORY_CACHE_TYPE_URL); -} - -#ifdef NU_CACHE -typedef struct _NuCacheConData { - void* cache_object; - NET_StreamClass *stream; -} NuCacheConData; - -#define FIRST_BUFF_SIZE 1024 - -PRIVATE int32 -net_NuCacheLoad (ActiveEntry * cur_entry) -{ - if (cur_entry && cur_entry->URL_s) - { - NuCacheConData* con_data = PR_NEW(NuCacheConData); - void* pObject = cur_entry->URL_s->cache_object; - - if (!con_data || !pObject) - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - cur_entry->status = MK_OUT_OF_MEMORY; - return cur_entry->status; - } - - cur_entry->protocol = NU_CACHE_TYPE_URL; - cur_entry->memory_file = (CacheObject_GetModule(pObject) == 0); /* TODO replace 0 with the enum */ - - /* CacheObject->SetReadLock(pObject); */ - cur_entry->local_file = TRUE; /* Check about this one- TODO */ - cur_entry->con_data = con_data; - cur_entry->socket = NULL; - - NET_SetCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - FE_EnableClicking(cur_entry->window_id); - - if (0==cur_entry->format_out) - { - /* This means that this is a CACHE_ONLY request and shouldn't - * be getting read from memory anyway. So mark it as not present in memory - * and return as such. */ - cur_entry->status = MK_OBJECT_NOT_IN_CACHE; - return cur_entry->status; - } - - /* Build the stream to read data from */ - con_data->stream = NET_StreamBuilder(cur_entry->format_out, cur_entry->URL_s, cur_entry->window_id); - if(!con_data->stream) - { - NET_ClearCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - PR_DELETE(con_data); - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - cur_entry->status = MK_UNABLE_TO_CONVERT; - return cur_entry->status; - } - - if (!cur_entry->URL_s->load_background) - FE_GraphProgressInit(cur_entry->window_id, cur_entry->URL_s, cur_entry->URL_s->content_length); - - /* Process the first chunk so that images can start loading */ - if (!CacheObject_IsPartial(pObject)) /*todo- change this to is Completed */ - { - char* firstBuffer = (char*) PR_Malloc(FIRST_BUFF_SIZE); - PRInt32 amountRead = 0; - if (!firstBuffer) - { - PR_DELETE(con_data); - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - amountRead = CacheObject_Read(pObject, firstBuffer, FIRST_BUFF_SIZE); - if (amountRead > 0) - { - cur_entry->status = (*con_data->stream->put_block)(con_data->stream, firstBuffer, amountRead); - if(cur_entry->status < 0) - { - NET_ClearCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - - if (!cur_entry->URL_s->load_background) - { - FE_GraphProgressDestroy(cur_entry->window_id, - cur_entry->URL_s, - cur_entry->URL_s->content_length, - cur_entry->bytes_received); - } - PR_DELETE(con_data); - return (cur_entry->status); - } - - cur_entry->bytes_received += amountRead; - PR_DELETE(firstBuffer); - } - } - else - { - cur_entry->status = 0; - } - } - return cur_entry->status; -} - -/* called repeatedly from NET_ProcessNet to push all the - * data up the stream - */ -PRIVATE int32 -net_ProcessNuCache (ActiveEntry * cur_entry) -{ - if (cur_entry) - { - PRUint32 amountRead; - PRUint32 buffer_size; - - NuCacheConData* con_data = (NuCacheConData*) cur_entry->con_data; - void* pObject = cur_entry->URL_s->cache_object; - - NET_SetCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - - if (!pObject) - { - cur_entry->status = MK_OBJECT_NOT_IN_CACHE; - return cur_entry->status; - } - - /* Wait for the object to complete */ - if (!CacheObject_GetIsCompleted(pObject)) - return 0; -#if 0 - /* If the object has been aborted or expired */ - if ((CACHEOBJECT_ABORTED == CacheObject_GetState(pObject)) || - (CACHEOBJECT_EXPIRED == CacheObject_GetState(pObject))) - { - (*con_data->stream->complete)(con_data->stream); - PR_Free(con_data->stream); - /* CacheObject->UnsetReadLock(pObject); */ - PR_Free(con_data); - - cur_entry->status = MK_DATA_LOADED; - NET_ClearCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - if (!cur_entry->URL_s->load_background) - FE_GraphProgressDestroy( - cur_entry->window_id, - cur_entry->URL_s, - cur_entry->URL_s->content_length, - cur_entry->bytes_received); - return -1; - } -#endif - /* Get the buffer size that the stream is ready to receive */ - buffer_size = (*con_data->stream->is_write_ready)(con_data->stream); - - /* if the stream doesn't want any data, continue */ - if (0 == buffer_size) - { - cur_entry->status = 1; - return cur_entry->status; - } - - /* Use the minimum from these factors. - * Not sure why we are doing this part. Will look into this later- Gagan - */ - buffer_size = MIN(buffer_size, (unsigned int) NET_Socket_Buffer_Size); - buffer_size = MIN(buffer_size, NET_MEM_CACHE_OUTPUT_SIZE); - - amountRead = CacheObject_Read(pObject, NET_Socket_Buffer, buffer_size); - if (amountRead > 0) - { - cur_entry->status = (*con_data->stream->put_block)(con_data->stream, NET_Socket_Buffer, amountRead); - - /* Update the progress control */ - if (!cur_entry->URL_s->load_background) - FE_GraphProgress( - cur_entry->window_id, - cur_entry->URL_s, - cur_entry->bytes_received, - amountRead, - cur_entry->URL_s->content_length); - - if(cur_entry->status < 0) - { - NET_ClearCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - - if (!cur_entry->URL_s->load_background) - { - FE_GraphProgressDestroy(cur_entry->window_id, - cur_entry->URL_s, - cur_entry->URL_s->content_length, - cur_entry->bytes_received); - } - PR_Free(con_data); - return (cur_entry->status); - } - - cur_entry->bytes_received += amountRead; - } - else /* we didn't read anything, must be the end. */ - { - (*con_data->stream->complete)(con_data->stream); - PR_Free(con_data->stream); - /* Reset read locks, reset streams, etc. */ - CacheObject_Reset(pObject); - - PR_Free(con_data); - - cur_entry->status = MK_DATA_LOADED; - NET_ClearCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - if (!cur_entry->URL_s->load_background) - FE_GraphProgressDestroy( - cur_entry->window_id, - cur_entry->URL_s, - cur_entry->URL_s->content_length, - cur_entry->bytes_received); - return -1; - } - - return cur_entry->status; - } - return -1; -} - -/* called by functions in mkgeturl to interrupt the loading of - * an object. (Usually a user interrupt) - */ -PRIVATE int32 -net_InterruptNuCache (ActiveEntry * cur_entry) -{ - if (cur_entry) - { - NuCacheConData* con_data = (NuCacheConData*) cur_entry->con_data; - void* pObject = cur_entry->URL_s->cache_object; - - (*con_data->stream->abort)(con_data->stream, MK_INTERRUPTED); - PR_Free(con_data->stream); - /* Reset read locks, reset streams, etc. */ - CacheObject_Reset(pObject); - - PR_Free(con_data); - - NET_ClearCallNetlibAllTheTime(cur_entry->window_id, "nucache"); - - cur_entry->status = MK_INTERRUPTED; - - return cur_entry->status; - } - return -1; -} - - -PRIVATE void -net_CleanupNuCacheProtocol(void) -{ -} - -void -NET_InitNuCacheProtocol(void) -{ - static NET_ProtoImpl nu_cache_proto_impl; - - nu_cache_proto_impl.init = net_NuCacheLoad; - nu_cache_proto_impl.process = net_ProcessNuCache; - nu_cache_proto_impl.interrupt = net_InterruptNuCache; - nu_cache_proto_impl.resume = NULL; - nu_cache_proto_impl.cleanup = net_CleanupNuCacheProtocol; - - NET_RegisterProtocolImplementation(&nu_cache_proto_impl, NU_CACHE_TYPE_URL); -} -#endif /* NU_CACHE */ -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cache/mkmemcac.h b/mozilla/network/cache/mkmemcac.h deleted file mode 100644 index bf616263231..00000000000 --- a/mozilla/network/cache/mkmemcac.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MK_MEMORY_CACHE_H - -#include "mkgeturl.h" - -/* A pointer to this struct is passed as the converter_obj argument to - * NET_MemCacheConverter. - */ -typedef struct net_MemCacheConverterObject { - NET_StreamClass *next_stream; - PRBool dont_hold_URL_s; -} net_MemCacheConverterObject; - -extern NET_StreamClass * -NET_MemCacheConverter (FO_Present_Types format_out, - void *converter_obj, - URL_Struct *URL_s, - MWContext *window_id); - -/* remove a URL from the memory cache - */ -extern void -NET_RemoveURLFromMemCache(URL_Struct *URL_s); - -/* set or unset a lock on a memory cache object - */ -extern void -NET_ChangeMemCacheLock(URL_Struct *URL_s, PRBool set); - -/* Create a wysiwyg cache converter to a copy of the current entry for URL_s. - */ -extern NET_StreamClass * -net_CloneWysiwygMemCacheEntry(MWContext *window_id, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href); -/* return the first cache object in memory */ -extern net_CacheObject * -NET_FirstMemCacheObject(XP_List* list_ptr); - -/* return the next cache object in memory */ -extern net_CacheObject * -NET_NextMemCacheObject(XP_List* list_ptr); - -#ifndef NU_CACHE -MODULE_PRIVATE int NET_FindURLInMemCache(URL_Struct * URL_s, MWContext *ctxt); -MODULE_PRIVATE void NET_DisplayMemCacheInfoAsHTML(ActiveEntry * cur_entry); -#endif - - -#ifdef NU_CACHE -extern void NET_InitNuCacheProtocol(void); -#else -extern void NET_InitMemCacProtocol(void); -#endif - -#endif /* MK_MEMORY_CACHE_H */ diff --git a/mozilla/network/cache/netcache.h b/mozilla/network/cache/netcache.h deleted file mode 100644 index 6767e0a6480..00000000000 --- a/mozilla/network/cache/netcache.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef NETCACHE_H -#define NETCACHE_H - -#include "mkgeturl.h" - -PR_BEGIN_EXTERN_C - -/* Initialization */ -extern void NET_CacheInit(void); -/* Shutdown */ -extern void NET_CleanupCache(void); - -/* create an HTML stream and push a bunch of HTML about - * the cache - */ -extern void NET_DisplayCacheInfoAsHTML(ActiveEntry * cur_entry); - -/* create an HTML stream and push a bunch of HTML about - * the memory cache - TODO consolidate these two into one function! - Gagan - */ -extern void NET_DisplayMemCacheInfoAsHTML(ActiveEntry * cur_entry); - -extern int NET_FindURLInCache(URL_Struct * URL_s, MWContext *ctxt); - -#ifdef NU_CACHE -extern void NET_InitNuCacheProtocol(void); -#else -extern void NET_InitMemCacProtocol(void); -#endif - -/* Will go away later */ -extern PRBool NET_IsCacheTraceOn(void); - -/* return TRUE if the URL is in the cache and - * is a partial cache file - TODO- only used in HTTP- cleanup - Gagan - */ -extern PRBool NET_IsPartialCacheFile(URL_Struct *URL_s); - -#ifdef NU_CACHE -/* return TRUE if the URL exists somewhere in the cache */ -extern PRBool NET_IsURLInCache(const URL_Struct *URL_s); -#endif - -/* Update cache entry on a 304 return*/ -extern void NET_RefreshCacheFileExpiration(URL_Struct * URL_s); - -/* remove a URL from the cache */ -extern void NET_RemoveURLFromCache(URL_Struct *URL_s); - -/* Removed in NU_Cache, SAR should go through new api. - Gagan */ -#ifndef NU_CACHE -extern void NET_OpenExtCacheFAT(MWContext *ctxt, char * cache_name, char * instructions); -extern void CACHE_CloseAllOpenSARCache(); -extern void CACHE_OpenAllSARCache(); -extern int NET_FindURLInMemCache(URL_Struct * URL_s, MWContext *ctxt); -/* lookup routine - * - * builds a key and looks for it in the database. Returns an access - * method and sets a filename in the URL struct if found - */ -extern int NET_FindURLInExtCache(URL_Struct * URL_s, MWContext *ctxt); -#endif - -PR_END_EXTERN_C - -#endif /* NETCACHE_H */ diff --git a/mozilla/network/cache/nu/Makefile.in b/mozilla/network/cache/nu/Makefile.in deleted file mode 100644 index 8e79579887a..00000000000 --- a/mozilla/network/cache/nu/Makefile.in +++ /dev/null @@ -1,32 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -DIRS = public src - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/nu/include/Makefile.in b/mozilla/network/cache/nu/include/Makefile.in deleted file mode 100644 index a3168e544c9..00000000000 --- a/mozilla/network/cache/nu/include/Makefile.in +++ /dev/null @@ -1,30 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/nu/include/makefile.win b/mozilla/network/cache/nu/include/makefile.win deleted file mode 100644 index c465941b2a3..00000000000 --- a/mozilla/network/cache/nu/include/makefile.win +++ /dev/null @@ -1,22 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -!include $(MOZ_SRC)\ns\config\rules.mak diff --git a/mozilla/network/cache/nu/include/nsCacheTrace.h b/mozilla/network/cache/nu/include/nsCacheTrace.h deleted file mode 100644 index e6191554c02..00000000000 --- a/mozilla/network/cache/nu/include/nsCacheTrace.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* created 02/02/98. - * nsCacheTrace is a silly little class to extract trace - * related functionality. I created this class to make it easier to - * change that at one place. In release mode this shouldn't even be there. - * I still have to make some changes on the calls to default to noop - * in release. -Gagan Saksena 09/15/98 - */ -#ifndef _nsCacheTrace_H_ -#define _nsCacheTrace_H_ - -#ifndef CRLF -# define CRLF "\r\n" -#endif - -#include "prtypes.h" -#include "prlog.h" - -class nsCacheTrace -{ - -public: - nsCacheTrace(void); - static void Enable(PRBool bEnable); - static PRBool IsEnabled(void); - static void Trace(const char* msg); - static void Traceln(const char* msg); - static void Use(char* buffer); - static char* m_TraceBuffer; -private: - PRBool m_bEnabled; -}; - -inline void nsCacheTrace::Trace(const char* msg) -{ - PR_ASSERT(msg); - //Do log stuff here TODO -} - -inline void nsCacheTrace::Traceln(const char* msg) -{ - Trace(msg); - Trace(CRLF); -} - -inline void nsCacheTrace::Use(char* buffer) -{ - m_TraceBuffer = buffer; -} -#endif diff --git a/mozilla/network/cache/nu/include/nsFFEntry.h b/mozilla/network/cache/nu/include/nsFFEntry.h deleted file mode 100644 index f68997b18a6..00000000000 --- a/mozilla/network/cache/nu/include/nsFFEntry.h +++ /dev/null @@ -1,141 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* This is part of the Flat-file cache architecture. The nsFFEntry class - * represents a single entry in the TOC. All io operations take place - * through the FFEntry's read and write functions. An entry may comprise - * of one or more objects which are blocks of data spread across the flat - * file. - Gagan Saksena 09/15/98 */ - -#ifndef nsFFEntry_h__ -#define nsFFEntry_h__ - - -#include "nsFFObject.h" -//#include "nsISupports.h" - -class nsFFEntry//: public nsISupports -{ - -public: - nsFFEntry(); - nsFFEntry(const PRUint32 i_ID); - //Single block entries can use this constructor - nsFFEntry(const PRUint32 i_ID, const PRUint32 i_offset, const PRUint32 i_size); - virtual ~nsFFEntry(); - - /* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); - */ - - PRBool AddObject(const nsFFObject* i_object); - - //Appends an entry to the list - PRBool AddEntry(const nsFFEntry* i_pEntry); - - nsFFObject* FirstObject(void) const; - void FirstObject(const nsFFObject* i_object); - - PRUint32 ID(void) const; - void ID(const PRUint32 i_ID); - - nsFFEntry* NextEntry(void) const; - void NextEntry(const nsFFEntry* i_pEntry); - - //Returns the number of objects in this entry. - PRUint32 Objects(void) const; - - PRBool Remove(void); - - PRUint32 Size(void) const; - -protected: - -private: - nsFFEntry(const nsFFEntry& o); - nsFFEntry& operator=(const nsFFEntry& o); - - nsFFObject* m_pFirstObject; - nsFFEntry* m_pNextEntry; - - PRUint32 m_ID; - PRUint32 m_Objects; -}; - -inline -PRBool nsFFEntry::AddEntry(const nsFFEntry* i_Entry) -{ - if (!i_Entry) - return PR_FALSE; - if (m_pNextEntry) - return m_pNextEntry->AddEntry(i_Entry); - m_pNextEntry = (nsFFEntry*) i_Entry; - return PR_TRUE; -} - -inline -nsFFObject* nsFFEntry::FirstObject(void) const -{ - return m_pFirstObject; -} - -inline -PRUint32 nsFFEntry::ID(void) const -{ - return m_ID; -} - -inline -void nsFFEntry::ID(const PRUint32 i_id) -{ - m_ID = i_id; -} - -inline -nsFFEntry* nsFFEntry::NextEntry(void) const -{ - return m_pNextEntry; -} - -inline -void nsFFEntry::NextEntry(const nsFFEntry* i_pEntry) -{ - m_pNextEntry = (nsFFEntry*) i_pEntry; -} - -inline -PRUint32 nsFFEntry::Objects(void) const -{ - return m_Objects; -} - -inline -PRUint32 nsFFEntry::Size(void) const -{ - return m_pFirstObject ? m_pFirstObject->TotalSize() : 0; // Assumption that there is no zero length files //TODO -} - -#endif // nsFFEntry_h__ - diff --git a/mozilla/network/cache/nu/include/nsFFObject.h b/mozilla/network/cache/nu/include/nsFFObject.h deleted file mode 100644 index 0cf4c08fa62..00000000000 --- a/mozilla/network/cache/nu/include/nsFFObject.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* The nsFFObject class represent a single object block that is the smallest - * page unit on the flat file. This class is part of the flat file cache architecture. - * It consists of the offset of the block and the size in use. - * -Gagan Saksena 09/15/98 */ - -#ifndef nsFFObject_h__ -#define nsFFObject_h__ - -#include "prtypes.h" - -class nsFFObject -{ - -public: - nsFFObject( - PRUint32 i_ID, - PRUint32 i_Offset, - PRUint32 i_Size = 0); - - virtual ~nsFFObject(); - - PRBool Add(const nsFFObject* i_object); - - PRUint32 ID(void) const; - void ID(const PRUint32 i_ID); - - nsFFObject* Next(void) const; - void Next(nsFFObject* io_pNext); - - PRUint32 Offset(void) const; - void Offset(const PRUint32 i_offset); - - PRUint32 Size(void) const; - void Size(const PRUint32 i_Size); - - PRUint32 TotalSize(void) const; - -protected: - -private: - nsFFObject(const nsFFObject& o); - nsFFObject& operator=(const nsFFObject& o); - - PRUint32 m_ID; - PRUint32 m_Offset; - PRUint32 m_Size; - - nsFFObject* m_pNext; -}; - -inline -PRUint32 nsFFObject::ID(void) const -{ - return m_ID; -} - -inline -void nsFFObject::ID(const PRUint32 i_ID) -{ - m_ID = i_ID; -} - -inline -nsFFObject* nsFFObject::Next(void) const -{ - return m_pNext; -} - -inline -void nsFFObject::Next(nsFFObject* io_pNext) -{ - if (io_pNext) - io_pNext->ID(m_ID); - m_pNext = io_pNext; - // Overlap check! //TODO - //PR_ASSERT(io_pNext->Offset() > m_Offset + m_Size) || - // (io_pNext->Offset() + io_pNext->Size() < m_Offset) -} - -inline -PRUint32 nsFFObject::Offset(void) const -{ - return m_Offset; -} - -inline -void nsFFObject::Offset(const PRUint32 i_Offset) -{ - m_Offset = i_Offset; - //TODO - overlap check. -} - -inline -PRUint32 nsFFObject::Size(void) const -{ - return m_Size; -} - -inline -void nsFFObject::Size(const PRUint32 i_Size) -{ - m_Size = i_Size; - //TODO - Overlap check. -} - -inline -PRUint32 nsFFObject::TotalSize(void) const -{ - return m_Size + (m_pNext ? m_pNext->TotalSize() : 0); -} -#endif // nsFFObject_h__ - diff --git a/mozilla/network/cache/nu/include/nsFlatFile.h b/mozilla/network/cache/nu/include/nsFlatFile.h deleted file mode 100644 index 0c1ad9363d5..00000000000 --- a/mozilla/network/cache/nu/include/nsFlatFile.h +++ /dev/null @@ -1,111 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* A class to handle flat file storage mechanism -Gagan Saksena 09/15/98 */ -#ifndef nsFlatFile_h__ -#define nsFlatFile_h__ - -#include "prtypes.h" -#include "prio.h" - -//#include "nsISupports.h" - -#ifdef IS_LITTLE_ENDIAN -#ifndef COPY_INT32 -#define COPY_INT32(_a,_b) memcpy(_a, _b, sizeof(int32)) -#else -#define COPY_INT32(_a,_b) /* swap */ \ - do { \ - ((char *)(_a))[0] = ((char *)(_b))[3]; \ - ((char *)(_a))[1] = ((char *)(_b))[2]; \ - ((char *)(_a))[2] = ((char *)(_b))[1]; \ - ((char *)(_a))[3] = ((char *)(_b))[0]; \ - } while(0) -#endif -#endif - -static const PRUint32 kPAGE_SIZE =4096; - -class nsFlatFile //: public nsISupports -{ -public: - - nsFlatFile(const char* i_pFilename, - const PRUint32 i_FileSize= 5242880); // 5 meg - // TODO think if we want to substract the toc size from this? - - virtual ~nsFlatFile(); - - const char* Filename(void) const; - - PRUint32 HeaderSize(void) const; - - void Init(void); - - PRBool IsValid(void) const; - - PRUint32 Size(void) const; - /* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); - */ -protected: - -private: - nsFlatFile(const nsFlatFile& o); - nsFlatFile& operator=(const nsFlatFile& o); - - PRBool m_bIsValid; - char* m_pFilename; - PRUint32 m_Size; - - PRFileDesc* m_pFD; - PRUint32 m_HeaderSize; -}; - -inline -const char* nsFlatFile::Filename(void) const -{ - return m_pFilename; -} - -inline -PRUint32 nsFlatFile::HeaderSize(void) const -{ - return m_HeaderSize; -} - -inline -PRBool nsFlatFile::IsValid(void) const -{ - return m_bIsValid; -} - -inline -PRUint32 nsFlatFile::Size(void) const -{ - return m_Size; -} -#endif // nsFlatFile_h__ - diff --git a/mozilla/network/cache/nu/include/nsTOC.h b/mozilla/network/cache/nu/include/nsTOC.h deleted file mode 100644 index 7ddeab6c740..00000000000 --- a/mozilla/network/cache/nu/include/nsTOC.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* This is the TOC or the Table of Contents for the flat file. This class - * is part of the flat file cache architecture. The first entry in the TOC - * is reserved for the list of free objects. - * -Gagan Saksena 09/15/98 - */ -#ifndef nsTOC_h__ -#define nsTOC_h__ - -//#include "nsISupports.h" - -#include "nsFlatFile.h" -#include "nsFFEntry.h" - -class nsTOC//: public nsISupports -{ - -public: - nsTOC(const char* i_pFilename, nsFlatFile* i_pFlatFile); - virtual ~nsTOC(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - - nsFFEntry* AddEntry(PRUint32 i_size = kPAGE_SIZE); - - PRUint32 Entries(void) const; - - const char* Filename(void) const; - - nsFFEntry* FirstDataEntry(void) const; - - nsFFEntry* FreeEntry(void) const; - - void Init(void); - - PRBool IsValid(void) const; - -protected: - PRUint32 NextID(void) const; - - PRBool Serialize(nsFFEntry* io_Entry, PRBool bRead = PR_FALSE); - - -private: - nsTOC(const nsTOC& o); - nsTOC& operator=(const nsTOC& o); - - nsFFEntry* m_pContents; // The first entry is reserved for free space list - PRUint32 m_Entries; - char* m_pFilename; - nsFlatFile* m_pFlatFile; - PRFileDesc* m_pFD; - PRBool m_bIsValid; -}; - -inline -PRUint32 nsTOC::Entries(void) const -{ - return m_Entries; -} - -inline -const char* nsTOC::Filename(void) const -{ - return m_pFilename; -} - -inline -nsFFEntry* nsTOC::FirstDataEntry(void) const -{ - return m_pContents ? m_pContents->NextEntry() : 0; -} - -inline -nsFFEntry* nsTOC::FreeEntry(void) const -{ - return m_pContents; -} - -inline -PRBool nsTOC::IsValid(void) const -{ - return m_bIsValid; -} - -inline -PRUint32 nsTOC::NextID(void) const -{ - return m_Entries + 1; -} -#endif // nsTOC_h__ - diff --git a/mozilla/network/cache/nu/include/nsTimeIt.h b/mozilla/network/cache/nu/include/nsTimeIt.h deleted file mode 100644 index 9a0a4bc59ab..00000000000 --- a/mozilla/network/cache/nu/include/nsTimeIt.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* A class to time excursion events. Declare an object of this class - * within the scope to be timed. - * - Gagan Saksena 09/15/98 - */ - -#ifndef nsTimeIt_h__ -#define nsTimeIt_h__ - -#include "prtypes.h" -#include "prinrval.h" - -class nsTimeIt -{ -public: - nsTimeIt(PRUint32& tmp); - ~nsTimeIt(); -private: - PRIntervalTime t; - PRUint32& dest; -}; - -inline -nsTimeIt::nsTimeIt(PRUint32& tmp):t(PR_IntervalNow()), dest(tmp) -{ -} - -inline -nsTimeIt::~nsTimeIt() -{ - dest = PR_IntervalToMicroseconds(PR_IntervalNow()-t); -} - -#endif // nsTimeIt_h__ - diff --git a/mozilla/network/cache/nu/macbuild/nuCache.Prefix b/mozilla/network/cache/nu/macbuild/nuCache.Prefix deleted file mode 100644 index c899b6b6d9b..00000000000 --- a/mozilla/network/cache/nu/macbuild/nuCache.Prefix +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -// -// nuCache.Prefix -// -// Global prefix file for the nuCache project. -// -// - -#include "MacPrefix_debug.h" -#include "nuCacheConfig.h" diff --git a/mozilla/network/cache/nu/macbuild/nuCache.mcp b/mozilla/network/cache/nu/macbuild/nuCache.mcp deleted file mode 100644 index 78316736904..00000000000 Binary files a/mozilla/network/cache/nu/macbuild/nuCache.mcp and /dev/null differ diff --git a/mozilla/network/cache/nu/macbuild/nuCacheConfig.h b/mozilla/network/cache/nu/macbuild/nuCacheConfig.h deleted file mode 100644 index 3d3be032542..00000000000 --- a/mozilla/network/cache/nu/macbuild/nuCacheConfig.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#define CGLUESUPPORTED 0 // turn off C glue support to avoid conflict on create() in RDF diff --git a/mozilla/network/cache/nu/macbuild/nuCacheDebug.Prefix b/mozilla/network/cache/nu/macbuild/nuCacheDebug.Prefix deleted file mode 100644 index 2295de70136..00000000000 --- a/mozilla/network/cache/nu/macbuild/nuCacheDebug.Prefix +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -// -// RDFDebug.Prefix -// -// Global prefix file for the nuCache project. -// -// - -#include "MacPrefix_debug.h" -#include "nuCacheConfig.h" diff --git a/mozilla/network/cache/nu/makefile.win b/mozilla/network/cache/nu/makefile.win deleted file mode 100644 index 6f7b1e55d43..00000000000 --- a/mozilla/network/cache/nu/makefile.win +++ /dev/null @@ -1,26 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -DEPTH=..\..\.. - -DIRS=public src - -include <$(DEPTH)\config\rules.mak> diff --git a/mozilla/network/cache/nu/nsGeneric.cpp b/mozilla/network/cache/nu/nsGeneric.cpp deleted file mode 100644 index ac16fc60deb..00000000000 --- a/mozilla/network/cache/nu/nsGeneric.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* This is my generic cpp file to aid in creating a new class. This file - * declares the implementation of nsGeneric class. This class is cool... - * -Gagan Saksena 09/15/98 - */ - -#include "nsGeneric.h" - -nsGeneric::nsGeneric() -{ -} - -nsGeneric::~nsGeneric() -{ -} - -nsrefcnt nsGeneric::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsGeneric::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsGeneric::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} - -nsGeneric:: diff --git a/mozilla/network/cache/nu/nsGeneric.h b/mozilla/network/cache/nu/nsGeneric.h deleted file mode 100644 index 1251a1be7fa..00000000000 --- a/mozilla/network/cache/nu/nsGeneric.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsGeneric_h__ -#define nsGeneric_h__ - -/* This is a generic header file for creating new classes. It is not - * part of the build system. -Gagan Saksena 09/15/98 - */ -#include "nsISupports.h" - -class nsGeneric: public nsISupports -{ - -public: - nsGeneric(); - virtual ~nsGeneric(); - - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); - -protected: - -private: - nsGeneric(const nsGeneric& o); - nsGeneric& operator=(const nsGeneric& o); -}; - -#endif // nsGeneric_h__ - diff --git a/mozilla/network/cache/nu/public/CacheStubs.h b/mozilla/network/cache/nu/public/CacheStubs.h deleted file mode 100644 index 8b15ec88d27..00000000000 --- a/mozilla/network/cache/nu/public/CacheStubs.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Design and original implementation by Gagan Saksena '98 - * Ideally we should be using the C++ api directly, but since the core of - * Netlib is still in C, this file uses the stub functions that call the C++ - * API internally, allowing C programs to use the new cache architecture. - * If you are accessing the cache, see if you can directly use the C++ api. - * -Gagan Saksena 09/15/98 - */ - -#ifndef CacheStubs_h__ -#define CacheStubs_h__ - -#include "prtypes.h" -#include "prinrval.h" - -#define MEM_MODULE_ID 0 -#define DISK_MODULE_ID 1 - -PR_BEGIN_EXTERN_C - - /* General mapped functions which resolve to a bunch of internal calls. */ - extern void Cache_Init(void); - extern void Cache_Shutdown(void); - - /* Cache Manager stub functions - Does not include some functions not required in the current - design like AddModule etc... If you need to these functions, try - accessing them directly thru the C++ api or let me know. - Check nsCacheManager.h for details on these functions.*/ - extern PRBool CacheManager_Contains(const char* i_url); - extern PRInt16 CacheManager_Entries(void); - extern void* CacheManager_GetObject(const char* i_url); - extern void CacheManager_InfoAsHTML(char* o_Buffer); - extern PRBool CacheManager_IsOffline(void); - extern void CacheManager_Offline(PRBool bSet); - extern PRBool CacheManager_Remove(const char* i_url); - extern PRUint32 CacheManager_WorstCaseTime(void); - - /* Cache Object- check nsCacheObject.h for details on these functions */ - extern void* CacheObject_Create(const char* i_url); - extern void CacheObject_Destroy(void* pThis); - extern const char* CacheObject_GetAddress(const void* pThis); - extern const char* CacheObject_GetCharset(const void* pThis); - extern const char* CacheObject_GetContentEncoding(const void* pThis); - extern PRUint32 CacheObject_GetContentLength(const void* pThis); - extern const char* CacheObject_GetContentType(const void* pThis); - extern const char* CacheObject_GetEtag(const void* pThis); - extern PRIntervalTime CacheObject_GetExpires(const void* pThis); - extern const char* CacheObject_GetFilename(const void* pThis); - extern PRBool CacheObject_GetIsCompleted(const void* pThis); - extern PRIntervalTime CacheObject_GetLastAccessed(const void* pThis); - extern PRIntervalTime CacheObject_GetLastModified(const void* pThis); - extern PRInt16 CacheObject_GetModule(const void* pThis); - extern const char* CacheObject_GetPageServicesURL(const void* pThis); - extern const char* CacheObject_GetPostData(const void* pThis); - extern PRUint32 CacheObject_GetPostDataLen(const void* pThis); - extern PRUint32 CacheObject_GetSize(const void* pThis); - extern PRUint32 CacheObject_GetState(const void* pThis); - extern PRUint32 CacheObject_Hits(const void* pThis); - extern PRBool CacheObject_IsExpired(const void* pThis); - extern PRBool CacheObject_IsPartial(const void* pThis); - extern PRUint32 CacheObject_Read(const void* pThis, char* o_Destination, PRUint32 i_Len); - extern void CacheObject_Reset(void* pThis); - extern void CacheObject_SetAddress(void* pThis, const char* i_Address); - extern void CacheObject_SetCharset(void* pThis, const char* i_CharSet); - extern void CacheObject_SetContentEncoding(void* pThis, const char* i_Encoding); - extern void CacheObject_SetContentLength(void* pThis, PRUint32 i_Len); - extern void CacheObject_SetContentType(void* pThis, const char* i_Type); - extern void CacheObject_SetEtag(void* pThis, const char* i_Etag); - extern void CacheObject_SetExpires(void *pThis, const PRIntervalTime i_Time); - extern void CacheObject_SetFilename(void *pThis, const char* i_Filename); - extern void CacheObject_SetIsCompleted(void *pThis, PRBool bComplete); - extern void CacheObject_SetLastModified(void* pThis, const PRIntervalTime i_Time); - extern void CacheObject_SetModule(void* pThis, const PRInt16 i_Module); - extern void CacheObject_SetPageServicesURL(void* pThis, const char* i_Url); - extern void CacheObject_SetPostData(void* pThis, const char* i_PostData, const PRUint32 i_Len); - extern void CacheObject_SetSize(void* pThis, const PRUint32 i_Size); - extern void CacheObject_SetState(void* pThis, const PRUint32 i_State); - extern PRBool CacheObject_Synch(void* pThis); - extern PRUint32 CacheObject_Write(void* pThis, const char* i_buffer, const PRUint32 i_length); - - /* Cache Prefs- check nsCachePref.h for details on these functions */ - extern PRUint32 CachePref_GetDiskCacheSize(void); - extern PRBool CachePref_GetDiskCacheSSL(void); - extern PRUint32 CachePref_GetMemCacheSize(void); - extern void CachePref_SetDiskCacheSize(const PRUint32 i_Size); - extern void CachePref_SetDiskCacheSSL(PRBool bSet); - extern void CachePref_SetMemCacheSize(const PRUint32 i_Size); - - /* Cache Trace- Check nsCacheTrace.h for details on these functions */ - extern void CacheTrace_Enable(PRBool bEnable); - extern PRBool CacheTrace_IsEnabled(void); - - /* Disk Module- Check nsDiskModule.h for details on these functions */ - extern PRBool DiskModule_AddObject(void* pCacheObject); - extern PRBool DiskModule_Contains(const char* i_url); - extern PRUint32 DiskModule_Entries(void); - extern PRUint32 DiskModule_GetSize(void); /* Should be the same as CachePref_DiskCacheSize */ - extern PRUint32 DiskModule_GetSizeInUse(void); - extern PRBool DiskModule_IsEnabled(void); - extern PRBool DiskModule_Remove(const char* i_url); - extern PRBool DiskModule_RemoveAll(void); - extern void DiskModule_SetSize(PRUint32 i_Size); - - /* Mem Module- Check nsMemModule.h for details on these functions */ - extern PRBool MemModule_AddObject(void* pCacheObject); - extern PRBool MemModule_Contains(const char* i_url); - extern PRUint32 MemModule_Entries(void); - extern PRUint32 MemModule_GetSize(void); /* Should be the same as CachePref_MemCacheSize */ - extern PRUint32 MemModule_GetSizeInUse(void); - extern PRBool MemModule_IsEnabled(void); - extern PRBool MemModule_Remove(const char* i_url); - extern PRBool MemModule_RemoveAll(void); - extern void MemModule_SetSize(PRUint32 i_Size); - -PR_END_EXTERN_C - -#endif // CacheStubs_h__ - diff --git a/mozilla/network/cache/nu/public/MANIFEST b/mozilla/network/cache/nu/public/MANIFEST deleted file mode 100644 index 82496c6ab8e..00000000000 --- a/mozilla/network/cache/nu/public/MANIFEST +++ /dev/null @@ -1,22 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -CacheStubs.h -nsBkgThread.h -nsCacheBkgThd.h -nsCacheIterator.h -nsCacheManager.h -nsCacheModule.h -nsCacheObject.h -nsCachePref.h -nsDiskModule.h -nsEnumeration.h -nsFileStream.h -nsHash.h -nsIterator.h -nsMemCacheObject.h -nsMemModule.h -nsMemStream.h -nsMonitorable.h -nsStream.h \ No newline at end of file diff --git a/mozilla/network/cache/nu/public/Makefile.in b/mozilla/network/cache/nu/public/Makefile.in deleted file mode 100644 index b9fcc56a2cf..00000000000 --- a/mozilla/network/cache/nu/public/Makefile.in +++ /dev/null @@ -1,54 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = cache - -EXPORTS = \ - CacheStubs.h \ - nsBkgThread.h \ - nsCacheBkgThd.h \ - nsCacheIterator.h \ - nsCacheManager.h \ - nsCacheModule.h \ - nsCacheObject.h \ - nsCachePref.h \ - nsDiskModule.h \ - nsEnumeration.h \ - nsFileStream.h \ - nsIterator.h \ - nsMemCacheObject.h \ - nsMemModule.h \ - nsMemStream.h \ - nsMonitorable.h \ - nsStream.h \ - $(NULL) - -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/nu/public/makefile.win b/mozilla/network/cache/nu/public/makefile.win deleted file mode 100644 index 40b7d6aadc2..00000000000 --- a/mozilla/network/cache/nu/public/makefile.win +++ /dev/null @@ -1,48 +0,0 @@ -#!nmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -DEPTH=..\..\..\.. - - -MODULE=cache - -EXPORTS= \ - CacheStubs.h \ - nsBkgThread.h \ - nsCacheBkgThd.h \ - nsCacheIterator.h \ - nsCacheManager.h \ - nsCacheModule.h \ - nsCacheObject.h \ - nsCachePref.h \ - nsDiskModule.h \ - nsEnumeration.h \ - nsFileStream.h \ - nsIterator.h \ - nsMemCacheObject.h \ - nsMemModule.h \ - nsMemStream.h \ - nsMonitorable.h \ - nsStream.h \ - $(NULL) - -include <$(DEPTH)\config\rules.mak> - diff --git a/mozilla/network/cache/nu/public/nsBkgThread.h b/mozilla/network/cache/nu/public/nsBkgThread.h deleted file mode 100644 index 9227fdc0a82..00000000000 --- a/mozilla/network/cache/nu/public/nsBkgThread.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* This is a super cool class that does the background thread magic using - * NSPR Threads. This class is used to maintain odd tasks in the background - * like like updating, expiration, validation and garbage collection. - * - * Note that this is a noop active when the cache manager is offline. - * - * In PRThread terms, this is a PR_USER_THREAD with local scope. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsBkgThread_h__ -#define nsBkgThread_h__ - -//#include "nsISupports.h" -#include "prthread.h" -#include "prinrval.h" - -class nsBkgThread//: public nsISupports -{ - -public: - nsBkgThread(PRIntervalTime iSleepTime, PRBool bStart=PR_TRUE); - virtual ~nsBkgThread(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - void Process(void); - virtual void Run(void) = 0; - void Stop(void); -protected: - PRThread* m_pThread; - PRBool m_bContinue; - PRIntervalTime m_SleepTime; - -private: - nsBkgThread(const nsBkgThread& o); - nsBkgThread& operator=(const nsBkgThread& o); - -}; - -#endif // nsBkgThread_h__ - diff --git a/mozilla/network/cache/nu/public/nsCacheBkgThd.h b/mozilla/network/cache/nu/public/nsCacheBkgThd.h deleted file mode 100644 index 741d09a29d2..00000000000 --- a/mozilla/network/cache/nu/public/nsCacheBkgThd.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* This class is the actual implementation of the original class nsBkgThread, - * but I am too lazy to move the comments from nsBkgThread's - * header file to here. :-) - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsCacheBkgThd_h__ -#define nsCacheBkgThd_h__ - -#include "nsBkgThread.h" - -class nsCacheBkgThd: public nsBkgThread -{ - -public: - nsCacheBkgThd(PRIntervalTime iSleepTime); - virtual ~nsCacheBkgThd(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - void Run(void); - -protected: - -private: - nsCacheBkgThd(const nsCacheBkgThd& o); - nsCacheBkgThd& operator=(const nsCacheBkgThd& o); -}; - -#endif // nsCacheBkgThd_h__ - diff --git a/mozilla/network/cache/nu/public/nsCacheFileStream.h b/mozilla/network/cache/nu/public/nsCacheFileStream.h deleted file mode 100644 index b9c55c1ee7e..00000000000 --- a/mozilla/network/cache/nu/public/nsCacheFileStream.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* nsCacheFileStream. The file/disk based implementation of the nsStream class. - * It basically maps the read write functions to the file equivalents. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsCacheFileStream_h__ -#define nsCacheFileStream_h__ - -//#include "nsISupports.h" -#include "nsStream.h" -#include "prio.h" // PRFileDesc - -/* now using the _real_ nsFileStream */ -#include "nsFileSpec.h" -#include "nsFileStream.h" - -class nsCacheFileStream: public nsStream -{ - -public: - nsCacheFileStream(const char* i_Filename); - virtual ~nsCacheFileStream(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ -#ifdef NU_CACHE_FILE_STREAM - PRFileDesc* FileDesc(void); -#endif - - PRInt32 Read(void* o_Buffer, PRUint32 i_Len); - void Reset(void); - PRInt32 Write(const void* i_Buffer, PRUint32 i_Len); - -protected: - - PRBool Open(void); - -private: - nsCacheFileStream(const nsCacheFileStream& o); - nsCacheFileStream& operator=(const nsCacheFileStream& o); -#ifdef NU_CACHE_FILE_STREAM - PRFileDesc* m_pFile; -#else - nsIOFileStream *m_pFile; -#endif - char* m_pFilename; -}; - -#ifdef NU_CACHE_FILE_STREAM -inline -PRFileDesc* nsCacheFileStream::FileDesc(void) -{ - return m_pFile; -} -#endif - -#endif // nsCacheFileStream_h__ - diff --git a/mozilla/network/cache/nu/public/nsCacheIterator.h b/mozilla/network/cache/nu/public/nsCacheIterator.h deleted file mode 100644 index ebadcf93643..00000000000 --- a/mozilla/network/cache/nu/public/nsCacheIterator.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* A simple cache iterator for cache architecture. This is a temporary class - * which will be (should be) replaced by more professional quality code, or - * at least moved to a more common area later on. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsCacheIterator_h__ -#define nsCacheIterator_h__ - -#include "nsIterator.h" -#include "prtypes.h" -#include "nsCacheModule.h" - -class nsCacheIterator: public nsIterator -{ - -public: - nsCacheIterator(nsCacheModule* i_pModule); - virtual ~nsCacheIterator(); - - virtual PRBool IsDone(void) const; - virtual nsCacheObject* Current(void) const; - -private: - nsCacheIterator(const nsCacheIterator& o); - nsCacheIterator& operator=(const nsCacheIterator& o); - nsCacheModule* m_pModule; -}; - -inline -nsCacheIterator::nsCacheIterator(nsCacheModule* i_pModule): m_pModule(i_pModule) -{ -} - -inline -nsCacheIterator::~nsCacheIterator() -{ -} - -inline -PRBool nsCacheIterator::IsDone(void) const -{ - if (m_pModule) - { - return m_pModule->Entries() <= m_Index; - } - else - return PR_FALSE; -} - -inline -nsCacheObject* nsCacheIterator::Current(void) const -{ - if (m_pModule) - { - return m_pModule->GetObject(m_Index); - } - return 0; -} -#endif // nsCacheIterator_h__ - diff --git a/mozilla/network/cache/nu/public/nsCacheManager.h b/mozilla/network/cache/nu/public/nsCacheManager.h deleted file mode 100644 index e06c6b164db..00000000000 --- a/mozilla/network/cache/nu/public/nsCacheManager.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * nsCacheManager- The boss of cache architecture. Contains all "external" - * functions for use by people who don't care/want to know the internals - * of the cache architecture. - * - * - Gagan Saksena 09/15/98 - * - * Design and original implementation by Gagan Saksena 02/02/98 - * - */ - -#ifndef _CacheManager_H_ -#define _CacheManager_H_ - -#if 0 -# include "nsISupports.h" -#endif - -#include "prlog.h" - -#include "nsMonitorable.h" -#include "nsCacheModule.h" -#include "nsCacheObject.h" - -class nsMemModule; -class nsDiskModule; -class nsCachePref; -class nsCacheBkgThd; - -class nsCacheManager : public nsMonitorable //: public nsISupports -{ - -public: - - //Reserved modules - enum modules - { - MEM =0, - DISK=1 - }; - - nsCacheManager(); - ~nsCacheManager(); - - PRInt32 AddModule(nsCacheModule* i_cacheModule); - // InsertModule - PRBool Contains(const char* i_url) const; - - /* Number of modules in the cache manager */ - PRInt16 Entries() const; - - /* Singleton */ - static nsCacheManager* GetInstance(); - - nsDiskModule* GetDiskModule() const; - - nsMemModule* GetMemModule() const; - - nsCacheModule* GetModule(PRInt16 i_index) const; - - nsCacheObject* GetObj(const char* i_url) const; - - nsCachePref* GetPrefs(void) const; - - // Initialize the cache manager. Constructor doesn't call this. - // So you must specify this separately. - void Init(); - - void InfoAsHTML(char* o_Buffer) const; - - PRBool IsOffline(void) const; - - void Offline(PRBool bSet); - - PRBool Remove(const char* i_url); - - const char* Trace() const; - - /* Performance measure- microseconds */ - PRUint32 WorstCaseTime(void) const; - -protected: - - PRBool ContainsExactly(const char* i_url) const; - - nsCacheModule* LastModule() const; - //PRBool Lock(void); - //void Unlock(void); - -/* - class MgrMonitor - { - public: - MgrMonitor() { nsCacheManager::GetInstance()->Lock();} - ~MgrMonitor() { nsCacheManager::GetInstance()->Unlock();} - }; - - friend MgrMonitor; -*/ - -private: - nsCacheBkgThd* m_pBkgThd; - nsCacheModule* m_pFirstModule; - PRMonitor* m_pMonitor; - PRBool m_bOffline; - nsCachePref* m_pPrefs; - - nsCacheManager(const nsCacheManager& cm); - nsCacheManager& operator=(const nsCacheManager& cm); -}; - -inline -nsDiskModule* nsCacheManager::GetDiskModule() const -{ - PR_ASSERT(m_pFirstModule && m_pFirstModule->NextModule()); - return (m_pFirstModule) ? (nsDiskModule*) m_pFirstModule->NextModule() : NULL; -} - -inline -nsMemModule* nsCacheManager::GetMemModule() const -{ - PR_ASSERT(m_pFirstModule); - return (nsMemModule*) m_pFirstModule; -} - -inline -nsCachePref* nsCacheManager::GetPrefs(void) const -{ - PR_ASSERT(m_pPrefs); - return m_pPrefs; -} - -inline -PRBool nsCacheManager::IsOffline(void) const -{ - return m_bOffline; -} - -inline -void nsCacheManager::Offline(PRBool i_bSet) -{ - m_bOffline = i_bSet; -} - -#endif diff --git a/mozilla/network/cache/nu/public/nsCacheModule.h b/mozilla/network/cache/nu/public/nsCacheModule.h deleted file mode 100644 index 6c49be8d43d..00000000000 --- a/mozilla/network/cache/nu/public/nsCacheModule.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * nsCacheModule. A class that defines the way a cache module - * should be written. Its the super class for any new modules. - * Two sample modules derived from this one are nsMemModule and nsDiskModule. - * - * Gagan Saksena 02/03/98 - * - */ - -#ifndef nsCacheModule_h__ -#define nsCacheModule_h__ - -//#include -#include "nsCacheObject.h" -#include "nsEnumeration.h" -#include "nsMonitorable.h" - -/* Why in the world is forward decl. not working? */ -//class nsCacheObject; - -/* -// {5D51B24F-E6C2-11d1-AFE5-006097BFC036} -static const NS_CACHEMODULE_ID = -{ 0x5d51b24f, 0xe6c2, 0x11d1, { 0xaf, 0xe5, 0x0, 0x60, 0x97, 0xbf, 0xc0, 0x36 } }; -*/ - -class nsCacheIterator; -class nsCacheModule : public nsMonitorable /*: public nsISupports */ -{ - -public: - nsCacheModule(const PRUint32 i_size /*= DEFAULT_SIZE */); - - virtual - ~nsCacheModule(); - - virtual - PRBool AddObject(nsCacheObject* i_pObject)=0; - - virtual - PRBool Contains(const char* i_url) const=0; - virtual - PRBool Contains(nsCacheObject* i_pObject) const=0; - - void Enable(PRBool i_Enable); - - const PRUint32 Entries(void) const; - - nsEnumeration* Enumeration(void) const; - /* Enumerations wiht a function pointer - TODO */ - - //TODO move to own interface for both Garbage Collection and Revalidation - virtual - void GarbageCollect(void); - - virtual - nsCacheObject* GetObject(const char* i_url) const=0; - - virtual - nsCacheObject* GetObject(const PRUint32 i_index) const =0; - - virtual - nsStream* GetStreamFor(const nsCacheObject* i_pObject)=0; - - PRBool IsEnabled(void) const; - - /* Cant do additions, deletions, validations, expirations */ - PRBool IsReadOnly(void) const; - - nsCacheModule* NextModule(void) const; - void NextModule(nsCacheModule*); - - virtual - PRBool Remove(const char* i_url) = 0; - - virtual - PRBool Remove(const PRUint32 i_index) = 0; - - virtual - PRBool RemoveAll(void); - - virtual - PRBool Revalidate(void) = 0; - - const PRUint32 Size(void) const; - - virtual - void SetSize(const PRUint32 i_size); - - PRUint32 SizeInUse(void) const; - - const char* Trace(void) const; - -protected: - - virtual - PRBool ReduceSizeTo(const PRUint32 i_NewSize); - - PRUint32 m_Entries; - PRUint32 m_Size; - PRUint32 m_SizeInUse; - PRBool m_Enabled; - nsEnumeration* m_pEnumeration; - nsCacheIterator* m_pIterator; - nsCacheModule* m_pNext; - -private: - nsCacheModule(const nsCacheModule& cm); - nsCacheModule& operator=(const nsCacheModule& cm); -}; - -inline void nsCacheModule::Enable(PRBool i_Enable) -{ - m_Enabled = i_Enable; -} - -inline const PRUint32 nsCacheModule::Entries() const -{ - return m_Entries; -} - -inline -nsEnumeration* nsCacheModule::Enumeration(void) const -{ - MonitorLocker ml((nsMonitorable*)this); - if (!m_pEnumeration) - { - PR_ASSERT(m_pIterator); - ((nsCacheModule*)this)->m_pEnumeration = new nsEnumeration((nsIterator*)m_pIterator); - } - else - ((nsCacheModule*)this)->m_pEnumeration->Reset(); - return m_pEnumeration; -} - -inline PRBool nsCacheModule::IsEnabled(void) const -{ - return m_Enabled; -} - -inline PRBool nsCacheModule::IsReadOnly(void) const -{ - return PR_FALSE; -} - -inline nsCacheModule* nsCacheModule::NextModule(void) const -{ - return m_pNext; -} - -inline void nsCacheModule::NextModule(nsCacheModule* pNext) -{ - /* No overwriting */ - PR_ASSERT(m_pNext == 0); - if (m_pNext) - { - /* ERROR */ - delete m_pNext; //Worst case. - m_pNext = 0; - } - m_pNext = pNext; -} - -inline const PRUint32 nsCacheModule::Size() const -{ - return m_Size; -} - -inline void nsCacheModule::SetSize(const PRUint32 size) -{ - m_Size = size; -} - -inline PRUint32 nsCacheModule::SizeInUse(void) const -{ - return m_SizeInUse; -} - -#endif // nsCacheModule_h__ diff --git a/mozilla/network/cache/nu/public/nsCacheObject.h b/mozilla/network/cache/nu/public/nsCacheObject.h deleted file mode 100644 index b4456fb745c..00000000000 --- a/mozilla/network/cache/nu/public/nsCacheObject.h +++ /dev/null @@ -1,349 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* nsCacheObject is the class that holds the basic definition of the - * cache object. A lot of changes are likely to occur before this - * goes on stage. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsCacheObject_h__ -#define nsCacheObject_h__ - -#if 0 -#include "nsISupports.h" -#endif - -#include "prtypes.h" -#include "prinrval.h" - -static const PRUint32 kCACHE_VERSION = 5; - -class nsStream; - -class nsCacheObject //: public nsISupports -{ - -public: - - enum state_flags - { - INIT=0, - PARTIAL=1, - COMPLETE=2, - ABORTED=3, - EXPIRED=4, - CORRUPT=5 - }; - - nsCacheObject(); - nsCacheObject(const nsCacheObject& another); - nsCacheObject(const char* i_url); - - virtual ~nsCacheObject(); - -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); - -*/ - - void Address(const char* i_url); - const char* Address(void) const; - - void Charset(const char* i_Charset); - const char* Charset(void) const; - - void ContentEncoding(const char* i_Encoding); - const char* ContentEncoding(void) const; - - void ContentLength(PRUint32 i_len); - PRUint32 ContentLength(void) const; - - void ContentType(const char* i_Type); - const char* ContentType(void) const; - - void Etag(const char* i_etag); - const char* Etag(void) const; - - void Expires(PRIntervalTime i_Expires); - PRIntervalTime Expires(void) const; - - void Filename(const char* i_Filename); - const char* Filename(void) const; - - PRUint16 Hits(void) const; - - /* Read and write info about this cache object */ - void* Info(void) const; - PRBool Info(void* /*, PRUint32 len */); - - PRUint32 InfoSize(void) const; - - PRBool IsCompleted(void) const; - void IsCompleted(PRBool bComplete); - - PRBool IsExpired(void) const; - - PRBool IsPartial(void) const; - - PRIntervalTime LastAccessed(void) const; - - PRIntervalTime LastModified(void) const; - void LastModified(const PRIntervalTime i_lastModified); - - PRInt16 Module(void) const; - void Module(PRUint16 i_m); - - void PageServicesURL(const char* i_Url); - const char* PageServicesURL(void) const; - - const char* PostData(void) const; - void PostData(const char* i_data, const PRUint32 i_Len); - - PRUint32 PostDataLen(void) const; - - PRUint32 Read(char* o_Buffer, PRUint32 len); - - /* Reset the streams/state, read/write locks, etc. */ - void Reset(void); - - /* Accessor functions for the size of the cache object */ - PRUint32 Size(void) const; - void Size(PRUint32 i_Size); - - /* Accessor functions for the state of the cache object. - * Some states are changed internally. - */ - PRUint32 State(void) const; - void State(PRUint32 i_State); - - nsStream* Stream(void) const; - - const char* Trace() const; - - PRUint32 Write(const char* i_Buffer, const PRUint32 len); - -protected: - - void Init(); - - char* m_Charset; - char* m_ContentEncoding; - PRUint32 m_ContentLength; - char* m_ContentType; - char* m_Etag; - PRIntervalTime m_Expires; - char* m_Filename; - PRUint16 m_Hits; - PRUint32 m_info_size; - PRBool m_bIsCompleted; /* Marked when the stream complete is called */ - PRIntervalTime m_LastAccessed, m_LastModified; - void* m_pInfo; - char* m_PageServicesURL; - char* m_PostData; - PRUint32 m_PostDataLen; - PRInt16 m_Module; - PRUint32 m_Size; - PRUint32 m_State; - nsStream* m_pStream; - char* m_URL; - -private: - nsCacheObject& operator=(const nsCacheObject& x); -}; - -inline -const char* nsCacheObject::Address(void) const -{ - return m_URL; -}; - -inline -const char* nsCacheObject::Charset(void) const -{ - return m_Charset; -} - -inline -const char* nsCacheObject::ContentEncoding(void) const -{ - return m_ContentEncoding; -} - -inline -PRUint32 nsCacheObject::ContentLength(void) const -{ - return m_ContentLength; -}; - -inline -void nsCacheObject::ContentLength(PRUint32 i_Size) -{ - m_ContentLength = i_Size; -}; - -inline -const char* nsCacheObject::ContentType(void) const -{ - return m_ContentType; -}; - -inline -const char* nsCacheObject::Etag(void) const -{ - return m_Etag; -}; - -inline -PRIntervalTime nsCacheObject::Expires(void) const -{ - return m_Expires; -}; - -inline -void nsCacheObject::Expires(PRIntervalTime i_Expires) -{ - m_Expires = i_Expires; -}; - -inline -const char* nsCacheObject::Filename(void) const -{ - return m_Filename; -} - -inline -PRUint16 nsCacheObject::Hits(void) const -{ - return m_Hits; -}; - -inline -PRBool nsCacheObject::IsCompleted(void) const -{ - return m_bIsCompleted; -} - -inline -void nsCacheObject::IsCompleted(PRBool bComplete) -{ - m_bIsCompleted = bComplete; -} - -inline -PRBool nsCacheObject::IsExpired(void) const -{ - if (nsCacheObject::EXPIRED==m_State) - return PR_TRUE; - if (m_Expires <= PR_IntervalNow()) - ((nsCacheObject*)this)->m_State = nsCacheObject::EXPIRED; - return (nsCacheObject::EXPIRED==m_State); -}; - -inline -PRBool nsCacheObject::IsPartial(void) const -{ - return (m_ContentLength != m_Size) ? PR_TRUE : PR_FALSE; -}; - -inline -PRIntervalTime nsCacheObject::LastAccessed(void) const -{ - return m_LastAccessed; -}; - -inline -PRIntervalTime nsCacheObject::LastModified(void) const -{ - return m_LastModified; -}; - -inline -void nsCacheObject::LastModified(const PRIntervalTime i_LastModified) -{ - m_LastModified = i_LastModified; -}; - -inline -PRInt16 nsCacheObject::Module(void) const -{ - return m_Module; -}; - -inline -void nsCacheObject::Module(PRUint16 i_Module) -{ - m_Module = i_Module; -}; - -inline -const char* nsCacheObject::PageServicesURL(void) const -{ - return m_PageServicesURL; -} - -inline -const char* nsCacheObject::PostData(void) const -{ - return m_PostData; -} - -inline -PRUint32 nsCacheObject::PostDataLen(void) const -{ - return m_PostDataLen; -} - -inline -PRUint32 nsCacheObject::Size(void) const -{ - return m_Size; -}; - -inline -void nsCacheObject::Size(PRUint32 i_Size) -{ - m_Size = i_Size; -}; - -inline -PRUint32 nsCacheObject::State(void) const -{ - return m_State; -}; - -inline -void nsCacheObject::State(PRUint32 i_State) -{ - m_State = i_State; -}; - -inline -nsStream* nsCacheObject::Stream(void) const -{ - return m_pStream; -} -#endif // nsCacheObject_h__ - diff --git a/mozilla/network/cache/nu/public/nsCachePref.h b/mozilla/network/cache/nu/public/nsCachePref.h deleted file mode 100644 index e116d8f80f3..00000000000 --- a/mozilla/network/cache/nu/public/nsCachePref.h +++ /dev/null @@ -1,151 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* nsCachePref. A class to separate the preference related code to - * one place. This is an incomplete implementation, I need to access - * the libprefs directly, but that would add another dependency. And - * libpref comes with a JS dependency... so holding this off for the - * moment. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsCachePref_h__ -#define nsCachePref_h__ - -//#include "nsISupports.h" -#include "prtypes.h" -#include "prlog.h" - -class nsCachePref //: public nsISupports -{ - -public: - static nsCachePref* GetInstance(void); - - nsCachePref(void); - ~nsCachePref(); - - enum Refresh - { - ONCE, - ALWAYS, - NEVER - }; - - const PRUint32 BkgSleepTime(void); - - const char* DiskCacheDBFilename(void); /* like Fat.db */ - const char* DiskCacheFolder(void); /* Cache dir */ - - PRBool DiskCacheSSL(void); - void DiskCacheSSL(PRBool bSet); - - PRUint32 DiskCacheSize(void); - void DiskCacheSize(const PRUint32 i_Size); - - PRUint32 MemCacheSize(void); - void MemCacheSize(const PRUint32 i_Size); - - nsCachePref::Refresh - Frequency(void); - - /* Revalidating in background, makes IMS calls in the bkg thread to - update cache entries. TODO, this should be at a bigger time period - than the cache cleanup routine */ - PRBool RevalidateInBkg(void); - - /* Setup all prefs */ - void SetupPrefs(const char* i_Pref); - -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ -private: - nsCachePref(const nsCachePref& o); - nsCachePref& operator=(const nsCachePref& o); - - PRBool m_bRevalidateInBkg; - PRBool m_bDiskCacheSSL; - nsCachePref::Refresh m_RefreshFreq; - PRUint32 m_MemCacheSize; - PRUint32 m_DiskCacheSize; - char* m_DiskCacheDBFilename; - char* m_DiskCacheFolder; - PRUint32 m_BkgSleepTime; -}; - -inline -PRUint32 nsCachePref::DiskCacheSize() -{ - return m_DiskCacheSize; -} - -inline -void nsCachePref::DiskCacheSize(const PRUint32 i_Size) -{ - m_DiskCacheSize = i_Size; -} - -inline -PRBool nsCachePref::DiskCacheSSL(void) -{ - return m_bDiskCacheSSL; -} - -inline -void nsCachePref::DiskCacheSSL(PRBool bSet) -{ - m_bDiskCacheSSL = bSet; -} - -inline -const char* -nsCachePref::DiskCacheFolder(void) -{ - PR_ASSERT(m_DiskCacheFolder); - return m_DiskCacheFolder; -} - -inline -PRUint32 nsCachePref::MemCacheSize() -{ - return m_MemCacheSize; -} - -inline -void nsCachePref::MemCacheSize(const PRUint32 i_Size) -{ - m_MemCacheSize = i_Size; -} - -inline -PRBool nsCachePref::RevalidateInBkg(void) -{ - return m_bRevalidateInBkg; -} - - -#endif // nsCachePref_h__ - diff --git a/mozilla/network/cache/nu/public/nsDiskModule.h b/mozilla/network/cache/nu/public/nsDiskModule.h deleted file mode 100644 index 1bd53d957d5..00000000000 --- a/mozilla/network/cache/nu/public/nsDiskModule.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * nsDiskModule. The disk cache module that stores the cache objects - * on the disk. - * - * Gagan Saksena 02/03/98 - * - */ -#ifndef _nsDiskModule_H_ -#define _nsDiskModule_H_ - -#include "nsCacheModule.h" -#include "nsCachePref.h" -#include "mcom_db.h" - -class nsDiskModule : public nsCacheModule -{ - -public: - nsDiskModule(const PRUint32 size = nsCachePref::GetInstance()->DiskCacheSize()); - ~nsDiskModule(); - - // Cache module interface - PRBool AddObject(nsCacheObject* io_pObject); - - PRUint32 AverageSize(void) const; - - PRBool Contains(nsCacheObject* io_pObject) const; - PRBool Contains(const char* i_url) const; - - void GarbageCollect(void); - - nsCacheObject* GetObject(const PRUint32 i_index) const; - nsCacheObject* GetObject(const char* i_url) const; - - nsStream* GetStreamFor(const nsCacheObject* i_pObject); - - PRBool Remove(const char* i_url); - PRBool Remove(nsCacheObject* pObject); - PRBool Remove(const PRUint32 i_index); - - // To do cleanup set size to zero. Else initialize disk cache - void SetSize(const PRUint32 i_size); - - PRBool Revalidate(void); - -protected: - - PRBool ReduceSizeTo(const PRUint32 i_NewSize); - -private: - enum sync_frequency - { - EVERYTIME, - IDLE, - NEVER - } m_Sync; - - PRBool InitDB(void); - - nsDiskModule(const nsDiskModule& dm); - nsDiskModule& operator=(const nsDiskModule& dm); - - DB* m_pDB; -}; - -inline -PRUint32 nsDiskModule::AverageSize(void) const -{ - MonitorLocker ml((nsDiskModule*)this); - if (Entries()>0) - { - return (PRUint32)(m_SizeInUse/m_Entries); - } - return 0; -} -#endif diff --git a/mozilla/network/cache/nu/public/nsEnumeration.h b/mozilla/network/cache/nu/public/nsEnumeration.h deleted file mode 100644 index b22e4fd4269..00000000000 --- a/mozilla/network/cache/nu/public/nsEnumeration.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Another temporary class that needs to be replaced by a commonly - * used one, or made a commonly used one. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsEnumeration_h__ -#define nsEnumeration_h__ - -//#include "nsISupports.h" -#include "nsIterator.h" -#include "prlog.h" - -class nsEnumeration //: public nsISupports -{ - -public: - nsEnumeration(nsIterator* iter); - virtual ~nsEnumeration(); - - PRBool HasMoreElements(void); - void* NextElement(void); - void Reset(void); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ -protected: - nsIterator* m_pIter; -private: - nsEnumeration(const nsEnumeration& o); - nsEnumeration& operator=(const nsEnumeration& o); -}; - -inline -nsEnumeration::nsEnumeration(nsIterator* iter):m_pIter(iter) -{ - PR_ASSERT(iter); - if (m_pIter) - m_pIter->First(); -} - -inline -nsEnumeration::~nsEnumeration() -{ -} - -inline -PRBool nsEnumeration::HasMoreElements(void) -{ - if (m_pIter) //remove this check for optimization? - return m_pIter->IsDone() ? PR_FALSE : PR_TRUE; - return PR_FALSE; -} - -inline -void* nsEnumeration::NextElement(void) -{ - if (m_pIter) - { - void* pTemp = m_pIter->CurrentItem(); - m_pIter->Next(); - return pTemp; - } - return 0; -} - -inline -void nsEnumeration::Reset(void) -{ - if (m_pIter) - { - m_pIter->First(); - } -} - -#endif // nsEnumeration_h__ - diff --git a/mozilla/network/cache/nu/public/nsFileStream.h b/mozilla/network/cache/nu/public/nsFileStream.h deleted file mode 100644 index be84d0d0233..00000000000 --- a/mozilla/network/cache/nu/public/nsFileStream.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* nsFileStream. The file/disk based implementation of the nsStream class. - * It basically maps the read write functions to the file equivalents. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsFileStream_h__ -#define nsFileStream_h__ - -//#include "nsISupports.h" -#include "nsStream.h" -#include "prio.h" // PRFileDesc - -class nsFileStream: public nsStream -{ - -public: - nsFileStream(const char* i_Filename); - virtual ~nsFileStream(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - PRFileDesc* FileDesc(void); - - PRInt32 Read(void* o_Buffer, PRUint32 i_Len); - void Reset(void); - PRInt32 Write(const void* i_Buffer, PRUint32 i_Len); - -protected: - - PRBool Open(void); - -private: - nsFileStream(const nsFileStream& o); - nsFileStream& operator=(const nsFileStream& o); - PRFileDesc* m_pFile; - char* m_pFilename; -}; - -inline -PRFileDesc* nsFileStream::FileDesc(void) -{ - return m_pFile; -} - -#endif // nsFileStream_h__ - diff --git a/mozilla/network/cache/nu/public/nsHash.h b/mozilla/network/cache/nu/public/nsHash.h deleted file mode 100644 index b297868e404..00000000000 --- a/mozilla/network/cache/nu/public/nsHash.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* A dummy class. Probably will be replaced/removed/recycled. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsHash_h__ -#define nsHash_h__ - -#include "plhash.h" - -class nsHashKey { -protected: - nsHashKey(void); -public: - virtual ~nsHashKey(void); - virtual PRUint32 HashValue(void) const = 0; - virtual PRBool Equals(const nsHashKey *aKey) const = 0; - virtual nsHashKey *Clone(void) const = 0; -}; - -// Enumerator callback function. Use - -typedef PRBool (*nsHashEnumFunc)(nsHashKey *aKey, void *aData); - -class nsHash { -private: - // members - PLHashTable *hashtable; - -public: - nsHash(PRUint32 aSize = 256); - ~nsHash(); - - void *Put(nsHashKey *aKey, void *aData); - void *Get(nsHashKey *aKey); - void *Remove(nsHashKey *aKey); - void Enumerate(nsHashEnumFunc aEnumFunc); -}; - -#endif diff --git a/mozilla/network/cache/nu/public/nsIterator.h b/mozilla/network/cache/nu/public/nsIterator.h deleted file mode 100644 index 21fed58285f..00000000000 --- a/mozilla/network/cache/nu/public/nsIterator.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Another common class that needs to be replaced/removed/recycled. - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsIterator_h__ -#define nsIterator_h__ - -//#include "nsISupports.h" -#include "prtypes.h" - -class nsIterator //:public nsISupports -{ - -public: - - virtual void First(void); - virtual PRBool IsDone(void) const = 0; - virtual void Next(void); - virtual void* CurrentItem(void) const; -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - -protected: - nsIterator() {m_Index = 0;}; - - PRUint32 m_Index; - -}; - -inline -void nsIterator::First(void) -{ - m_Index = 0; -} - -inline -void nsIterator::Next(void) -{ - ++m_Index; -} - -inline -void* nsIterator::CurrentItem(void) const -{ - return 0; -} -#endif // nsIterator_h__ - diff --git a/mozilla/network/cache/nu/public/nsMemCacheObject.h b/mozilla/network/cache/nu/public/nsMemCacheObject.h deleted file mode 100644 index 08c183dc80f..00000000000 --- a/mozilla/network/cache/nu/public/nsMemCacheObject.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* The nsMemCacheObject class holds the actual nsCacheObject and a pointer - * to the next nsMemCacheObject. Pretty simple solution for the time being. - * Should be replaced once the memory hash table stuff gets up and running. - * - * -Gagan Saksena 09/15/98. - */ - -#ifndef _nsMemCacheObject_h_ -#define _nsMemCacheObject_h_ - -#include "prtypes.h" -#include "prlog.h" -#include "nsCacheObject.h" - -class nsMemCacheObject -{ -public: - - nsMemCacheObject(void); - nsMemCacheObject(nsCacheObject* io_pObject); - nsMemCacheObject(const char* i_url); - ~nsMemCacheObject(); - - void Next(nsMemCacheObject* pObject); - void Next(nsCacheObject* io_pObject); - - nsMemCacheObject* Next(void) const; - - nsCacheObject* ThisObject(void) const; - -private: - nsMemCacheObject* m_pNextObject; - nsCacheObject* m_pObject; - - nsMemCacheObject& operator=(const nsMemCacheObject& mco); - nsMemCacheObject(const nsMemCacheObject&); - -}; - -inline nsMemCacheObject::nsMemCacheObject(void): - m_pObject(new nsCacheObject()), - m_pNextObject(0) -{ -} - -inline nsMemCacheObject::nsMemCacheObject(nsCacheObject* io_pObject): - m_pObject(io_pObject), - m_pNextObject(0) -{ -} - -inline nsMemCacheObject::nsMemCacheObject(const char* i_url): - m_pObject(new nsCacheObject(i_url)), - m_pNextObject(0) -{ -} - -inline nsMemCacheObject* nsMemCacheObject::Next(void) const -{ - return m_pNextObject; -} - -inline void nsMemCacheObject::Next(nsMemCacheObject* pObject) -{ - PR_ASSERT(0==m_pNextObject); - m_pNextObject = pObject; -} - -inline void nsMemCacheObject::Next(nsCacheObject* pObject) -{ - PR_ASSERT(0==m_pNextObject); - m_pNextObject = new nsMemCacheObject(pObject); -} - -inline nsCacheObject* nsMemCacheObject::ThisObject(void) const -{ - return m_pObject; -} - -#endif //_nsMemCacheObject_h_ diff --git a/mozilla/network/cache/nu/public/nsMemModule.h b/mozilla/network/cache/nu/public/nsMemModule.h deleted file mode 100644 index a0103131014..00000000000 --- a/mozilla/network/cache/nu/public/nsMemModule.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* -* nsMemModule. The memory based cache module. -* -* Gagan Saksena -* 02/03/98 -* -*/ - -#ifndef _nsMemModule_H_ -#define _nsMemModule_H_ - -#include "nsCacheModule.h" -#include "nsMemCacheObject.h" -#include "nsCachePref.h" - -//#include "nsHash.h" // TODO - replace with nsHashtable when the XPCOM_BRANCH merges - -//#include "nsHashtable.h" -/* -// {5D51B250-E6C2-11d1-AFE5-006097BFC036} -static const NS_MEMMODULE_IID = -{ 0x5d51b250, 0xe6c2, 0x11d1, { 0xaf, 0xe5, 0x0, 0x60, 0x97, 0xbf, 0xc0, 0x36 } }; -*/ - -class nsMemModule : public nsCacheModule -{ - -public: - nsMemModule(const PRUint32 size=nsCachePref::GetInstance()->MemCacheSize()); - ~nsMemModule(); - -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); - -*/ - PRBool AddObject(nsCacheObject* io_pObject); - - PRBool Contains(nsCacheObject* io_pObject) const; - PRBool Contains(const char* i_url) const; - - void GarbageCollect(void); - - nsCacheObject* GetObject(const PRUint32 i_index) const; - nsCacheObject* GetObject(const char* i_url) const; - - nsStream* GetStreamFor(const nsCacheObject* i_pObject); - - PRBool ReduceSizeTo(const PRUint32 i_NewSize); - - PRBool Remove(const char* i_url); - PRBool Remove(const PRUint32 i_index); - -// PRBool RemoveAll(void); - - PRBool Revalidate(void); - - - // Start of nsMemModule specific stuff... - // Here is a sample implementation using linked list -protected: - nsMemCacheObject* LastObject(void) const; - -private: - nsMemCacheObject* m_pFirstObject; - - //nsHash m_ht; //TODO replace with nsHashtable - //Optimization - nsMemCacheObject* m_pLastObject; - - nsMemModule(const nsMemModule& mm); - nsMemModule& operator=(const nsMemModule& mm); - -/* - class nsMemKey : public nsHashKey - { - public: - nsMemKey(); - ~nsMemKey(); - PRUint32 HashValue(); - PRBool Equals(nsHashKey *aKey); - nsHashKey* Clone(); - }; -*/ -}; - -inline -PRBool nsMemModule::Revalidate(void) -{ - /* Mem module elements are never revalidated */ - return PR_FALSE; -} - -#endif diff --git a/mozilla/network/cache/nu/public/nsMemStream.h b/mozilla/network/cache/nu/public/nsMemStream.h deleted file mode 100644 index fa168c69665..00000000000 --- a/mozilla/network/cache/nu/public/nsMemStream.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* nsMemStream. A memory based stream for use with memory objects - * - * -Gagan Saksena 09/15/98. - */ -#ifndef nsMemStream_h__ -#define nsMemStream_h__ - -//#include "nsISupports.h" -#include "nsStream.h" - -class nsMemStream: public nsStream -{ - -public: - nsMemStream(); - virtual ~nsMemStream(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - PRInt32 Read(void* o_Buffer, PRUint32 i_Len); - void Reset(void); - PRInt32 Write(const void* i_Buffer, PRUint32 i_Len); - -protected: - -private: - nsMemStream(const nsMemStream& o); - nsMemStream& operator=(const nsMemStream& o); - - PRUint32 m_AllocSize; - PRUint32 m_ReadOffset; - PRUint32 m_WriteOffset; - void* m_pStart; - PRUint32 m_Size; -}; - -#endif // nsMemStream_h__ - diff --git a/mozilla/network/cache/nu/public/nsMonitorable.h b/mozilla/network/cache/nu/public/nsMonitorable.h deleted file mode 100644 index cddc86d5edb..00000000000 --- a/mozilla/network/cache/nu/public/nsMonitorable.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* nsMonitorable. This is a cool class too. Its an easy of adding monitors - * actually PRMonitor behaviour to existing classes. The nsMonitorLocker is - * an excursion class that locks the scope in which is declared (on stack). - * - * -Gagan Saksena 09/15/98 - */ -#ifndef nsMonitorable_h__ -#define nsMonitorable_h__ - -//#include "nsISupports.h" - -#include "prmon.h" -#include "prlog.h" - -class nsMonitorable//: public nsISupports -{ - -public: - nsMonitorable(); - virtual ~nsMonitorable(); - -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - PRBool Lock(void); - void Unlock(void); - -protected: - - class MonitorLocker - { - public: - MonitorLocker(nsMonitorable* i_pThis); - ~MonitorLocker(); - private: - nsMonitorable* m_pMonitorable; - }; - - PRMonitor* m_pMonitor; - -private: - nsMonitorable(const nsMonitorable& o); - nsMonitorable& operator=(const nsMonitorable& o); -}; - -inline -nsMonitorable::nsMonitorable(void):m_pMonitor(PR_NewMonitor()) -{ -} - -inline -nsMonitorable::~nsMonitorable() -{ - if (m_pMonitor) - { - PR_DestroyMonitor(m_pMonitor); - m_pMonitor = 0; - } -} - -inline -PRBool nsMonitorable::Lock(void) -{ - if (!m_pMonitor) - { - m_pMonitor = PR_NewMonitor(); - if (!m_pMonitor) - return PR_FALSE; - } - PR_EnterMonitor(m_pMonitor); - return PR_TRUE; -} - - -inline -void nsMonitorable::Unlock(void) -{ - PR_ASSERT(m_pMonitor); - if (m_pMonitor) - PR_ExitMonitor(m_pMonitor); -} - -#endif // nsMonitorable_h__ - diff --git a/mozilla/network/cache/nu/public/nsStream.h b/mozilla/network/cache/nu/public/nsStream.h deleted file mode 100644 index 499644a2d21..00000000000 --- a/mozilla/network/cache/nu/public/nsStream.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* A placeholder for the actual professional strength streams class. Works - * ok for me for now. - * - * -Gagan Saksena 09/15/98 - */ - -#ifndef nsStream_h__ -#define nsStream_h__ - -//#include "nsISupports.h" - -#include "prtypes.h" - -class nsStream//: public nsISupports -{ - -public: - nsStream(); - virtual ~nsStream(); -/* - NS_IMETHOD QueryInterface(const nsIID& aIID, - void** aInstancePtr); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); -*/ - virtual - PRInt32 Read(void* o_Buffer, PRUint32 i_Len) = 0; - virtual - void Reset(void) = 0; - virtual - PRInt32 Write(const void* i_Buffer, PRUint32 i_Len) = 0; - -protected: - -private: - nsStream(const nsStream& o); - nsStream& operator=(const nsStream& o); -}; - -inline -nsStream::nsStream(void) -{ - //noop -} - -inline -nsStream::~nsStream() -{ - //noop -} -#endif // nsStream_h__ - diff --git a/mozilla/network/cache/nu/src/CacheStubs.cpp b/mozilla/network/cache/nu/src/CacheStubs.cpp deleted file mode 100644 index 10cdd43120e..00000000000 --- a/mozilla/network/cache/nu/src/CacheStubs.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Design and original implementation by Gagan Saksena '98 */ - -#include "CacheStubs.h" -#include "nsCacheManager.h" -#include "nsDiskModule.h" -#include "nsMemModule.h" -#include "nsCacheTrace.h" -#include "prlog.h" - -#define CACHEMGR nsCacheManager::GetInstance() - -void -Cache_Init(void) -{ - CACHEMGR->Init(); -} - -void -Cache_Shutdown(void) -{ - /* todo- Should the destructor for nsCacheManager object be forced here?*/ -} - -/* CacheManager functions */ -PRBool -CacheManager_Contains(const char* i_url) -{ - return CACHEMGR->Contains(i_url); -} - -PRInt16 -CacheManager_Entries() -{ - return CACHEMGR->Entries(); -} - -void* -CacheManager_GetObject(const char* i_url) -{ - return CACHEMGR->GetObj(i_url); -} - -void -CacheManager_InfoAsHTML(char* o_Buffer) -{ - CACHEMGR->InfoAsHTML(o_Buffer); -} - -PRBool -CacheManager_IsOffline(void) -{ - return CACHEMGR->IsOffline(); -} - -void -CacheManager_Offline(PRBool bSet) -{ - CACHEMGR->Offline(bSet); -} - -PRBool -CacheManager_Remove(const char* i_url) -{ - return CACHEMGR->Remove(i_url); -} - -PRUint32 -CacheManager_WorstCaseTime(void) -{ - return CACHEMGR->WorstCaseTime(); -} - -/* CacheObject functions */ -void* -CacheObject_Create(const char* i_url) -{ - return new nsCacheObject(i_url); -} - -void -CacheObject_Destroy(void* pThis) -{ - if (pThis) - { - ((nsCacheObject*)pThis)->~nsCacheObject(); - pThis = 0; - } -} - -const char* -CacheObject_GetAddress(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Address() : 0; -} - -const char* -CacheObject_GetCharset(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Charset() : 0; -} - -const char* -CacheObject_GetContentEncoding(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->ContentEncoding() : 0; -} - -PRUint32 -CacheObject_GetContentLength(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->ContentLength() : 0; -} - -const char* -CacheObject_GetContentType(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->ContentType() : 0; -} - -const char* -CacheObject_GetEtag(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Etag() : 0; -} - -PRIntervalTime -CacheObject_GetExpires(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Expires() : 0; -} - -const char* -CacheObject_GetFilename(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Filename() : 0; -} - -PRBool -CacheObject_GetIsCompleted(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->IsCompleted() : PR_TRUE; -} - -PRIntervalTime -CacheObject_GetLastAccessed(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->LastAccessed() : 0; -} - -PRIntervalTime -CacheObject_GetLastModified(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->LastModified() : 0; -} - -PRInt16 -CacheObject_GetModule(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Module() : -1; -} - -const char* -CacheObject_GetPageServicesURL(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->PageServicesURL() : 0; -} - -const char* -CacheObject_GetPostData(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->PostData() : 0; -} - -PRUint32 -CacheObject_GetPostDataLen(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->PostDataLen() : 0; -} - -PRUint32 -CacheObject_GetSize(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Size() : 0; -} - -PRUint32 -CacheObject_GetState(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->State() : 0; -} - -PRUint32 -CacheObject_Hits(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->Hits() : 0; -} - -PRBool -CacheObject_IsExpired(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->IsExpired() : PR_FALSE; -} - -PRBool -CacheObject_IsPartial(const void* pThis) -{ - return pThis ? ((nsCacheObject*)pThis)->IsPartial() : PR_FALSE; -} - -PRUint32 -CacheObject_Read(const void* pThis, char* o_Buffer, PRUint32 i_Len) -{ - return pThis ? ((nsCacheObject*)pThis)->Read(o_Buffer, i_Len) : 0; -} - -void -CacheObject_Reset(void* pThis) -{ - if (pThis) - ((nsCacheObject*)pThis)->Reset(); -} - -void -CacheObject_SetAddress(void* pThis, const char* i_Address) -{ - if (pThis) - ((nsCacheObject*)pThis)->Address(i_Address); -} - -void -CacheObject_SetCharset(void* pThis, const char* i_Charset) -{ - if (pThis) - ((nsCacheObject*)pThis)->Charset(i_Charset); -} - -void -CacheObject_SetContentEncoding(void* pThis, const char* i_Encoding) -{ - if (pThis) - ((nsCacheObject*)pThis)->ContentEncoding(i_Encoding); -} - -void -CacheObject_SetContentLength(void* pThis, PRUint32 i_ContentLen) -{ - if (pThis) - ((nsCacheObject*)pThis)->ContentLength(i_ContentLen); -} - -void -CacheObject_SetContentType(void* pThis, const char* i_ContentType) -{ - if (pThis) - ((nsCacheObject*)pThis)->ContentType(i_ContentType); -} - -void -CacheObject_SetEtag(void* pThis, const char* i_Etag) -{ - if (pThis) - ((nsCacheObject*)pThis)->Etag(i_Etag); -} - -void -CacheObject_SetExpires(void *pThis, const PRIntervalTime i_Time) -{ - if (pThis) - ((nsCacheObject*)pThis)->Expires(i_Time); -} - -void -CacheObject_SetFilename(void* pThis, const char* i_Filename) -{ - if (pThis) - ((nsCacheObject*)pThis)->Filename(i_Filename); -} - -void -CacheObject_SetIsCompleted(void* pThis, PRBool bCompleted) -{ - if (pThis) - ((nsCacheObject*)pThis)->IsCompleted(bCompleted); -} - -void -CacheObject_SetLastModified(void* pThis, const PRIntervalTime i_Time) -{ - if (pThis) - ((nsCacheObject*)pThis)->LastModified(i_Time); -} - -void -CacheObject_SetModule(void* pThis, const PRInt16 i_Module) -{ - if (pThis) - ((nsCacheObject*)pThis)->Module(i_Module); -} - -void -CacheObject_SetPageServicesURL(void* pThis, const char* i_Url) -{ - if (pThis) - ((nsCacheObject*)pThis)->PageServicesURL(i_Url); -} - -void -CacheObject_SetPostData(void* pThis, const char* i_PostData, const PRUint32 i_Len) -{ - if (pThis) - ((nsCacheObject*)pThis)->PostData(i_PostData, i_Len); -} - -void -CacheObject_SetSize(void* pThis, const PRUint32 i_Size) -{ - if (pThis) - ((nsCacheObject*)pThis)->Size(i_Size); -} - -void -CacheObject_SetState(void* pThis, const PRUint32 i_State) -{ - if (pThis) - ((nsCacheObject*)pThis)->State(i_State); -} - -PRBool -CacheObject_Synch(void* pThis) -{ - if (pThis) - { - nsCacheObject* pObj = (nsCacheObject*) pThis; - return CACHEMGR->GetModule(pObj->Module())->AddObject(pObj); - } - return PR_FALSE; -} - -PRUint32 -CacheObject_Write(void* pThis, const char* i_buffer, const PRUint32 i_length) -{ - if (pThis) - { - nsCacheObject* pObj = (nsCacheObject*) pThis; - return pObj->Write(i_buffer, i_length); - } - return 0; -} - -/* CachePref functions */ -PRUint32 -CachePref_GetDiskCacheSize(void) -{ - return nsCachePref::GetInstance()->DiskCacheSize(); -} - -PRBool -CachePref_GetDiskCacheSSL(void) -{ - return nsCachePref::GetInstance()->DiskCacheSSL(); -} - -PRUint32 -CachePref_GetMemCacheSize(void) -{ - return nsCachePref::GetInstance()->MemCacheSize(); -} - -void -CachePref_SetDiskCacheSize(const PRUint32 i_Size) -{ - nsCachePref::GetInstance()->DiskCacheSize(i_Size); -} - -void -CachePref_SetDiskCacheSSL(PRBool bSet) -{ - nsCachePref::GetInstance()->DiskCacheSSL(bSet); -} - -void -CachePref_SetMemCacheSize(const PRUint32 i_Size) -{ - nsCachePref::GetInstance()->MemCacheSize(i_Size); -} - -/* CacheTrace functions */ -void -CacheTrace_Enable(PRBool bEnable) -{ - nsCacheTrace::Enable(bEnable); -} - -PRBool -CacheTrace_IsEnabled(void) -{ - return nsCacheTrace::IsEnabled(); -} - -/* DiskModule functions */ -#define DISKMOD nsCacheManager::GetInstance()->GetDiskModule() - -PRBool -DiskModule_AddObject(void* pObject) -{ - return DISKMOD->AddObject((nsCacheObject*)pObject); -} - -PRBool -DiskModule_Contains(const char* i_url) -{ - return DISKMOD->Contains(i_url); -} - -PRUint32 -DiskModule_Entries(void) -{ - return DISKMOD->Entries(); -} - -PRUint32 -DiskModule_GetSize(void) -{ - return DISKMOD->Size(); -} - -PRUint32 -DiskModule_GetSizeInUse(void) -{ - return DISKMOD->SizeInUse(); -} - -PRBool -DiskModule_IsEnabled(void) -{ - return DISKMOD->IsEnabled(); -} - -PRBool -DiskModule_Remove(const char* i_url) -{ - return DISKMOD->Remove(i_url); -} - -PRBool -DiskModule_RemoveAll(void) -{ - return DISKMOD->RemoveAll(); -} - -void -DiskModule_SetSize(PRUint32 i_Size) -{ - DISKMOD->SetSize(i_Size); -} - -/* MemModule functions */ -#define MEMMOD nsCacheManager::GetInstance()->GetMemModule() - -PRBool -MemModule_AddObject(void* pObject) -{ - return MEMMOD->AddObject((nsCacheObject*)pObject); -} - -PRBool -MemModule_Contains(const char* i_url) -{ - return MEMMOD->Contains(i_url); -} - -PRUint32 -MemModule_Entries(void) -{ - return MEMMOD->Entries(); -} - -PRUint32 -MemModule_GetSize(void) -{ - return MEMMOD->Size(); -} - -PRUint32 -MemModule_GetSizeInUse(void) -{ - return MEMMOD->SizeInUse() ; -} - -PRBool -MemModule_IsEnabled(void) -{ - return MEMMOD->IsEnabled(); -} - -PRBool -MemModule_Remove(const char* i_url) -{ - return MEMMOD->Remove(i_url); -} - -PRBool -MemModule_RemoveAll(void) -{ - return MEMMOD->RemoveAll(); -} - -void -MemModule_SetSize(PRUint32 i_Size) -{ - MEMMOD->SetSize(i_Size); -} - -#undef MEMMOD -#undef DISKMOD -#undef CACHEMGR diff --git a/mozilla/network/cache/nu/src/Makefile.in b/mozilla/network/cache/nu/src/Makefile.in deleted file mode 100644 index 67450388fe9..00000000000 --- a/mozilla/network/cache/nu/src/Makefile.in +++ /dev/null @@ -1,56 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = cache -LIBRARY_NAME = cache - -REQUIRES = dbm pref js xpcom - -CPPSRCS = \ - nsCacheObject.cpp \ - nsCacheModule.cpp \ - nsCacheManager.cpp \ - nsMemModule.cpp \ - nsDiskModule.cpp \ - nsCacheTrace.cpp \ - nsCachePref.cpp \ - nsMemCacheObject.cpp \ - nsBkgThread.cpp \ - nsCacheBkgThd.cpp \ - CacheStubs.cpp \ - nsFileStream.cpp \ - nsMemStream.cpp \ - nsMonitorable.cpp \ - $(NULL) - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - -INCLUDES += -I$(srcdir)/../include -I$(srcdir)/../public - diff --git a/mozilla/network/cache/nu/src/makefile.win b/mozilla/network/cache/nu/src/makefile.win deleted file mode 100644 index fe89a789b66..00000000000 --- a/mozilla/network/cache/nu/src/makefile.win +++ /dev/null @@ -1,87 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -IGNORE_MANIFEST = 1 - -DEPTH=..\..\..\.. - -MAKE_OBJ_TYPE = EXE -DLLNAME = cache -#DLL = .\$(OBJDIR)\$(DLLNAME).dll - -LIBRARY_NAME=cache - -# -# Remember to change libplc3 to $whatever it is... -# -LLIBS = \ - $(LIBNSPR) \ - $(DIST)\lib\dbm32.lib \ - $(DIST)\lib\xpcom.lib \ - $(DIST)\lib\libpref.lib \ - $(NULL) - -MODULE = cache - -OBJS = \ - .\$(OBJDIR)\nsCacheObject.obj \ - .\$(OBJDIR)\nsCacheModule.obj \ - .\$(OBJDIR)\nsMemModule.obj \ - .\$(OBJDIR)\nsDiskModule.obj \ - .\$(OBJDIR)\nsCacheTrace.obj \ - .\$(OBJDIR)\nsCacheManager.obj \ - .\$(OBJDIR)\nsCachePref.obj \ - .\$(OBJDIR)\nsMemCacheObject.obj \ - .\$(OBJDIR)\nsBkgThread.obj \ - .\$(OBJDIR)\nsCacheBkgThd.obj \ - .\$(OBJDIR)\CacheStubs.obj \ - .\$(OBJDIR)\nsFileStream.obj \ - .\$(OBJDIR)\nsMemStream.obj \ - .\$(OBJDIR)\nsMonitorable.obj \ - $(NULL) - -LINCS = \ - -I$(PUBLIC)\xpcom \ - -I$(PUBLIC)\dbm \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\js \ - -I..\public \ - -I..\include \ - $(NULL) - -LCFLAGS = \ - $(LCFLAGS) \ - $(NULL) - #-DNS_DLLNAME=$(DLLNAME).dll \ - -include <$(DEPTH)\config\rules.mak> - -install:: $(EXE) - $(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).$(LIB_SUFFIX) $(DIST)\lib - -install:: $(LIBRARY) - $(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).$(LIB_SUFFIX) $(DIST)\lib - -# $(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).$(DLL_SUFFIX) $(DIST)\bin - -clobber:: - rm -f $(DIST)\lib\$(DLLNAME).$(LIB_SUFFIX) - diff --git a/mozilla/network/cache/nu/src/nsBkgThread.cpp b/mozilla/network/cache/nu/src/nsBkgThread.cpp deleted file mode 100644 index 1b202a37f57..00000000000 --- a/mozilla/network/cache/nu/src/nsBkgThread.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsBkgThread.h" -#include "prlog.h" - -static void PR_CALLBACK RunFunction(void* arg); - -static void PR_CALLBACK RunFunction(void* arg) -{ - nsBkgThread* pBT = (nsBkgThread*) arg; - if (pBT) - { - pBT->Process(); - } -} - -nsBkgThread::nsBkgThread(PRIntervalTime iSleepTime, PRBool bStart /* =PR_TRUE */) -{ - m_SleepTime = iSleepTime; - m_bContinue = bStart; - m_pThread = PR_CreateThread( - PR_USER_THREAD, - RunFunction, - this, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_JOINABLE_THREAD, - 0); - PR_ASSERT(NULL != m_pThread); -} - -nsBkgThread::~nsBkgThread() -{ - m_bContinue = PR_FALSE; - if (m_pThread != NULL) - { - Stop(); - } -} -/* -nsrefcnt nsBkgThread::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsBkgThread::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsBkgThread::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} - -*/ -void nsBkgThread::Process(void) -{ - while (m_bContinue) - { - PR_Sleep(m_SleepTime); - Run(); - } -} - -void nsBkgThread::Stop(void) -{ - m_bContinue = PR_FALSE; - PRStatus status = PR_Interrupt(m_pThread); - PR_ASSERT(PR_SUCCESS == status); -} diff --git a/mozilla/network/cache/nu/src/nsCacheBkgThd.cpp b/mozilla/network/cache/nu/src/nsCacheBkgThd.cpp deleted file mode 100644 index 125cfc14506..00000000000 --- a/mozilla/network/cache/nu/src/nsCacheBkgThd.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "prlog.h" -#include "nsCacheBkgThd.h" -#include "nsCacheManager.h" -#include "nsCacheModule.h" -#include "nsCachePref.h" - -nsCacheBkgThd::nsCacheBkgThd(PRIntervalTime iSleepTime): - nsBkgThread(iSleepTime) -{ -} - -nsCacheBkgThd::~nsCacheBkgThd() -{ -} - -/* -nsrefcnt nsCacheBkgThd::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsCacheBkgThd::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsCacheBkgThd::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} -*/ - -void nsCacheBkgThd::Run(void) -{ - /* Step thru all the modules and call cleanup on each */ - nsCacheManager* pCM = nsCacheManager::GetInstance(); - PR_ASSERT(pCM); - if (pCM->IsOffline()) - return; /* Dont update entries if offline */ - PRInt16 i = pCM->Entries(); - while (i>0) - { - nsCacheModule* pModule = pCM->GetModule(--i); - PR_ASSERT(pModule); - /* TODO change this based on if it supports garbage cleaning */ - if (!pModule->IsReadOnly()) - { - pModule->GarbageCollect(); - if (nsCachePref::GetInstance()->RevalidateInBkg()) - { - pModule->Revalidate(); - } - } - } -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/src/nsCacheFileStream.cpp b/mozilla/network/cache/nu/src/nsCacheFileStream.cpp deleted file mode 100644 index b608e41787a..00000000000 --- a/mozilla/network/cache/nu/src/nsCacheFileStream.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * Updated to use mozilla/base nsFileStream class - spence 02/10/99 - */ - -#include "nsCacheFileStream.h" -#include "plstr.h" -#include "prlog.h" -#ifdef XP_UNIX -#include "prio.h" -#include "sys/param.h" -#include "prsystem.h" -#endif - -nsCacheFileStream::nsCacheFileStream(const char* i_Filename):m_pFile(0),m_pFilename(0) -{ - PR_ASSERT(i_Filename); - if (i_Filename) - { - m_pFilename = new char[PL_strlen(i_Filename)+1]; - PL_strcpy(m_pFilename, i_Filename); - Open(); - } -} - -nsCacheFileStream::~nsCacheFileStream() -{ - if (m_pFilename) - { - delete[] m_pFilename; - m_pFilename = 0; - } - if (m_pFile) - m_pFile->close(); -} - -/* -nsrefcnt nsCacheFileStream::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsCacheFileStream::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsCacheFileStream::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} -*/ - -PRBool nsCacheFileStream::Open() -{ - if (m_pFile) - m_pFile->close(); - PR_ASSERT(m_pFilename); - if (m_pFilename) - { - /* does 'browser.cache.directory/' exist? */ - char *cacheDir = new char [MAXPATHLEN]; - PRFileInfo dir; - - int slash = PL_strrchr (m_pFilename, PR_GetDirectorySeparator()) - - m_pFilename + 1; - PL_strncpyz (cacheDir, m_pFilename, slash); - - PRStatus status = PR_GetFileInfo (cacheDir, &dir); - if (PR_FAILURE == status) { - status = PR_MkDir(cacheDir, 0600); - if (PR_SUCCESS != status) { - return PR_FALSE; - } - } - - nsFilePath ioPath (m_pFilename); - m_pFile = new nsIOFileStream (ioPath, PR_CREATE_FILE | PR_RDWR, 0600); - - PR_ASSERT(m_pFile); - if (m_pFile) - return PR_TRUE; - } - return PR_FALSE; -} - -PRInt32 nsCacheFileStream::Read(void* o_Buffer, PRUint32 i_Len) -{ - if (!m_pFile && !Open()) - return 0; - return m_pFile->read((void *)o_Buffer, i_Len); -} - -void nsCacheFileStream::Reset() -{ - Open(); -} - -PRInt32 nsCacheFileStream::Write(const void* i_Buffer, PRUint32 i_Len) -{ - if (!m_pFile && !Open()) - return 0; - return m_pFile->write((void *)i_Buffer, i_Len); -} - diff --git a/mozilla/network/cache/nu/src/nsCacheManager.cpp b/mozilla/network/cache/nu/src/nsCacheManager.cpp deleted file mode 100644 index 196bb95faa4..00000000000 --- a/mozilla/network/cache/nu/src/nsCacheManager.cpp +++ /dev/null @@ -1,307 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * Gagan Saksena 02/02/98 - * - */ - -#include "prtypes.h" -#include "prinrval.h" -#include "plstr.h" -#include "prprf.h" //PR_smprintf and PR_smprintf_free - -#include "nsCacheManager.h" -#include "nsCacheTrace.h" -#include "nsCachePref.h" -#include "nsCacheModule.h" -#include "nsMemModule.h" -#include "nsDiskModule.h" -#include "nsCacheBkgThd.h" - -/* TODO move this to InitNetLib */ -static nsCacheManager TheManager; - -PRUint32 NumberOfObjects(void); - -nsCacheManager::nsCacheManager(): - m_pFirstModule(0), - m_bOffline(PR_FALSE), - m_pPrefs(0) -{ -} - -nsCacheManager::~nsCacheManager() -{ - if (m_pPrefs) - { - delete m_pPrefs; - m_pPrefs = 0; - } - if (m_pFirstModule) - { - delete m_pFirstModule; - m_pFirstModule = 0; - } - if (m_pBkgThd) - { - m_pBkgThd->Stop(); - delete m_pBkgThd; - m_pBkgThd = 0; - } -} - -nsCacheManager* -nsCacheManager::GetInstance() -{ - return &TheManager; -} - -#if 0 -/* Caller must free returned char* */ -const char* -nsCacheManager::Trace() const -{ - - char linebuffer[128]; - char* total; - - sprintf(linebuffer, "nsCacheManager: Modules = %d\n", Entries()); - - total = new char[strlen(linebuffer) + 1]; - strcpy(total, linebuffer); - return total; -} -#endif - -PRInt32 -nsCacheManager::AddModule(nsCacheModule* pModule) -{ - MonitorLocker ml(this); - if (pModule) - { - if (m_pFirstModule) - LastModule()->NextModule(pModule); - else - m_pFirstModule = pModule; - - return Entries()-1; - } - else - return -1; -} - -PRBool -nsCacheManager::Contains(const char* i_url) const -{ - MonitorLocker ml((nsMonitorable*)this); - // Add logic to check for IMAP type URLs, byteranges, and search with / appended as well... - // TODO - PRBool bStatus = ContainsExactly(i_url); - if (!bStatus) - { - // try alternate stuff - /* - char* extraBytes; - char extraBytesSeparator; - */ - } -#if !defined(NDEBUG) && defined(DEBUG_gagan) - fputs(i_url, stdout); - fputs(bStatus ? " is " : " is not ", stdout); - fputs("in cache\n", stdout); -#endif - return bStatus; -} - -PRBool -nsCacheManager::ContainsExactly(const char* i_url) const -{ - if (m_pFirstModule) - { - nsCacheModule* pModule = m_pFirstModule; - while (pModule) - { - if (pModule->Contains(i_url)) - { - return PR_TRUE; - } - pModule = pModule->NextModule(); - } - } - return PR_FALSE; -} - -nsCacheObject* -nsCacheManager::GetObj(const char* i_url) const -{ - MonitorLocker ml((nsMonitorable*)this); - if (m_pFirstModule) - { - nsCacheModule* pModule = m_pFirstModule; - nsCacheObject* obj = 0; - while (pModule) - { - obj = pModule->GetObject(i_url); - if (obj) - return obj; - pModule = pModule->NextModule(); - } - } - return 0; -} - -PRInt16 -nsCacheManager::Entries() const -{ - MonitorLocker ml((nsMonitorable*)this); - if (m_pFirstModule) - { - PRInt16 count=1; - nsCacheModule* pModule = m_pFirstModule->NextModule(); - while (pModule) - { - count++; - pModule = pModule->NextModule(); - } - return count; - } - return 0; -} - -nsCacheModule* -nsCacheManager::GetModule(PRInt16 i_index) const -{ - MonitorLocker ml((nsMonitorable*)this); - if ((i_index < 0) || (i_index >= Entries())) - return 0; - nsCacheModule* pModule = m_pFirstModule; - PR_ASSERT(pModule); - for (PRInt16 i=0; iNextModule()) - { - i++; - PR_ASSERT(pModule); - } - return pModule; -} - -void -nsCacheManager::InfoAsHTML(char* o_Buffer) const -{ - MonitorLocker ml((nsMonitorable*)this); - - char* tmpBuffer =/* TODO - make this cool */ - PR_smprintf("

Your cache has %d modules

\ - It has a total of %d cache objects. Hang in there for the details. \0", - Entries(), - NumberOfObjects()); - - if (tmpBuffer) - { - PL_strncpyz(o_Buffer, tmpBuffer, PL_strlen(tmpBuffer)+1); - PR_smprintf_free(tmpBuffer); - } - } - -void -nsCacheManager::Init() -{ - MonitorLocker ml(this); - - //Init prefs - if (!m_pPrefs) - m_pPrefs = new nsCachePref(); - - if (m_pFirstModule) - delete m_pFirstModule; - - m_pFirstModule = new nsMemModule(nsCachePref::GetInstance()->MemCacheSize()); - PR_ASSERT(m_pFirstModule); - if (m_pFirstModule) - { - nsDiskModule* pTemp = new nsDiskModule(nsCachePref::GetInstance()->DiskCacheSize()); - PR_ASSERT(pTemp); - m_pFirstModule->NextModule(pTemp); - m_pBkgThd = new nsCacheBkgThd(PR_SecondsToInterval(nsCachePref::GetInstance()->BkgSleepTime())); - PR_ASSERT(m_pBkgThd); - } -} - -nsCacheModule* -nsCacheManager::LastModule() const -{ - MonitorLocker ml((nsMonitorable*)this); - if (m_pFirstModule) - { - nsCacheModule* pModule = m_pFirstModule; - while(pModule->NextModule()) { - pModule = pModule->NextModule(); - } - return pModule; - } - return 0; -} - -PRBool -nsCacheManager::Remove(const char* i_url) -{ - MonitorLocker ml(this); - PRBool bStatus = PR_FALSE; - if (m_pFirstModule) - { - nsCacheModule* pModule = m_pFirstModule; - bStatus = pModule->Remove(i_url); - if (bStatus) - return bStatus; - while(pModule->NextModule()) { - pModule = pModule->NextModule(); - bStatus = pModule->Remove(i_url); - if (bStatus) - return bStatus; - } - } - return bStatus; -} - -PRUint32 -nsCacheManager::WorstCaseTime(void) const -{ - PRIntervalTime start = PR_IntervalNow(); - if (this->Contains("a vague string that should not be in any of the modules")) - { - PR_ASSERT(0); - } - return PR_IntervalToMicroseconds(PR_IntervalNow() - start); -} - -PRUint32 -NumberOfObjects(void) -{ - PRUint32 objs = 0; - int i = TheManager.Entries(); - while (i>0) - { - objs += TheManager.GetModule(--i)->Entries(); - } - return objs; -} - diff --git a/mozilla/network/cache/nu/src/nsCacheModule.cpp b/mozilla/network/cache/nu/src/nsCacheModule.cpp deleted file mode 100644 index 8df836831c0..00000000000 --- a/mozilla/network/cache/nu/src/nsCacheModule.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsCacheModule.h" -#include "nsCacheTrace.h" -#include "nsCacheIterator.h" - -/* - * nsCacheModule - * - * Gagan Saksena 02/02/98 - * - */ - - -#define DEFAULT_SIZE 10*0x100000L - -nsCacheModule::nsCacheModule(const PRUint32 i_size=DEFAULT_SIZE): - m_Size(i_size), - m_SizeInUse(0), - m_pEnumeration(0), - m_pNext(0), - m_Entries(0) -{ - m_pIterator = new nsCacheIterator(this); -} - -nsCacheModule::~nsCacheModule() -{ - if (m_pNext) - { - delete m_pNext; - m_pNext = 0; - } - if (m_pIterator) - { - delete m_pIterator; - m_pIterator = 0; - } - if (m_pEnumeration) - { - delete m_pEnumeration; - m_pEnumeration = 0; - } -} - -void nsCacheModule::GarbageCollect(void) -{ -} - -PRBool nsCacheModule::ReduceSizeTo(const PRUint32 i_NewSize) -{ - MonitorLocker ml(this); - //TODO - return PR_TRUE; -} - -PRBool nsCacheModule::RemoveAll(void) -{ - MonitorLocker ml(this); - PRBool status = PR_TRUE; - while (m_Entries > 0) - { - status &= Remove(--m_Entries); - } - return status; -} - -#if 0 -// Caller must free this -const char* nsCacheModule::Trace() const -{ - char linebuffer[128]; - char* total; - - PR_sprintf(linebuffer, "nsCacheModule: Objects = %d\n", Entries()); - - total = new char[PR_strlen(linebuffer) + 1]; - strcpy(total, linebuffer); - - return total; -} -#endif diff --git a/mozilla/network/cache/nu/src/nsCacheObject.cpp b/mozilla/network/cache/nu/src/nsCacheObject.cpp deleted file mode 100644 index 142dbec1473..00000000000 --- a/mozilla/network/cache/nu/src/nsCacheObject.cpp +++ /dev/null @@ -1,624 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef XP_MAC -#include "memory.h" -#else -#include "cstring" -#endif - -#include "prmem.h" -#include "prprf.h" -#include "plstr.h" - -#include "nsCacheObject.h" -#include "nsCacheTrace.h" -#include "nsCacheModule.h" -#include "nsCacheManager.h" -#include "nsStream.h" - -/* - * nsCacheObject - * - * Gagan Saksena 02/02/98 - * - */ - -static const PRIntervalTime DEFAULT_EXPIRES = PR_SecondsToInterval(86400); - -#if !defined(IS_LITTLE_ENDIAN) && !defined(IS_BIG_ENDIAN) -ERROR! Must have a byte order -#endif - -#ifdef IS_LITTLE_ENDIAN -#define COPY_INT32(_a,_b) memcpy(_a, _b, sizeof(int32)) -#else -#define COPY_INT32(_a,_b) /* swap */ \ - do { \ - ((char *)(_a))[0] = ((char *)(_b))[3]; \ - ((char *)(_a))[1] = ((char *)(_b))[2]; \ - ((char *)(_a))[2] = ((char *)(_b))[1]; \ - ((char *)(_a))[3] = ((char *)(_b))[0]; \ - } while(0) -#endif - -/* Convenient macros used in stuffing and reading back cache object to a void * */ -/* TODO: Change these to file scope functions */ -#define STUFF_STRING(string) \ -{ \ - len = (string ? PL_strlen(string)+1 : 0); \ - COPY_INT32((void *)cur_ptr, &len); \ - cur_ptr = cur_ptr + sizeof(int32); \ - if(len) \ - memcpy((void *)cur_ptr, string, len); \ - cur_ptr += len; \ -} - -#define STUFF_NUMBER(number) \ -{ \ - COPY_INT32((void *)cur_ptr, &number); \ - cur_ptr = cur_ptr + sizeof(PRUint32); \ -} - -#define STUFF_TIME(number) \ -{ \ - COPY_INT32((void *)cur_ptr, &number); \ - cur_ptr = cur_ptr + sizeof(PRIntervalTime); \ -} - -#define STUFF_BOOL(bool_val) \ -{ \ - if(bool_val) \ - ((char *)(cur_ptr))[0] = 1; \ - else \ - ((char *)(cur_ptr))[0] = 0; \ - cur_ptr = cur_ptr + sizeof(char); \ -} - -/* if any strings are larger than this then - * there was a serious database error - */ -#define MAX_HUGE_STRING_SIZE 10000 - -#define RETRIEVE_STRING(string) \ -{ \ - if(cur_ptr > max_ptr) \ - { \ - return PR_TRUE; \ - } \ - COPY_INT32(&len, cur_ptr); \ - cur_ptr += sizeof(int32); \ - if(len) \ - { \ - if(len > MAX_HUGE_STRING_SIZE) \ - { \ - return PR_FALSE; \ - } \ - string = new char[len]; \ - if(!string) \ - { \ - return PR_FALSE; \ - } \ - memcpy(string, cur_ptr, len); \ - cur_ptr += len; \ - } \ -} - -#define RETRIEVE_NUMBER(number) \ -{ \ - if(cur_ptr > max_ptr) \ - return PR_TRUE; \ - COPY_INT32(&number, cur_ptr); \ - cur_ptr += sizeof(int32); \ -} - -#define RETRIEVE_TIME(number) \ -{ \ - if(cur_ptr > max_ptr) \ - return PR_TRUE; \ - COPY_INT32(&number, cur_ptr); \ - cur_ptr += sizeof(PRIntervalTime); \ -} - -#define RETRIEVE_BOOL(bool) \ -{ \ - if(cur_ptr > max_ptr) \ - return PR_TRUE; \ - if(((char *)(cur_ptr))[0]) \ - bool = TRUE; \ - else \ - bool = FALSE; \ - cur_ptr += sizeof(char); \ -} - -/* TODO- Further optimization, initialize these to null, - but that will add more work on copy constructor which is ok */ -nsCacheObject::nsCacheObject(): - m_Charset(new char[1]), - m_ContentEncoding(new char[1]), - m_ContentType(new char[1]), - m_Etag(new char[1]), - m_Filename(new char[1]), - m_State(INIT), - m_bIsCompleted(PR_FALSE), - m_Module(-1), - m_pInfo(0), - m_PageServicesURL(new char[1]), - m_PostData(new char[1]), - m_PostDataLen(0), - m_pStream(0), - m_URL(new char[1]) -{ - Init(); - *m_Charset = '\0'; - *m_ContentEncoding = '\0'; - *m_ContentType = '\0'; - *m_Etag = '\0'; - *m_Filename = '\0'; - *m_PageServicesURL = '\0'; - *m_PostData = '\0'; - *m_URL = '\0'; -} - -nsCacheObject::~nsCacheObject() -{ - if (m_Charset) - delete[] m_Charset; - if (m_ContentEncoding) - delete[] m_ContentEncoding; - if (m_ContentType) - delete[] m_ContentType; - if (m_Etag) - delete[] m_Etag; - if (m_Filename) - delete[] m_Filename; - if (m_PageServicesURL) - delete[] m_PageServicesURL; - if (m_PostData) - delete[] m_PostData; - if (m_URL) - delete[] m_URL; - if (m_pStream) - delete m_pStream; -} - -nsCacheObject::nsCacheObject(const nsCacheObject& another): - m_Charset(new char[PL_strlen(another.m_Charset)+1]), - m_ContentEncoding(new char[PL_strlen(another.m_ContentEncoding)+1]), - m_ContentType(new char[PL_strlen(another.m_ContentType)+1]), - m_Etag(new char[PL_strlen(another.m_Etag)+1]), - m_Filename(new char[PL_strlen(another.m_Filename)+1]), - m_State(another.m_State), - m_bIsCompleted(another.m_bIsCompleted), - m_PageServicesURL(new char[PL_strlen(another.m_PageServicesURL)+1]), - m_PostDataLen(another.m_PostDataLen), - m_PostData(new char[another.m_PostDataLen+1]), - m_URL(new char[PL_strlen(another.m_URL)+1]), - m_pStream(0), - m_pInfo(0) /* Should this be copied as well? */ -{ - PL_strncpyz(m_Charset, another.m_Charset, PL_strlen(another.m_Charset)+1); - PL_strncpyz(m_ContentEncoding, another.m_ContentEncoding, PL_strlen(another.m_ContentEncoding)+1); - PL_strncpyz(m_ContentType, another.m_ContentType, PL_strlen(another.m_ContentType)+1); - PL_strncpyz(m_Etag, another.m_Etag, PL_strlen(another.m_Etag)+1); - PL_strncpyz(m_Filename, another.m_Filename, PL_strlen(another.m_Filename)+1); - PL_strncpyz(m_PageServicesURL, another.m_PageServicesURL, PL_strlen(another.m_PageServicesURL)+1); - PL_strncpyz(m_PostData, another.m_PostData, another.m_PostDataLen+1); - PL_strncpyz(m_URL, another.m_URL, PL_strlen(another.m_URL)+1); - - m_Hits = another.m_Hits; - m_LastAccessed = another.m_LastAccessed; - m_LastModified = another.m_LastModified; - m_Size = another.m_Size; - m_Module = another.m_Module; -} - -nsCacheObject::nsCacheObject(const char* i_url): - m_Charset(new char[1]), - m_ContentEncoding(new char[1]), - m_ContentType(new char[1]), - m_Etag(new char[1]), - m_Filename(new char[1]), - m_State(INIT), - m_bIsCompleted(PR_FALSE), - m_PageServicesURL(new char[1]), - m_PostData(new char[1]), - m_PostDataLen(0), - m_URL(new char[PL_strlen(i_url)+1]), - m_Module(-1), - m_pStream(0), - m_pInfo(0) -{ - Init(); - PR_ASSERT(i_url); - PL_strncpyz(m_URL, i_url, PL_strlen(i_url)+1); - - *m_Charset = '\0'; - *m_ContentEncoding = '\0'; - *m_ContentType = '\0'; - *m_Etag = '\0'; - *m_Filename = '\0'; - *m_PageServicesURL = '\0'; - *m_PostData = '\0'; -} - -void nsCacheObject::Address(const char* i_url) -{ - PR_ASSERT(i_url && *i_url); - if (!i_url) - return; - if (m_URL) - delete[] m_URL; - int len = PL_strlen(i_url); - m_URL = new char[len + 1]; - PL_strncpyz(m_URL, i_url, len+1); -} - -void nsCacheObject::Charset(const char* i_Charset) -{ -// PR_ASSERT(i_Charset && *i_Charset); - if (!i_Charset) //TODO reset m_charset here - return; - if (m_Charset) - delete[] m_Charset; - int len = PL_strlen(i_Charset); - m_Charset = new char[len + 1]; - PL_strncpyz(m_Charset, i_Charset, len+1); -} - -void nsCacheObject::ContentEncoding(const char* i_Encoding) -{ -// PR_ASSERT(i_Encoding && *i_Encoding); - if (!i_Encoding) - return; - if (m_ContentEncoding) - delete[] m_ContentEncoding; - int len = PL_strlen(i_Encoding); - m_ContentEncoding = new char[len + 1]; - PL_strncpyz(m_ContentEncoding, i_Encoding, len+1); -} - -void nsCacheObject::ContentType(const char* i_Type) -{ -// PR_ASSERT(i_Type && *i_Type); - if (!i_Type) - { - /* Reset to empty */ // TODO ?? - return; - } - if (m_ContentType) - delete[] m_ContentType; - int len = PL_strlen(i_Type); - m_ContentType = new char[len + 1]; - PL_strncpyz(m_ContentType, i_Type, len+1); -} - -void nsCacheObject::Etag(const char* i_etag) -{ -// PR_ASSERT(i_etag && *i_etag); - if (!i_etag) - return; - if (m_Etag) - delete[] m_Etag; - m_Etag = new char[PL_strlen(i_etag) + 1]; - PL_strncpyz(m_Etag, i_etag, PL_strlen(i_etag)+1); -} - -void nsCacheObject::Filename(const char* i_Filename) -{ -// PR_ASSERT(i_Filename && *i_Filename); - if (!i_Filename) - return; - if (m_Filename) - delete[] m_Filename; - int len = PL_strlen(i_Filename); - m_Filename = new char[len +1]; - PL_strncpyz(m_Filename, i_Filename, len+1); -} - -void* nsCacheObject::Info(void) const -{ - if (m_pInfo) - return m_pInfo; - - nsCacheObject* pThis = (nsCacheObject*) this; - if (m_URL){ - - pThis->m_info_size = sizeof(nsCacheObject); - - pThis->m_info_size -= sizeof(void*); // m_info itself is not being serialized - pThis->m_info_size -= sizeof(char*); // neither is m_PostData - pThis->m_info_size -= sizeof(nsStream*); // nor the stream - pThis->m_info_size -= sizeof(PRBool); // bIsCompleted. - //todo -optimize till here - - //Add the strings sizes - pThis->m_info_size += PL_strlen(m_Charset)+1; - pThis->m_info_size += PL_strlen(m_ContentEncoding)+1; - pThis->m_info_size += PL_strlen(m_ContentType)+1; - pThis->m_info_size += PL_strlen(m_Etag)+1; - pThis->m_info_size += PL_strlen(m_Filename)+1; - pThis->m_info_size += PL_strlen(m_PageServicesURL)+1; - pThis->m_info_size += PL_strlen(m_URL)+1; - - //Add the Postdata len - pThis->m_info_size += m_PostDataLen+1; - - void* new_obj = PR_Calloc(1, m_info_size * sizeof(char)); - - if (!new_obj) - { - PR_Free(new_obj); - return 0; - } - - PRUint32 len; - - char* cur_ptr = (char*) new_obj; - /* put the total size of the struct into - * the first field so that we have - * a cross check against corruption - */ - COPY_INT32((void *)cur_ptr, &m_info_size); - cur_ptr += sizeof(PRUint32); - - /* put the version number of the structure - * format that we are using. By using a version - * string when writting we can support - * backwards compatibility in our reading code - */ - COPY_INT32((void *)cur_ptr, &kCACHE_VERSION); - cur_ptr += sizeof(PRUint32); - - STUFF_STRING(m_Charset); - STUFF_STRING(m_ContentEncoding); - STUFF_NUMBER(m_ContentLength); - STUFF_STRING(m_ContentType); - STUFF_STRING(m_Etag); - STUFF_TIME(m_Expires); - STUFF_STRING(m_Filename); - STUFF_NUMBER(m_Hits); - STUFF_TIME(m_LastAccessed); - STUFF_TIME(m_LastModified); - STUFF_NUMBER(m_Module); - STUFF_STRING(m_PageServicesURL); - STUFF_NUMBER(m_PostDataLen); - /* There is a possibility of it not being a string! */ - if (m_PostData) - { - memcpy(cur_ptr, m_PostData, m_PostDataLen+1); - cur_ptr += m_PostDataLen+1; - } - STUFF_NUMBER(m_Size); - STUFF_NUMBER(m_State); - STUFF_STRING(m_URL); - - // Important Assertion. Dont remove! - // If this fails then you or somebody has added a variable to the - // nsCacheObject class and a decision on its "cacheability" has - // not yet been made. - PR_ASSERT(cur_ptr == (char*) new_obj + m_info_size); - pThis->m_pInfo = new_obj; - } - return m_pInfo; -} - -PRBool nsCacheObject::Info(void* i_data) -{ - if (!i_data) - return PR_FALSE; - - char* cur_ptr = (char*) i_data; - - //Reset the m_pInfo; - if (m_pInfo) - { - PR_Free(m_pInfo); - m_pInfo = 0; - } - - //Reset all strings - if (m_Charset) - delete[] m_Charset; - if (m_ContentEncoding) - delete[] m_ContentEncoding; - if (m_ContentType) - delete[] m_ContentType; - if (m_Etag) - delete[] m_Etag; - if (m_Filename) - delete[] m_Filename; - if (m_PageServicesURL) - delete[] m_PageServicesURL; - if (m_URL) - delete[] m_URL; - if (m_PostData) - delete[] m_PostData; - - m_PostDataLen = 0; - - COPY_INT32(&m_info_size, cur_ptr); - char* max_ptr = cur_ptr + m_info_size; - cur_ptr += sizeof(PRUint32); - - PRUint32 version; - COPY_INT32(&version, cur_ptr); - cur_ptr += sizeof(PRUint32); - - PR_ASSERT(version == kCACHE_VERSION); - if (version != kCACHE_VERSION) - { - //TODO Bad cache version - return PR_FALSE; - } - - PRUint32 len; - - RETRIEVE_STRING(m_Charset); - RETRIEVE_STRING(m_ContentEncoding); - RETRIEVE_NUMBER(m_ContentLength); - RETRIEVE_STRING(m_ContentType); - RETRIEVE_STRING(m_Etag); - RETRIEVE_TIME(m_Expires); - RETRIEVE_STRING(m_Filename); - RETRIEVE_NUMBER(m_Hits); - RETRIEVE_TIME(m_LastAccessed); - RETRIEVE_TIME(m_LastModified); - RETRIEVE_NUMBER(m_Module); - RETRIEVE_STRING(m_PageServicesURL); - RETRIEVE_NUMBER(m_PostDataLen); - // Special case- - m_PostData = new char[m_PostDataLen + 1]; - if (m_PostData) - { - memcpy(m_PostData, cur_ptr, m_PostDataLen+1); - } - cur_ptr += m_PostDataLen +1; - - RETRIEVE_NUMBER(m_Size); - RETRIEVE_NUMBER(m_State); - RETRIEVE_STRING(m_URL); - - // Most important assertion! Don't ever remove! - PR_ASSERT(cur_ptr == max_ptr); - - // Since we are reading off its info from an indexed entry - m_bIsCompleted = PR_TRUE; - - return PR_TRUE; -} - -PRUint32 nsCacheObject::InfoSize(void) const -{ - if (!m_pInfo) - { - ((nsCacheObject*) this)->Info(); - } - return m_info_size; -} - -void nsCacheObject::Init() -{ - m_Size = 0; - m_Expires = PR_IntervalNow() + DEFAULT_EXPIRES; - m_Hits = 0; -} - -void nsCacheObject::PageServicesURL(const char* i_Url) -{ -// PR_ASSERT(i_Url && *i_Url); - if (!i_Url) - return; - if (m_PageServicesURL) - delete[] m_PageServicesURL; - m_PageServicesURL = new char[PL_strlen(i_Url) + 1]; - PL_strncpyz(m_PageServicesURL, i_Url, PL_strlen(i_Url)+1); -} - -void nsCacheObject::PostData(const char* i_data, const PRUint32 i_Len) -{ - if (!i_data || (0 ==i_Len)) - return; - if (m_PostData) - delete[] m_PostData; - m_PostData = new char[i_Len+1]; - PL_strncpyz(m_PostData, i_data, i_Len+1); - m_PostDataLen = i_Len; -} - -PRUint32 nsCacheObject::Read(char* o_Buffer, PRUint32 len) -{ - if (!m_pStream) - { - PR_ASSERT(m_Module >=0); - if (0 <= m_Module) - { - nsCacheModule* pModule = nsCacheManager::GetInstance()->GetModule(m_Module); - if (pModule) - { - m_pStream = pModule->GetStreamFor(this); - if (m_pStream) - { - return m_pStream->Read(o_Buffer, len); - } - } - } - return 0; - } - return m_pStream->Read(o_Buffer, len); -} - -void nsCacheObject::Reset() -{ - if (m_pStream) - m_pStream->Reset(); - // TODO change states too. -} - -#if 0 -/* Caller must free returned string */ -// TODO change to use PR_stuff... -const char* nsCacheObject::Trace() const -{ - char linebuffer[256]; - char* total; - - PR_Sprintf(linebuffer, "nsCacheObject:URL=%s,SIZE=%d,ET=%s,\n\tLM=%d,LA=%d,EXP=%d,HITS=%d\n", - m_URL, - m_Size, - m_Etag, - m_LastModified, - m_LastAccessed, - m_Expires, - m_Hits); - - total = new char[PL_strlen(linebuffer) +1]; - PL_strcpy(total, linebuffer); - - return total; -} -#endif - -PRUint32 nsCacheObject::Write(const char* i_Buffer, const PRUint32 len) -{ - PRUint32 amountWritten = 0; - if (!m_pStream) - { - PR_ASSERT(m_Module >=0); - if (0 <= m_Module) - { - nsCacheModule* pModule = nsCacheManager::GetInstance()->GetModule(m_Module); - if (pModule) - { - m_pStream = pModule->GetStreamFor(this); - PR_ASSERT(m_pStream); - if (!m_pStream) - return 0; - } - } - else - return 0; - } - amountWritten = m_pStream->Write(i_Buffer, len); - m_Size += amountWritten; - return amountWritten; -} diff --git a/mozilla/network/cache/nu/src/nsCachePref.cpp b/mozilla/network/cache/nu/src/nsCachePref.cpp deleted file mode 100644 index eec5d50775d..00000000000 --- a/mozilla/network/cache/nu/src/nsCachePref.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsCachePref.h" -#ifndef XP_UNIX -#include "xp.h" // This complains on unix. Works ok without there. -#endif -#include "prefapi.h" -#include "prmem.h" -#include "nsCacheManager.h" -#include "plstr.h" -#if defined(XP_PC) -#include -#include "nspr.h" -#endif /* XP_PC */ - -#ifdef XP_MAC -#include "uprefd.h" -#endif - - -static const PRUint32 MEM_CACHE_SIZE_DEFAULT = 1024*1024; -static const PRUint32 DISK_CACHE_SIZE_DEFAULT = 5*MEM_CACHE_SIZE_DEFAULT; -static const PRUint32 BKG_THREAD_SLEEP = 15*60; /*in seconds, 15 minutes */ -static const PRUint16 BUGS_FOUND_SO_FAR = 0; - -//Preferences -static const char * const MEM_CACHE_PREF = "browser.cache.memory_cache_size"; -static const char * const DISK_CACHE_PREF = "browser.cache.disk_cache_size"; -static const char * const CACHE_DIR_PREF = "browser.cache.directory"; -static const char * const FREQ_PREF = "browser.cache.check_doc_frequency"; -//Not implemented as yet... -static const char * const BKG_CLEANUP = "browser.cache.cleanup_period"; //Default for BKG_THREAD_SLEEP - -/* Find a bug in NU_CACHE, get these many chocolates */ -static const PRUint16 CHOCOLATES_PER_BUG_FOUND = 2^BUGS_FOUND_SO_FAR; - -static int PR_CALLBACK Cache_PrefChangedFunc(const char *pref, void *data); - -nsCachePref::nsCachePref(void): - m_BkgSleepTime(BKG_THREAD_SLEEP), - m_DiskCacheDBFilename(new char[6+1]), - m_DiskCacheFolder(0), - m_DiskCacheSize(DISK_CACHE_SIZE_DEFAULT), - m_MemCacheSize(MEM_CACHE_SIZE_DEFAULT), - m_RefreshFreq(ONCE) -{ - PREF_RegisterCallback("browser.cache",Cache_PrefChangedFunc,0); - SetupPrefs(0); -} - -nsCachePref::~nsCachePref() -{ - if (m_DiskCacheFolder) - { - delete m_DiskCacheFolder; - m_DiskCacheFolder = 0; - } -} - -//Read all the stuff from pref here. -void -nsCachePref::SetupPrefs(const char* i_Pref) -{ - PRBool bSetupAll = PR_FALSE; - - PRInt32 nTemp; - char* tempPref=0; - - if (!i_Pref) - bSetupAll = PR_TRUE; - - if (bSetupAll || !PL_strcmp(i_Pref,MEM_CACHE_PREF)) - { - if (PREF_OK == PREF_GetIntPref(MEM_CACHE_PREF,&nTemp)) - m_MemCacheSize = 1024*nTemp; - else - m_MemCacheSize = MEM_CACHE_SIZE_DEFAULT; - } - - if (bSetupAll || !PL_strcmp(i_Pref,DISK_CACHE_PREF)) - { - if (PREF_OK == PREF_GetIntPref(DISK_CACHE_PREF,&nTemp)) - m_DiskCacheSize = 1024*nTemp; - else - m_DiskCacheSize = DISK_CACHE_SIZE_DEFAULT; - } - - if (bSetupAll || !PL_strcmp(i_Pref,FREQ_PREF)) - { - if (PREF_OK == PREF_GetIntPref(FREQ_PREF,&nTemp)) - { - m_RefreshFreq = (nsCachePref::Refresh)nTemp; - } - else - m_RefreshFreq = ONCE; - } - - if (bSetupAll || !PL_strcmp(i_Pref,CACHE_DIR_PREF)) - { - if (PREF_OK == PREF_CopyPathPref(CACHE_DIR_PREF,&tempPref)) - { - PR_ASSERT(tempPref); - delete [] m_DiskCacheFolder; - m_DiskCacheFolder = new char[PL_strlen(tempPref)+2]; - if (!m_DiskCacheFolder) - { - if (tempPref) - PR_Free(tempPref); - return; - } - PL_strcpy(m_DiskCacheFolder, tempPref); - } - else //TODO set to temp folder - { -#if defined(XP_PC) - char tmpBuf[_MAX_PATH]; - PRFileInfo dir; - PRStatus status; - char *cacheDir = new char [_MAX_PATH]; - if (!cacheDir) - return; - cacheDir = _getcwd(cacheDir, _MAX_PATH); - - // setup the cache dir. - PL_strcpy(tmpBuf, cacheDir); - sprintf(cacheDir,"%s%s%s%s", tmpBuf, "\\", "cache", "\\"); - status = PR_GetFileInfo(cacheDir, &dir); - if (PR_FAILURE == status) { - // Create the dir. - status = PR_MkDir(cacheDir, 0600); - if (PR_SUCCESS != status) { - m_DiskCacheFolder = new char[1]; - *m_DiskCacheFolder = '\0'; - return; - } - } - m_DiskCacheFolder = cacheDir; -#endif /* XP_PC */ - } - } - - if (tempPref) - PR_Free(tempPref); -} - -const PRUint32 -nsCachePref::BkgSleepTime(void) -{ - return BKG_THREAD_SLEEP; -} - -const char* nsCachePref::DiskCacheDBFilename(void) -{ - return "nufat.db"; -} - -nsCachePref* nsCachePref::GetInstance() -{ - PR_ASSERT(nsCacheManager::GetInstance()->GetPrefs()); - return nsCacheManager::GetInstance()->GetPrefs(); -} - -/* -nsrefcnt nsCachePref::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsCachePref::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsCachePref::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} -*/ - -int PR_CALLBACK Cache_PrefChangedFunc(const char *pref, void *data) { - nsCachePref::GetInstance()->SetupPrefs(pref); - return PR_TRUE; -} - diff --git a/mozilla/network/cache/nu/src/nsCacheTrace.cpp b/mozilla/network/cache/nu/src/nsCacheTrace.cpp deleted file mode 100644 index fc556a34e1c..00000000000 --- a/mozilla/network/cache/nu/src/nsCacheTrace.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * nsCacheTrace - * - * Gagan Saksena 02/02/98 - * - */ - -#include "nsCacheTrace.h" - -static nsCacheTrace TheTrace; - -nsCacheTrace::nsCacheTrace():m_bEnabled(PR_FALSE) -{ - -} - -void nsCacheTrace::Enable(PRBool bEnable) -{ - TheTrace.m_bEnabled = bEnable; -} - -PRBool nsCacheTrace::IsEnabled(void) -{ - return TheTrace.m_bEnabled; -} - diff --git a/mozilla/network/cache/nu/src/nsDiskModule.cpp b/mozilla/network/cache/nu/src/nsDiskModule.cpp deleted file mode 100644 index df3ad62edd7..00000000000 --- a/mozilla/network/cache/nu/src/nsDiskModule.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * nsDiskModule - * - * Gagan Saksena 02/02/98 - * - */ - -#include "prtypes.h" -#include "prmem.h" -#include "plstr.h" -#include "prlog.h" -#include "prclist.h" -#include "prio.h" -#include "prsystem.h" // Directory Separator - -#include "nsDiskModule.h" -#include "nsCacheObject.h" -#include "nsCacheManager.h" -#include "nsFileStream.h" -#include "nsCachePref.h" - -#include "mcom_db.h" - -#define ENSURE_INIT \ - if (!m_pDB) \ - { \ - nsDiskModule* pThis = (nsDiskModule*) this; \ - PRBool res = pThis->InitDB(); \ - PR_ASSERT(res); \ - } - -struct recentlyUsedObject { - PRCList link; - nsCacheObject* cacheObject; -}; - -/* Find pointer to recentlyUsedObject struct - * from the list linkaged embedded in it - */ -#define OBJECT_PTR(_link) \ - ((recentlyUsedObject*) ((char*) (_link) - offsetof(recentlyUsedObject,link))) - -//File static list of recently used cache objects -static PRCList g_RecentlyUsedList; -static nsCacheObject* g_pTempObj=0; -static char* g_FullFilename=0; -const static int MAX_FILENAME_LEN = 512; -const static int MAX_OBJECTS_IN_RECENTLY_USED_LIST = 20; // change later TODO. - -// Every time we cleanup we cleanup to 75% of the max available size. -// This should ideally change to a more const number than a percentage. -// Since someone may have a bigger cache size, so we don't really want to -// be cleaning up 5 megs if some one has a 20 megs cache size. -// I will revisit this issue once the basic architecture is up and running. -#define CLEANUP_FACTOR 0.75 - -//Returns the full filename including the cache directory. -static char* FullFilename(const char* i_Filename); - -//Returns the Least Recently Used object in the database -static nsCacheObject* LRUObject(DB* pDB); - -// -// Constructor: nsDiskModule -// -nsDiskModule::nsDiskModule(const PRUint32 size): - nsCacheModule(size), - m_pDB(0) -{ - PR_INIT_CLIST(&g_RecentlyUsedList); -} - -nsDiskModule::~nsDiskModule() -{ - //This will free up any operational "over the limit" cache objects. - GarbageCollect(); - - if (m_pDB) - { - (*m_pDB->sync)(m_pDB, 0); - (*m_pDB->close)(m_pDB); - m_pDB = 0; - } - - /* Clean up the recently used list */ - recentlyUsedObject* obj; - while (!PR_CLIST_IS_EMPTY(&g_RecentlyUsedList)) - { - obj = (recentlyUsedObject*) PR_LIST_HEAD(&g_RecentlyUsedList); - if (obj->cacheObject) - delete obj->cacheObject; - PR_REMOVE_LINK(&obj->link); - } - - PR_ASSERT(PR_CLIST_IS_EMPTY(&g_RecentlyUsedList)); - - if (g_FullFilename) - { - delete[] g_FullFilename; - g_FullFilename = 0; - } - - if (g_pTempObj) - { - delete g_pTempObj; - g_pTempObj = 0; - } -} - -PRBool nsDiskModule::AddObject(nsCacheObject* io_pObject) -{ - ENSURE_INIT; - - if (!m_pDB || !io_pObject) - { - // Set some error state TODO - return PR_FALSE; - } - - if (io_pObject->Address()) - { - MonitorLocker ml(this); - - //Remove the earliar copy- silently handles if not found - Remove(io_pObject->Address()); - - // TODO optimize these further- make static - Gagan - DBT* key = PR_NEW(DBT); - DBT* data = PR_NEW(DBT); - - //Set the module - io_pObject->Module(nsCacheManager::DISK); - - //Close the corresponding file - PR_ASSERT(io_pObject->Stream()); - if (io_pObject->Stream()) - PR_Close(((nsFileStream*)io_pObject->Stream())->FileDesc()); - - key->data = (void*)io_pObject->Address(); - /* Later on change this to include post data- io_pObject->KeyData() */ - key->size = PL_strlen(io_pObject->Address()); - - data->data = io_pObject->Info(); - data->size = io_pObject->InfoSize(); - - int status = (*m_pDB->put)(m_pDB, key, data, 0); - if (status == 0) - { -// if (m_Sync == EVERYTIME) - status = (*m_pDB->sync)(m_pDB, 0); - m_Entries++; - m_SizeInUse += io_pObject->Size(); - } - PR_Free(key); - PR_Free(data); - return (status == 0); - } - return PR_FALSE; -} - -PRBool nsDiskModule::Contains(nsCacheObject* io_pObject) const -{ - ENSURE_INIT; - - if (!m_pDB || !io_pObject) - return PR_FALSE; - - nsCacheObject* pTemp = GetObject(io_pObject->Address()); - if (pTemp) - { - //PR_ASSERT(io_pObject == pTemp); - // until I do a copyFrom function - return PR_TRUE; - } - return PR_FALSE; -} - -PRBool nsDiskModule::Contains(const char* i_url) const -{ - - ENSURE_INIT; - - if (!m_pDB || !i_url || !*i_url) - return PR_FALSE; - - DBT key, data; - - key.data = (void*) i_url; - key.size = PL_strlen(i_url); - - int status = (*m_pDB->get)(m_pDB, &key, &data, 0); - - return (status == 0); - -} - -void nsDiskModule::GarbageCollect(void) -{ - MonitorLocker ml(this); - ReduceSizeTo((PRUint32)(CLEANUP_FACTOR*m_Size)); - - // if the recentlyusedlist has grown too big, trim some objects from there as well - // Count how many are there - int count=0; - if (!PR_CLIST_IS_EMPTY(&g_RecentlyUsedList)) - { - PRCList* list = g_RecentlyUsedList.next; - while (list != &g_RecentlyUsedList) - { - count++; - list = list->next; - } - } - // Then trim the extra ones. - int extra = count-MAX_OBJECTS_IN_RECENTLY_USED_LIST; - while (extra>0) - { - recentlyUsedObject* obj = (recentlyUsedObject*) PR_LIST_HEAD(&g_RecentlyUsedList); - if (obj->cacheObject) - delete obj->cacheObject; - PR_REMOVE_LINK(&obj->link); - extra--; - } -} - -nsCacheObject* nsDiskModule::GetObject(const PRUint32 i_index) const -{ - ENSURE_INIT; - if (!m_pDB) - return 0; -//todo - return 0; -} - -nsCacheObject* nsDiskModule::GetObject(const char* i_url) const -{ - ENSURE_INIT; - MonitorLocker ml((nsDiskModule*)this); - - if (!m_pDB || !i_url || !*i_url) - return 0; - - /* Check amongst recently used objects */ - recentlyUsedObject* obj; - PRCList* list = &g_RecentlyUsedList; - if (!PR_CLIST_IS_EMPTY(&g_RecentlyUsedList)) - { - list = g_RecentlyUsedList.next; - nsCacheObject* pObj; - while (list != &g_RecentlyUsedList) - { - obj = OBJECT_PTR(list); - pObj = obj->cacheObject; - if (0 == PL_strcasecmp(i_url, pObj->Address())) //todo also validate - return pObj; - list = list->next; - } - } - - DBT key, data; - - key.data = (void*) i_url; - key.size = PL_strlen(i_url); - - if (0 == (*m_pDB->get)(m_pDB, &key, &data, 0)) - { - nsCacheObject* pTemp = new nsCacheObject(); - pTemp->Info(data.data); - recentlyUsedObject* pNode = PR_NEWZAP(recentlyUsedObject); - PR_APPEND_LINK(&pNode->link, &g_RecentlyUsedList); - pNode->cacheObject = pTemp; - return pTemp; - } - - return 0; -} - -nsStream* nsDiskModule::GetStreamFor(const nsCacheObject* i_pObject) -{ - ENSURE_INIT; - MonitorLocker ml(this); - if (i_pObject) - { - nsStream* pStream = i_pObject->Stream(); - if (pStream) - return pStream; - - PR_ASSERT(*i_pObject->Filename()); - - char* fullname = FullFilename(i_pObject->Filename()); - - if (fullname) - { - return new nsFileStream(fullname); - } - } - return 0; -} - -PRBool nsDiskModule::InitDB(void) -{ - MonitorLocker ml(this); - - if (m_pDB) - return PR_TRUE; - - HASHINFO hash_info = { - 16*1024, /* bucket size */ - 0, /* fill factor */ - 0, /* number of elements */ - 0, /* bytes to cache */ - 0, /* hash function */ - 0}; /* byte order */ - - m_pDB = dbopen( - FullFilename(nsCachePref::GetInstance()->DiskCacheDBFilename()), - O_RDWR | O_CREAT, - 0600, - DB_HASH, - &hash_info); - - if (!m_pDB) - return PR_FALSE; - - /* Open and read in the number of existing entries */ - m_Entries = 0; - m_SizeInUse = 0; - int status; - DBT key, data; - if (0 == g_pTempObj) - g_pTempObj = new nsCacheObject(); - if(!(status = (*m_pDB->seq)(m_pDB, &key, &data, R_FIRST))) - { - do - { - /* Also validate the corresponding file here *///TODO - g_pTempObj->Info(data.data); - m_SizeInUse += g_pTempObj->Size(); - m_Entries++; - } - while(!(status = (*m_pDB->seq) (m_pDB, &key, &data, R_NEXT))); - } - - if (status < 0) - return PR_FALSE; - - return PR_TRUE; -} - -PRBool nsDiskModule::ReduceSizeTo(const PRUint32 i_NewSize) -{ - MonitorLocker ml(this); - - PRInt32 needToFree = m_SizeInUse - i_NewSize; - if ((m_Entries>0) && (needToFree > 0)) - { - PRUint32 avg = m_SizeInUse/m_Entries; - if (avg==0) - return PR_FALSE; - - PRUint32 nObjectsToFree = needToFree/avg; - if (nObjectsToFree < 1) - nObjectsToFree = 1; - - while (nObjectsToFree > 0) - { - Remove(LRUObject(m_pDB)); - --nObjectsToFree; - } - - return PR_TRUE; - } - - return PR_FALSE; -} - -PRBool nsDiskModule::Remove(const char* i_url) -{ - ENSURE_INIT; - return Remove(GetObject(i_url)); -} - -PRBool nsDiskModule::Remove(nsCacheObject* pObject) -{ - MonitorLocker ml(this); - PRBool bStatus = PR_FALSE; - if (!pObject) - return bStatus; - - //PR_ASSERT(Contains(pObject); - - // TODO Mark the objects state for deletion so that we dont - // read it in the meanwhile. - pObject->State(nsCacheObject::EXPIRED); - - //Remove it from the index - DBT key; - key.data = (void*) pObject->Address(); - key.size = PL_strlen(pObject->Address()); - if (0 == (*m_pDB->del)(m_pDB, &key, 0)) - { - --m_Entries; - m_SizeInUse -= pObject->Size(); - if (-1 == (*m_pDB->sync)(m_pDB, 0)) - { - //Failed to sync database - PR_ASSERT(0); - } - } - - //Remove it from the recently used list - recentlyUsedObject* obj; - PRCList* list = &g_RecentlyUsedList; - if (!PR_CLIST_IS_EMPTY(&g_RecentlyUsedList)) - { - list = g_RecentlyUsedList.next; - nsCacheObject* pObj; - PRBool bDone = PR_FALSE; - while ((list != &g_RecentlyUsedList) && !bDone) - { - obj = OBJECT_PTR(list); - pObj = obj->cacheObject; - if (pObj == pObject) - { - bDone = PR_TRUE; - PR_REMOVE_LINK(&obj->link); - } - list = list->next; - } - } - - //Remove it from the disk - if (PR_SUCCESS == PR_Delete(FullFilename(pObject->Filename()))) - { - bStatus = PR_TRUE; - } - else - { - //Failed to delete the file off the disk! - bStatus = PR_FALSE; - } - - //Finally delete it - delete pObject; - pObject = 0; - - return PR_FALSE; -} -PRBool nsDiskModule::Remove(const PRUint32 i_index) -{ - //This will probably go away. - ENSURE_INIT; - //TODO - // Also remove the file corresponding to this item. - return PR_FALSE; -} - -PRBool nsDiskModule::Revalidate(void) -{ - ENSURE_INIT; - //TODO - This will add a dependency on HTTP lib - return PR_FALSE; -} - -void nsDiskModule::SetSize(const PRUint32 i_Size) -{ - MonitorLocker ml(this); - m_Size = i_Size; - if (m_Size >0) - { - ReduceSizeTo((PRUint32)(CLEANUP_FACTOR*m_Size)); - } - else - { - RemoveAll(); - } -} - -char* FullFilename(const char* i_Filename) -{ - static int cacheFolderLength=0; - if (0 == g_FullFilename) - { - g_FullFilename = new char[MAX_FILENAME_LEN]; - *g_FullFilename = '\0'; - if (0 == g_FullFilename) - return 0; - } - PL_strcpy(g_FullFilename, nsCachePref::GetInstance()->DiskCacheFolder()); - if (0==cacheFolderLength) - cacheFolderLength = PL_strlen(nsCachePref::GetInstance()->DiskCacheFolder()); -#ifndef XP_MAC - if (g_FullFilename[cacheFolderLength-1]!=PR_GetDirectorySeparator()) - { - g_FullFilename[cacheFolderLength] = PR_GetDirectorySeparator(); - g_FullFilename[cacheFolderLength+1] = '\0'; - } -#endif - PL_strcat(g_FullFilename, i_Filename); - return g_FullFilename; -} - -nsCacheObject* LRUObject(DB* pDB) -{ - int status; - DBT key, data; - - nsCacheObject* pTempObj = new nsCacheObject(); - - nsCacheObject* pOldest=0; - if(!(status = (*pDB->seq)(pDB, &key, &data, R_FIRST))) - { - do - { - pTempObj->Info(data.data); - if (!pOldest || - (pOldest->LastAccessed() > pTempObj->LastAccessed())) - pOldest = pTempObj; - } - while(!(status = (*pDB->seq) (pDB, &key, &data, R_NEXT))); - } - return pOldest; -} - -#undef ENSURE_INIT diff --git a/mozilla/network/cache/nu/src/nsFFEntry.cpp b/mozilla/network/cache/nu/src/nsFFEntry.cpp deleted file mode 100644 index 5620246d4d2..00000000000 --- a/mozilla/network/cache/nu/src/nsFFEntry.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsFFEntry.h" -#include "prmem.h" -#include "prlog.h" - -nsFFEntry::nsFFEntry(): - m_ID(0), - m_pFirstObject(0), - m_pNextEntry(0), - m_Objects(0) -{ -} - -nsFFEntry::nsFFEntry(const PRUint32 i_ID): - m_ID(i_ID), - m_pFirstObject(0), - m_pNextEntry(0), - m_Objects(0) -{ -} - -nsFFEntry::nsFFEntry(const PRUint32 i_ID, const PRUint32 i_offset, const PRUint32 i_size): - m_ID(i_ID), - m_pFirstObject(new nsFFObject(i_ID, i_offset, i_size)), - m_pNextEntry(0), - m_Objects(1) -{ - //PR_ASSERT(i_offset > nsFlatFile::HeaderSize()); -} - -nsFFEntry::~nsFFEntry() -{ - PR_FREEIF(m_pFirstObject); - PR_FREEIF(m_pNextEntry); -} - - -/* -nsrefcnt nsFFEntry::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsFFEntry::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsFFEntry::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} - -nsFFEntry:: -*/ - -PRBool nsFFEntry::AddObject(const nsFFObject* i_object) -{ - PR_ASSERT(i_object); - if (!i_object) - return PR_FALSE; - if (!m_pFirstObject) - { - m_pFirstObject = (nsFFObject*) i_object; - m_Objects++; - } - return m_pFirstObject->Add(i_object); - return PR_FALSE; -} diff --git a/mozilla/network/cache/nu/src/nsFFObject.cpp b/mozilla/network/cache/nu/src/nsFFObject.cpp deleted file mode 100644 index fb7dc6f9d56..00000000000 --- a/mozilla/network/cache/nu/src/nsFFObject.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsFFObject.h" -#include "prlog.h" - -nsFFObject::nsFFObject(PRUint32 i_ID, PRUint32 i_Offset, PRUint32 i_Size): - m_ID(i_ID), - m_Offset(i_Offset), - m_Size(i_Size), - m_pNext(0) -{ -} - -nsFFObject::~nsFFObject() -{ -} - - -PRBool nsFFObject::Add(const nsFFObject* i_object) -{ - PR_ASSERT(i_object); - if (!i_object) - return PR_FALSE; - if (m_pNext) - return m_pNext->Add(i_object); - m_pNext = (nsFFObject*) i_object; - return PR_TRUE; -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/src/nsFileStream.cpp b/mozilla/network/cache/nu/src/nsFileStream.cpp deleted file mode 100644 index ab3db078d06..00000000000 --- a/mozilla/network/cache/nu/src/nsFileStream.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsFileStream.h" -#include "plstr.h" -#include "prlog.h" - -nsFileStream::nsFileStream(const char* i_Filename):m_pFile(0),m_pFilename(0) -{ - PR_ASSERT(i_Filename); - if (i_Filename) - { - m_pFilename = new char[PL_strlen(i_Filename)+1]; - PL_strcpy(m_pFilename, i_Filename); - Open(); - } -} - -nsFileStream::~nsFileStream() -{ - if (m_pFilename) - { - delete[] m_pFilename; - m_pFilename = 0; - } - if (m_pFile) - PR_Close(m_pFile); -} - -/* -nsrefcnt nsFileStream::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsFileStream::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsFileStream::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} -*/ - -PRBool nsFileStream::Open() -{ - if (m_pFile) - PR_Close(m_pFile); - PR_ASSERT(m_pFilename); - if (m_pFilename) - { - m_pFile = PR_Open( - m_pFilename, - PR_CREATE_FILE | PR_RDWR, - 600);// Read and write by owner only - - PR_ASSERT(m_pFile); - if (m_pFile) - return PR_TRUE; - } - return PR_FALSE; -} - -PRInt32 nsFileStream::Read(void* o_Buffer, PRUint32 i_Len) -{ - if (!m_pFile && !Open()) - return 0; - return PR_Read(m_pFile, o_Buffer, i_Len); -} - -void nsFileStream::Reset() -{ - Open(); -} - -PRInt32 nsFileStream::Write(const void* i_Buffer, PRUint32 i_Len) -{ - if (!m_pFile && !Open()) - return 0; - return PR_Write(m_pFile, i_Buffer, i_Len); -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/src/nsFlatFile.cpp b/mozilla/network/cache/nu/src/nsFlatFile.cpp deleted file mode 100644 index e831c6d4301..00000000000 --- a/mozilla/network/cache/nu/src/nsFlatFile.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsFlatFile.h" -#include "plstr.h" -#include "prmem.h" -#include "memory.h" - -static const PRUint32 kFLAT_FILE_VERSION = 1; -static const PRUint32 kMAGIC_NUMBER = 3739142906; // Facede de //TODO -static const char kFILL_CHAR = 'G'; - -nsFlatFile::nsFlatFile(const char* i_pFilename, const PRUint32 i_Size): - m_bIsValid(PR_FALSE), - m_pFD(0), - m_Size(i_Size), - m_HeaderSize(2*sizeof(PRUint32)), - m_pFilename(new char[PL_strlen(i_pFilename) + 1]) - -{ - PL_strcpy(m_pFilename, i_pFilename); - Init(); -} - -nsFlatFile::~nsFlatFile() -{ - delete[] m_pFilename; - if (m_pFD) - { - PR_Close(m_pFD); - m_pFD = 0; - } -} - -void nsFlatFile::Init(void) -{ - if (m_pFilename) - { - m_pFD = PR_Open(m_pFilename, PR_CREATE_FILE | PR_RDWR, 0600); - if (!m_pFD) - { - return; - } - PRFileInfo info; - // if the file is just being created then write magic number - // and flat file version, else verify - if (PR_SUCCESS == PR_GetOpenFileInfo(m_pFD, &info)) - { - PRInt32 status; - if (info.size > 0) - { - char* buf = new char[m_HeaderSize]; - //verify - status = PR_Read(m_pFD, buf, m_HeaderSize); - if (status > 0) - { - char* cur_ptr = buf; - PRUint32 test; - COPY_INT32(&test, cur_ptr); - if (test != kMAGIC_NUMBER) - { - PR_Close(m_pFD); - m_pFD = 0; - //PR_ASSERT(!"Bad flat file!"); - return; - } - cur_ptr += sizeof(PRUint32); - COPY_INT32(&test, cur_ptr); - if (test != kFLAT_FILE_VERSION) - { - PR_Close(m_pFD); - m_pFD = 0; - //PR_ASSERT(!"Bad version of flat file format!"); - return; - } - //Everything was as expected so - m_bIsValid = PR_TRUE; - } - delete[] buf; - } - else - { - //write out - char* buf = new char[m_HeaderSize]; - PRUint32 test = m_HeaderSize; - char* cur_ptr = buf; - COPY_INT32((void*) cur_ptr, &kMAGIC_NUMBER); - cur_ptr += sizeof(PRUint32); - COPY_INT32((void*) cur_ptr, &kFLAT_FILE_VERSION); - status = PR_Write(m_pFD, buf, m_HeaderSize); - delete[] buf; - - PRBool bFillChar = PR_FALSE; - - if (bFillChar) - { - buf = new char[kPAGE_SIZE]; - for (int i = 0; i< kPAGE_SIZE; ++i) - buf[i] = kFILL_CHAR; - int j = (int)((m_Size - m_HeaderSize) / kPAGE_SIZE); - int k; - for (k = j; k > 0; --k) - { - status = PR_Write(m_pFD, (void*) buf, kPAGE_SIZE); - } - delete[] buf; - int remaining = (m_Size-m_HeaderSize) % kPAGE_SIZE; - for (k = remaining; k>0; --k) - { - status = PR_Write(m_pFD, (void*) &kFILL_CHAR, 1); - } - } - } - } - } -} - -/* -nsrefcnt nsFlatFile::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsFlatFile::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsFlatFile::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} -*/ diff --git a/mozilla/network/cache/nu/src/nsHash.cpp b/mozilla/network/cache/nu/src/nsHash.cpp deleted file mode 100644 index a0764702878..00000000000 --- a/mozilla/network/cache/nu/src/nsHash.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "prmem.h" -#include "nsHash.h" - -// -// Key operations -// - -static PR_CALLBACK PLHashNumber _hashValue(const void *key) -{ - return ((const nsHashKey *) key)->HashValue(); -} - -static PR_CALLBACK PRIntn _hashKeyCompare(const void *key1, const void *key2) { - return ((const nsHashKey *) key1)->Equals((const nsHashKey *) key2); -} - -static PR_CALLBACK PRIntn _hashValueCompare(const void *value1, - const void *value2) { - // We're not going to make any assumptions about value equality - return 0; -} - -// -// Memory callbacks -// - -static PR_CALLBACK void *_hashAllocTable(void *pool, PRSize size) { - return PR_MALLOC(size); -} - -static PR_CALLBACK void _hashFreeTable(void *pool, void *item) { - PR_DELETE(item); -} - -static PR_CALLBACK PLHashEntry *_hashAllocEntry(void *pool, const void *key) { - return PR_NEW(PLHashEntry); -} - -static PR_CALLBACK void _hashFreeEntry(void *pool, PLHashEntry *entry, - PRUintn flag) { - if (flag == HT_FREE_ENTRY) { - delete (nsHashKey *) (entry->key); - PR_DELETE(entry); - } -} - -static PLHashAllocOps _hashAllocOps = { - _hashAllocTable, _hashFreeTable, - _hashAllocEntry, _hashFreeEntry -}; - -// -// Enumerator callback -// - -static PR_CALLBACK PRIntn _hashEnumerate(PLHashEntry *he, PRIntn i, void *arg) -{ - return ((nsHashEnumFunc) arg)((nsHashKey *) he->key, he->value) ? - HT_ENUMERATE_NEXT : - HT_ENUMERATE_STOP; -} - -// -// HashKey -// -nsHashKey::nsHashKey(void) -{ -} - -nsHashKey::~nsHashKey(void) -{ -} - -nsHash::nsHash(PRUint32 aInitSize) { - hashtable = PL_NewHashTable(aInitSize, - _hashValue, - _hashKeyCompare, - _hashValueCompare, - &_hashAllocOps, - NULL); -} - -nsHash::~nsHash() { - PL_HashTableDestroy(hashtable); -} - -void *nsHash::Put(nsHashKey *aKey, void *aData) { - void *res = NULL; - PLHashNumber hash = aKey->HashValue(); - PLHashEntry *he; - PLHashEntry **hep = PL_HashTableRawLookup(hashtable, hash, (void *) aKey); - - if ((he = *hep) != NULL) { - res = he->value; - he->value = aData; - } else { - PL_HashTableRawAdd(hashtable, hep, hash, - (void *) aKey->Clone(), aData); - } - - return res; -} - -void *nsHash::Get(nsHashKey *aKey) { - return PL_HashTableLookup(hashtable, (void *) aKey); -} - -void *nsHash::Remove(nsHashKey *aKey) { - PLHashNumber hash = aKey->HashValue(); - PLHashEntry *he; - PLHashEntry **hep = PL_HashTableRawLookup(hashtable, hash, (void *) aKey); - void *res = NULL; - - if ((he = *hep) != NULL) { - res = he->value; - PL_HashTableRawRemove(hashtable, hep, he); - } - - return res; -} - -void nsHash::Enumerate(nsHashEnumFunc aEnumFunc) { - PL_HashTableEnumerateEntries(hashtable, _hashEnumerate, aEnumFunc); -} diff --git a/mozilla/network/cache/nu/src/nsMemCacheObject.cpp b/mozilla/network/cache/nu/src/nsMemCacheObject.cpp deleted file mode 100644 index 6fd1b646c73..00000000000 --- a/mozilla/network/cache/nu/src/nsMemCacheObject.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * nsMemCacheObject - * - * Gagan Saksena 04/22/98 - * - */ -#include "prtypes.h" -#include "nsMemCacheObject.h" -#include "nsMemStream.h" - -nsMemCacheObject::~nsMemCacheObject() -{ - if (m_pNextObject) - { - delete m_pNextObject; - m_pNextObject = 0; - } - - if (m_pObject) - { - delete (nsMemStream*)m_pObject->Stream(); - delete m_pObject; - m_pObject = 0; - } -} diff --git a/mozilla/network/cache/nu/src/nsMemModule.cpp b/mozilla/network/cache/nu/src/nsMemModule.cpp deleted file mode 100644 index b84b3fabe9e..00000000000 --- a/mozilla/network/cache/nu/src/nsMemModule.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "prtypes.h" -#include "plstr.h" -#include "prlog.h" - -#include "nsMemModule.h" -#include "nsMemCacheObject.h" -#include "nsCacheManager.h" -#include "nsMemStream.h" - -/* - * nsMemModule - * - * Gagan Saksena 02/02/98 - * - */ - -//NS_DEFINE_IID(kMemModuleIID, NS_MEMMODULE_IID); - -nsMemModule::nsMemModule(const PRUint32 size): - m_pFirstObject(0), - nsCacheModule(size) -{ - SetSize(size); -} - -nsMemModule::~nsMemModule() -{ - if (m_pFirstObject) { - delete m_pFirstObject; - m_pFirstObject = 0; - } -} - -PRBool nsMemModule::AddObject(nsCacheObject* io_pObject) -{ - -#if 0 - if (io_pObject) - { - m_ht.Put(io_pObject->Address(), io_pObject); - } - return PR_FALSE; -#endif - - if (io_pObject) - { - MonitorLocker ml(this); - PR_ASSERT(io_pObject->Stream()); // A valid stream does exist for this - if (m_pFirstObject) - { - LastObject()->Next(new nsMemCacheObject(io_pObject)); - } - else - { - m_pFirstObject = new nsMemCacheObject(io_pObject); - } - m_Entries++; - - io_pObject->Module(nsCacheManager::MEM); - - return PR_TRUE; - } - return PR_FALSE; -} - -PRBool nsMemModule::Contains(const char* i_url) const -{ - MonitorLocker ml((nsMonitorable*)this); - - if (m_pFirstObject && i_url && *i_url) - { - nsMemCacheObject* pObj = m_pFirstObject; - do - { - if (0 == PL_strcasecmp(pObj->ThisObject()->Address(), i_url)) - return PR_TRUE; - pObj = pObj->Next(); - } - while (pObj); - } - return PR_FALSE; -} - -PRBool nsMemModule::Contains(nsCacheObject* i_pObject) const -{ - MonitorLocker ml((nsMonitorable*)this); - - if (i_pObject && *i_pObject->Address()) - { - return this->Contains(i_pObject->Address()); - } - return 0; -} - -void nsMemModule::GarbageCollect(void) -{ - MonitorLocker ml(this); - - if (m_Entries > 0) - { - nsEnumeration* pEnum = Enumeration(); - PRUint32 index = 0; - while (pEnum->HasMoreElements()) - { - nsCacheObject* pObj = (nsCacheObject*) pEnum->NextElement(); - if (pObj && pObj->IsExpired()) - { - PRBool status = Remove(index); - PR_ASSERT(status == PR_TRUE); - } - ++index; - } - } -} - -nsCacheObject* nsMemModule::GetObject(const PRUint32 i_index) const -{ - MonitorLocker ml((nsMonitorable*)this); - nsMemCacheObject* pNth = 0; - if (m_pFirstObject) - { - PRUint32 index = 0; - pNth = m_pFirstObject; - while (pNth->Next() && (index++ != i_index )) - { - pNth = pNth->Next(); - } - } - return pNth->ThisObject(); -} - -nsCacheObject* nsMemModule::GetObject(const char* i_url) const -{ - MonitorLocker ml((nsMonitorable*)this); - if (m_pFirstObject && i_url && *i_url) - { - nsMemCacheObject* pObj = m_pFirstObject; - do - { - if (0 == PL_strcasecmp(pObj->ThisObject()->Address(), i_url)) - return pObj->ThisObject(); - pObj = pObj->Next(); - } - while (pObj); - } - return 0; -} - -nsStream* nsMemModule::GetStreamFor(const nsCacheObject* i_pObject) -{ - MonitorLocker ml(this); - if (i_pObject) - { - if (Contains((nsCacheObject*)i_pObject)) - { - nsStream* pStream = i_pObject->Stream(); - if (pStream) - return pStream; - } - // Set up a new stream for this object - return new nsMemStream(); - } - return 0; -} - -nsMemCacheObject* nsMemModule::LastObject(void) const -{ - MonitorLocker ml((nsMonitorable*)this); - - nsMemCacheObject* pLast = 0; - if (m_pFirstObject) - { - pLast = m_pFirstObject; - while (pLast->Next()) - pLast = pLast->Next(); - } - return pLast; -} - -PRBool nsMemModule::ReduceSizeTo(const PRUint32 i_NewSize) -{ - //TODO - return PR_TRUE; -} - -PRBool nsMemModule::Remove(const char* i_url) -{ - //TODO - return PR_FALSE; -} - -PRBool nsMemModule::Remove(const PRUint32 i_index) -{ - //TODO - return PR_FALSE; -} - -/* -NS_IMETHOD nsMemModule::QueryInterface(const nsIID& aIID, void** aInstancePtr) -{ - -} -NS_IMETHOD_(nsrefcnt) nsMemModule::AddRef(void) -{ - -} - -NS_IMETHOD_(nsrefcnt) nsMemModule::Release(void) -{ - -} -*/ - -/* -PRUint32 nsMemModule::nsMemKey::HashValue() -{ - return 0; -} -PRBool nsMemModule::nsMemKey::Equals(nsHashKey *aKey) -{ - return PR_FALSE; -} - -nsHashKey* nsMemModule::nsMemKey::Clone() -{ - return new nsMemModule::nsMemKey(); -} - -nsMemModule::nsMemKey::neMemKey() -{ -} - - */ diff --git a/mozilla/network/cache/nu/src/nsMemStream.cpp b/mozilla/network/cache/nu/src/nsMemStream.cpp deleted file mode 100644 index 59e63aa8649..00000000000 --- a/mozilla/network/cache/nu/src/nsMemStream.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsMemStream.h" -#include "prmem.h" -#include "prlog.h" /* Assert */ - -#ifndef XP_MAC -#include "memory.h" -#else -#include "cstring" -#endif - -static const PRUint32 kPageSize = 1024;//4096; -nsMemStream::nsMemStream():m_AllocSize(0),m_Size(0),m_pStart(0),m_ReadOffset(0),m_WriteOffset(0) -{ -} - -nsMemStream::~nsMemStream() -{ - PR_FREEIF(m_pStart); -} -/* -nsrefcnt nsMemStream::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsMemStream::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsMemStream::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} -*/ - -PRInt32 nsMemStream::Read(void* o_Buffer, PRUint32 i_Len) -{ - if (m_Size > 0) - { - PR_ASSERT(m_pStart); //This has to be there if m_Size > 0 - - char* pCurrentRead = (char*) m_pStart + m_ReadOffset; - - unsigned int validLen = m_Size - m_ReadOffset; - - if (0 == validLen) - return 0; - - if (validLen > i_Len) - validLen = i_Len; - - memcpy(o_Buffer, pCurrentRead, validLen); - m_ReadOffset += validLen; - return validLen; - } - return 0; -} - -void nsMemStream::Reset() -{ - m_ReadOffset = 0; -} - -PRInt32 nsMemStream::Write(const void* i_Buffer, PRUint32 i_Len) -{ - if (!m_pStart) - { - m_pStart = PR_Calloc(1, kPageSize); - if (!m_pStart) - { - PR_Free(m_pStart); - return 0; - } - m_WriteOffset = 0; - m_AllocSize = kPageSize; - } - unsigned int validLen = m_AllocSize - m_Size; - while (validLen < i_Len) - { - //Alloc some more - m_pStart = PR_Realloc(m_pStart, m_AllocSize+kPageSize); - if (!m_pStart) - { - PR_Free(m_pStart); - m_AllocSize = 0; - m_WriteOffset = 0; - m_Size = 0; - return 0; - } - m_AllocSize += kPageSize; - validLen += kPageSize; - } - char* pCurrentWrite = (char*)m_pStart + m_WriteOffset; - memcpy(pCurrentWrite, i_Buffer, i_Len); - m_WriteOffset += i_Len; - m_Size += i_Len; - return i_Len; -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/src/nsMonitorable.cpp b/mozilla/network/cache/nu/src/nsMonitorable.cpp deleted file mode 100644 index 4def54b102e..00000000000 --- a/mozilla/network/cache/nu/src/nsMonitorable.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * This is the implementation of the nsMonitorable::MonitorLocker class. - * Although the inlines work ok elsewhere, IRIX chokes on these. Hence - * moving these to a cpp. - * -Gagan Saksena 09/15/98 - */ - -#include "nsMonitorable.h" - -nsMonitorable::MonitorLocker::MonitorLocker(nsMonitorable* i_pThis): - m_pMonitorable(i_pThis) -{ - if (m_pMonitorable) m_pMonitorable->Lock(); -} - -nsMonitorable::MonitorLocker::~MonitorLocker() -{ - if (m_pMonitorable) m_pMonitorable->Unlock(); -} diff --git a/mozilla/network/cache/nu/src/nsTOC.cpp b/mozilla/network/cache/nu/src/nsTOC.cpp deleted file mode 100644 index 65a495e16e1..00000000000 --- a/mozilla/network/cache/nu/src/nsTOC.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsTOC.h" -#include "plstr.h" -#include "memory.h" -#include "prlog.h" - -static const PRUint32 kTOC_FLAT_FILE_VERSION = 1; -static const PRUint32 kTOC_MAGIC_NUMBER = 19712809; -static const PRUint32 kTOC_HEADER_SIZE = 2* sizeof(PRUint32); - -//TODO change this to a memory mapped file! -nsTOC::nsTOC(const char* i_pFilename, nsFlatFile* i_pFlatFile): - m_pFilename( new char[PL_strlen(i_pFilename) + 1]), - m_pFD(0), - m_bIsValid(PR_FALSE), - m_pFlatFile(i_pFlatFile), - m_Entries(1) -{ - PL_strcpy(m_pFilename, i_pFilename); - Init(); -} - -nsTOC::~nsTOC() -{ - delete[] m_pFilename; - if (m_pFD) - { - PR_Close(m_pFD); - m_pFD = 0; - } -} - -/* -nsrefcnt nsTOC::AddRef(void) -{ - return ++m_RefCnt; -} -nsrefcnt nsTOC::Release(void) -{ - if (--m_RefCnt == 0) - { - delete this; - return 0; - } - return m_RefCnt; -} - -nsresult nsTOC::QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - return NS_OK; -} - -*/ - -void nsTOC::Init(void) -{ - if (m_pFilename) - { - m_pFD = PR_Open(m_pFilename, PR_CREATE_FILE | PR_RDWR, 0600); - if (!m_pFD) - { - return; - } - PRFileInfo info; - // if the file is just being created then write magic number - // and flat file version, else verify - if (PR_SUCCESS == PR_GetOpenFileInfo(m_pFD, &info)) - { - PRInt32 status; - if (info.size > 0) - { - char buf[kTOC_HEADER_SIZE]; - //verify - status = PR_Read(m_pFD, &buf, kTOC_HEADER_SIZE); - if (status > 0) - { - char* cur_ptr = &buf[0]; - PRUint32 test; - COPY_INT32(&test, cur_ptr); - if (test != kTOC_MAGIC_NUMBER) - { - PR_Close(m_pFD); - m_pFD = 0; - //PR_ASSERT(!"Bad TOC file!"); - return; - } - cur_ptr += sizeof(PRUint32); - COPY_INT32(&test, cur_ptr); - if (test != kTOC_FLAT_FILE_VERSION) - { - PR_Close(m_pFD); - m_pFD = 0; - //PR_ASSERT(!"Bad version of TOC file!"); - return; - } - - // Number of entries in the TOC - status = PR_Read(m_pFD, &buf, sizeof(PRUint32)); - if (status > 0) - { - cur_ptr = &buf[0]; - COPY_INT32(&m_Entries, cur_ptr); - } - //Read in the list of entries - nsFFEntry* pCurrent; - Serialize(pCurrent, PR_TRUE); - //There has got to be a free entry. - PR_ASSERT(pCurrent /*&& pCurrent->IsValid() TODO*/); - m_pContents = pCurrent; - PRUint32 count = 1; //Definitely one! - Serialize(pCurrent, PR_TRUE); - while (pCurrent) - { - count++; - m_pContents->AddEntry(pCurrent); - Serialize(pCurrent, PR_TRUE); - } - - PR_ASSERT(count == m_Entries); - - //Everything was as expected so - m_bIsValid = PR_TRUE; - } - } - else - { - //write out - char* buf = new char[kTOC_HEADER_SIZE]; - char* cur_ptr = buf; - COPY_INT32((void*) cur_ptr, &kTOC_MAGIC_NUMBER); - cur_ptr += sizeof(PRUint32); - COPY_INT32((void*) cur_ptr, &kTOC_FLAT_FILE_VERSION); - status = PR_Write(m_pFD, buf, kTOC_HEADER_SIZE); - - // Number of entries in the TOC - COPY_INT32((void*)buf, &m_Entries); - status = PR_Write(m_pFD, buf, sizeof(PRUint32)); - - delete[] buf; - - //Since the TOC is being created afresh, reset the flat file with everything marked as - //free. - m_pContents = new nsFFEntry( - 0, - m_pFlatFile->HeaderSize(), - m_pFlatFile->Size()-m_pFlatFile->HeaderSize()); - //Serialize the only entry- - Serialize(m_pContents); - - m_bIsValid = PR_TRUE; - } - } - } -} - -nsFFEntry* nsTOC::AddEntry(PRUint32 i_Size) -{ - if (i_Size > FreeEntry()->Size()) - { - //Garbage collect - } - nsFFEntry* pEntry = new nsFFEntry( - NextID(), - FreeEntry()->FirstObject()->Offset(), - i_Size); - - return pEntry; -} - -PRBool nsTOC::Serialize(nsFFEntry* io_Entry, PRBool bRead ) -{ - PR_ASSERT(m_pFD); - if (bRead) - { - io_Entry = new nsFFEntry(); - if (!io_Entry) - return PR_FALSE; - char* buf = new char[sizeof(PRUint32)]; - PRUint32 temp, objects, size; - //Read ID - PR_Read(m_pFD, buf, sizeof(PRUint32)); - COPY_INT32(&temp, buf); - io_Entry->ID(temp); - //Read number of objects - PR_Read(m_pFD, buf, sizeof(PRUint32)); - COPY_INT32(&objects, buf); - //Read objects - for (int i= objects; i>0; --i) - { - PR_Read(m_pFD, buf, sizeof(PRUint32)); - COPY_INT32(&temp, buf); - PR_Read(m_pFD, buf, sizeof(PRUint32)); - COPY_INT32(&size, buf); - io_Entry->AddObject(new nsFFObject(io_Entry->ID(), temp, size)); - } - delete[] buf; - PR_ASSERT(io_Entry->Objects() == objects); - if (io_Entry->Objects() != objects) - return PR_FALSE; - return PR_TRUE; - } - else - { - PR_ASSERT(io_Entry); - if (!io_Entry) - return PR_FALSE; - - //TODO speed this up by increasing the buffer size to write out - //more than one int at a time! - - char* buf = new char[sizeof(PRUint32)]; - PRUint32 temp; - //Write ID - temp = io_Entry->ID(); - COPY_INT32((void*) buf, &temp); - PR_Write(m_pFD, buf, sizeof(PRUint32)); - //Write number of Objects - temp = io_Entry->Objects(); - COPY_INT32((void*) buf, &temp); - PR_Write(m_pFD, buf, sizeof(PRUint32)); - //Write Objects - if (temp > 0) - { - nsFFObject* current = io_Entry->FirstObject(); - while (current) - { - PR_ASSERT(current->ID() == io_Entry->ID()); - //Offset - temp = current->Offset(); - COPY_INT32((void*) buf, &temp); - PR_Write(m_pFD, buf, sizeof(PRUint32)); - //size - temp = current->Size(); - COPY_INT32((void*) buf, &temp); - PR_Write(m_pFD, buf, sizeof(PRUint32)); - - current = current->Next(); - } - } - delete[] buf; - return PR_TRUE; - } - return PR_FALSE; -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/tests/Makefile.in b/mozilla/network/cache/nu/tests/Makefile.in deleted file mode 100644 index 47a327bbe0c..00000000000 --- a/mozilla/network/cache/nu/tests/Makefile.in +++ /dev/null @@ -1,32 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -DIRS = fftest - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/nu/tests/cb/CacheTreeView.cpp b/mozilla/network/cache/nu/tests/cb/CacheTreeView.cpp deleted file mode 100644 index 052f8bad5b4..00000000000 --- a/mozilla/network/cache/nu/tests/cb/CacheTreeView.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// CacheTreeView.cpp : implementation file -// - -#include "stdafx.h" -#include "cb.h" -#include "CacheTreeView.h" -#include "cbdoc.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CCacheTreeView - -IMPLEMENT_DYNCREATE(CCacheTreeView, CTreeView) - -CCacheTreeView::CCacheTreeView() -{ - m_pImgList = new CImageList(); -} - -CCacheTreeView::~CCacheTreeView() -{ - delete m_pImgList; -} - - -BEGIN_MESSAGE_MAP(CCacheTreeView, CTreeView) - //{{AFX_MSG_MAP(CCacheTreeView) - ON_WM_CREATE() - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -int CCacheTreeView::OnCreate(LPCREATESTRUCT lpCreateStruct) -{ - - lpCreateStruct->style = TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT; - if (CView::OnCreate(lpCreateStruct) == -1) - return -1; - - GetDocument()->m_pTreeView = this; - - // Create the Image List - m_pImgList->Create(IDB_CACHEICONS,16,0,RGB(255,0,255)); - m_pImgList->SetBkColor(GetSysColor(COLOR_WINDOW)); - - // Attach image list to Tree - GetTreeCtrl().SetImageList(m_pImgList, TVSIL_NORMAL); - GetTreeCtrl().SetIndent(10); - return 0; -} - -void CCacheTreeView::OnDraw(CDC* pDC) -{ - CDocument* pDoc = GetDocument(); - // TODO: add draw code here -} - - -#ifdef _DEBUG -void CCacheTreeView::AssertValid() const -{ - CTreeView::AssertValid(); -} - -void CCacheTreeView::Dump(CDumpContext& dc) const -{ - CTreeView::Dump(dc); -} - -CCbDoc* CCacheTreeView::GetDocument() -{ - ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCbDoc))); - return (CCbDoc*)m_pDocument; -} - -#endif //_DEBUG - -void CCacheTreeView::Populate() { - AssertValid(); - GetTreeCtrl().DeleteAllItems(); - - TV_INSERTSTRUCT insertStruct; - TV_ITEM itemStruct; - - insertStruct.hParent = TVI_ROOT; - insertStruct.hInsertAfter = TVI_FIRST; - insertStruct.item = itemStruct; - - HTREEITEM hti = GetTreeCtrl().InsertItem(&insertStruct); - GetTreeCtrl().SetItemText(hti, "Your Cache"); - - insertStruct.hParent = hti; - insertStruct.hInsertAfter = hti; - insertStruct.item = itemStruct; - - HTREEITEM htiDisk = GetTreeCtrl().InsertItem(&insertStruct); - GetTreeCtrl().SetItemText(htiDisk, "Disk"); - HTREEITEM htiMem = GetTreeCtrl().InsertItem(&insertStruct); - GetTreeCtrl().SetItemText(htiMem, "Memory"); -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/tests/cb/CacheTreeView.h b/mozilla/network/cache/nu/tests/cb/CacheTreeView.h deleted file mode 100644 index d1bcc0d147d..00000000000 --- a/mozilla/network/cache/nu/tests/cb/CacheTreeView.h +++ /dev/null @@ -1,54 +0,0 @@ -// CacheTreeView.h : header file -// -#ifndef _CacheTreeView_h_ -#define _CacheTreeView_h_ - -#include -class CImageList; -class CCbDoc; -class CCacheTreeView : public CTreeView -{ -protected: - CCacheTreeView(); // protected constructor used by dynamic creation - DECLARE_DYNCREATE(CCacheTreeView) - -// Attributes -public: - CCbDoc* GetDocument(); - void Populate(); -// Operations -public: - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CCacheTreeView) - protected: - virtual void OnDraw(CDC* pDC); // overridden to draw this view - //}}AFX_VIRTUAL - -protected: - virtual ~CCacheTreeView(); -#ifdef _DEBUG - virtual void AssertValid() const; - virtual void Dump(CDumpContext& dc) const; -#endif - - // Generated message map functions -protected: - //{{AFX_MSG(CCacheTreeView) - afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); - //}}AFX_MSG - - DECLARE_MESSAGE_MAP() - - CImageList* m_pImgList; -}; - -#ifndef _DEBUG // debug version in AnimalView.cpp -inline CCbDoc* CCacheTreeView::GetDocument() - { return (CCbDoc*)m_pDocument; } -#endif - -#endif - - diff --git a/mozilla/network/cache/nu/tests/cb/MainFrm.cpp b/mozilla/network/cache/nu/tests/cb/MainFrm.cpp deleted file mode 100644 index 8ebf1b12f5a..00000000000 --- a/mozilla/network/cache/nu/tests/cb/MainFrm.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// MainFrm.cpp : implementation of the CMainFrame class -// - -#include "stdafx.h" -#include "cb.h" - -#include "MainFrm.h" -#include "CacheTreeView.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CMainFrame - -IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) - -BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) - //{{AFX_MSG_MAP(CMainFrame) - ON_WM_CREATE() - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -static UINT indicators[] = -{ - ID_SEPARATOR, // status line indicator - ID_INDICATOR_CAPS, - ID_INDICATOR_NUM, - ID_INDICATOR_SCRL, -}; - -///////////////////////////////////////////////////////////////////////////// -// CMainFrame construction/destruction - -CMainFrame::CMainFrame() -{ -} - -CMainFrame::~CMainFrame() -{ -} - -int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) -{ - if (CFrameWnd::OnCreate(lpCreateStruct) == -1) - return -1; - - if (!m_wndToolBar.Create(this) || - !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) - { - TRACE0("Failed to create toolbar\n"); - return -1; // fail to create - } - - if (!m_wndStatusBar.Create(this) || - !m_wndStatusBar.SetIndicators(indicators, - sizeof(indicators)/sizeof(UINT))) - { - TRACE0("Failed to create status bar\n"); - return -1; // fail to create - } - - m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() | - CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); - - m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); - EnableDocking(CBRS_ALIGN_ANY); - DockControlBar(&m_wndToolBar); - return 0; -} - -BOOL CMainFrame::OnCreateClient( LPCREATESTRUCT /*lpcs*/, - CCreateContext* pContext) -{ - // create a splitter with 1 row, 2 columns - if (!m_wndSplitter.CreateStatic(this, 1, 2)) - { - TRACE0("Failed to CreateStaticSplitter\n"); - return FALSE; - } - - // add the first splitter pane - the default view in column 0 - if (!m_wndSplitter.CreateView(0, 0, - RUNTIME_CLASS(CCacheTreeView), CSize(250, 50), pContext)) - { - TRACE0("Failed to create first pane\n"); - return FALSE; - } - - // add the second splitter pane - an input view in column 1 - if (!m_wndSplitter.CreateView(0, 1, pContext->m_pNewViewClass, CSize(0, 0), pContext)) - { - TRACE0("Failed to create second pane\n"); - return FALSE; - } - - // activate the tree view - SetActiveView((CView*)m_wndSplitter.GetPane(0,1)); - return TRUE; - -} - -BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) -{ - return CFrameWnd::PreCreateWindow(cs); -} - -///////////////////////////////////////////////////////////////////////////// -// CMainFrame diagnostics - -#ifdef _DEBUG -void CMainFrame::AssertValid() const -{ - CFrameWnd::AssertValid(); -} - -void CMainFrame::Dump(CDumpContext& dc) const -{ - CFrameWnd::Dump(dc); -} - -#endif //_DEBUG - -///////////////////////////////////////////////////////////////////////////// -// CMainFrame message handlers diff --git a/mozilla/network/cache/nu/tests/cb/MainFrm.h b/mozilla/network/cache/nu/tests/cb/MainFrm.h deleted file mode 100644 index 73759dfd181..00000000000 --- a/mozilla/network/cache/nu/tests/cb/MainFrm.h +++ /dev/null @@ -1,48 +0,0 @@ -// MainFrm.h : interface of the CMainFrame class -// -///////////////////////////////////////////////////////////////////////////// - -class CMainFrame : public CFrameWnd -{ -protected: // create from serialization only - CMainFrame(); - DECLARE_DYNCREATE(CMainFrame) - -// Attributes -protected: - CSplitterWnd m_wndSplitter; -public: - - void Status(const char* mesg); -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CMainFrame) - public: - virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); - virtual BOOL PreCreateWindow(CREATESTRUCT& cs); - //}}AFX_VIRTUAL - -// Implementation -public: - virtual ~CMainFrame(); -#ifdef _DEBUG - virtual void AssertValid() const; - virtual void Dump(CDumpContext& dc) const; -#endif - -protected: // control bar embedded members - CStatusBar m_wndStatusBar; - CToolBar m_wndToolBar; - -// Generated message map functions -protected: - //{{AFX_MSG(CMainFrame) - afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -inline void CMainFrame::Status(const char* mesg) { - m_wndStatusBar.SetPaneText(0, mesg); -} -///////////////////////////////////////////////////////////////////////////// diff --git a/mozilla/network/cache/nu/tests/cb/StdAfx.cpp b/mozilla/network/cache/nu/tests/cb/StdAfx.cpp deleted file mode 100644 index 764d580cddf..00000000000 --- a/mozilla/network/cache/nu/tests/cb/StdAfx.cpp +++ /dev/null @@ -1,6 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// cb.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - diff --git a/mozilla/network/cache/nu/tests/cb/StdAfx.h b/mozilla/network/cache/nu/tests/cb/StdAfx.h deleted file mode 100644 index 12f69127c68..00000000000 --- a/mozilla/network/cache/nu/tests/cb/StdAfx.h +++ /dev/null @@ -1,16 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers - -#include // MFC core and standard components -#include // MFC extensions -#ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls -#endif // _AFX_NO_AFXCMN_SUPPORT - - - - diff --git a/mozilla/network/cache/nu/tests/cb/cb.cpp b/mozilla/network/cache/nu/tests/cb/cb.cpp deleted file mode 100644 index 13d0eeefd63..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cb.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// cb.cpp : Defines the class behaviors for the application. -// - -#include "stdafx.h" -#include "cb.h" - -#include "MainFrm.h" -#include "cbDoc.h" -#include "cbView.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CCbApp - -BEGIN_MESSAGE_MAP(CCbApp, CWinApp) - //{{AFX_MSG_MAP(CCbApp) - ON_COMMAND(ID_APP_ABOUT, OnAppAbout) - //}}AFX_MSG_MAP - // Standard file based document commands - ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) - ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) - // Standard print setup command - ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CCbApp construction - -CCbApp::CCbApp() -{ -} - -///////////////////////////////////////////////////////////////////////////// -// The one and only CCbApp object - -CCbApp theApp; - -///////////////////////////////////////////////////////////////////////////// -// CCbApp initialization - -BOOL CCbApp::InitInstance() -{ - // Standard initialization - -#ifdef _AFXDLL - Enable3dControls(); // Call this when using MFC in a shared DLL -#else - Enable3dControlsStatic(); // Call this when linking to MFC statically -#endif - - LoadStdProfileSettings(0); // Load standard INI file options (including MRU) - - // Register document templates - - CSingleDocTemplate* pDocTemplate; - pDocTemplate = new CSingleDocTemplate( - IDR_MAINFRAME, - RUNTIME_CLASS(CCbDoc), - RUNTIME_CLASS(CMainFrame), // main SDI frame window - RUNTIME_CLASS(CCbView)); - AddDocTemplate(pDocTemplate); - - // Enable DDE Execute open - EnableShellOpen(); - RegisterShellFileTypes(TRUE); - - // Parse command line for standard shell commands, DDE, file open - CCommandLineInfo cmdInfo; - ParseCommandLine(cmdInfo); - - // Dispatch commands specified on the command line - if (!ProcessShellCommand(cmdInfo)) - return FALSE; - - // Enable drag/drop open - m_pMainWnd->DragAcceptFiles(); - - return TRUE; -} - -///////////////////////////////////////////////////////////////////////////// -// CAboutDlg dialog used for App About - -class CAboutDlg : public CDialog -{ -public: - CAboutDlg(); - -// Dialog Data - //{{AFX_DATA(CAboutDlg) - enum { IDD = IDD_ABOUTBOX }; - //}}AFX_DATA - - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAboutDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - //{{AFX_MSG(CAboutDlg) - // No message handlers - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) -{ - //{{AFX_DATA_INIT(CAboutDlg) - //}}AFX_DATA_INIT -} - -void CAboutDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CAboutDlg) - //}}AFX_DATA_MAP -} - -BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) - //{{AFX_MSG_MAP(CAboutDlg) - // No message handlers - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -// App command to run the dialog -void CCbApp::OnAppAbout() -{ - CAboutDlg aboutDlg; - aboutDlg.DoModal(); -} - -///////////////////////////////////////////////////////////////////////////// -// CCbApp commands diff --git a/mozilla/network/cache/nu/tests/cb/cb.h b/mozilla/network/cache/nu/tests/cb/cb.h deleted file mode 100644 index 27b8f228a60..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cb.h +++ /dev/null @@ -1,36 +0,0 @@ -// cb.h : main header file for the CB application -// - -#ifndef __AFXWIN_H__ - #error include 'stdafx.h' before including this file for PCH -#endif - -#include "resource.h" // main symbols - -///////////////////////////////////////////////////////////////////////////// -// CCbApp: -// See cb.cpp for the implementation of this class -// - -class CCbApp : public CWinApp -{ -public: - CCbApp(); - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CCbApp) - public: - virtual BOOL InitInstance(); - //}}AFX_VIRTUAL - -// Implementation - - //{{AFX_MSG(CCbApp) - afx_msg void OnAppAbout(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - - -///////////////////////////////////////////////////////////////////////////// diff --git a/mozilla/network/cache/nu/tests/cb/cb.mak b/mozilla/network/cache/nu/tests/cb/cb.mak deleted file mode 100644 index 97010e76a31..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cb.mak +++ /dev/null @@ -1,526 +0,0 @@ -# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Application" 0x0101 - -!IF "$(CFG)" == "" -CFG=cb - Win32 Debug -!MESSAGE No configuration specified. Defaulting to cb - Win32 Debug. -!ENDIF - -!IF "$(CFG)" != "cb - Win32 Release" && "$(CFG)" != "cb - Win32 Debug" -!MESSAGE Invalid configuration "$(CFG)" specified. -!MESSAGE You can specify a configuration when running NMAKE on this makefile -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "cb.mak" CFG="cb - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "cb - Win32 Release" (based on "Win32 (x86) Application") -!MESSAGE "cb - Win32 Debug" (based on "Win32 (x86) Application") -!MESSAGE -!ERROR An invalid configuration is specified. -!ENDIF - -!IF "$(OS)" == "Windows_NT" -NULL= -!ELSE -NULL=nul -!ENDIF -################################################################################ -# Begin Project -# PROP Target_Last_Scanned "cb - Win32 Debug" -CPP=cl.exe -RSC=rc.exe -MTL=mktyplib.exe - -!IF "$(CFG)" == "cb - Win32 Release" - -# PROP BASE Use_MFC 6 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 6 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -OUTDIR=.\Release -INTDIR=.\Release - -ALL : "$(OUTDIR)\cb.exe" - -CLEAN : - -@erase "$(INTDIR)\CacheTreeView.obj" - -@erase "$(INTDIR)\cb.obj" - -@erase "$(INTDIR)\cb.pch" - -@erase "$(INTDIR)\cb.res" - -@erase "$(INTDIR)\cbDoc.obj" - -@erase "$(INTDIR)\cbView.obj" - -@erase "$(INTDIR)\MainFrm.obj" - -@erase "$(INTDIR)\StdAfx.obj" - -@erase "$(OUTDIR)\cb.exe" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c -# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\..\..\..\..\dist\public\cache" /I "..\..\..\..\..\dist\win32_d.obj\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c -CPP_PROJ=/nologo /MD /W3 /GX /O2 /I "..\..\..\..\..\dist\public\cache" /I\ - "..\..\..\..\..\dist\win32_d.obj\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS"\ - /D "_AFXDLL" /D "_MBCS" /Fp"$(INTDIR)/cb.pch" /Yu"stdafx.h" /Fo"$(INTDIR)/" /c -CPP_OBJS=.\Release/ -CPP_SBRS=.\. -# ADD BASE MTL /nologo /D "NDEBUG" /win32 -# ADD MTL /nologo /D "NDEBUG" /win32 -MTL_PROJ=/nologo /D "NDEBUG" /win32 -# ADD BASE RSC /l 0x409 /d "NDEBUG" /d "_AFXDLL" -# ADD RSC /l 0x409 /d "NDEBUG" /d "_AFXDLL" -RSC_PROJ=/l 0x409 /fo"$(INTDIR)/cb.res" /d "NDEBUG" /d "_AFXDLL" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -BSC32_FLAGS=/nologo /o"$(OUTDIR)/cb.bsc" -BSC32_SBRS= \ - -LINK32=link.exe -# ADD BASE LINK32 /nologo /subsystem:windows /machine:I386 -# ADD LINK32 /nologo /subsystem:windows /machine:I386 -LINK32_FLAGS=/nologo /subsystem:windows /incremental:no /pdb:"$(OUTDIR)/cb.pdb"\ - /machine:I386 /out:"$(OUTDIR)/cb.exe" -LINK32_OBJS= \ - "$(INTDIR)\CacheTreeView.obj" \ - "$(INTDIR)\cb.obj" \ - "$(INTDIR)\cb.res" \ - "$(INTDIR)\cbDoc.obj" \ - "$(INTDIR)\cbView.obj" \ - "$(INTDIR)\MainFrm.obj" \ - "$(INTDIR)\StdAfx.obj" - -"$(OUTDIR)\cb.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) - $(LINK32) @<< - $(LINK32_FLAGS) $(LINK32_OBJS) -<< - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - -# PROP BASE Use_MFC 6 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 6 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -OUTDIR=.\Debug -INTDIR=.\Debug - -ALL : "$(OUTDIR)\cb.exe" "$(OUTDIR)\cb.bsc" - -CLEAN : - -@erase "$(INTDIR)\CacheTreeView.obj" - -@erase "$(INTDIR)\CacheTreeView.sbr" - -@erase "$(INTDIR)\cb.obj" - -@erase "$(INTDIR)\cb.pch" - -@erase "$(INTDIR)\cb.res" - -@erase "$(INTDIR)\cb.sbr" - -@erase "$(INTDIR)\cbDoc.obj" - -@erase "$(INTDIR)\cbDoc.sbr" - -@erase "$(INTDIR)\cbView.obj" - -@erase "$(INTDIR)\cbView.sbr" - -@erase "$(INTDIR)\MainFrm.obj" - -@erase "$(INTDIR)\MainFrm.sbr" - -@erase "$(INTDIR)\StdAfx.obj" - -@erase "$(INTDIR)\StdAfx.sbr" - -@erase "$(INTDIR)\vc40.idb" - -@erase "$(INTDIR)\vc40.pdb" - -@erase "$(OUTDIR)\cb.bsc" - -@erase "$(OUTDIR)\cb.exe" - -@erase "$(OUTDIR)\cb.ilk" - -@erase "$(OUTDIR)\cb.pdb" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /Yu"stdafx.h" /c -# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\..\..\..\dist\public\cache" /I "..\..\..\..\..\dist\win32_d.obj\include" /I "..\..\..\..\..\dist\public\dbm" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_AFXDLL" /D "_MBCS" /FR /Yu"stdafx.h" /V"ERBOSE:lib" /c -CPP_PROJ=/nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\..\..\..\dist\public\cache"\ - /I "..\..\..\..\..\dist\win32_d.obj\include" /I\ - "..\..\..\..\..\dist\public\dbm" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D\ - "_AFXDLL" /D "_MBCS" /FR"$(INTDIR)/" /Fp"$(INTDIR)/cb.pch" /Yu"stdafx.h"\ - /Fo"$(INTDIR)/" /Fd"$(INTDIR)/" /V"ERBOSE:lib" /c -CPP_OBJS=.\Debug/ -CPP_SBRS=.\Debug/ -# ADD BASE MTL /nologo /D "_DEBUG" /win32 -# ADD MTL /nologo /D "_DEBUG" /win32 -MTL_PROJ=/nologo /D "_DEBUG" /win32 -# ADD BASE RSC /l 0x409 /d "_DEBUG" /d "_AFXDLL" -# ADD RSC /l 0x409 /d "_DEBUG" /d "_AFXDLL" -RSC_PROJ=/l 0x409 /fo"$(INTDIR)/cb.res" /d "_DEBUG" /d "_AFXDLL" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -BSC32_FLAGS=/nologo /o"$(OUTDIR)/cb.bsc" -BSC32_SBRS= \ - "$(INTDIR)\CacheTreeView.sbr" \ - "$(INTDIR)\cb.sbr" \ - "$(INTDIR)\cbDoc.sbr" \ - "$(INTDIR)\cbView.sbr" \ - "$(INTDIR)\MainFrm.sbr" \ - "$(INTDIR)\StdAfx.sbr" - -"$(OUTDIR)\cb.bsc" : "$(OUTDIR)" $(BSC32_SBRS) - $(BSC32) @<< - $(BSC32_FLAGS) $(BSC32_SBRS) -<< - -LINK32=link.exe -# ADD BASE LINK32 /nologo /subsystem:windows /debug /machine:I386 -# ADD LINK32 ..\..\..\..\..\dist\win32_d.obj\lib\nspr3.lib ..\..\..\..\..\dist\win32_d.obj\lib\plc3.lib ..\..\..\..\..\dist\win32_d.obj\lib\dbm32.lib ..\..\..\..\..\dist\win32_d.obj\lib\cachelib.lib /nologo /subsystem:windows /debug /machine:I386 -# SUBTRACT LINK32 /nodefaultlib -LINK32_FLAGS=..\..\..\..\..\dist\win32_d.obj\lib\nspr3.lib\ - ..\..\..\..\..\dist\win32_d.obj\lib\plc3.lib\ - ..\..\..\..\..\dist\win32_d.obj\lib\dbm32.lib\ - ..\..\..\..\..\dist\win32_d.obj\lib\cachelib.lib /nologo /subsystem:windows\ - /incremental:yes /pdb:"$(OUTDIR)/cb.pdb" /debug /machine:I386\ - /out:"$(OUTDIR)/cb.exe" -LINK32_OBJS= \ - "$(INTDIR)\CacheTreeView.obj" \ - "$(INTDIR)\cb.obj" \ - "$(INTDIR)\cb.res" \ - "$(INTDIR)\cbDoc.obj" \ - "$(INTDIR)\cbView.obj" \ - "$(INTDIR)\MainFrm.obj" \ - "$(INTDIR)\StdAfx.obj" - -"$(OUTDIR)\cb.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) - $(LINK32) @<< - $(LINK32_FLAGS) $(LINK32_OBJS) -<< - -!ENDIF - -.c{$(CPP_OBJS)}.obj: - $(CPP) $(CPP_PROJ) $< - -.cpp{$(CPP_OBJS)}.obj: - $(CPP) $(CPP_PROJ) $< - -.cxx{$(CPP_OBJS)}.obj: - $(CPP) $(CPP_PROJ) $< - -.c{$(CPP_SBRS)}.sbr: - $(CPP) $(CPP_PROJ) $< - -.cpp{$(CPP_SBRS)}.sbr: - $(CPP) $(CPP_PROJ) $< - -.cxx{$(CPP_SBRS)}.sbr: - $(CPP) $(CPP_PROJ) $< - -################################################################################ -# Begin Target - -# Name "cb - Win32 Release" -# Name "cb - Win32 Debug" - -!IF "$(CFG)" == "cb - Win32 Release" - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - -!ENDIF - -################################################################################ -# Begin Source File - -SOURCE=.\cb.cpp -DEP_CPP_CB_CP=\ - ".\cb.h"\ - ".\cbDoc.h"\ - ".\cbView.h"\ - ".\MainFrm.h"\ - ".\StdAfx.h"\ - - -!IF "$(CFG)" == "cb - Win32 Release" - - -"$(INTDIR)\cb.obj" : $(SOURCE) $(DEP_CPP_CB_CP) "$(INTDIR)" "$(INTDIR)\cb.pch" - - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - - -"$(INTDIR)\cb.obj" : $(SOURCE) $(DEP_CPP_CB_CP) "$(INTDIR)" "$(INTDIR)\cb.pch" - -"$(INTDIR)\cb.sbr" : $(SOURCE) $(DEP_CPP_CB_CP) "$(INTDIR)" "$(INTDIR)\cb.pch" - - -!ENDIF - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=.\StdAfx.cpp -DEP_CPP_STDAF=\ - ".\StdAfx.h"\ - - -!IF "$(CFG)" == "cb - Win32 Release" - -# ADD CPP /Yc"stdafx.h" - -BuildCmds= \ - $(CPP) /nologo /MD /W3 /GX /O2 /I "..\..\..\..\..\dist\public\cache" /I\ - "..\..\..\..\..\dist\win32_d.obj\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS"\ - /D "_AFXDLL" /D "_MBCS" /Fp"$(INTDIR)/cb.pch" /Yc"stdafx.h" /Fo"$(INTDIR)/" /c\ - $(SOURCE) \ - - -"$(INTDIR)\StdAfx.obj" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" - $(BuildCmds) - -"$(INTDIR)\cb.pch" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" - $(BuildCmds) - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - -# ADD CPP /Yc"stdafx.h" - -BuildCmds= \ - $(CPP) /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\..\..\..\dist\public\cache"\ - /I "..\..\..\..\..\dist\win32_d.obj\include" /I\ - "..\..\..\..\..\dist\public\dbm" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D\ - "_AFXDLL" /D "_MBCS" /FR"$(INTDIR)/" /Fp"$(INTDIR)/cb.pch" /Yc"stdafx.h"\ - /Fo"$(INTDIR)/" /Fd"$(INTDIR)/" /V"ERBOSE:lib" /c $(SOURCE) \ - - -"$(INTDIR)\StdAfx.obj" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" - $(BuildCmds) - -"$(INTDIR)\StdAfx.sbr" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" - $(BuildCmds) - -"$(INTDIR)\cb.pch" : $(SOURCE) $(DEP_CPP_STDAF) "$(INTDIR)" - $(BuildCmds) - -!ENDIF - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=.\MainFrm.cpp -DEP_CPP_MAINF=\ - ".\CacheTreeView.h"\ - ".\cb.h"\ - ".\MainFrm.h"\ - ".\StdAfx.h"\ - - -!IF "$(CFG)" == "cb - Win32 Release" - - -"$(INTDIR)\MainFrm.obj" : $(SOURCE) $(DEP_CPP_MAINF) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - - -"$(INTDIR)\MainFrm.obj" : $(SOURCE) $(DEP_CPP_MAINF) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - -"$(INTDIR)\MainFrm.sbr" : $(SOURCE) $(DEP_CPP_MAINF) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ENDIF - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=.\cbDoc.cpp -DEP_CPP_CBDOC=\ - ".\CacheTreeView.h"\ - ".\cb.h"\ - ".\cbDoc.h"\ - ".\StdAfx.h"\ - - -!IF "$(CFG)" == "cb - Win32 Release" - - -"$(INTDIR)\cbDoc.obj" : $(SOURCE) $(DEP_CPP_CBDOC) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - - -"$(INTDIR)\cbDoc.obj" : $(SOURCE) $(DEP_CPP_CBDOC) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - -"$(INTDIR)\cbDoc.sbr" : $(SOURCE) $(DEP_CPP_CBDOC) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ENDIF - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=.\cbView.cpp - -!IF "$(CFG)" == "cb - Win32 Release" - -DEP_CPP_CBVIE=\ - "..\..\..\..\..\dist\public\cache\nsBkgThread.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheBkgThd.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheManager.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheModule.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheObject.h"\ - "..\..\..\..\..\dist\public\cache\nsCachePref.h"\ - "..\..\..\..\..\dist\public\cache\nsDiskModule.h"\ - "..\..\..\..\..\dist\public\cache\nsEnumeration.h"\ - "..\..\..\..\..\dist\public\cache\nsIterator.h"\ - "..\..\..\..\..\dist\public\cache\nsMemCacheObject.h"\ - "..\..\..\..\..\dist\public\cache\nsMemModule.h"\ - "..\..\..\..\..\dist\public\cache\nsMemStream.h"\ - "..\..\..\..\..\dist\public\cache\nsMonitorable.h"\ - "..\..\..\..\..\dist\public\cache\nsStream.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinrval.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlog.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prmon.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prthread.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - ".\cb.h"\ - ".\cbDoc.h"\ - ".\cbView.h"\ - ".\MainFrm.h"\ - ".\nsTimeIt.h"\ - ".\StdAfx.h"\ - {$(INCLUDE)}"\sys\TYPES.H"\ - -NODEP_CPP_CBVIE=\ - "..\..\..\..\..\dist\public\cache\mcom_db.h"\ - "..\..\..\..\..\dist\public\cache\nsISupports.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\cbView.obj" : $(SOURCE) $(DEP_CPP_CBVIE) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - -DEP_CPP_CBVIE=\ - "..\..\..\..\..\dist\public\cache\nsBkgThread.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheBkgThd.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheManager.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheModule.h"\ - "..\..\..\..\..\dist\public\cache\nsCacheObject.h"\ - "..\..\..\..\..\dist\public\cache\nsCachePref.h"\ - "..\..\..\..\..\dist\public\cache\nsDiskModule.h"\ - "..\..\..\..\..\dist\public\cache\nsEnumeration.h"\ - "..\..\..\..\..\dist\public\cache\nsIterator.h"\ - "..\..\..\..\..\dist\public\cache\nsMemCacheObject.h"\ - "..\..\..\..\..\dist\public\cache\nsMemModule.h"\ - "..\..\..\..\..\dist\public\cache\nsMemStream.h"\ - "..\..\..\..\..\dist\public\cache\nsMonitorable.h"\ - "..\..\..\..\..\dist\public\cache\nsStream.h"\ - "..\..\..\..\..\dist\public\dbm\cdefs.h"\ - "..\..\..\..\..\dist\public\dbm\mcom_db.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinrval.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlog.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prmon.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prthread.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - ".\cb.h"\ - ".\cbDoc.h"\ - ".\cbView.h"\ - ".\MainFrm.h"\ - ".\nsTimeIt.h"\ - ".\StdAfx.h"\ - {$(INCLUDE)}"\sys\STAT.H"\ - {$(INCLUDE)}"\sys\TYPES.H"\ - -NODEP_CPP_CBVIE=\ - "..\..\..\..\..\dist\public\cache\nsISupports.h"\ - "..\..\..\..\..\dist\public\dbm\prmacos.h"\ - "..\..\..\..\..\dist\public\dbm\xp_mcom.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\cbView.obj" : $(SOURCE) $(DEP_CPP_CBVIE) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - -"$(INTDIR)\cbView.sbr" : $(SOURCE) $(DEP_CPP_CBVIE) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ENDIF - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=.\cb.rc -DEP_RSC_CB_RC=\ - ".\res\cacheico.bmp"\ - ".\res\cb.ico"\ - ".\res\cb.rc2"\ - ".\res\cbDoc.ico"\ - ".\res\Toolbar.bmp"\ - - -"$(INTDIR)\cb.res" : $(SOURCE) $(DEP_RSC_CB_RC) "$(INTDIR)" - $(RSC) $(RSC_PROJ) $(SOURCE) - - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=.\CacheTreeView.cpp -DEP_CPP_CACHE=\ - ".\CacheTreeView.h"\ - ".\cb.h"\ - ".\cbDoc.h"\ - ".\StdAfx.h"\ - - -!IF "$(CFG)" == "cb - Win32 Release" - - -"$(INTDIR)\CacheTreeView.obj" : $(SOURCE) $(DEP_CPP_CACHE) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ELSEIF "$(CFG)" == "cb - Win32 Debug" - - -"$(INTDIR)\CacheTreeView.obj" : $(SOURCE) $(DEP_CPP_CACHE) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - -"$(INTDIR)\CacheTreeView.sbr" : $(SOURCE) $(DEP_CPP_CACHE) "$(INTDIR)"\ - "$(INTDIR)\cb.pch" - - -!ENDIF - -# End Source File -# End Target -# End Project -################################################################################ diff --git a/mozilla/network/cache/nu/tests/cb/cb.mdp b/mozilla/network/cache/nu/tests/cb/cb.mdp deleted file mode 100644 index aa50bcc0180..00000000000 Binary files a/mozilla/network/cache/nu/tests/cb/cb.mdp and /dev/null differ diff --git a/mozilla/network/cache/nu/tests/cb/cb.rc b/mozilla/network/cache/nu/tests/cb/cb.rc deleted file mode 100644 index 8a5847f8973..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cb.rc +++ /dev/null @@ -1,387 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "#define _AFX_NO_OLE_RESOURCES\r\n" - "#define _AFX_NO_TRACKER_RESOURCES\r\n" - "#define _AFX_NO_PROPERTY_RESOURCES\r\n" - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "#ifdef _WIN32\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#endif\r\n" - "#include ""res\\cb.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#include ""afxres.rc"" // Standard components\r\n" - "#include ""afxprint.rc"" // printing/print preview resources\r\n" - "#endif\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON DISCARDABLE "res\\cb.ico" -IDR_DBTYPE ICON DISCARDABLE "res\\cbDoc.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDR_MAINFRAME BITMAP MOVEABLE PURE "res\\Toolbar.bmp" -IDB_CACHEICONS BITMAP DISCARDABLE "res\\cacheico.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Toolbar -// - -IDR_MAINFRAME TOOLBAR DISCARDABLE 16, 15 -BEGIN - BUTTON ID_FILE_NEW - BUTTON ID_FILE_OPEN - BUTTON ID_FILE_SAVE - SEPARATOR - BUTTON ID_EDIT_CUT - BUTTON ID_EDIT_COPY - BUTTON ID_EDIT_PASTE - SEPARATOR - BUTTON ID_FILE_PRINT - BUTTON ID_APP_ABOUT -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MAINFRAME MENU PRELOAD DISCARDABLE -BEGIN - POPUP "&File" - BEGIN - MENUITEM "&New\tCtrl+N", ID_FILE_NEW - MENUITEM "&Open...\tCtrl+O", ID_FILE_OPEN - MENUITEM "&Save\tCtrl+S", ID_FILE_SAVE - MENUITEM "Save &As...", ID_FILE_SAVE_AS - MENUITEM SEPARATOR - MENUITEM "&Print...\tCtrl+P", ID_FILE_PRINT - MENUITEM "Print Pre&view", ID_FILE_PRINT_PREVIEW - MENUITEM "P&rint Setup...", ID_FILE_PRINT_SETUP - MENUITEM SEPARATOR - MENUITEM "E&xit", ID_APP_EXIT - END - POPUP "&Edit" - BEGIN - MENUITEM "&Undo\tCtrl+Z", ID_EDIT_UNDO - MENUITEM SEPARATOR - MENUITEM "Cu&t\tCtrl+X", ID_EDIT_CUT - MENUITEM "&Copy\tCtrl+C", ID_EDIT_COPY - MENUITEM "&Paste\tCtrl+V", ID_EDIT_PASTE - END - POPUP "&View" - BEGIN - MENUITEM "&Toolbar", ID_VIEW_TOOLBAR - MENUITEM "&Status Bar", ID_VIEW_STATUS_BAR - MENUITEM "S&plit", ID_WINDOW_SPLIT - END - POPUP "&Help" - BEGIN - MENUITEM "&About cb...", ID_APP_ABOUT - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDR_MAINFRAME ACCELERATORS PRELOAD MOVEABLE PURE -BEGIN - "N", ID_FILE_NEW, VIRTKEY, CONTROL - "O", ID_FILE_OPEN, VIRTKEY, CONTROL - "S", ID_FILE_SAVE, VIRTKEY, CONTROL - "P", ID_FILE_PRINT, VIRTKEY, CONTROL - "Z", ID_EDIT_UNDO, VIRTKEY, CONTROL - "X", ID_EDIT_CUT, VIRTKEY, CONTROL - "C", ID_EDIT_COPY, VIRTKEY, CONTROL - "V", ID_EDIT_PASTE, VIRTKEY, CONTROL - VK_BACK, ID_EDIT_UNDO, VIRTKEY, ALT - VK_DELETE, ID_EDIT_CUT, VIRTKEY, SHIFT - VK_INSERT, ID_EDIT_COPY, VIRTKEY, CONTROL - VK_INSERT, ID_EDIT_PASTE, VIRTKEY, SHIFT - VK_F6, ID_NEXT_PANE, VIRTKEY - VK_F6, ID_PREV_PANE, VIRTKEY, SHIFT -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 217, 55 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "About cb" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 - LTEXT "cb Version 1.0",IDC_STATIC,40,10,119,8,SS_NOPREFIX - LTEXT "Copyright © 1998",IDC_STATIC,40,25,119,8 - DEFPUSHBUTTON "OK",IDOK,178,7,32,14,WS_GROUP -END - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "CB MFC Application\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "CB\0" - VALUE "LegalCopyright", "Copyright © 1998\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "CB.EXE\0" - VALUE "ProductName", "CB Application\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 48 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE PRELOAD DISCARDABLE -BEGIN - IDR_MAINFRAME "Cache Browser\n\nDB\n\n.DB\nCb.Document\nDB Document" -END - -STRINGTABLE PRELOAD DISCARDABLE -BEGIN - AFX_IDS_APP_TITLE "cb" - AFX_IDS_IDLEMESSAGE "Ready" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_INDICATOR_EXT "EXT" - ID_INDICATOR_CAPS "CAP" - ID_INDICATOR_NUM "NUM" - ID_INDICATOR_SCRL "SCRL" - ID_INDICATOR_OVR "OVR" - ID_INDICATOR_REC "REC" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_FILE_NEW "Create a new document\nNew" - ID_FILE_OPEN "Open an existing document\nOpen" - ID_FILE_CLOSE "Close the active document\nClose" - ID_FILE_SAVE "Save the active document\nSave" - ID_FILE_SAVE_AS "Save the active document with a new name\nSave As" - ID_FILE_PAGE_SETUP "Change the printing options\nPage Setup" - ID_FILE_PRINT_SETUP "Change the printer and printing options\nPrint Setup" - ID_FILE_PRINT "Print the active document\nPrint" - ID_FILE_PRINT_PREVIEW "Display full pages\nPrint Preview" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_APP_ABOUT "Display program information, version number and copyright\nAbout" - ID_APP_EXIT "Quit the application; prompts to save documents\nExit" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_FILE_MRU_FILE1 "Open this document" - ID_FILE_MRU_FILE2 "Open this document" - ID_FILE_MRU_FILE3 "Open this document" - ID_FILE_MRU_FILE4 "Open this document" - ID_FILE_MRU_FILE5 "Open this document" - ID_FILE_MRU_FILE6 "Open this document" - ID_FILE_MRU_FILE7 "Open this document" - ID_FILE_MRU_FILE8 "Open this document" - ID_FILE_MRU_FILE9 "Open this document" - ID_FILE_MRU_FILE10 "Open this document" - ID_FILE_MRU_FILE11 "Open this document" - ID_FILE_MRU_FILE12 "Open this document" - ID_FILE_MRU_FILE13 "Open this document" - ID_FILE_MRU_FILE14 "Open this document" - ID_FILE_MRU_FILE15 "Open this document" - ID_FILE_MRU_FILE16 "Open this document" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_NEXT_PANE "Switch to the next window pane\nNext Pane" - ID_PREV_PANE "Switch back to the previous window pane\nPrevious Pane" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_WINDOW_SPLIT "Split the active window into panes\nSplit" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_EDIT_CLEAR "Erase the selection\nErase" - ID_EDIT_CLEAR_ALL "Erase everything\nErase All" - ID_EDIT_COPY "Copy the selection and put it on the Clipboard\nCopy" - ID_EDIT_CUT "Cut the selection and put it on the Clipboard\nCut" - ID_EDIT_FIND "Find the specified text\nFind" - ID_EDIT_PASTE "Insert Clipboard contents\nPaste" - ID_EDIT_REPEAT "Repeat the last action\nRepeat" - ID_EDIT_REPLACE "Replace specific text with different text\nReplace" - ID_EDIT_SELECT_ALL "Select the entire document\nSelect All" - ID_EDIT_UNDO "Undo the last action\nUndo" - ID_EDIT_REDO "Redo the previously undone action\nRedo" -END - -STRINGTABLE DISCARDABLE -BEGIN - ID_VIEW_TOOLBAR "Show or hide the toolbar\nToggle ToolBar" - ID_VIEW_STATUS_BAR "Show or hide the status bar\nToggle StatusBar" -END - -STRINGTABLE DISCARDABLE -BEGIN - AFX_IDS_SCSIZE "Change the window size" - AFX_IDS_SCMOVE "Change the window position" - AFX_IDS_SCMINIMIZE "Reduce the window to an icon" - AFX_IDS_SCMAXIMIZE "Enlarge the window to full size" - AFX_IDS_SCNEXTWINDOW "Switch to the next document window" - AFX_IDS_SCPREVWINDOW "Switch to the previous document window" - AFX_IDS_SCCLOSE "Close the active window and prompts to save the documents" -END - -STRINGTABLE DISCARDABLE -BEGIN - AFX_IDS_SCRESTORE "Restore the window to normal size" - AFX_IDS_SCTASKLIST "Activate Task List" -END - -STRINGTABLE DISCARDABLE -BEGIN - AFX_IDS_PREVIEW_CLOSE "Close print preview mode\nCancel Preview" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#define _AFX_NO_OLE_RESOURCES -#define _AFX_NO_TRACKER_RESOURCES -#define _AFX_NO_PROPERTY_RESOURCES - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE 9, 1 -#pragma code_page(1252) -#endif -#include "res\cb.rc2" // non-Microsoft Visual C++ edited resources -#include "afxres.rc" // Standard components -#include "afxprint.rc" // printing/print preview resources -#endif -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/mozilla/network/cache/nu/tests/cb/cbDoc.cpp b/mozilla/network/cache/nu/tests/cb/cbDoc.cpp deleted file mode 100644 index 0d7ed7e3fb8..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cbDoc.cpp +++ /dev/null @@ -1,75 +0,0 @@ -// cbDoc.cpp : implementation of the CCbDoc class -// - -#include "stdafx.h" -#include "cb.h" - -#include "cbDoc.h" -#include "CacheTreeView.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CCbDoc - -IMPLEMENT_DYNCREATE(CCbDoc, CDocument) - -BEGIN_MESSAGE_MAP(CCbDoc, CDocument) - //{{AFX_MSG_MAP(CCbDoc) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CCbDoc construction/destruction - -CCbDoc::CCbDoc() -{ -} - -CCbDoc::~CCbDoc() -{ -} - -BOOL CCbDoc::OnNewDocument() -{ - if (!CDocument::OnNewDocument()) - return FALSE; - if (m_pTreeView) - m_pTreeView->Populate(); - return TRUE; -} - -///////////////////////////////////////////////////////////////////////////// -// CCbDoc serialization - -void CCbDoc::Serialize(CArchive& ar) -{ - if (ar.IsStoring()) - { - } - else - { - } -} - -///////////////////////////////////////////////////////////////////////////// -// CCbDoc diagnostics - -#ifdef _DEBUG -void CCbDoc::AssertValid() const -{ - CDocument::AssertValid(); -} - -void CCbDoc::Dump(CDumpContext& dc) const -{ - CDocument::Dump(dc); -} -#endif //_DEBUG - -///////////////////////////////////////////////////////////////////////////// -// CCbDoc commands diff --git a/mozilla/network/cache/nu/tests/cb/cbDoc.h b/mozilla/network/cache/nu/tests/cb/cbDoc.h deleted file mode 100644 index c995570a62b..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cbDoc.h +++ /dev/null @@ -1,43 +0,0 @@ -// cbDoc.h : interface of the CCbDoc class -// -///////////////////////////////////////////////////////////////////////////// -class CCacheTreeView; -class CCbDoc : public CDocument -{ -protected: // create from serialization only - CCbDoc(); - DECLARE_DYNCREATE(CCbDoc) - -// Attributes -public: - CCacheTreeView* m_pTreeView; -// Operations -public: - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CCbDoc) - public: - virtual BOOL OnNewDocument(); - virtual void Serialize(CArchive& ar); - //}}AFX_VIRTUAL - -// Implementation -public: - virtual ~CCbDoc(); -#ifdef _DEBUG - virtual void AssertValid() const; - virtual void Dump(CDumpContext& dc) const; -#endif - -protected: - -// Generated message map functions -protected: - //{{AFX_MSG(CCbDoc) - //}}AFX_MSG - DECLARE_MESSAGE_MAP() - -}; - -///////////////////////////////////////////////////////////////////////////// diff --git a/mozilla/network/cache/nu/tests/cb/cbView.cpp b/mozilla/network/cache/nu/tests/cb/cbView.cpp deleted file mode 100644 index 7211cd5bc79..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cbView.cpp +++ /dev/null @@ -1,197 +0,0 @@ -// cbView.cpp : implementation of the CCbView class -// - -#include "stdafx.h" -#include "cb.h" - -#include "cbDoc.h" -#include "cbView.h" -#include -#include "MainFrm.h" - -#include "nsCacheManager.h" -#include "nsMemModule.h" -#include "nsDiskModule.h" -#include "nsCacheObject.h" -#include "nsTimeIt.h" -#include "nsCacheBkgThd.h" -#include "nsMemStream.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -#define ID_TREECTRL (WM_USER +1) - -#define STATUS(s) ((CMainFrame*)GetParentFrame())->Status(s) - -IMPLEMENT_DYNCREATE(CCbView, CView) - -BEGIN_MESSAGE_MAP(CCbView, CView) - //{{AFX_MSG_MAP(CCbView) - //}}AFX_MSG_MAP - // Standard printing commands - ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) - ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) - ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CCbView construction/destruction - -CCbView::CCbView() -{ -} - -CCbView::~CCbView() -{ -} - -BOOL CCbView::PreCreateWindow(CREATESTRUCT& cs) -{ - return CView::PreCreateWindow(cs); -} - -///////////////////////////////////////////////////////////////////////////// -// CCbView drawing - -void CCbView::OnDraw(CDC* pDC) -{ - CRect rect; - GetClientRect(&rect); - - pDC->SetBkColor(RGB(192,192,192)); - pDC->FillSolidRect(rect, RGB(192,192,192)); - - rect.DeflateRect(10,10); - pDC->DrawText(m_Mesg.GetBuffer(m_Mesg.GetLength()), -1, rect, DT_WORDBREAK | DT_EXPANDTABS); -} - -///////////////////////////////////////////////////////////////////////////// -// CCbView printing - -BOOL CCbView::OnPreparePrinting(CPrintInfo* pInfo) -{ - // default preparation - return DoPreparePrinting(pInfo); -} - -void CCbView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) -{ -} - -void CCbView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) -{ -} - -///////////////////////////////////////////////////////////////////////////// -// CCbView diagnostics - -#ifdef _DEBUG -void CCbView::AssertValid() const -{ - CView::AssertValid(); -} - -void CCbView::Dump(CDumpContext& dc) const -{ - CView::Dump(dc); -} - -CCbDoc* CCbView::GetDocument() // non-debug version is inline -{ - ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCbDoc))); - return (CCbDoc*)m_pDocument; -} -#endif //_DEBUG - -///////////////////////////////////////////////////////////////////////////// -// CCbView message handlers - -void CCbView::OnInitialUpdate() -{ - //STATUS("Loading lib..."); - - nsCacheManager* pCM = nsCacheManager::GetInstance(); - nsMemModule* pMM = pCM->GetMemModule(); - nsDiskModule* pDM = new nsDiskModule(); - pCM->AddModule(pDM); - - nsCacheObject* pCO = new nsCacheObject("http://www.netscape.com/"); - pCO->Etag("Etag-testing"); - pCO->Size(2250); - pCO->LastModified(time(0)); - pDM->AddObject(pCO); - - /* -// if (!pDM->Contains("http://www.netscape.com/")) -// pDM->AddObject(pCO); -// else - { - nsCacheObject* pTemp = new nsCacheObject("http://www.netscape.com/"); - if (pDM->Contains(pTemp)) - { - m_Mesg += pTemp->Trace(); - } - } - int j = 1000; - char tmpBuff[10]; - while (j--) - { - pCO = new nsCacheObject(itoa(j,tmpBuff,10)); - VERIFY(pDM->AddObject(pCO)); - } - - m_Mesg += itoa(pDM->Entries(), tmpBuff, 10); - m_Mesg += " nsCacheObject(s) added.\n"; - - char* traceBuff =(char*) pCM->Trace(); - m_Mesg += "-----------------\n"; - m_Mesg += traceBuff; - delete[] traceBuff; - traceBuff = (char*) pMM->Trace(); - m_Mesg += traceBuff; - delete[] traceBuff; - - m_Mesg += "-----------------\n"; - -*/ - char buffer[10]; - m_Mesg += "Worst case time= "; - m_Mesg += itoa(pCM->WorstCaseTime(), buffer, 10); - m_Mesg += " microsec.\n"; - m_Mesg += "Worst case time= "; - m_Mesg += itoa(pCM->WorstCaseTime(), buffer, 10); - m_Mesg += " microsec.\n"; - - PRUint32 t; - /* Test reading and writing to memory streams */ - nsMemStream* ms = new nsMemStream(); - - t = ms->Write("Hello ", 6); - t = ms->Write("World", 5); - - char tempBuff[15]; - - t = ms->Read(&tempBuff, 15); - t = ms->Read(&tempBuff, 6); - - delete ms; - /* Time the lookup time */ - { - nsTimeIt tmp(t); - if (pCM->Contains("999")) - m_Mesg += "!"; - } - m_Mesg += "-----------------\n"; - m_Mesg += "An item found in "; - m_Mesg += itoa(t, buffer, 10); - m_Mesg += " microsec.\n"; - - CView::OnInitialUpdate(); -} - - - diff --git a/mozilla/network/cache/nu/tests/cb/cbView.h b/mozilla/network/cache/nu/tests/cb/cbView.h deleted file mode 100644 index 7de4738ce4e..00000000000 --- a/mozilla/network/cache/nu/tests/cb/cbView.h +++ /dev/null @@ -1,54 +0,0 @@ -// cbView.h : interface of the CCbView class -// -///////////////////////////////////////////////////////////////////////////// -class CCbView : public CView -{ -protected: // create from serialization only - CCbView(); - DECLARE_DYNCREATE(CCbView) - -// Attributes -public: - CCbDoc* GetDocument(); - -// Operations -public: - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CCbView) - public: - virtual void OnDraw(CDC* pDC); // overridden to draw this view - virtual BOOL PreCreateWindow(CREATESTRUCT& cs); - virtual void OnInitialUpdate(); - protected: - virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); - virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); - virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); - //}}AFX_VIRTUAL - -// Implementation -public: - virtual ~CCbView(); -#ifdef _DEBUG - virtual void AssertValid() const; - virtual void Dump(CDumpContext& dc) const; -#endif - -protected: - -// Generated message map functions -protected: - //{{AFX_MSG(CCbView) - //}}AFX_MSG - DECLARE_MESSAGE_MAP() - - CString m_Mesg; -}; - -#ifndef _DEBUG // debug version in cbView.cpp -inline CCbDoc* CCbView::GetDocument() - { return (CCbDoc*)m_pDocument; } -#endif - -///////////////////////////////////////////////////////////////////////////// diff --git a/mozilla/network/cache/nu/tests/cb/nsTimeIt.h b/mozilla/network/cache/nu/tests/cb/nsTimeIt.h deleted file mode 100644 index becbc23b90e..00000000000 --- a/mozilla/network/cache/nu/tests/cb/nsTimeIt.h +++ /dev/null @@ -1,26 +0,0 @@ -/* TODO put NPL here */ -/* A class to time excursion events */ -/* declare an object of this class within the scope to be timed. */ -#include -#include - -class nsTimeIt -{ -public: - nsTimeIt(PRUint32& tmp); - ~nsTimeIt(); -private: - PRIntervalTime t; - PRUint32& dest; -}; - -inline -nsTimeIt::nsTimeIt(PRUint32& tmp):t(PR_IntervalNow()), dest(tmp) -{ -} - -inline -nsTimeIt::~nsTimeIt() -{ - dest = PR_IntervalToMicroseconds(PR_IntervalNow()-t); -} diff --git a/mozilla/network/cache/nu/tests/cb/res/Toolbar.bmp b/mozilla/network/cache/nu/tests/cb/res/Toolbar.bmp deleted file mode 100644 index d501723c1ce..00000000000 Binary files a/mozilla/network/cache/nu/tests/cb/res/Toolbar.bmp and /dev/null differ diff --git a/mozilla/network/cache/nu/tests/cb/res/cacheico.bmp b/mozilla/network/cache/nu/tests/cb/res/cacheico.bmp deleted file mode 100644 index bdb64e5c0cb..00000000000 Binary files a/mozilla/network/cache/nu/tests/cb/res/cacheico.bmp and /dev/null differ diff --git a/mozilla/network/cache/nu/tests/cb/res/cb.ico b/mozilla/network/cache/nu/tests/cb/res/cb.ico deleted file mode 100644 index 7eef0bcbe65..00000000000 Binary files a/mozilla/network/cache/nu/tests/cb/res/cb.ico and /dev/null differ diff --git a/mozilla/network/cache/nu/tests/cb/res/cb.rc2 b/mozilla/network/cache/nu/tests/cb/res/cb.rc2 deleted file mode 100644 index 74ccd4cfeff..00000000000 --- a/mozilla/network/cache/nu/tests/cb/res/cb.rc2 +++ /dev/null @@ -1,13 +0,0 @@ -// -// CB.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// diff --git a/mozilla/network/cache/nu/tests/cb/res/cbDoc.ico b/mozilla/network/cache/nu/tests/cb/res/cbDoc.ico deleted file mode 100644 index 2a1f1ae6ef1..00000000000 Binary files a/mozilla/network/cache/nu/tests/cb/res/cbDoc.ico and /dev/null differ diff --git a/mozilla/network/cache/nu/tests/cb/resource.h b/mozilla/network/cache/nu/tests/cb/resource.h deleted file mode 100644 index eeb206e7ff8..00000000000 --- a/mozilla/network/cache/nu/tests/cb/resource.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by cb.rc -// -#define IDD_ABOUTBOX 100 -#define IDR_MAINFRAME 128 -#define IDR_DBTYPE 129 -#define IDB_CACHEICONS 130 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_3D_CONTROLS 1 -#define _APS_NEXT_RESOURCE_VALUE 131 -#define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/mozilla/network/cache/nu/tests/fftest/FlatFileTest.cpp b/mozilla/network/cache/nu/tests/fftest/FlatFileTest.cpp deleted file mode 100644 index 646cf12c502..00000000000 --- a/mozilla/network/cache/nu/tests/fftest/FlatFileTest.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include -#include -#include -#include "nsFlatFile.h" -#include "nsTOC.h" - -int main() -{ - PRFileDesc* pfd = PR_GetSpecialFD(PR_StandardOutput); - - nsFlatFile tf("CACHE.DAT"); - nsTOC toc("Cache.TOC", &tf); - - if (tf.IsValid() && toc.IsValid()) - { - PR_Write(pfd, tf.Filename(), PL_strlen(tf.Filename())); - PR_Write(pfd, " ", 2); - PR_Write(pfd, toc.Filename(), PL_strlen(toc.Filename())); - - } - - - return 1; -} \ No newline at end of file diff --git a/mozilla/network/cache/nu/tests/fftest/Makefile.in b/mozilla/network/cache/nu/tests/fftest/Makefile.in deleted file mode 100644 index 2d43923f775..00000000000 --- a/mozilla/network/cache/nu/tests/fftest/Makefile.in +++ /dev/null @@ -1,64 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -PROGRAM = FlatFile - -REQUIRES = cache - -CPPSRCS = FlatFileTest.cpp - -LOCAL_INCLUDES = -I../../include - -LIBS = \ - -lcache \ - -lmozdbm \ - -lnetlib \ - -lnetcache \ - -lmimetype \ - -lremoturl \ - -lsockstuburl \ - -lhttpurl \ - -lfileurl \ - -lftpurl \ - -lgophurl \ - -lpwcac \ - -labouturl \ - -lnetwork \ - -lnetcnvts \ - $(TK_LIBS) \ - -lpref \ - -lmozjs \ - -lsecfree \ - -lxpcom \ - -lxp \ - $(ZLIB_LIBS) \ - $(NSPR_LIBS) \ - $(NULL) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cache/nu/tests/fftest/fftest.mak b/mozilla/network/cache/nu/tests/fftest/fftest.mak deleted file mode 100644 index d901894fbe9..00000000000 --- a/mozilla/network/cache/nu/tests/fftest/fftest.mak +++ /dev/null @@ -1,329 +0,0 @@ -# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -!IF "$(CFG)" == "" -CFG=fftest - Win32 Debug -!MESSAGE No configuration specified. Defaulting to fftest - Win32 Debug. -!ENDIF - -!IF "$(CFG)" != "fftest - Win32 Release" && "$(CFG)" != "fftest - Win32 Debug" -!MESSAGE Invalid configuration "$(CFG)" specified. -!MESSAGE You can specify a configuration when running NMAKE on this makefile -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "fftest.mak" CFG="fftest - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "fftest - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "fftest - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE -!ERROR An invalid configuration is specified. -!ENDIF - -!IF "$(OS)" == "Windows_NT" -NULL= -!ELSE -NULL=nul -!ENDIF -################################################################################ -# Begin Project -# PROP Target_Last_Scanned "fftest - Win32 Debug" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "fftest - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -OUTDIR=.\Release -INTDIR=.\Release - -ALL : "$(OUTDIR)\fftest.exe" - -CLEAN : - -@erase "$(INTDIR)\FlatFileTest.obj" - -@erase "$(INTDIR)\nsFFEntry.obj" - -@erase "$(INTDIR)\nsFFObject.obj" - -@erase "$(INTDIR)\nsFlatFile.obj" - -@erase "$(INTDIR)\nsTOC.obj" - -@erase "$(OUTDIR)\fftest.exe" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c -# ADD CPP /nologo /W4 /GX /O2 /I "..\..\..\..\..\dist\win32_d.obj\include" /I "..\..\include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c -CPP_PROJ=/nologo /ML /W4 /GX /O2 /I "..\..\..\..\..\dist\win32_d.obj\include"\ - /I "..\..\include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE"\ - /Fp"$(INTDIR)/fftest.pch" /YX /Fo"$(INTDIR)/" /c -CPP_OBJS=.\Release/ -CPP_SBRS=.\. -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -BSC32_FLAGS=/nologo /o"$(OUTDIR)/fftest.bsc" -BSC32_SBRS= \ - -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 ..\..\..\..\..\dist\win32_d.obj\lib\nspr3.lib ..\..\..\..\..\dist\win32_d.obj\lib\plc3.lib /nologo /subsystem:console /machine:I386 -LINK32_FLAGS=..\..\..\..\..\dist\win32_d.obj\lib\nspr3.lib\ - ..\..\..\..\..\dist\win32_d.obj\lib\plc3.lib /nologo /subsystem:console\ - /incremental:no /pdb:"$(OUTDIR)/fftest.pdb" /machine:I386\ - /out:"$(OUTDIR)/fftest.exe" -LINK32_OBJS= \ - "$(INTDIR)\FlatFileTest.obj" \ - "$(INTDIR)\nsFFEntry.obj" \ - "$(INTDIR)\nsFFObject.obj" \ - "$(INTDIR)\nsFlatFile.obj" \ - "$(INTDIR)\nsTOC.obj" - -"$(OUTDIR)\fftest.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) - $(LINK32) @<< - $(LINK32_FLAGS) $(LINK32_OBJS) -<< - -!ELSEIF "$(CFG)" == "fftest - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -OUTDIR=.\Debug -INTDIR=.\Debug - -ALL : "$(OUTDIR)\fftest.exe" - -CLEAN : - -@erase "$(INTDIR)\FlatFileTest.obj" - -@erase "$(INTDIR)\nsFFEntry.obj" - -@erase "$(INTDIR)\nsFFObject.obj" - -@erase "$(INTDIR)\nsFlatFile.obj" - -@erase "$(INTDIR)\nsTOC.obj" - -@erase "$(INTDIR)\vc40.idb" - -@erase "$(INTDIR)\vc40.pdb" - -@erase "$(OUTDIR)\fftest.exe" - -@erase "$(OUTDIR)\fftest.ilk" - -@erase "$(OUTDIR)\fftest.pdb" - -"$(OUTDIR)" : - if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" - -# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /YX /c -# ADD CPP /nologo /W4 /Gm /GX /Zi /Od /I "..\..\..\..\..\dist\win32_d.obj\include" /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /YX /c -CPP_PROJ=/nologo /MLd /W4 /Gm /GX /Zi /Od /I\ - "..\..\..\..\..\dist\win32_d.obj\include" /I "..\..\include" /D "WIN32" /D\ - "_DEBUG" /D "_CONSOLE" /Fp"$(INTDIR)/fftest.pch" /YX /Fo"$(INTDIR)/"\ - /Fd"$(INTDIR)/" /c -CPP_OBJS=.\Debug/ -CPP_SBRS=.\. -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -BSC32_FLAGS=/nologo /o"$(OUTDIR)/fftest.bsc" -BSC32_SBRS= \ - -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 -# ADD LINK32 ..\..\..\..\..\dist\win32_d.obj\lib\nspr3.lib ..\..\..\..\..\dist\win32_d.obj\lib\plc3.lib /nologo /subsystem:console /debug /machine:I386 -LINK32_FLAGS=..\..\..\..\..\dist\win32_d.obj\lib\nspr3.lib\ - ..\..\..\..\..\dist\win32_d.obj\lib\plc3.lib /nologo /subsystem:console\ - /incremental:yes /pdb:"$(OUTDIR)/fftest.pdb" /debug /machine:I386\ - /out:"$(OUTDIR)/fftest.exe" -LINK32_OBJS= \ - "$(INTDIR)\FlatFileTest.obj" \ - "$(INTDIR)\nsFFEntry.obj" \ - "$(INTDIR)\nsFFObject.obj" \ - "$(INTDIR)\nsFlatFile.obj" \ - "$(INTDIR)\nsTOC.obj" - -"$(OUTDIR)\fftest.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS) - $(LINK32) @<< - $(LINK32_FLAGS) $(LINK32_OBJS) -<< - -!ENDIF - -.c{$(CPP_OBJS)}.obj: - $(CPP) $(CPP_PROJ) $< - -.cpp{$(CPP_OBJS)}.obj: - $(CPP) $(CPP_PROJ) $< - -.cxx{$(CPP_OBJS)}.obj: - $(CPP) $(CPP_PROJ) $< - -.c{$(CPP_SBRS)}.sbr: - $(CPP) $(CPP_PROJ) $< - -.cpp{$(CPP_SBRS)}.sbr: - $(CPP) $(CPP_PROJ) $< - -.cxx{$(CPP_SBRS)}.sbr: - $(CPP) $(CPP_PROJ) $< - -################################################################################ -# Begin Target - -# Name "fftest - Win32 Release" -# Name "fftest - Win32 Debug" - -!IF "$(CFG)" == "fftest - Win32 Release" - -!ELSEIF "$(CFG)" == "fftest - Win32 Debug" - -!ENDIF - -################################################################################ -# Begin Source File - -SOURCE=.\FlatFileTest.cpp -DEP_CPP_FLATF=\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\plstr.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinet.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinrval.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prio.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlong.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtime.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - "..\..\include\nsFFEntry.h"\ - "..\..\include\nsFFObject.h"\ - "..\..\include\nsFlatFile.h"\ - "..\..\include\nsTOC.h"\ - {$(INCLUDE)}"\sys\types.h"\ - -NODEP_CPP_FLATF=\ - "..\..\..\..\..\dist\win32_d.obj\include\macsocket.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\FlatFileTest.obj" : $(SOURCE) $(DEP_CPP_FLATF) "$(INTDIR)" - - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=\work\mozilla\network\cache\nu\src\nsFlatFile.cpp -DEP_CPP_NSFLA=\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\plstr.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinet.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinrval.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prio.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlong.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prmem.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtime.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - "..\..\include\nsFlatFile.h"\ - {$(INCLUDE)}"\sys\types.h"\ - -NODEP_CPP_NSFLA=\ - "..\..\..\..\..\dist\win32_d.obj\include\macsocket.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\nsFlatFile.obj" : $(SOURCE) $(DEP_CPP_NSFLA) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=\work\mozilla\network\cache\nu\src\nsFFObject.cpp -DEP_CPP_NSFFO=\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - "..\..\include\nsFFObject.h"\ - -NODEP_CPP_NSFFO=\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\nsFFObject.obj" : $(SOURCE) $(DEP_CPP_NSFFO) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=\work\mozilla\network\cache\nu\src\nsTOC.cpp -DEP_CPP_NSTOC=\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\plstr.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinet.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prinrval.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prio.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlog.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlong.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtime.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - "..\..\include\nsFFEntry.h"\ - "..\..\include\nsFFObject.h"\ - "..\..\include\nsFlatFile.h"\ - "..\..\include\nsTOC.h"\ - {$(INCLUDE)}"\sys\types.h"\ - -NODEP_CPP_NSTOC=\ - "..\..\..\..\..\dist\win32_d.obj\include\macsocket.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\nsTOC.obj" : $(SOURCE) $(DEP_CPP_NSTOC) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -# End Source File -################################################################################ -# Begin Source File - -SOURCE=\work\mozilla\network\cache\nu\src\nsFFEntry.cpp -DEP_CPP_NSFFE=\ - "..\..\..\..\..\dist\win32_d.obj\include\obsolete\protypes.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prcpucfg.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prlog.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prmem.h"\ - "..\..\..\..\..\dist\win32_d.obj\include\prtypes.h"\ - "..\..\include\nsFFEntry.h"\ - "..\..\include\nsFFObject.h"\ - -NODEP_CPP_NSFFE=\ - "..\..\..\..\..\dist\win32_d.obj\include\protypes.h"\ - - -"$(INTDIR)\nsFFEntry.obj" : $(SOURCE) $(DEP_CPP_NSFFE) "$(INTDIR)" - $(CPP) $(CPP_PROJ) $(SOURCE) - - -# End Source File -# End Target -# End Project -################################################################################ diff --git a/mozilla/network/cache/nu/tests/fftest/fftest.mdp b/mozilla/network/cache/nu/tests/fftest/fftest.mdp deleted file mode 100644 index f2b9911559d..00000000000 Binary files a/mozilla/network/cache/nu/tests/fftest/fftest.mdp and /dev/null differ diff --git a/mozilla/network/cache/nu/todo b/mozilla/network/cache/nu/todo deleted file mode 100644 index b1f33683db5..00000000000 --- a/mozilla/network/cache/nu/todo +++ /dev/null @@ -1,3 +0,0 @@ -List of items todo- -- Remove stub calls of earliar api and replace with new ones. -- Remove #defines of MEMORY_CACHE_TYPE_URL, FILE_CACHE_TYPE_URL diff --git a/mozilla/network/client/MANIFEST b/mozilla/network/client/MANIFEST deleted file mode 100644 index 10dfa02912f..00000000000 --- a/mozilla/network/client/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -cnetinit.h diff --git a/mozilla/network/client/Makefile.in b/mozilla/network/client/Makefile.in deleted file mode 100644 index da2d4e81f67..00000000000 --- a/mozilla/network/client/Makefile.in +++ /dev/null @@ -1,34 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = cnetinit - -EXPORTS = $(srcdir)/cnetinit.h - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/client/cnetinit.c b/mozilla/network/client/cnetinit.c deleted file mode 100644 index 58dae230511..00000000000 --- a/mozilla/network/client/cnetinit.c +++ /dev/null @@ -1,132 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "xp.h" -#include "mkutils.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "plstr.h" -#include "prmem.h" - -#include "fileurl.h" -#include "httpurl.h" -#include "ftpurl.h" -#include "abouturl.h" -#include "gophurl.h" -#include "jsurl.h" -#include "fileurl.h" -#include "remoturl.h" -#include "dataurl.h" -#include "netcache.h" - -#if defined(JAVA) && defined(XP_MAC) -#include "marimurl.h" -#endif - -/* For about handlers */ -#include "il_strm.h" -#include "glhist.h" - -PRIVATE void net_InitAboutURLs(); - -PUBLIC void -NET_ClientProtocolInitialize(void) -{ - - NET_InitFileProtocol(); - NET_InitHTTPProtocol(); -#ifdef NU_CACHE - NET_InitNuCacheProtocol(); -#else - NET_InitMemCacProtocol(); -#endif - NET_InitFTPProtocol(); - NET_InitAboutProtocol(); - NET_InitGopherProtocol(); - NET_InitMochaProtocol(); - NET_InitRemoteProtocol(); - NET_InitDataURLProtocol(); - -#ifdef JAVA - NET_InitMarimbaProtocol(); -#endif - - net_InitAboutURLs(); -} - -#ifdef XP_UNIX -extern void FE_ShowMinibuffer(MWContext *); - -PRBool net_AboutMinibuffer(const char *token, - FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *window_id) -{ - FE_ShowMinibuffer(window_id); - - return PR_TRUE; -} -#endif - -#ifdef WEBFONTS -PRBool net_AboutFonts(const char *token, - FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *window_id) -{ - NF_AboutFonts(window_id, which); - return PR_TRUE; -} -#endif /* WEBFONTS */ - -PRBool net_AboutImageCache(const char *token, - FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *window_id) -{ - IL_DisplayMemCacheInfoAsHTML(format_out, URL_s, window_id); - return PR_TRUE; -} - -PRBool net_AboutGlobalHistory(const char *token, - FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *window_id) -{ - NET_DisplayGlobalHistoryInfoAsHTML(window_id, URL_s, format_out); - - return PR_TRUE; -} - -PRIVATE void net_InitAboutURLs() -{ - NET_RegisterAboutProtocol("image-cache", net_AboutImageCache); - NET_RegisterAboutProtocol("global", net_AboutGlobalHistory); -#ifdef XP_UNIX - NET_RegisterAboutProtocol("minibuffer", net_AboutMinibuffer); -#endif -#ifdef WEBFONTS - NET_RegisterAboutProtocol("fonts", net_AboutFonts); -#endif -} diff --git a/mozilla/network/client/cnetinit.h b/mozilla/network/client/cnetinit.h deleted file mode 100644 index 61aa8cc37e1..00000000000 --- a/mozilla/network/client/cnetinit.h +++ /dev/null @@ -1,9 +0,0 @@ - - -#ifndef CLINIT_H -#define CLINIT_H - -void -NET_ClientProtocolInitialize(void); - -#endif /* CLINIT_H */ diff --git a/mozilla/network/client/makefile.win b/mozilla/network/client/makefile.win deleted file mode 100644 index e6b63306f07..00000000000 --- a/mozilla/network/client/makefile.win +++ /dev/null @@ -1,45 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - -DEPTH=..\.. -MODULE=cnetinit -EXPORTS= cnetinit.h - -include <$(DEPTH)\config\rules.mak> - -!ifndef MODULAR_NETLIB -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" - -!endif diff --git a/mozilla/network/cnvts/MANIFEST b/mozilla/network/cnvts/MANIFEST deleted file mode 100644 index cf44ccbd579..00000000000 --- a/mozilla/network/cnvts/MANIFEST +++ /dev/null @@ -1,17 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -cvactive.h -cvchunk.h -cvcolor.h -cvdisk.h -cvmime.h -cvpics.h -cvsimple.h -cvunzip.h -cvjscfg.h -nsINetPlugin.h -nsINetPluginInstance.h -nsINetOStream.h - diff --git a/mozilla/network/cnvts/Makefile.in b/mozilla/network/cnvts/Makefile.in deleted file mode 100644 index c01ccd7b287..00000000000 --- a/mozilla/network/cnvts/Makefile.in +++ /dev/null @@ -1,74 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = netcnvts -LIBRARY_NAME = netcnvts - -REQUIRES = network img lay layer util parse pref js security marimurl style mimetype ldap zlib - -CSRCS = \ - cvactive.c \ - cvchunk.c \ - cvcolor.c \ - cvdisk.c \ - cvextcon.c \ - cvjscfg.c \ - cvsimple.c \ - cvunzip.c \ - txview.c \ - $(NULL) - -CPPSRCS = \ - cvplugin.cpp \ - nsNetConverterStream.cpp \ - $(NULL) - -EXPORTS = \ - nsINetPlugin.h \ - nsINetPluginInstance.h \ - nsINetOStream.h \ - cvactive.h \ - cvview.h \ - cvproxy.h \ - cvextcon.h \ - txview.h \ - cvchunk.h \ - cvcolor.h \ - cvdisk.h \ - cvsimple.h \ - cvplugin.h \ - cvunzip.h \ - cvjscfg.h \ - $(NULL) - -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/cnvts/cvactive.c b/mozilla/network/cnvts/cvactive.c deleted file mode 100644 index da7a050d5c8..00000000000 --- a/mozilla/network/cnvts/cvactive.c +++ /dev/null @@ -1,480 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "cvactive.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "glhist.h" -#include "merrors.h" - - -extern int MK_OUT_OF_MEMORY; - - -typedef struct _DataObject { - int state; - NET_StreamClass *next_stream; - char *prev_buffer; - int32 prev_buffer_len; - MWContext *window_id; - int format_out; - URL_Struct *URL_s; - PRBool signal_at_end_of_multipart; -} DataObject; - -#define NORMAL_S 1 -#define FOUND_BOUNDARY_S 2 - -#define MAX_MIME_LINE 200 - -/* parse a mime/multipart stream. The boundary is already - * known and we start off in the content of the original - * message/822 body. - * - * buffer data up to the size of the passed in data length - * for efficiency of the upstream module. - */ -PRIVATE int net_MultipleDocumentWrite (NET_StreamClass *stream, CONST char* s, int32 l) -{ - int32 i=0; - int32 line_length=1; - int rv=0; - char *cp; - char *line; - char *push_buffer=NULL; - int32 push_buffer_size=0; - PRBool all_done=PR_FALSE; - DataObject *obj=stream->data_object; - BlockAllocCat(obj->prev_buffer, obj->prev_buffer_len, s, l); - obj->prev_buffer_len += l; - - if(!obj->prev_buffer) - return(MK_OUT_OF_MEMORY); - - line = obj->prev_buffer; - - /* try and find a line - */ - for(cp=obj->prev_buffer; i < obj->prev_buffer_len; cp++, i++, line_length++) - { - if(*cp == '\n') - { - - switch(obj->state) - { - case NORMAL_S: - { - char *cp2 = line; - int blength = PL_strlen(obj->URL_s->boundary); - - /* look for boundary. We can rest assured that these - PL_strncmp() calls are safe, because we know that the - valid portion of the string starting at cp2 has a - newline in it (at *cp), and we know that boundary - strings never have newlines in them. */ - if((!PL_strncmp(cp2, "--",2) && - !PL_strncmp(cp2+2, - obj->URL_s->boundary, - blength)) - || (!PL_strncmp(cp2, - obj->URL_s->boundary, - blength))) - { - TRACEMSG(("Found boundary: %s", obj->URL_s->boundary)); - obj->state = FOUND_BOUNDARY_S; - - if(obj->next_stream) - { - - if(push_buffer) - { - /* strip the last newline before the - * boundary - */ - push_buffer_size--; - /* if there is a CR as well as a LF - * strip that too - */ - if(push_buffer_size > 0 && push_buffer[push_buffer_size-1] == CR) - push_buffer_size--; - rv = (*obj->next_stream->put_block) - (obj->next_stream, - push_buffer, - push_buffer_size); - PR_Free(push_buffer); - push_buffer = NULL; - push_buffer_size = 0; - } - - TRACEMSG(("Completeing an open stream")); - /* if this stream is not the last one, set a flag - before completion to let completion do special stuff */ - PR_ASSERT(cp2 + blength <= cp); - /* Because the above PL_strcmp calls succeeded. - Because this is true, we know the first call - to PL_strncmp below is always safe, but we - need to check lengths before we can be sure - the other call is safe. */ - - if( (cp2 + blength + 2 < cp && - !PL_strncmp(cp2+2+blength, "--",2)) - || !PL_strncmp(cp2+blength, "--",2)) - { - /* very last boundary */ - obj->next_stream->is_multipart = PR_FALSE; - - /* set the all_done flag when - * we have found the final boundary - */ - all_done = PR_TRUE; - } - else - { - obj->next_stream->is_multipart = PR_TRUE; - } - - /* complete the last stream - */ - (*obj->next_stream->complete) - (obj->next_stream); - PR_Free(obj->next_stream); - obj->next_stream = NULL; - } - - /* move the line ptr up to new data */ - line = cp+1; - line_length=1; /* reset */ - - if(all_done && obj->signal_at_end_of_multipart) - return(MK_MULTIPART_MESSAGE_COMPLETED); - break; - } - else - { - TRACEMSG(("Pushing line (actually buffering)")); - - /* didn't find the boundary - */ - if(obj->next_stream) - { - - BlockAllocCat(push_buffer, push_buffer_size, - line, line_length); - push_buffer_size += line_length; - if(!push_buffer) - return(MK_OUT_OF_MEMORY); - } - - /* move the line ptr up to new data */ - line = cp+1; - line_length=0; /* reset */ - } - break; - } - - case FOUND_BOUNDARY_S: - - PR_ASSERT(*cp == '\n'); /* from the 'if' above */ - - /* terminate at the newline. - * now 'line' points to a valid NULL terminated C string - */ - *cp = '\0'; - - TRACEMSG(("Parsing header: >%s<", line)); - - /* parse mime headers - * stop when a blank line is encountered - */ - if(*line == '\0' || *line == '\r') - { - int format_out; - obj->state = NORMAL_S; - - TRACEMSG(("Found end of headers")); - if (obj->URL_s->content_type == NULL) - StrAllocCopy(obj->URL_s->content_type, TEXT_PLAIN); - - /* abort all existing streams. We - * have to do this to prevent the - * image lib and other things from - * continuing to load the page after - * we left. - * - * don't abort other streams if it's - * just a new inline image or if the - * stream is not going to the screen - */ - if(CLEAR_CACHE_BIT(obj->format_out) != FO_INTERNAL_IMAGE - && (!PL_strncasecmp(obj->URL_s->content_type, - "text", 4) - || - !PL_strncasecmp(obj->URL_s->content_type, - "image", 4)) ) - { - NET_SilentInterruptWindow(obj->window_id); - format_out = obj->format_out; - } - else - { - /* don't cache image animations... */ - format_out = CLEAR_CACHE_BIT(obj->format_out); - } - - /* build a stream - */ - obj->next_stream = NET_StreamBuilder(format_out, - obj->URL_s, - obj->window_id); - - if(!obj->next_stream) - return(MK_UNABLE_TO_CONVERT); - - } - else if(!PL_strncasecmp(line, "CONTENT-TYPE:", 13)) - { - - strtok(line+13, ";"); /* terminate at ; */ - - StrAllocCopy(obj->URL_s->content_type, - XP_StripLine(line+13)); - - if(!obj->URL_s->content_type || !*obj->URL_s->content_type) - StrAllocCopy(obj->URL_s->content_type, TEXT_PLAIN); - - TRACEMSG(("found new content_type: %s", - obj->URL_s->content_type)); - - } - else - { - /* Pass all other headers to the MIME header parser - */ - char *value = PL_strchr(line, ':'); - if(value) - value++; - NET_ParseMimeHeader(NET_AllowForeignCookies, - obj->window_id, - obj->URL_s, - line, - value, PR_FALSE); - } - line = cp+1; - line_length = 0; - break; - - default: - assert(0); - break; - - } - } /* end if */ - } /* end for */ - - if(line_length > MAX_MIME_LINE * 2) - { - int32 new_size; - - TRACEMSG(("Line too long pushing it")); - - if(obj->next_stream) - { - if(push_buffer) - { - rv = (*obj->next_stream->put_block)(obj->next_stream, - push_buffer, - push_buffer_size); - rv = (*obj->next_stream->put_block)(obj->next_stream, - line, - MAX_MIME_LINE); - PR_Free(push_buffer); - push_buffer = 0; - push_buffer_size = 0; - } - else - { - rv = (*obj->next_stream->put_block)(obj->next_stream, - line, - MAX_MIME_LINE); - } - - if(rv < 0) - return(rv); - } - - /* newsize equals the old size minus the difference - * between line and the start of the old buffer and - * the MAX_MIME_LENGTH that we just wrote out - */ - new_size = obj->prev_buffer_len - - ((line - obj->prev_buffer) + MAX_MIME_LINE); - - memmove(obj->prev_buffer, line+MAX_MIME_LINE, new_size); - obj->prev_buffer_len = new_size; - - return(0); - } - - if(line != obj->prev_buffer) - { - /* some part of the line has been digested, get rid of - * the part that has been used - */ - obj->prev_buffer_len -= (line - obj->prev_buffer); - memmove(obj->prev_buffer, line, obj->prev_buffer_len); - } - - /* if there is anything in the push buffer send it now - */ - if(push_buffer) - { - if(obj->next_stream) - { - TRACEMSG(("Pushing buffered data")); - rv = (*obj->next_stream->put_block)(obj->next_stream, - push_buffer, - push_buffer_size); - } - PR_Free(push_buffer); - if (rv < 0) - return rv; - } - - return(0); -} - -/* is the stream ready for writeing? - */ -PRIVATE unsigned int net_MultipleDocumentWriteReady (NET_StreamClass * stream) -{ - DataObject *obj=stream->data_object; - if(obj->next_stream) - return((*obj->next_stream->is_write_ready)(obj->next_stream)); - else - return(MAX_WRITE_READY); -} - - -PRIVATE void net_MultipleDocumentComplete (NET_StreamClass *stream) -{ - DataObject *obj=stream->data_object; - - if(obj->next_stream) - { - (*obj->next_stream->complete)(obj->next_stream); - PR_Free(obj->next_stream); - } - - PR_FREEIF(obj->prev_buffer); - PR_Free(obj); - - return; -} - -PRIVATE void net_MultipleDocumentAbort (NET_StreamClass *stream, int status) -{ - DataObject *obj=stream->data_object; - if(obj->next_stream) - { - (*obj->next_stream->abort)(obj->next_stream, status); - PR_Free(obj->next_stream); - } - - PR_FREEIF(obj->prev_buffer); - PR_Free(obj); - - return; -} - - -PUBLIC NET_StreamClass * -CV_MakeMultipleDocumentStream (int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id) -{ - DataObject* obj; - NET_StreamClass* stream; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - GH_UpdateGlobalHistory(URL_s); - - URL_s->is_active = PR_TRUE; /* set to disable view source */ - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEW(DataObject); - if (obj == NULL) - return(NULL); - - memset(obj, 0, sizeof(DataObject)); - - if(CVACTIVE_SIGNAL_AT_END_OF_MULTIPART == (int) data_object) - obj->signal_at_end_of_multipart = PR_TRUE; - - stream->name = "Multiple Document"; - stream->complete = (MKStreamCompleteFunc) net_MultipleDocumentComplete; - stream->abort = (MKStreamAbortFunc) net_MultipleDocumentAbort; - stream->put_block = (MKStreamWriteFunc) net_MultipleDocumentWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_MultipleDocumentWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - /* don't cache these - format_out = CLEAR_CACHE_BIT(format_out); - */ - - /* enable clicking since it doesnt go through the cache - * code - */ - FE_EnableClicking(window_id); - - obj->next_stream = NULL; - obj->window_id = window_id; - obj->format_out = format_out; - obj->URL_s = URL_s; - obj->state = NORMAL_S; - - /* make sure that we have a real boundary. - * if not fill in '--' as a boundary - */ - if(!URL_s->boundary) - StrAllocCopy(URL_s->boundary, "--"); - - /* overwrite the current content type with TEXT/PLAIN since - * we want that as the default content-type for - * body parts - */ - StrAllocCopy(URL_s->content_type, TEXT_PLAIN); - - TRACEMSG(("Returning stream from NET_MultipleDocumentConverter\n")); - - return stream; -} diff --git a/mozilla/network/cnvts/cvactive.h b/mozilla/network/cnvts/cvactive.h deleted file mode 100644 index e9af2b77716..00000000000 --- a/mozilla/network/cnvts/cvactive.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CV_ACTIVE -#define CV_ACTIVE - -#include "net.h" - -/* define a constant to be passed to CV_MakeMultipleDocumentStream - * as the data_object to signify that it should return - * MK_END_OF_MULTIPART_MESSAGE when it gets to the end - * of the multipart instead of waiting for the complete - * function to be called - */ -#define CVACTIVE_SIGNAL_AT_END_OF_MULTIPART 999 - -PR_BEGIN_EXTERN_C - -extern NET_StreamClass * -CV_MakeMultipleDocumentStream (int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id); -PR_END_EXTERN_C - -#endif /* CV_ACTIVE */ diff --git a/mozilla/network/cnvts/cvchunk.c b/mozilla/network/cnvts/cvchunk.c deleted file mode 100644 index 5a77ac1e7f0..00000000000 --- a/mozilla/network/cnvts/cvchunk.c +++ /dev/null @@ -1,333 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* Please leave outside of ifdef for windows precompiled headers */ -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" - -#ifdef MOZILLA_CLIENT - -#include "cvchunk.h" /* prototype */ - -extern int MK_OUT_OF_MEMORY; - -typedef enum { - FIND_CHUNK_SIZE, - READ_CHUNK, - STRIP_CRLF, - PARSE_FOOTER -} States; - -typedef struct _DataObject { - NET_StreamClass *next_stream; - char *in_buf; - uint32 in_buf_size; - uint32 chunk_size; - uint32 amount_of_chunk_parsed; - States cur_state; - FO_Present_Types format_out; - MWContext *context; - URL_Struct *URL_s; -} DataObject; - - -/* unchunk the message and return MK_MULTIPART_MESSAGE_COMPLETED - * when end detected - */ -PRIVATE int net_ChunkedWrite (NET_StreamClass *stream, char* s, int32 l) -{ - DataObject *obj=stream->data_object; - BlockAllocCat(obj->in_buf, obj->in_buf_size, s, l); - if(!obj->in_buf) - return MK_OUT_OF_MEMORY; - obj->in_buf_size += l; - - while(obj->in_buf_size > 0) - { - if(obj->cur_state == FIND_CHUNK_SIZE) - { - char *line_feed; - char *semicolon; - char *end; - - /* we don't have a current chunk size - * look for a new chunk size - * - * make sure the line has a CRLF - */ - if((line_feed = PL_strnchr(obj->in_buf, LF, obj->in_buf_size)) == NULL) - { - return 1; /* need more data */ - } - - *line_feed = '\0'; - - semicolon = PL_strnchr(obj->in_buf, ';', line_feed-obj->in_buf); - - if(semicolon) - *semicolon = '\0'; - - end = semicolon ? semicolon : line_feed; - - /* read the first integer and ignore any thing - * else on the line. Extensions are allowed - */ - obj->chunk_size = strtol(obj->in_buf, &end, 16); - - /* strip everything up to the line feed */ - obj->in_buf_size -= (line_feed+1) - obj->in_buf; - if(obj->in_buf_size) - memmove(obj->in_buf, - line_feed+1, - obj->in_buf_size); - - if(obj->chunk_size == 0) - { - /* the stream should be done now */ - obj->cur_state = PARSE_FOOTER; - } - else - { - obj->cur_state = READ_CHUNK; - } - - } - else if(obj->cur_state == READ_CHUNK) - { - uint32 data_size; - int32 status; - - /* take as much data as we have and push it up the stream - */ - - data_size = MIN(obj->in_buf_size, obj->chunk_size-obj->amount_of_chunk_parsed); - - status = (obj->next_stream->put_block)(obj->next_stream, - obj->in_buf, - data_size); - if(status < 0) - return status; - - /* remove the part that has been pushed */ - obj->in_buf_size -= data_size; - if(obj->in_buf_size) - memmove(obj->in_buf, - obj->in_buf+data_size, - obj->in_buf_size); - - obj->amount_of_chunk_parsed += data_size; - - if(obj->amount_of_chunk_parsed >= obj->chunk_size) - { - PR_ASSERT(obj->amount_of_chunk_parsed == obj->chunk_size); - /* reinit */ - obj->amount_of_chunk_parsed = 0; - obj->cur_state = STRIP_CRLF; - } - } - else if(obj->cur_state == STRIP_CRLF) - { - if(PL_strnchr(obj->in_buf, LF, obj->in_buf_size) == NULL) - { - return 1; /* No LF, need more data. */ - } - - if(obj->in_buf_size > 1 && obj->in_buf[0] == CR && obj->in_buf[1] == LF) - { - /* strip two bytes */ - obj->in_buf_size -= 2; - if(obj->in_buf_size) - memmove(obj->in_buf, - obj->in_buf+2, - obj->in_buf_size); - obj->cur_state = FIND_CHUNK_SIZE; - } - else if(obj->in_buf[0] == LF) - { - /* strip one bytes */ - obj->in_buf_size -= 1; - if(obj->in_buf_size) - memmove(obj->in_buf, - obj->in_buf+1, - obj->in_buf_size); - obj->cur_state = FIND_CHUNK_SIZE; - } - else - { - if(obj->in_buf_size >= 2) - { - int status; - - /* a fatal parse error */ - PR_ASSERT(0); - - /* just spew the buf to the screen */ - status = (obj->next_stream->put_block)(obj->next_stream, - obj->in_buf, - obj->in_buf_size); - if(status < 0) - return status; - - /* remove the part that has been pushed */ - obj->in_buf_size = 0; - } - } - } - else if(obj->cur_state == PARSE_FOOTER) - { - char *line_feed; - char *value; - - /* parse until we see two CRLF's in a row */ - if((line_feed = PL_strnchr(obj->in_buf, LF, obj->in_buf_size)) == NULL) - { - return 1; /* need more data */ - } - - *line_feed = '\0'; - - /* strip the CR */ - if(line_feed != obj->in_buf && *(line_feed-1) == CR) - *(line_feed-1) = '\0'; - - if(*obj->in_buf == '\0') - { - /* end of parse stream */ - return MK_MULTIPART_MESSAGE_COMPLETED; - } - - /* names are separated from values with a colon - */ - value = PL_strchr(obj->in_buf, ':'); - if(value) - value++; - - /* otherwise parse the line as a mime header */ - NET_ParseMimeHeader(obj->format_out, - obj->context, - obj->URL_s, - obj->in_buf, - value, - FALSE); - - /* strip the line from the buffer */ - obj->in_buf_size -= (line_feed+1) - obj->in_buf; - if(obj->in_buf_size) - memmove(obj->in_buf, - line_feed+1, - obj->in_buf_size); - } - } - - PR_ASSERT(obj->in_buf_size == 0); - - return(1); -} - -/* is the stream ready for writeing? - */ -PRIVATE unsigned int net_ChunkedWriteReady (NET_StreamClass * stream) -{ - DataObject *obj=stream->data_object; - return (*obj->next_stream->is_write_ready)(obj->next_stream); -} - - -PRIVATE void net_ChunkedComplete (NET_StreamClass *stream) -{ - DataObject *obj=stream->data_object; - (*obj->next_stream->complete)(obj->next_stream); - - PR_Free(obj); - return; -} - -PRIVATE void net_ChunkedAbort (NET_StreamClass *stream, int status) -{ - DataObject *obj=stream->data_object; - (*obj->next_stream->abort)(obj->next_stream, status); - - return; -} - - -MODULE_PRIVATE NET_StreamClass * -NET_ChunkedDecoderStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - DataObject* obj; - NET_StreamClass* stream; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEWZAP(DataObject); - if (obj == NULL) - return(NULL); - - stream->name = "Chunked decoder"; - stream->complete = (MKStreamCompleteFunc) net_ChunkedComplete; - stream->abort = (MKStreamAbortFunc) net_ChunkedAbort; - stream->put_block = (MKStreamWriteFunc) net_ChunkedWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_ChunkedWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - /* clear the "chunked" encoding */ - if(URL_s->transfer_encoding) - { - PR_FREEIF(URL_s->transfer_encoding); - URL_s->transfer_encoding = NULL; - } - else - { - PR_FREEIF(URL_s->content_encoding); - URL_s->content_encoding = NULL; - } - obj->next_stream = NET_StreamBuilder(format_out, URL_s, window_id); - - if(!obj->next_stream) - { - PR_Free(obj); - PR_Free(stream); - return NULL; - } - - obj->context = window_id; - obj->format_out = format_out; - obj->URL_s = URL_s; - - TRACEMSG(("Returning stream from NET_ChunkedConverter\n")); - - return stream; -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cnvts/cvchunk.h b/mozilla/network/cnvts/cvchunk.h deleted file mode 100644 index 8f2ca1c802b..00000000000 --- a/mozilla/network/cnvts/cvchunk.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVCHUNK_H -#define CVCHUNK_H - -MODULE_PRIVATE NET_StreamClass * -NET_ChunkedDecoderStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* CVCHUNK_H */ diff --git a/mozilla/network/cnvts/cvcolor.c b/mozilla/network/cnvts/cvcolor.c deleted file mode 100644 index 63973523bb6..00000000000 --- a/mozilla/network/cnvts/cvcolor.c +++ /dev/null @@ -1,586 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* Please leave outside of ifdef for windows precompiled headers */ -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" - -#ifdef MOZILLA_CLIENT - -/* take an HTML stream. Escape all the HTML and - * use to color the different syntactical parts - * of the HTML stream - */ -#include "xpgetstr.h" -#include "intl_csi.h" -#define VIEW_SOURCE_TARGET_WINDOW_NAME "%ViewSourceWindow" - -typedef enum StatesEnum { - IN_CONTENT, - IN_SCRIPT, - ABOUT_TO_BEGIN_TAG, - IN_BEGIN_TAG, - IN_TAG, - BEGIN_ATTRIBUTE_VALUE, - IN_QUOTED_ATTRIBUTE_VALUE, - IN_BROKEN_QUOTED_ATTRIBUTE_VALUE, - IN_UNQUOTED_ATTRIBUTE_VALUE, - IN_COMMENT, - IN_AMPERSAND_THINGY -} StatesEnum; - -#define MAXTAGLEN 15 - -typedef struct _DataObject { - NET_StreamClass * next_stream; - StatesEnum state; - char tag[MAXTAGLEN+1]; - uint tag_index; - PRBool in_broken_html; -} DataObject; - -#define BEGIN_TAG_MARKUP "" -#define END_TAG_MARKUP "" -#define BEGIN_TAG_NAME_MARKUP "" -#define END_TAG_NAME_MARKUP "" -#define BEGIN_ATTRIBUTE_VALUE_MARKUP "
" -#define END_ATTRIBUTE_VALUE_MARKUP "" -#define BEGIN_BROKEN_ATTRIBUTE_MARKUP "" -#define END_BROKEN_ATTRIBUTE_MARKUP "" -#define BEGIN_COMMENT_MARKUP "" -#define END_COMMENT_MARKUP "" -#define BEGIN_AMPERSAND_THINGY_MARKUP "" -#define END_AMPERSAND_THINGY_MARKUP "" - -extern int MK_CVCOLOR_SOURCE_OF; - -PRIVATE char *net_BeginColorHTMLTag (DataObject *obj) -{ - char *new_markup = 0; - - StrAllocCat(new_markup, BEGIN_TAG_MARKUP); - StrAllocCat(new_markup, "<"); - StrAllocCat(new_markup, BEGIN_TAG_NAME_MARKUP); - obj->state = ABOUT_TO_BEGIN_TAG; - return new_markup; -} - -PRIVATE char *net_EndColorHTMLTag (DataObject *obj) -{ - char *new_markup = 0; - - if(obj->in_broken_html) - { - StrAllocCopy(new_markup, END_BROKEN_ATTRIBUTE_MARKUP); - obj->in_broken_html = PR_FALSE; - } - StrAllocCat(new_markup, ">"); - StrAllocCat(new_markup, END_TAG_MARKUP); - return new_markup; -} - -PRIVATE int net_ColorHTMLWrite (NET_StreamClass *stream, CONST char *s, int32 l) -{ - int32 i; - int32 last_output_point; - char *new_markup=0; - char *tmp_markup=0; - char tiny_buf[4]; - CONST char *cp; - int status; - DataObject *obj=stream->data_object; - - last_output_point = 0; - - for(i = 0, cp = s; i < l; i++, cp++) - { - switch(obj->state) - { - case IN_CONTENT: - /* do nothing until you find a '<' "' */ - if(!PL_strncmp(cp, "-->", 3)) - { - StrAllocCopy(new_markup, ">"); - cp += 2; - i += 2; - StrAllocCat(new_markup, END_COMMENT_MARKUP); - obj->state = IN_CONTENT; - } - else if(*cp == '<') - { - /* protect ourselves from markup */ - StrAllocCopy(new_markup, "<"); - } - break; - case IN_AMPERSAND_THINGY: - /* do nothing until you find a ';' or space */ - if(*cp == ';' || NET_IS_SPACE(*cp)) - { - sprintf(tiny_buf, "%c", *cp); - StrAllocCopy(new_markup, tiny_buf); - StrAllocCat(new_markup, END_AMPERSAND_THINGY_MARKUP); - obj->state = IN_CONTENT; - } - else if(*cp == '<') - { - /* protect ourselves from markup */ - StrAllocCopy(new_markup, "<"); - } - break; - default: - PR_ASSERT(0); - break; - } - - if(new_markup) - { - /* push all the way up to but not including *cp */ - status = (*obj->next_stream->put_block) - (obj->next_stream, - &s[last_output_point], - i-last_output_point); - last_output_point = i+1; - - if(status < 0) - { - PR_Free(new_markup); - return(status); - } - - /* add new markup */ - status = (*obj->next_stream->put_block) - (obj->next_stream, - new_markup, PL_strlen(new_markup)); - if(status < 0) - { - PR_Free(new_markup); - return(status); - } - - PR_FREEIF(new_markup); - new_markup = NULL; - } - } - - if(last_output_point < l) - return((*obj->next_stream->put_block)(obj->next_stream, - &s[last_output_point], - (l-last_output_point))); - else - return(0); -} - -/* is the stream ready for writeing? - */ -PRIVATE unsigned int net_ColorHTMLWriteReady (NET_StreamClass * stream) -{ - DataObject *obj=stream->data_object; - return((*obj->next_stream->is_write_ready)(obj->next_stream)); -} - - -PRIVATE void net_ColorHTMLComplete (NET_StreamClass *stream) -{ - DataObject *obj=stream->data_object; - (*obj->next_stream->complete)(obj->next_stream); -} - -PRIVATE void net_ColorHTMLAbort (NET_StreamClass *stream, int status) -{ - DataObject *obj=stream->data_object; - (*obj->next_stream->abort)(obj->next_stream, status); -} - -PUBLIC NET_StreamClass * -net_ColorHTMLStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - DataObject* obj; - char *new_markup=0; - char *new_url=0; - char *old_url; - int status, type; - NET_StreamClass *next_stream, *new_stream; - PRBool is_html_stream = PR_FALSE; - INTL_CharSetInfo csi = LO_GetDocumentCharacterSetInfo(window_id); - INTL_CharSetInfo next_csi; - - TRACEMSG(("Setting up ColorHTML stream. Have URL: %s\n", URL_s->address)); - - /* treat the stream as html if the closure data says - * it's HTML and it is also not a mail or news message - */ - type = NET_URL_Type(URL_s->address); - if(data_obj - && !PL_strcmp((char *)data_obj, TEXT_HTML) - && type != MAILBOX_TYPE_URL - && type != IMAP_TYPE_URL - && type != NEWS_TYPE_URL) - is_html_stream = PR_TRUE; - - /* use a new named window */ - StrAllocCopy(URL_s->window_target, VIEW_SOURCE_TARGET_WINDOW_NAME); - - /* add the url address to the name so that there can be - * one view source window per url - */ - StrAllocCat(URL_s->window_target, URL_s->address); - - /* zero position_tag to prevent hash lossage */ - URL_s->position_tag = 0; - - /* alloc a new chrome struct and stick it in the URL - * so that we can turn off the relavent stuff - */ - URL_s->window_chrome = PR_NEW(Chrome); - if(URL_s->window_chrome) - { - /* zero everything to turn off all chrome */ - memset(URL_s->window_chrome, 0, sizeof(Chrome)); - URL_s->window_chrome->type = MWContextDialog; - URL_s->window_chrome->show_scrollbar = PR_TRUE; - URL_s->window_chrome->allow_resize = PR_TRUE; - URL_s->window_chrome->allow_close = PR_TRUE; - } - - /* call the HTML parser */ - StrAllocCopy(URL_s->content_type, INTERNAL_PARSER); - - /* use the view-source: url instead */ - StrAllocCopy(new_url, VIEW_SOURCE_URL_PREFIX); - StrAllocCat(new_url, URL_s->address); - old_url = URL_s->address; - URL_s->address = new_url; - - format_out = FO_PRESENT; - - /* open next stream */ - next_stream = NET_StreamBuilder(format_out, URL_s, window_id); - - if(!next_stream) - { - PR_Free(old_url); - return(NULL); - } - next_csi = LO_GetDocumentCharacterSetInfo(next_stream->window_id); - - /* jliu: for international's reason, - set the value ASAP, so the following stream can share it */ - INTL_SetCSIWinCSID(next_csi, INTL_GetCSIWinCSID(csi)); - INTL_SetCSIDocCSID(next_csi, INTL_GetCSIDocCSID(csi)); - - -#define DEF_PICS_LABEL "" - - /* add a PICS label */ - StrAllocCopy(new_markup, DEF_PICS_LABEL); - StrAllocCat(new_markup, ""); - StrAllocCat(new_markup, XP_GetString(MK_CVCOLOR_SOURCE_OF)); - StrAllocCat(new_markup, old_url); - StrAllocCat(new_markup, ""); - - - if(!is_html_stream) - StrAllocCat(new_markup, ""); - else - StrAllocCat(new_markup, "<PRE>"); - - PR_Free(old_url); - - status = (*next_stream->put_block)(next_stream, - new_markup, - PL_strlen(new_markup)); - PR_Free(new_markup); - - if(status < 0) - { - (*next_stream->abort)(next_stream, status); - PR_Free(next_stream); - return(NULL); - } - - if(!is_html_stream) - return(next_stream); - - /* else; continue on and build up this stream module - * and attach the next stream to it - */ - - new_stream = PR_NEW(NET_StreamClass); - if(new_stream == NULL) - { - (*next_stream->abort)(next_stream, status); - PR_Free(next_stream); - return(NULL); - } - - obj = PR_NEW(DataObject); - - if (obj == NULL) - { - (*next_stream->abort)(next_stream, status); - PR_Free(next_stream); - PR_Free(new_stream); - return(NULL); - } - - memset(obj, 0, sizeof(DataObject)); - - obj->state = IN_CONTENT; - - obj->next_stream = next_stream; - - new_stream->name = "HTML Colorer"; - new_stream->complete = (MKStreamCompleteFunc) net_ColorHTMLComplete; - new_stream->abort = (MKStreamAbortFunc) net_ColorHTMLAbort; - new_stream->put_block = (MKStreamWriteFunc) net_ColorHTMLWrite; - new_stream->is_write_ready = (MKStreamWriteReadyFunc) - net_ColorHTMLWriteReady; - new_stream->data_object = (void *) obj; /* document info object */ - new_stream->window_id = window_id; - - TRACEMSG(("Returning stream from HTMLColorConverter\n")); - - return new_stream; -} -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cnvts/cvcolor.h b/mozilla/network/cnvts/cvcolor.h deleted file mode 100644 index 6d6d6e75548..00000000000 --- a/mozilla/network/cnvts/cvcolor.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -#ifndef CVCOLOR_H -#define CVCOLOR_H - -extern NET_StreamClass * -net_ColorHTMLStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* CVCOLOR_H */ diff --git a/mozilla/network/cnvts/cvdisk.c b/mozilla/network/cnvts/cvdisk.c deleted file mode 100644 index 8093404b19b..00000000000 --- a/mozilla/network/cnvts/cvdisk.c +++ /dev/null @@ -1,123 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* Please leave outside of ifdef for windows precompiled headers */ -#include "xp.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" - -#ifdef MOZILLA_CLIENT - -typedef struct _DataObject { - FILE * fp; - char * filename; -} DataObject; - - -PRIVATE int net_SaveToDiskWrite (NET_StreamClass *stream, CONST char* s, int32 l) -{ - DataObject *obj=stream->data_object; - fwrite(s, 1, l, obj->fp); - return(1); -} - -/* is the stream ready for writeing? - */ -PRIVATE unsigned int net_SaveToDiskWriteReady (NET_StreamClass * stream) -{ - DataObject *obj; - obj=stream->data_object; - return(MAX_WRITE_READY); /* always ready for writing */ -} - - -PRIVATE void net_SaveToDiskComplete (NET_StreamClass *stream) -{ - DataObject *obj=stream->data_object; - fclose(obj->fp); - - PR_FREEIF(obj->filename); - - PR_Free(obj); - return; -} - -PRIVATE void net_SaveToDiskAbort (NET_StreamClass *stream, int status) -{ - DataObject *obj=stream->data_object; - fclose(obj->fp); - - if(obj->filename) - { - remove(obj->filename); - PR_Free(obj->filename); - } - - return; -} - - -PUBLIC NET_StreamClass * -fe_MakeSaveAsStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - DataObject* obj; - NET_StreamClass* stream; - static int count=0; - char filename[256]; - FILE *fp = stdout; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - PR_snprintf(filename, sizeof(filename), "foo%d.unknown",count++); - fp = fopen(filename,"w"); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEW(DataObject); - if (obj == NULL) - return(NULL); - - stream->name = "FileWriter"; - stream->complete = (MKStreamCompleteFunc) net_SaveToDiskComplete; - stream->abort = (MKStreamAbortFunc) net_SaveToDiskAbort; - stream->put_block = (MKStreamWriteFunc) net_SaveToDiskWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_SaveToDiskWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - obj->fp = fp; - obj->filename = 0; - StrAllocCopy(obj->filename, filename); - - TRACEMSG(("Returning stream from NET_SaveToDiskConverter\n")); - - return stream; -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cnvts/cvdisk.h b/mozilla/network/cnvts/cvdisk.h deleted file mode 100644 index 81a2d06728b..00000000000 --- a/mozilla/network/cnvts/cvdisk.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVDISK_H -#define CVDISK_H - -extern NET_StreamClass* fe_MakeSaveAsStream (FO_Present_Types format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* CVDISK_H */ diff --git a/mozilla/network/cnvts/cvextcon.c b/mozilla/network/cnvts/cvextcon.c deleted file mode 100644 index 4fffab0fa56..00000000000 --- a/mozilla/network/cnvts/cvextcon.c +++ /dev/null @@ -1,424 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* cvextcon.c --- using external Unix programs as content-encoding filters. - */ - -#include "xp.h" -#include "prmem.h" -#include "plstr.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "cvextcon.h" -#include "mkformat.h" - -#include <fcntl.h> -#include <sys/wait.h> -#include <signal.h> - -#ifdef __sgi -#include <bstring.h> /* FD_ZERO uses bzero() which needs this */ - /* file for its prototype. */ -#endif - -#ifdef NTO -#include <sys/select.h> /* For definition of fd_set */ -#endif - -typedef struct _CVG_DataObject { - NET_StreamClass *next_stream; /* Where the output goes */ - pid_t pid; /* process in which the filter is running */ - int infd; /* for reading from the process */ - int outfd; /* for writing to the process */ - struct sigaction oldact; /* Old SIGCHLD handler */ -} CVG_DataObject; - - -PRIVATE int net_ExtConverterRead (CVG_DataObject *data, PRBool block_p) -{ - char input_buffer [1024]; - int bytes_read; - - AGAIN: - while ((bytes_read = read (data->infd, input_buffer, sizeof (input_buffer))) - > 0) - { - if (data->next_stream) - { - int status = ((*data->next_stream->put_block) - (data->next_stream, - input_buffer, bytes_read)); - /* abort */ - if (status < 0) - return status; - } - } - - /* It's necessary that we block here waiting for the process to produce - the rest of its output before we allow the `complete' method to return. - We've already set the socket to be nonblocking, and there doesn't appear - to be any way to set it to do blocking reads again, so instead, we'll - use select() to block for it. That will return when there is some input - available, and we'll read it, and (maybe) block again, repeating until - we get an EOF. - - To implement this in a non-blocking way would require the input and - output sides of this to be disconnected - the output side would be as in - this file, but the input side would need to be a new stream type in - NET_ProcessNet(), at the level of http, ftp, and file streams. - */ - if (bytes_read == -1 && block_p && - (errno == EAGAIN || errno == EWOULDBLOCK)) - { - fd_set rset; - FD_ZERO (&rset); - FD_SET (data->infd, &rset); - if (select (data->infd+1, &rset, 0, 0, 0) < 0) - perror ("select"); - goto AGAIN; - } - - return 1; -} - - -PRIVATE int net_ExtConverterWrite (NET_StreamClass *stream, - CONST char* output_buffer, - int32 output_length) -{ - CVG_DataObject *data = (CVG_DataObject *) stream->data_object; - - while (output_length > 0) - { - int bytes_written = 0; - - /* write as much as possible (until done, or the pipe is full.) - */ - while (output_length > 0 && - (bytes_written = write (data->outfd, output_buffer, - output_length)) - > 0) - { - output_buffer += bytes_written; - output_length -= bytes_written; - } - - if (bytes_written == -1 && errno != EAGAIN && errno != EWOULDBLOCK) - { - perror ("write"); - return -1; - } - - /* Now read as much as possible (until done, or the pipe is drained.) - */ - { - int status = net_ExtConverterRead (data, PR_FALSE); - /* abort */ - if (status < 0) - return status; - } - - /* Now go around the loop again, if we weren't able to write all of - the output buffer at once (because the pipe filled up.) Now that - we've read the available data from the pipe, we will presumably - be able to write to it again. - */ - } - return 1; -} - -PRIVATE int net_ExtConverterWriteReady (NET_StreamClass *stream) -{ - /* #### I'm not sure what the right thing to do here is. --jwz */ -#if 1 - return (MAX_WRITE_READY); -#else - CVG_DataObject *data = (CVG_DataObject *) stream->data_object; - if(data->next_stream) - return ((*data->next_stream->is_write_ready) - (data->next_stream)); - else - return (MAX_WRITE_READY); -#endif -} - - -PRIVATE void -net_KillConverterProcess (CVG_DataObject *data) -{ - pid_t wait_status; - /* It may not actually be necessary to kill the process here if we have - exited normally, since in that case it has already closed its stdout; - but it can't hurt. - - After it dies, we have to wait() for it, or it becomes a zombie. - I'm not entirely sure that the perror() is correct - it could be that - 0 is a legitimate value from waitpid() if the process had already - exited before we kill()ed it, but I'm not sure. - */ - - kill (data->pid, SIGINT); - wait_status = waitpid (data->pid, 0, 0); -#ifdef DEBUG_dp - fprintf(stderr, "Restoring sigchild handler for pid %d.\n", data->pid); -#endif - /* Reset SIGCHLD signal hander before returning */ - sigaction(SIGCHLD, &data->oldact, NULL); - - if (wait_status != data->pid) - perror ("waitpid"); -} - -PRIVATE void net_ExtConverterComplete (NET_StreamClass *stream) -{ - CVG_DataObject *data = (CVG_DataObject *) stream->data_object; - - /* Send an EOF to the stdin of the subprocess; then wait for the rest - of its output to show up on its stdout; then close stdout, and kill - the process. */ - close (data->outfd); - net_ExtConverterRead (data, PR_TRUE); - close (data->infd); - net_KillConverterProcess (data); - - /* complete the next stream */ - if (data->next_stream) - { - (*data->next_stream->complete) (data->next_stream); - free (data->next_stream); - } - free (data); -} - -PRIVATE void net_ExtConverterAbort (NET_StreamClass *stream, int status) -{ - CVG_DataObject *data = (CVG_DataObject *) stream->data_object; - - /* Close the streams and kill the process, discarding any output still - in the pipe. */ - close (data->outfd); - close (data->infd); - net_KillConverterProcess (data); - - /* abort the next stream */ - if (data->next_stream) - { - (*data->next_stream->abort) (data->next_stream, status); - free (data->next_stream); - } - free (data); -} - - -PUBLIC NET_StreamClass * -NET_ExtConverterConverter (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - CVG_DataObject* obj; - CV_ExtConverterStruct * ext_con_obj = (CV_ExtConverterStruct *) data_obj; - NET_StreamClass* stream; - struct sigaction newact; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - memset(stream, 0, sizeof(NET_StreamClass)); - - obj = PR_NEW(CVG_DataObject); - if (obj == NULL) - return(NULL); - memset(obj, 0, sizeof(CVG_DataObject)); - - stream->name = "Filter Stream"; - stream->complete = (MKStreamCompleteFunc) net_ExtConverterComplete; - stream->abort = (MKStreamAbortFunc) net_ExtConverterAbort; - stream->put_block = (MKStreamWriteFunc) net_ExtConverterWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_ExtConverterWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - /* Open the next stream. - First, swap in the content-encoding or content-type of the document - as we are about to convert it, to look up the proper next converter - (and to avoid looping.) But once we have set up the stream, put the - original encoding back, so that the URL_Struct is not permanently - altered - foo.html.gz must still have content-encoding x-gzip even - though it has been decoded for display. - */ - { - char *old, *new; - if (ext_con_obj->is_encoding_converter) - { - old = URL_s->content_encoding; - new = PL_strdup (ext_con_obj->new_format); - if (!new) return (NULL); - URL_s->content_encoding = new; - } - else - { - old = URL_s->content_type; - new = PL_strdup (ext_con_obj->new_format); - if (!new) return (NULL); - URL_s->content_type = new; - } - - obj->next_stream = NET_StreamBuilder (format_out, URL_s, window_id); - - if (ext_con_obj->is_encoding_converter) - { - PR_Free (URL_s->content_encoding); - URL_s->content_encoding = old; - } - else - { - PR_Free (URL_s->content_type); - URL_s->content_type = old; - } - } - - if (!obj->next_stream) - return (NULL); - - /* Open two pipes, one for writing to a subprocess, and one for reading - from it (for a total of four file descriptors, I/O for us, and O/I - for the kid.) - */ - { - int infds [2]; - int outfds[2]; - pid_t forked; - - if (pipe (infds)) - { - perror ("creating input pipe"); - free (stream); - free (obj); - return 0; - } - if (pipe (outfds)) - { - perror ("creating output pipe"); - free (stream); - free (obj); - return 0; - } - obj->infd = infds [0]; - obj->outfd = outfds [1]; - - /* Set our side of the pipes to be nonblocking. (It's important not - to set the other side of the pipes to be nonblocking - that - decision must be left up to the process on the other end. */ - -#if defined(O_NONBLOCK) -# define NONBLOCK_FLAG O_NONBLOCK -#elif defined(O_NDELAY) -# define NONBLOCK_FLAG O_NDELAY -#else - ERROR!! neither O_NONBLOCK nor O_NDELAY are defined. -#endif - fcntl (obj->infd, F_SETFL, NONBLOCK_FLAG); - fcntl (obj->outfd, F_SETFL, NONBLOCK_FLAG); -#undef NONBLOCK_FLAG - - obj->pid = 0; - -#ifdef DEBUG_dp - fprintf(stderr, "Ignoring sigchild.\n"); -#endif - /* Setup signals so that SIGCHLD is ignored as we want to do waitpid - * when the helperapp ends - */ - newact.sa_handler = SIG_DFL; - newact.sa_flags = 0; - sigfillset(&newact.sa_mask); - sigaction (SIGCHLD, &newact, &obj->oldact); - - switch (forked = fork ()) - { - case -1: - perror ("fork"); - close (outfds[0]); - close (outfds[1]); - close (infds [0]); - close (infds [1]); - free (stream); - free (obj); - /* Reset SIGCHLD signal hander before returning */ - sigaction(SIGCHLD, &obj->oldact, NULL); - return 0; - case 0: - { - /* This is the new process. exec() the filter here. - We do this with sh to get tokenization and pipelines - and all that junk. - */ - char *av[10]; - int ac = 0; - - av [ac++] = "/bin/sh"; - av [ac++] = "-c"; - av [ac++] = ext_con_obj->command; - av [ac++] = 0; - - dup2 (outfds[0], 0); /* stdin */ - dup2 (infds [1], 1); /* stdout */ - /* dup2 (infds [1], 2); * stderr */ - - /* We have copied the two pipes to stdin/stdout. - We no longer need the other file descriptors hanging around. - (Actually I think we need to close these, or the other side - of the pipe doesn't see an eof when we close stdout...) - */ - close (outfds[0]); - close (outfds[1]); - close (infds [0]); - close (infds [1]); - - execv (av[0], av); - /* exec() should never return. */ - perror ("execv"); - exit (1); /* This only exits a child fork. */ - break; - } - default: - /* This is the "old" process (subproc pid is in `forked'.) */ - obj->pid = forked; - - /* These are the file descriptors we created for the benefit - of the child process - we don't need them in the parent. */ - close (outfds[0]); - close (infds [1]); - - break; - } - } - - TRACEMSG(("Returning stream from NET_ExtConverterConverter\n")); - - return stream; -} diff --git a/mozilla/network/cnvts/cvextcon.h b/mozilla/network/cnvts/cvextcon.h deleted file mode 100644 index ad129cf5366..00000000000 --- a/mozilla/network/cnvts/cvextcon.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVEXTCON_H -#define CVEXTCON_H - -typedef struct _CV_ExtConverterStruct { - char * command; - char * new_format; - Bool is_encoding_converter; -} CV_ExtConverterStruct; - -extern NET_StreamClass * -NET_ExtConverterConverter(FO_Present_Types format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* CVEXTCON_H */ diff --git a/mozilla/network/cnvts/cvjscfg.c b/mozilla/network/cnvts/cvjscfg.c deleted file mode 100644 index d722a221846..00000000000 --- a/mozilla/network/cnvts/cvjscfg.c +++ /dev/null @@ -1,341 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "cvjscfg.h" -#include "cvsimple.h" -#include "prefapi.h" -#include "mkutils.h" -#include "netutils.h" -#include "xpgetstr.h" -#include "jsapi.h" -#include "fe_proto.h" -#include "net_xp_file.h" - -static XP_Bool m_GettingConfigFile = FALSE; -static XP_Bool m_FindProxyInJSC = FALSE; -static XP_Bool m_TimesUp = FALSE; - -extern int XP_CONFIG_BLAST_WARNING; -extern int XP_RECEIVING_PROXY_AUTOCFG; -extern int XP_AUTOADMIN_MISSING; -extern int XP_BAD_AUTOCONFIG_NO_FAILOVER; -extern int XP_GLOBAL_EVEN_SAVED_IS_BAD; -extern int XP_CONF_LOAD_FAILED_USE_PREV; - -extern void NET_DisableGetURL(void); - -PRIVATE int jsc_try_failover(MWContext*); -PRIVATE XP_Bool jsc_check_for_find_proxy(void); -extern XP_Bool NET_InitPacfContext(void); - -PRIVATE void AutoAdminRefreshCallback(void *closure) -{ - NET_DownloadAutoAdminCfgFile(); -} - - -/* - * pref_DownloadDone - * Sets 'm_GettingConfigFile' to FALSE, and registers a timeout for - * jsc file polling. - */ -PRIVATE void -pref_DownloadDone(URL_Struct* URL_s, int status, MWContext* window_id) -{ - PRInt32 minutes = 0; - - /* Might have been cancelled by a timeout */ - if ( m_GettingConfigFile == FALSE ) { - return; - } - - m_GettingConfigFile = FALSE; - - if (URL_s->server_status == 0) { - jsc_try_failover(window_id); - m_FindProxyInJSC = jsc_check_for_find_proxy(); - } - - if (PREF_OK == PREF_GetConfigInt("autoadmin.refresh_interval", &minutes)) { - if ( minutes > 0 ) { - FE_SetTimeout((TimeoutCallbackFunction) AutoAdminRefreshCallback, - NULL, minutes * 60 * 1000); - } - } -} - - -/* - * AutoAdminTimeoutCallback - */ -PRIVATE void -AutoAdminTimeoutCallback(void *closure) -{ - m_TimesUp = TRUE; -} - - -/* - * PREF_DownloadConfigFile - * Get the global config file and execute it. - * Called at startup, and at the interval specified by - * "autoadmin.refresh_interval". - * The first time we get this file, we need to loop over FEU_StayingAlive(). - * After that, the main event loop will be happening, so we don't loop - * ourselves, or we'd freeze up the browser. - */ -PUBLIC void -NET_DownloadAutoAdminCfgFile() -{ -#if 0 /* Used to be MODULAR_NETLIB */ - static XP_Bool first_time = TRUE; - XP_Bool append_email; - char* email_addr; - char* url = NULL; - MWContext* context; - -#ifdef MOZ_OFFLINE - if ( NET_IsOffline() ) return; -#endif - - if(first_time) - context = FE_GetInitContext(); - else - context = XP_FindSomeContext(); - - if ( first_time && (NET_InitPacfContext() == FALSE) ) return; - - if (PREF_OK != PREF_CopyConfigString("autoadmin.global_config_url", &url)) { - return; - } - - if (( url == NULL ) || (!(*url))) { - return; - } - - if ( !PREF_IsAutoAdminEnabled() ) { - XP_Bool failover = FALSE; - if (PREF_OK != PREF_GetConfigBool("autoadmin.failover_to_cached", &failover)) { - return; - } - if ( failover == FALSE ) { - NET_DisableGetURL(); - } - FE_Alert(context, XP_GetString(XP_AUTOADMIN_MISSING)); - return; - } - - if (PREF_OK == PREF_GetConfigBool("autoadmin.append_emailaddr", &append_email)) { - if ( append_email ) { - StrAllocCat(url, "?"); - if (PREF_OK == PREF_CopyCharPref("mail.identity.useremail", &email_addr)) { - if ( email_addr ) { - StrAllocCat(url, email_addr); - XP_FREE(email_addr); - } - } - } - } - - if ( url && *url ) { - URL_Struct* url_s = NET_CreateURLStruct(url, NET_SUPER_RELOAD); - - NET_GetURL(url_s, FO_JAVASCRIPT_CONFIG, context, pref_DownloadDone); - - m_GettingConfigFile = TRUE; - - if ( first_time ) { - int32 seconds; - first_time = FALSE; - /* Timeout so we don't hang here */ - if (PREF_OK == PREF_GetConfigInt("autoadmin.timeout", &seconds)) { - if ( seconds > 0 ) { - FE_SetTimeout((TimeoutCallbackFunction) AutoAdminTimeoutCallback, - NULL, seconds * 1000); - } - } - while ( m_GettingConfigFile && !m_TimesUp ) { - FEU_StayingAlive(); - } - if ( m_TimesUp ) { - /* Give up, cause jsc download to fail */ - pref_DownloadDone(url_s, 0, context); - } - } - } -#endif -} - - -/* - * jsc_save - */ -PRIVATE void -jsc_save_config(char* bytes, int32 num_bytes) -{ - XP_File fp; - - if ( bytes == NULL || num_bytes <= 0 ) return; - - if( (fp = NET_XP_FileOpen("", xpJSConfig, XP_FILE_WRITE)) == NULL ) return; - - NET_XP_FileWrite(bytes, num_bytes, fp); - NET_XP_FileClose(fp); -} - - -/* - * jsc_try_failover - */ -PRIVATE int -jsc_try_failover(MWContext* w) -{ - PRBool failover; - char* bytes = NULL; - int32 num_bytes; - XP_StatStruct st; - XP_File fp = NULL; - - if (PREF_OK != PREF_GetConfigBool("autoadmin.failover_to_cached", &failover)) { - goto failed; - } - - if ( failover == FALSE ) { - FE_Alert(w, XP_GetString(XP_BAD_AUTOCONFIG_NO_FAILOVER)); - NET_DisableGetURL(); - return -1; - } - - if ( !FE_Confirm(w, XP_GetString(XP_CONF_LOAD_FAILED_USE_PREV)) ) return -1; - - if (NET_XP_Stat("", &st, xpJSConfig) == -1) goto failed; - - if ( (fp = NET_XP_FileOpen("", xpJSConfig, XP_FILE_READ)) == NULL ) goto failed; - - num_bytes = st.st_size; - - if ( num_bytes <= 0 ) goto failed; - - bytes = (char *)XP_ALLOC(num_bytes + 1); - - if ( bytes == NULL ) goto failed; - - if ( (num_bytes = NET_XP_FileRead(bytes, num_bytes, fp)) <= 0 ) goto failed; - - bytes[num_bytes] = '\0'; - -#ifdef NEW_PREF_ARCH - if ( !PREF_EvaluateConfigScript(bytes, num_bytes, NULL, TRUE, TRUE, FALSE) )goto failed; -#else - if ( !PREF_EvaluateConfigScript(bytes, num_bytes, NULL, TRUE, TRUE) )goto failed; -#endif - - NET_XP_FileClose(fp); - XP_FREEIF(bytes); - - return 0; - -failed: - FE_Alert(w, XP_GetString(XP_GLOBAL_EVEN_SAVED_IS_BAD)); - if ( fp != NULL ) NET_XP_FileClose(fp); - XP_FREEIF(bytes); - return -1; -} - - -/* - * jsc_check_for_find_proxy - */ -PRIVATE XP_Bool -jsc_check_for_find_proxy(void) -{ - JSObject* globalConfig; - JSContext* configContext; - char buf[1024]; - JSBool ok; - jsval rv; - - if (PREF_OK != PREF_GetConfigContext(&configContext) || - PREF_OK != PREF_GetGlobalConfigObject(&globalConfig) ) { - return FALSE; - } - - XP_SPRINTF(buf, "typeof(ProxyConfig.FindProxyForURL) == \"function\""); - ok = JS_EvaluateScript(configContext, globalConfig, buf, strlen(buf), 0, 0, - &rv); - - return (ok && JSVAL_IS_BOOLEAN(rv) && JSVAL_TO_BOOLEAN(rv) == JS_TRUE); -} - - -/* - * jsc_complete - */ -PRIVATE void -jsc_complete(void* bytes, int32 num_bytes) -{ -#ifdef DEBUG_malmer - extern FILE* real_stderr; - - fwrite(bytes, sizeof(char), num_bytes, real_stderr); -#endif - - if ( bytes ) { -#ifdef NEW_PREF_ARCH - PREF_EvaluateConfigScript(bytes, num_bytes, NULL, TRUE, TRUE, FALSE); -#else - PREF_EvaluateConfigScript(bytes, num_bytes, NULL, TRUE, TRUE); -#endif - } else { - /* If failover is ok, read the local cached config */ - } - - /* Need to hash and save to disk here */ -} - - -/* - * NET_JavascriptConfig - */ -MODULE_PRIVATE NET_StreamClass* -NET_JavascriptConfig(int fmt, void* data_obj, URL_Struct* URL_s, MWContext* w) -{ - if ( URL_s == NULL || URL_s->address == NULL ) { - return NULL; - } - - NET_Progress(w, XP_GetString(XP_RECEIVING_PROXY_AUTOCFG)); - - return NET_SimpleStream(fmt, (void*) jsc_complete, URL_s, w); -} - - -/* - * NET_FindProxyInJSC - */ -MODULE_PRIVATE XP_Bool -NET_FindProxyInJSC(void) -{ - return m_FindProxyInJSC; -} - - diff --git a/mozilla/network/cnvts/cvjscfg.h b/mozilla/network/cnvts/cvjscfg.h deleted file mode 100644 index 3b539a4439c..00000000000 --- a/mozilla/network/cnvts/cvjscfg.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* By Daniel Malmer <malmer@netscape.com> */ -#ifndef __mkjscfg_h -#define __mkjscfg_h - -#include "net.h" - -MODULE_PRIVATE NET_StreamClass* -NET_JavascriptConfig(int fmt, void* data_obj, URL_Struct* URL_s, MWContext* w); - -MODULE_PRIVATE XP_Bool NET_FindProxyInJSC(void); - -#endif diff --git a/mozilla/network/cnvts/cvmime.c b/mozilla/network/cnvts/cvmime.c deleted file mode 100644 index 436b789a635..00000000000 --- a/mozilla/network/cnvts/cvmime.c +++ /dev/null @@ -1,1021 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Please leave outside of ifdef for window precompiled headers */ -#include "xp.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "prmem.h" -#include "plstr.h" -#include "net_xp_file.h" - -#ifdef MOZILLA_CLIENT - - -#include "mkstream.h" -#include "cvextcon.h" -#include "mkformat.h" -#include "il_strm.h" /* Image Library stream converters. */ - -#include "mime.h" -#include "cvactive.h" -#include "cvunzip.h" -#include "cvchunk.h" -#include "gui.h" -#include "msgcom.h" -#include "msgnet.h" -#include "mkautocf.h" /* Proxy auto-config */ -#include "cvjscfg.h" /* Javascript config */ -#include "mkhelp.h" - -#include "xlate.h" /* Text and PostScript converters */ -#include "libi18n.h" /* For INTL_ConvCharCode() */ -#include "edt.h" -#include "secnav.h" -#include "intl_csi.h" - - -#include "m_cvstrm.h" -#include "cvmime.h" - -#include "mimeenc.h" - -#include "xpgetstr.h" -extern int XP_EDITOR_NON_HTML; - -#ifdef CRAWLER -/* crawler converters */ -#include "pagescan.h" -#include "crawler.h" -#include "robotxt.h" -#endif - -#ifdef MOZ_MAIL_NEWS -/* #### defined in libmsg/msgutils.c */ -extern NET_StreamClass * -msg_MakeRebufferingStream (NET_StreamClass *next_stream, - URL_Struct *url, - MWContext *context); -#endif /* MOZ_MAIL_NEWS */ - -/* defined at the bottom of this file */ -NET_StreamClass * -NET_PrintRawToDisk(int format_out, - void *data_obj, - URL_Struct *url_struct, - MWContext *context); - -#ifdef MOZ_MAIL_NEWS -typedef struct MIME_DataObject { - MimeDecoderData *decoder; /* State used by the decoder */ - NET_StreamClass *next_stream; /* Where the output goes */ - PRBool partial_p; /* Whether we should close that stream */ -} MIME_DataObject; - - - - - -static int -net_mime_decoder_cb (const char *buf, int32 size, void *closure) -{ - MIME_DataObject *obj = (MIME_DataObject *) closure; - NET_StreamClass *stream = (obj ? obj->next_stream : 0); - if (stream) - return stream->put_block (stream, (char *) buf, size); - else - return 0; -} - -static int -net_MimeEncodingConverterWrite (NET_StreamClass *stream, CONST char* buffer, - int32 length) -{ - MIME_DataObject *obj = (MIME_DataObject *) stream->data_object; - return MimeDecoderWrite (obj->decoder, (char *) buffer, length); -} - - -PRIVATE unsigned int net_MimeEncodingConverterWriteReady (NET_StreamClass *stream) -{ -#if 1 - return (MAX_WRITE_READY); -#else - MIME_DataObject *data = (MIME_DataObject *) stream->data_object; - if(data->next_stream) - return ((*data->next_stream->is_write_ready) - (data->next_stream)); - else - return (MAX_WRITE_READY); -#endif -} - -PRIVATE void net_MimeEncodingConverterComplete (NET_StreamClass *stream) -{ - MIME_DataObject *data = (MIME_DataObject *) stream->data_object; - - if (data->decoder) - { - MimeDecoderDestroy(data->decoder, PR_FALSE); - data->decoder = 0; - } - - /* complete the next stream */ - if (!data->partial_p && data->next_stream) - { - (*data->next_stream->complete) (data->next_stream); - PR_Free (data->next_stream); - } - PR_Free (data); -} - -PRIVATE void net_MimeEncodingConverterAbort (NET_StreamClass *stream, int status) -{ - MIME_DataObject *data = (MIME_DataObject *) stream->data_object; - - if (data->decoder) - { - MimeDecoderDestroy(data->decoder, PR_TRUE); - data->decoder = 0; - } - - /* abort the next stream */ - if (!data->partial_p && data->next_stream) - { - (*data->next_stream->abort) (data->next_stream, status); - PR_Free (data->next_stream); - } - PR_Free (data); -} -#endif /* MOZ_MAIL_NEWS */ - -PRIVATE NET_StreamClass * -NET_MimeEncodingConverter_1 (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id, - PRBool partial_p, - NET_StreamClass *next_stream) -{ -#ifdef MOZ_MAIL_NEWS - MIME_DataObject* obj; - MimeDecoderData *(*fn) (int (*) (const char*, int32, void*), void*) = 0; - - NET_StreamClass* stream; - char *type = (char *) data_obj; - - TRACEMSG(("Setting up encoding stream. Have URL: %s\n", URL_s->address)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - memset(stream, 0, sizeof(NET_StreamClass)); - - obj = PR_NEW(MIME_DataObject); - if (obj == NULL) - return(NULL); - memset(obj, 0, sizeof(MIME_DataObject)); - - if (!PL_strcasecmp (type, ENCODING_QUOTED_PRINTABLE)) - fn = &MimeQPDecoderInit; - else if (!PL_strcasecmp (type, ENCODING_BASE64)) - fn = &MimeB64DecoderInit; - else if (!PL_strcasecmp (type, ENCODING_UUENCODE) || - !PL_strcasecmp (type, ENCODING_UUENCODE2) || - !PL_strcasecmp (type, ENCODING_UUENCODE3) || - !PL_strcasecmp (type, ENCODING_UUENCODE4)) - fn = &MimeUUDecoderInit; - else - abort (); - obj->decoder = fn (net_mime_decoder_cb, obj); - if (!obj->decoder) - { - PR_Free(obj); - return 0; - } - - stream->put_block = net_MimeEncodingConverterWrite; - - stream->name = "Mime Stream"; - stream->complete = net_MimeEncodingConverterComplete; - stream->abort = net_MimeEncodingConverterAbort; - stream->is_write_ready = net_MimeEncodingConverterWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - if (partial_p) - { - PR_ASSERT (next_stream); - obj->next_stream = next_stream; - TRACEMSG(("Using existing stream in NET_MimeEncodingConverter\n")); - } - else - { - PR_ASSERT (!next_stream); - - /* open next stream - */ - PR_FREEIF (URL_s->content_encoding); - obj->next_stream = NET_StreamBuilder (format_out, URL_s, window_id); - - if (!obj->next_stream) - return (NULL); - - /* When uudecoding, we tend to come up with tiny chunks of data - at a time. Make a stream to put them back together, so that - we hand bigger pieces to the image library. - */ - { - NET_StreamClass *buffer = - msg_MakeRebufferingStream (obj->next_stream, URL_s, window_id); - if (buffer) - obj->next_stream = buffer; - } - - TRACEMSG(("Returning stream from NET_MimeEncodingConverter\n")); - } - - return stream; -#else - PR_ASSERT(0); - return(NULL); -#endif /* MOZ_MAIL_NEWS */ -} - - -PUBLIC NET_StreamClass * -NET_MimeEncodingConverter (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - return NET_MimeEncodingConverter_1 (format_out, data_obj, URL_s, window_id, - PR_FALSE, 0); -} - -NET_StreamClass * -NET_MimeMakePartialEncodingConverterStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id, - NET_StreamClass *next_stream) -{ - return NET_MimeEncodingConverter_1 (format_out, data_obj, URL_s, window_id, - PR_TRUE, next_stream); -} - -/* Registers the default things that should be registered cross-platform. - Really this doesn't belong in this file. - */ - - -PRIVATE -NET_StreamClass * -EDT_ErrorOut (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - - FE_Alert(window_id, XP_GetString(XP_EDITOR_NON_HTML)); - - return(NULL); -} - - -PRIVATE void -net_RegisterDefaultDecoders (void) -{ - static PA_InitData parser_data; - -#ifdef XP_UNIX - NET_ClearExternalViewerConverters (); -#endif /* XP_UNIX */ - - /* for the parser/layout functionality - */ -#ifdef EDITOR - parser_data.output_func = EDT_ProcessTag; -#else - parser_data.output_func = LO_ProcessTag; -#endif - - /* Convert the charsets of HTML into the canonical internal form. - */ - NET_RegisterContentTypeConverter (TEXT_HTML, FO_PRESENT, - NULL, INTL_ConvCharCode); - - NET_RegisterContentTypeConverter (TEXT_HTML, FO_PRESENT_INLINE, - NULL, INTL_ConvCharCode); - - /* send all HTML to the editor, everything else as error - */ - NET_RegisterContentTypeConverter (TEXT_HTML, FO_EDIT, - NULL, INTL_ConvCharCode); - - /* send file listings to html converter */ - NET_RegisterContentTypeConverter (APPLICATION_HTTP_INDEX, FO_PRESENT, - NULL, NET_HTTPIndexFormatToHTMLConverter); - - NET_RegisterContentTypeConverter ("*", FO_EDIT, - NULL, EDT_ErrorOut); - - NET_RegisterContentTypeConverter("*", FO_LOAD_HTML_HELP_MAP_FILE, - NULL, NET_HTMLHelpMapToURL); - -#ifdef CRAWLER - NET_RegisterContentTypeConverter(TEXT_HTML, FO_CRAWL_PAGE, - NULL, INTL_ConvCharCode); - - NET_RegisterContentTypeConverter("*", FO_CRAWL_PAGE, - NULL, CRAWL_CrawlerConverter); - - NET_RegisterContentTypeConverter("*", FO_CRAWL_RESOURCE, - NULL, CRAWL_CrawlerResourceConverter); - - NET_RegisterContentTypeConverter("*", FO_ROBOTS_TXT, - NULL, CRAWL_RobotsTxtConverter); -#endif /* CRAWLER */ - - /* this should be windows and mac soon too... */ -#ifdef XP_UNIX - /* the view source converter */ - NET_RegisterContentTypeConverter ("*", FO_VIEW_SOURCE, - TEXT_PLAIN, net_ColorHTMLStream); - NET_RegisterContentTypeConverter (TEXT_HTML, FO_VIEW_SOURCE, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (MESSAGE_RFC822, FO_VIEW_SOURCE, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (MESSAGE_NEWS, FO_VIEW_SOURCE, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_VIEW_SOURCE, - TEXT_HTML, net_ColorHTMLStream); - NET_RegisterContentTypeConverter (APPLICATION_HTTP_INDEX, FO_VIEW_SOURCE, - NULL, NET_HTTPIndexFormatToHTMLConverter); -#endif /* XP_UNIX */ - - NET_RegisterContentTypeConverter (TEXT_HTML, FO_SAVE_AS_TEXT, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (TEXT_HTML, FO_QUOTE_MESSAGE, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (APPLICATION_HTTP_INDEX, FO_QUOTE_MESSAGE, - NULL, NET_HTTPIndexFormatToHTMLConverter); - NET_RegisterContentTypeConverter (APPLICATION_HTTP_INDEX, FO_SAVE_AS_TEXT, - NULL, NET_HTTPIndexFormatToHTMLConverter); - -#ifdef XP_UNIX - NET_RegisterContentTypeConverter (TEXT_HTML, FO_SAVE_AS_POSTSCRIPT, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (APPLICATION_HTTP_INDEX, - FO_SAVE_AS_POSTSCRIPT, - NULL, NET_HTTPIndexFormatToHTMLConverter); -#endif /* XP_UNIX */ - - /* And MDL too, sigh. */ - NET_RegisterContentTypeConverter (TEXT_MDL, FO_PRESENT, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (TEXT_MDL, FO_SAVE_AS_TEXT, - NULL, INTL_ConvCharCode); - NET_RegisterContentTypeConverter (TEXT_MDL, FO_QUOTE_MESSAGE, - NULL, INTL_ConvCharCode); -#ifdef XP_UNIX - NET_RegisterContentTypeConverter (TEXT_MDL, FO_SAVE_AS_POSTSCRIPT, - NULL, INTL_ConvCharCode); -#endif /* XP_UNIX */ - - /* Convert the charsets of plain text into the canonical internal form. - */ - NET_RegisterContentTypeConverter (TEXT_PLAIN, FO_PRESENT, - NULL, NET_PlainTextConverter); - NET_RegisterContentTypeConverter (TEXT_PLAIN, FO_EDIT, - NULL, NET_PlainTextConverter); - NET_RegisterContentTypeConverter (TEXT_PLAIN, FO_QUOTE_MESSAGE, - NULL, NET_PlainTextConverter); - /* don't register TEXT_PLAIN for FO_SAVE_AS_TEXT - * since it is already text - */ -#ifdef XP_UNIX - NET_RegisterContentTypeConverter (TEXT_PLAIN, FO_SAVE_AS_POSTSCRIPT, - NULL, NET_PlainTextConverter); -#endif /* XP_UNIX */ - - /* always treat unknown content types as text/plain */ - NET_RegisterContentTypeConverter (UNKNOWN_CONTENT_TYPE, FO_PRESENT, - NULL, NET_PlainTextConverter); - NET_RegisterContentTypeConverter (UNKNOWN_CONTENT_TYPE, FO_QUOTE_MESSAGE, - NULL, NET_PlainTextConverter); - /* let mail view forms sent via web browsers */ - NET_RegisterContentTypeConverter (APPLICATION_WWW_FORM_URLENCODED, - FO_PRESENT, - NULL, - NET_PlainTextConverter); - -#if defined(MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) -#if defined(XP_MAC) - NET_RegisterContentTypeConverter (MULTIPART_APPLEDOUBLE, FO_SAVE_AS, - NULL, fe_MakeAppleDoubleDecodeStream_1); - NET_RegisterContentTypeConverter (APPLICATION_APPLEFILE, FO_SAVE_AS, - NULL, fe_MakeAppleSingleDecodeStream_1); -#endif -#if defined(XP_MAC) || defined(XP_UNIX) || defined(XP_PC) || defined(XP_BEOS) - /* the new apple single/double and binhex decode. 20oct95 */ - NET_RegisterContentTypeConverter (APPLICATION_BINHEX, FO_PRESENT, - NULL, fe_MakeBinHexDecodeStream); - NET_RegisterContentTypeConverter (MULTIPART_APPLEDOUBLE, FO_PRESENT, - NULL, fe_MakeAppleDoubleDecodeStream_1); - NET_RegisterContentTypeConverter (MULTIPART_HEADER_SET, FO_PRESENT, - NULL, fe_MakeAppleDoubleDecodeStream_1); - NET_RegisterContentTypeConverter (APPLICATION_APPLEFILE, FO_PRESENT, - NULL, fe_MakeAppleSingleDecodeStream_1); - - NET_RegisterContentTypeConverter (UUENCODE_APPLE_SINGLE, FO_PRESENT, - NULL, fe_MakeAppleSingleDecodeStream_1); - NET_RegisterContentTypeConverter (UUENCODE_APPLE_SINGLE, FO_SAVE_AS, - NULL, fe_MakeAppleSingleDecodeStream_1); - -#endif /* XP_MAC || XP_UNIX */ -#endif /* MOZ_MAIL_NEWS || MOZ_MAIL_COMPOSE */ - /* don't register UNKNOWN_CONTENT_TYPE for FO_SAVE_AS_TEXT - * since it is already text - */ -#ifdef XP_UNIX - NET_RegisterContentTypeConverter (UNKNOWN_CONTENT_TYPE, - FO_SAVE_AS_POSTSCRIPT, - NULL, NET_PlainTextConverter); -#endif /* XP_UNIX */ - - - /* Take the canonical internal form and do layout on it. - We do the same thing when the format_out is PRESENT or any of - the SAVE_AS types; the different behavior is gotten by the use - of a different context rather than a different stream. - */ - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_PRESENT, - (void *) &parser_data, PA_BeginParseMDL); - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_PRESENT_INLINE, - (void *) &parser_data, PA_BeginParseMDL); - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_SAVE_AS_TEXT, - (void *) &parser_data, PA_BeginParseMDL); - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_QUOTE_MESSAGE, - (void *) &parser_data, PA_BeginParseMDL); -#ifdef XP_UNIX - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_SAVE_AS_POSTSCRIPT, - (void *) &parser_data, PA_BeginParseMDL); -#endif /* XP_UNIX */ - - /* one for the editor */ - NET_RegisterContentTypeConverter (INTERNAL_PARSER, FO_EDIT, - (void *) &parser_data, PA_BeginParseMDL); - - /* Note that we don't register a converter for "*" to FO_SAVE_AS, - because the FE needs to do that specially to set up an output file. - (The file I/O stuff for SAVE_AS_TEXT and SAVE_AS_POSTSCRIPT is dealt - with by libxlate.a, which could also handle SAVE_AS, but it's probably - not worth the effort.) - */ - - - /* Do the same for the internally-handled image types when the format_out - is SAVE_AS_POSTSCRIPT, because the TEXT->PS code can handle that. But - do not register converters to feed the image types to the HTML->TEXT - code, because that doesn't work. - */ -#ifdef XP_UNIX - NET_RegisterContentTypeConverter (IMAGE_GIF, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - NET_RegisterContentTypeConverter (IMAGE_JPG, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - NET_RegisterContentTypeConverter (IMAGE_PJPG, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - - NET_RegisterContentTypeConverter (IMAGE_PNG, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - - NET_RegisterContentTypeConverter (IMAGE_ART, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - NET_RegisterContentTypeConverter (IMAGE_ART2, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - - NET_RegisterContentTypeConverter (IMAGE_XBM, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - NET_RegisterContentTypeConverter (IMAGE_XBM2, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); - NET_RegisterContentTypeConverter (IMAGE_XBM3, FO_SAVE_AS_POSTSCRIPT, - NULL, IL_ViewStream); -#endif /* XP_UNIX */ - - - /* register default (non)decoders for the text printer - */ - NET_RegisterContentTypeConverter ("*", FO_SAVE_AS_TEXT, - NULL, NET_PrintRawToDisk); - NET_RegisterContentTypeConverter ("*", FO_QUOTE_MESSAGE, - NULL, NET_PrintRawToDisk); -#ifdef XP_UNIX - NET_RegisterContentTypeConverter ("*", FO_SAVE_AS_POSTSCRIPT, - NULL, NET_PrintRawToDisk); -#endif /* XP_UNIX */ - - /* cache things */ - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_PRESENT, - NULL, NET_CacheConverter); - - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_PRESENT_INLINE, - NULL, NET_CacheConverter); - - NET_RegisterContentTypeConverter ("*", FO_CACHE_ONLY, - NULL, NET_CacheConverter); - - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_INTERNAL_IMAGE, - NULL, NET_CacheConverter); - - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_SAVE_AS, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_SAVE_AS_TEXT, - NULL, NET_CacheConverter); -#ifdef XP_UNIX - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_SAVE_AS_POSTSCRIPT, - NULL, NET_CacheConverter); -#endif /* XP_UNIX */ - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_QUOTE_MESSAGE, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_VIEW_SOURCE, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_MAIL_TO, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_EDIT, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_LOAD_HTML_HELP_MAP_FILE, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_SOFTUPDATE, - NULL, NET_CacheConverter); -#ifdef CRAWLER - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_CRAWL_PAGE, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_CRAWL_RESOURCE, - NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_ROBOTS_TXT, - NULL, NET_CacheConverter); -#endif /* CRAWLER */ - - -#ifndef MCC_PROXY - NET_RegisterContentTypeConverter(APPLICATION_NS_PROXY_AUTOCONFIG, - FO_CACHE_AND_PRESENT, - (void *)0, NET_ProxyAutoConfig); - NET_RegisterContentTypeConverter(APPLICATION_NS_PROXY_AUTOCONFIG, - FO_PRESENT, - (void *)0, NET_ProxyAutoConfig); - NET_RegisterContentTypeConverter(APPLICATION_NS_JAVASCRIPT_AUTOCONFIG, - FO_CACHE_AND_PRESENT, - (void *)0, NET_JavascriptConfig); - NET_RegisterContentTypeConverter(APPLICATION_NS_JAVASCRIPT_AUTOCONFIG, - FO_PRESENT, - (void *)0, NET_JavascriptConfig); -#endif - - /* - * call security library to register all security related content - * type converters. - */ - SECNAV_RegisterNetlibMimeConverters(); -#ifdef JAVA - { /* stuff from ns/sun-java/netscape/net/netStubs.c */ - extern void NSN_RegisterJavaConverter(void); - NSN_RegisterJavaConverter(); - } -#endif /* JAVA */ - - /* Register object data handler (see layobj.c) */ - NET_RegisterContentTypeConverter("*", FO_OBJECT, NULL, LO_NewObjectStream); - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_OBJECT, NULL, NET_CacheConverter); - -#ifdef JAVA - /* Castanet stuff can't work in non-java enabled environments */ - /* Register Marimba handler only if netcaster installed */ - if (FE_IsNetcasterInstalled()) { - NET_RegisterContentTypeConverter(APPLICATION_MARIMBA, - FO_PRESENT, - NULL, - NET_DoMarimbaApplication); - - NET_RegisterContentTypeConverter(APPLICATION_XMARIMBA, - FO_PRESENT, - NULL, - NET_DoMarimbaApplication); - } -#endif - - /* RDF */ - { - /* XXX - move these to a header file soon */ -NET_StreamClass * rdf_Converter(FO_Present_Types format_out, void *data_object, URL_Struct *URL_s, MWContext *window_id); -NET_StreamClass * XML_XMLConverter(FO_Present_Types format_out, void *data_object, URL_Struct *URL_s, MWContext *window_id); -NET_StreamClass * XML_CSSConverter(FO_Present_Types format_out, void *data_object, URL_Struct *URL_s, MWContext *window_id); -NET_StreamClass * XML_HTMLConverter(FO_Present_Types format_out, void *data_object, URL_Struct *URL_s, MWContext *window_id); - - NET_RegisterContentTypeConverter( "*", FO_CACHE_AND_RDF, NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter( "*", FO_RDF, NULL, rdf_Converter); - - /* XML for direct presentation */ - - NET_RegisterContentTypeConverter (TEXT_XML, FO_CACHE_AND_PRESENT, NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter (TEXT_XML, FO_PRESENT, NULL, XML_XMLConverter); - NET_RegisterContentTypeConverter (TEXT_XML, FO_EDIT, NULL, XML_XMLConverter); - NET_RegisterContentTypeConverter ("*", FO_XMLHTML, NULL, XML_HTMLConverter); - NET_RegisterContentTypeConverter ("*", FO_XMLCSS, NULL, XML_CSSConverter); - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_XMLHTML, NULL, NET_CacheConverter); - NET_RegisterContentTypeConverter ("*", FO_CACHE_AND_XMLCSS, NULL, NET_CacheConverter); - } - -} - - -PRIVATE void -net_RegisterDefaultEncodingDecoders (void) -{ - /* Register the decompression content-encoding converters for those - types which are displayed internally. */ - NET_RegisterAllEncodingConverters (INTERNAL_PARSER, FO_PRESENT); - NET_RegisterAllEncodingConverters (TEXT_HTML, FO_PRESENT); - NET_RegisterAllEncodingConverters (TEXT_MDL, FO_PRESENT); - NET_RegisterAllEncodingConverters (TEXT_PLAIN, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_GIF, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_JPG, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_PJPG, FO_PRESENT); - - NET_RegisterAllEncodingConverters (IMAGE_PNG, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_ART, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_ART2, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_XBM, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_XBM2, FO_PRESENT); - NET_RegisterAllEncodingConverters (IMAGE_XBM3, FO_PRESENT); - /* always treat unknown content types as text/plain */ - NET_RegisterAllEncodingConverters (UNKNOWN_CONTENT_TYPE, FO_PRESENT); - - /* when displaying anything in a news mime-multipart image - * de compress it first - */ - NET_RegisterAllEncodingConverters ("*", FO_MULTIPART_IMAGE); - - /* When saving anything as Text or PostScript, it's necessary to - uncompress it first. */ - NET_RegisterAllEncodingConverters ("*", FO_SAVE_AS_TEXT); -# ifdef XP_UNIX - NET_RegisterAllEncodingConverters ("*", FO_SAVE_AS_POSTSCRIPT); -# endif /* XP_UNIX */ - - /* Whenever we save text or HTML to disk, we uncompress it first, - because the rules we decided upon is: - - - When Netscape saves text/plain or text/html documents to a - user-specified file, they are always uncompressed first. - - - When Netscape saves any other kind of document to a user-specified - file, it is always saved in its compressed state. - - - When Netscape saves a document to a temporary file before handing - it off to an external viewer, it is always uncompressed first. - */ - NET_RegisterAllEncodingConverters (TEXT_HTML, FO_SAVE_AS); - NET_RegisterAllEncodingConverters (TEXT_MDL, FO_SAVE_AS); - NET_RegisterAllEncodingConverters (TEXT_PLAIN, FO_SAVE_AS); - NET_RegisterAllEncodingConverters (INTERNAL_PARSER, FO_SAVE_AS); - /* always treat unknown content types as text/plain */ - NET_RegisterAllEncodingConverters (UNKNOWN_CONTENT_TYPE, FO_SAVE_AS); -} - - -PUBLIC void -NET_RegisterMIMEDecoders (void) -{ - net_RegisterDefaultDecoders (); - - NET_RegisterEncodingConverter (ENCODING_GZIP, - (void *) ENCODING_GZIP, - NET_UnZipConverter); - NET_RegisterEncodingConverter (ENCODING_GZIP2, - (void *) ENCODING_GZIP2, - NET_UnZipConverter); - NET_RegisterEncodingConverter (ENCODING_QUOTED_PRINTABLE, - (void *) ENCODING_QUOTED_PRINTABLE, - NET_MimeEncodingConverter); - NET_RegisterEncodingConverter (ENCODING_BASE64, - (void *) ENCODING_BASE64, - NET_MimeEncodingConverter); -#ifndef IRIX_STARTUP_SPEEDUPS - NET_RegisterEncodingConverter (ENCODING_UUENCODE, - (void *) ENCODING_UUENCODE, - NET_MimeEncodingConverter); - NET_RegisterEncodingConverter (ENCODING_UUENCODE2, - (void *) ENCODING_UUENCODE2, - NET_MimeEncodingConverter); -#endif - NET_RegisterEncodingConverter (ENCODING_UUENCODE3, - (void *) ENCODING_UUENCODE3, - NET_MimeEncodingConverter); -#ifndef IRIX_STARTUP_SPEEDUPS - NET_RegisterEncodingConverter (ENCODING_UUENCODE4, - (void *) ENCODING_UUENCODE4, - NET_MimeEncodingConverter); -#endif - -#if defined(SMART_MAIL) || defined(XP_UNIX) - /* #### This should really be done all the time, because all versions of - Mozilla should be able to sensibly display documents of type - message/rfc822. But I don't know what Makefile arcanity has happened on - Windows, so for now, this only gets called if SMART_MAIL is defined, or - if we're on Unix. Someone please fix this on non-SmartMail Windows, and - on Mac. - */ - - /* Decoders for libmime/mimemoz.c */ - MIME_RegisterConverters(); -#endif /* SMART_MAIL */ - -#if defined(MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) - /* Decoders for libmsg/compose.c */ - MSG_RegisterConverters (); -#endif - - NET_RegisterUniversalEncodingConverter("chunked", - NULL, - NET_ChunkedDecoderStream); - - NET_RegisterContentTypeConverter("multipart/x-mixed-replace", - FO_CACHE_AND_PRESENT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - NET_RegisterContentTypeConverter("multipart/x-mixed-replace", - FO_CACHE_AND_PRINT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - NET_RegisterContentTypeConverter("multipart/x-mixed-replace", - FO_CACHE_AND_INTERNAL_IMAGE, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - NET_RegisterContentTypeConverter("multipart/x-byteranges", - FO_CACHE_AND_PRESENT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - NET_RegisterContentTypeConverter("multipart/byteranges", - FO_CACHE_AND_PRESENT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - NET_RegisterContentTypeConverter("multipart/mixed", - FO_CACHE_AND_PRESENT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - - net_RegisterDefaultEncodingDecoders (); -} - - -#if 0 -void -main () -{ - unsigned char *s; - int32 i; -#define TEST(S) \ - /*MIME_EncodeBase64String*/ \ - MIME_EncodeQuotedPrintableString \ - (S, strlen(S), &s, &i); \ - printf ("---------\n" \ - "%s\n" \ - "---------\n" \ - "%s\n" \ - "---------\n", \ - S, s); \ - free(s) - - TEST("ThisThisThisThis\n" - "This is a line with a c\238ntr\001l character in it.\n" - "This line has whitespace at EOL. \n" - "This is a long line. All work and no play makes Jack a dull boy. " - "All work and no play makes Jack a dull boy. " - "All work and no play makes Jack a dull boy. " - "All work and no play makes Jack a dull boy. \n" - "\n" - "Here's an equal sign: =\n" - "and here's a return\r..." - "Now make it realloc:" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" - ); -} -#endif - -typedef struct _NET_PrintRawToDiskStruct { - XP_File fp; - MWContext *context; - int32 content_length; - int32 bytes_read; - int16 mail_csid; - int16 win_csid; - CCCDataObject conv; - PRBool doConvert; -} NET_PrintRawToDiskStruct; - -/* this converter uses the - * (context->prSetup->filename) variable to - * open the filename specified and save all data raw to - * the file. - */ -PRIVATE -int -net_PrintRawToDiskWrite (NET_StreamClass *stream, CONST char *str, int32 len) -{ - NET_PrintRawToDiskStruct *obj = (NET_PrintRawToDiskStruct *) stream->data_object; - char *newStr = NULL; - int32 origLen = len; - int32 rv = 0; - - if (obj->doConvert) - { - char *dupStr = (char *) PR_Malloc(len+1); - - if (dupStr) - { - memcpy(dupStr, str, len); - *(dupStr + len) = 0; - newStr = (char *) INTL_CallCharCodeConverter(obj->conv, - (unsigned char *)dupStr, - len); - if (!newStr) - newStr = dupStr; - else if (newStr != dupStr) - PR_Free(dupStr); - - if (newStr) - { - str = newStr; - len = INTL_GetCCCLen(obj->conv); - } - } - } - -/* int32 rv = fwrite ((char *) str, 1, len, obj->fp);*/ - rv = NET_XP_FileWrite(str, len, obj->fp); - - if (newStr) - PR_Free(newStr); - - obj->bytes_read += origLen; - - if (obj->content_length > 0) - FE_SetProgressBarPercent (obj->context, - (obj->bytes_read * 100) / - obj->content_length); - - if(rv == len) - return(0); - else - return(-1); -} - -PRIVATE unsigned int -net_PrintRawToDiskIsWriteReady (NET_StreamClass *stream) -{ - return(MAX_WRITE_READY); -} - -PRIVATE void -net_PrintRawToDiskComplete (NET_StreamClass *stream) -{ - NET_PrintRawToDiskStruct *obj = (NET_PrintRawToDiskStruct *) stream->data_object; - - if (obj->conv) { - INTL_DestroyCharCodeConverter(obj->conv); - obj->conv = NULL; - } - - /* NET_XP_FileClose(obj->fp); DONT DO THIS the FE's do this */ -} - -PRIVATE void -net_PrintRawToDiskAbort (NET_StreamClass *stream, int status) -{ - NET_PrintRawToDiskStruct *obj = (NET_PrintRawToDiskStruct *) stream->data_object; - - if (obj->conv) { - INTL_DestroyCharCodeConverter(obj->conv); - obj->conv = NULL; - } - - /* NET_XP_FileClose(obj->fp); DONT DO THIS the FE's do this */ -} - -/* this converter uses the - * (context->prSetup->out) file pointer variable to - * save all data raw to the file. - */ -PUBLIC NET_StreamClass * -NET_PrintRawToDisk(int format_out, - void *data_obj, - URL_Struct *url_struct, - MWContext *context) -{ - NET_PrintRawToDiskStruct *obj = PR_NEW(NET_PrintRawToDiskStruct); - NET_StreamClass * stream; - INTL_CharSetInfo csi = NULL; - char *mime_charset = NULL; - - if(!obj) - return(NULL); - - memset(obj, 0, sizeof(NET_PrintRawToDiskStruct)); - - if(!context->prSetup || !context->prSetup->out) - { - PR_Free(obj); - return NULL; - } - -#ifdef NOT /* file ptr should already be open in context->prSetup->out */ - if(!(obj->fp = NET_XP_FileOpen(context->prSetup->filename, - xpTemporary, - XP_FILE_WRITE_BIN))) - { - PR_Free(obj); - return NULL; - } -#endif - - obj->fp = context->prSetup->out; - - obj->context = context; - obj->content_length = url_struct->content_length; - - stream = (NET_StreamClass *) PR_NEW(NET_StreamClass); - if (!stream) - { - PR_Free(obj); - return NULL; - } - - memset(stream, 0, sizeof(NET_StreamClass)); - - stream->name = "PrintRawToDisk"; - stream->complete = net_PrintRawToDiskComplete; - stream->abort = net_PrintRawToDiskAbort; - stream->put_block = net_PrintRawToDiskWrite; - stream->is_write_ready = net_PrintRawToDiskIsWriteReady; - stream->data_object = obj; - stream->window_id = context; - - csi = LO_GetDocumentCharacterSetInfo(context); - mime_charset = INTL_GetCSIMimeCharset(csi); - if (mime_charset && *(mime_charset)) - { - obj->conv = INTL_CreateCharCodeConverter(); - obj->mail_csid = INTL_CharSetNameToID(mime_charset); - obj->win_csid = INTL_DocToWinCharSetID(obj->mail_csid); - - if (obj->conv) - obj->doConvert = INTL_GetCharCodeConverter(obj->mail_csid, - obj->win_csid, - obj->conv); - } - - return(stream); -} - - - - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cnvts/cvmime.h b/mozilla/network/cnvts/cvmime.h deleted file mode 100644 index 420deaa4abc..00000000000 --- a/mozilla/network/cnvts/cvmime.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVMIME_H -#define CVMIME_H - -extern NET_StreamClass * -NET_MimeEncodingConverter(int, void *, URL_Struct *, MWContext *); - -#endif /* CVMIME_H */ diff --git a/mozilla/network/cnvts/cvpics.c b/mozilla/network/cnvts/cvpics.c deleted file mode 100644 index e9c11722f3a..00000000000 --- a/mozilla/network/cnvts/cvpics.c +++ /dev/null @@ -1,386 +0,0 @@ - -/* this set of functions parses an incoming stream of HTML and tries to find - * any PICS label within it. It doesn't do anything accept parse the pics label - * and finish - */ -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "pa_parse.h" -#include "xpgetstr.h" -#include "layout.h" -#include "pics.h" - -typedef enum StatesEnum { - IN_CONTENT, - IN_SCRIPT, - ABOUT_TO_BEGIN_TAG, - IN_BEGIN_TAG, - IN_TAG, - BEGIN_ATTRIBUTE_VALUE, - IN_QUOTED_ATTRIBUTE_VALUE, - IN_BROKEN_QUOTED_ATTRIBUTE_VALUE, - IN_UNQUOTED_ATTRIBUTE_VALUE, - IN_COMMENT, - IN_AMPERSAND_THINGY -} StatesEnum; - -#define MAXTAGLEN 15 - -typedef struct _DataObject { - MWContext *context; - URL_Struct *URL_s; - StatesEnum state; - char tag[MAXTAGLEN+1]; - uint tag_index; - int tag_type; - PRBool in_broken_html; - char *tag_data; /* the contents of the current tag */ -} DataObject; - -extern int MK_CVCOLOR_SOURCE_OF; - -PRIVATE void net_BeginPICSLabelFinderTag (DataObject *obj) -{ - if(obj->tag_data) - *obj->tag_data = '\0'; /* empty tag_data */ - - if (obj->tag_type == P_SCRIPT) - { - obj->tag_type = P_UNKNOWN; - } - obj->state = ABOUT_TO_BEGIN_TAG; - return ; -} - -PRIVATE void net_EndPICSLabelFinderTag (DataObject *obj) -{ - if(obj->in_broken_html) - { - obj->in_broken_html = PR_FALSE; - } - - if (obj->tag_type == P_SCRIPT) - { - obj->state = IN_SCRIPT; - } - else - { - obj->state = IN_CONTENT; - } - - /* check tag_data for a META tag */ - if(obj->tag_data && !PL_strncasecmp(obj->tag_data, "META", 4)) - { - PA_Tag tmp_tag; - char *name; - - tmp_tag.type = P_META; - tmp_tag.data = (void*)obj->tag_data; - tmp_tag.data_len = PL_strlen((char*)tmp_tag.data); - - name = (char *)lo_FetchParamValue(obj->context, &tmp_tag, PARAM_HTTP_EQUIV); - -#define PICS_HEADER "PICS-Label" - if(name && !PL_strcasecmp(name, PICS_HEADER)) - { - char *label = (char *)lo_FetchParamValue(obj->context, &tmp_tag, PARAM_CONTENT); - - if(label) - { - PICS_RatingsStruct * rs = PICS_ParsePICSLable(label); - PR_Free(label); - PICS_CompareToUserSettings(rs, obj->URL_s->address); - PICS_FreeRatingsStruct(rs); /* handles NULL */ - } - } - - PR_FREEIF(name); - } - - return; -} - -PRIVATE int net_PICSLabelFinderWrite (NET_StreamClass *stream, CONST char *s, int32 l) -{ - int32 i; - CONST char *cp; - DataObject *obj = (DataObject *)stream->data_object; - char tiny_buf[8]; - - for(i = 0, cp = s; i < l; i++, cp++) - { - switch(obj->state) - { - case IN_CONTENT: - /* do nothing until you find a '<' "<!--" or '&' */ - if(*cp == '<') - { - /* XXX we can miss a comment spanning a block boundary */ - if(i+4 <= l && !PL_strncmp(cp, "<!--", 4)) - { - obj->state = IN_COMMENT; - } - else - { - net_BeginPICSLabelFinderTag(obj); - } - } - else if(*cp == '&') - { - obj->state = IN_AMPERSAND_THINGY; - } - break; - case IN_SCRIPT: - /* do nothing until you find '</SCRIPT>' */ - if(*cp == '<') - { - /* XXX we can miss a </SCRIPT> spanning a block boundary */ - if(i+8 <= l && !PL_strncasecmp(cp, "</SCRIPT", 8)) - { - net_BeginPICSLabelFinderTag(obj); - } - } - break; - case ABOUT_TO_BEGIN_TAG: - /* we have seen the first '<' - * once we see a non-whitespace character - * we will be in the tag identifier - */ - if(*cp == '>') - { - net_EndPICSLabelFinderTag(obj); - } - else if(!NET_IS_SPACE(*cp)) - { - /* capture all tag data */ - tiny_buf[0] = *cp; - tiny_buf[1] = '\0'; - StrAllocCat(obj->tag_data, tiny_buf); - - obj->state = IN_BEGIN_TAG; - obj->tag_index = 0; - obj->tag[obj->tag_index++] = *cp; - - } - break; - case IN_BEGIN_TAG: - /* go to the IN_TAG state when we see - * the first whitespace - */ - - /* capture all tag data */ - tiny_buf[0] = *cp; - tiny_buf[1] = '\0'; - StrAllocCat(obj->tag_data, tiny_buf); - - if(NET_IS_SPACE(*cp)) - { - obj->state = IN_TAG; - obj->tag[obj->tag_index] = '\0'; - obj->tag_type = pa_tokenize_tag(obj->tag); - } - else if(*cp == '>') - { - net_EndPICSLabelFinderTag(obj); - } - else if(*cp == '<') - { - /* protect ourselves from markup */ - if(!obj->in_broken_html) - { - obj->in_broken_html = PR_TRUE; - } - } - else - { - if (obj->tag_index < MAXTAGLEN) - obj->tag[obj->tag_index++] = *cp; - } - break; - case IN_TAG: - /* capture all tag data */ - tiny_buf[0] = *cp; - tiny_buf[1] = '\0'; - StrAllocCat(obj->tag_data, tiny_buf); - - /* do nothing until you find a opening '=' or end '>' */ - if(*cp == '=') - { - obj->state = BEGIN_ATTRIBUTE_VALUE; - } - else if(*cp == '>') - { - net_EndPICSLabelFinderTag(obj); - } - break; - case BEGIN_ATTRIBUTE_VALUE: - /* capture all tag data */ - tiny_buf[0] = *cp; - tiny_buf[1] = '\0'; - StrAllocCat(obj->tag_data, tiny_buf); - - /* when we reach the first non-whitespace - * we will enter the UNQUOTED or the QUOTED - * ATTRIBUTE state - */ - if(!NET_IS_SPACE(*cp)) - { - if(*cp == '"') - { - obj->state = IN_QUOTED_ATTRIBUTE_VALUE; - /* no need to jump to the quoted attr handler - * since this char can't be a dangerous char - */ - } - else - { - obj->state = IN_UNQUOTED_ATTRIBUTE_VALUE; - /* need to jump to the unquoted attr handler - * since this char can be a dangerous character - */ - goto unquoted_attribute_jump_point; - } - } - else if(*cp == '>') - { - net_EndPICSLabelFinderTag(obj); - } - break; - case IN_UNQUOTED_ATTRIBUTE_VALUE: - /* capture all tag data */ - tiny_buf[0] = *cp; - tiny_buf[1] = '\0'; - StrAllocCat(obj->tag_data, tiny_buf); - -unquoted_attribute_jump_point: - /* do nothing until you find a whitespace */ - if(NET_IS_SPACE(*cp)) - { - obj->state = IN_TAG; - } - else if(*cp == '>') - { - net_EndPICSLabelFinderTag(obj); - } - break; - case IN_QUOTED_ATTRIBUTE_VALUE: - /* capture all tag data */ - tiny_buf[0] = *cp; - tiny_buf[1] = '\0'; - StrAllocCat(obj->tag_data, tiny_buf); - - /* do nothing until you find a closing '"' */ - if(*cp == '\"') - { - if(obj->in_broken_html) - { - obj->in_broken_html = PR_FALSE; - } - obj->state = IN_TAG; - } - else if(*cp == '>') - { - /* probably a broken attribute value */ - if(!obj->in_broken_html) - { - obj->in_broken_html = PR_TRUE; - } - } - break; - case IN_COMMENT: - /* do nothing until you find a closing '-->' */ - if(!PL_strncmp(cp, "-->", 3)) - { - cp += 2; - i += 2; - obj->state = IN_CONTENT; - } - break; - case IN_AMPERSAND_THINGY: - /* do nothing until you find a ';' or space */ - if(*cp == ';' || NET_IS_SPACE(*cp)) - { - sprintf(tiny_buf, "%c", *cp); - obj->state = IN_CONTENT; - } - break; - default: - PR_ASSERT(0); - break; - } - - } - - return(0); -} - -/* is the stream ready for writeing? - */ -PRIVATE unsigned int net_PICSLabelFinderWriteReady (NET_StreamClass *stream) -{ - return(MAX_WRITE_READY); -} - - -PRIVATE void net_PICSLabelFinderComplete (NET_StreamClass *stream) -{ -} - -PRIVATE void net_PICSLabelFinderAbort (NET_StreamClass *stream, int status) -{ -} - -PUBLIC NET_StreamClass * -net_PICSLabelFinderStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - DataObject* obj; - NET_StreamClass *new_stream; - PRBool is_html_stream = PR_FALSE; - - TRACEMSG(("Setting up PICSLabelFinder stream. Have URL: %s\n", URL_s->address)); - - new_stream = PR_NEWZAP(NET_StreamClass); - - if(!new_stream) - return NULL; - - obj = PR_NEW(DataObject); - - if (obj == NULL) - { - PR_Free(new_stream); - return(NULL); - } - - memset(obj, 0, sizeof(DataObject)); - - obj->state = IN_CONTENT; - - obj->tag_type = P_UNKNOWN; - - obj->context = window_id; - obj->URL_s = URL_s; - - new_stream->name = "PICSLabelFinder"; - new_stream->complete = (MKStreamCompleteFunc) net_PICSLabelFinderComplete; - new_stream->abort = (MKStreamAbortFunc) net_PICSLabelFinderAbort; - new_stream->put_block = (MKStreamWriteFunc) net_PICSLabelFinderWrite; - new_stream->is_write_ready = (MKStreamWriteReadyFunc) - net_PICSLabelFinderWriteReady; - new_stream->data_object = (void *) obj; /* document info object */ - new_stream->window_id = window_id; - - /* don't cache this URL, since the content type is wrong */ - URL_s->dont_cache = PR_TRUE; - - return new_stream; -} diff --git a/mozilla/network/cnvts/cvpics.h b/mozilla/network/cnvts/cvpics.h deleted file mode 100644 index 919ea4e8f05..00000000000 --- a/mozilla/network/cnvts/cvpics.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVPICS_H -#define CVPICS_H - -PUBLIC NET_StreamClass * -net_PICSLabelFinderStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* CVPICS_H */ diff --git a/mozilla/network/cnvts/cvplugin.cpp b/mozilla/network/cnvts/cvplugin.cpp deleted file mode 100644 index 4e17197e72e..00000000000 --- a/mozilla/network/cnvts/cvplugin.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -#include "xp.h" -#include "np.h" -#include "prmem.h" -#include "plstr.h" -#include "nsINetPlugin.h" -#include "nsINetPluginInstance.h" -#include "nsIComponentManager.h" -#include "nsNetConverterStream.h" -#include "nsCOMPtr.h" -#include "nscore.h" - -static NS_DEFINE_CID(kINetPluginCID, NS_INET_PLUGIN_CID); - -static NS_DEFINE_IID(kINetPluginInstanceIID, NS_INETPLUGININSTANCE_IID); -static NS_DEFINE_IID(kINetOStreamIID, NS_INETOSTREAM_IID); - - -PRIVATE void -plugin_stream_complete(NET_StreamClass *stream) -{ - nsINetOStream *instance_stream = (nsINetOStream *)stream->data_object; - - instance_stream->Complete(); - // mscott -- release instance_stream because we are done with it.. - // the owner of the NET_Stream object just frees the struct.. - NS_RELEASE(instance_stream); -} - - -PRIVATE void -plugin_stream_abort(NET_StreamClass *stream, int status) -{ - nsINetOStream *instance_stream = (nsINetOStream *)stream->data_object; - - instance_stream->Abort(status); - // mscott -- release instance_stream because we are done with it.. - // the owner of the NET_Stream object just frees the struct.. - NS_RELEASE(instance_stream); -} - - -PRIVATE int -plugin_stream_write(NET_StreamClass *stream, const char* str, int32 len) -{ - nsINetOStream *instance_stream = (nsINetOStream *)stream->data_object; - nsresult res; - int32 written; - - res = instance_stream->Write(str, (unsigned int)len, (unsigned int *)&written); - if (res == NS_OK) - { - return written; - } - return -1; -} - - -PRIVATE unsigned int -plugin_stream_write_ready(NET_StreamClass *stream) -{ - nsINetOStream *instance_stream = (nsINetOStream *)stream->data_object; - nsresult res; - unsigned int ready; - - res = instance_stream->WriteReady(&ready); - if (res == NS_OK) - { - return ready; - } - return 0; -} - - -typedef struct UsedConverter { - void *data_id; - char *mime_type; - struct UsedConverter *next; -} UsedConverter; -UsedConverter *RegisteredConverters = NULL; - -PRIVATE PRBool -register_converter(char *mime_type, void *data_id) -{ - UsedConverter *converter = RegisteredConverters; - - if ((mime_type == NULL)||(data_id == NULL)) - { - return PR_FALSE; - } - - while (converter != NULL) - { - if ((converter->data_id == data_id)&& - (PL_strcmp(converter->mime_type, mime_type) == 0)) - { - return PR_FALSE; - } - converter = converter->next; - } - converter = PR_NEWZAP(UsedConverter); - converter->mime_type = PL_strdup(mime_type); - converter->data_id = data_id; - converter->next = RegisteredConverters; - RegisteredConverters = converter; - return PR_TRUE; -} - - -PRIVATE void -unregister_converter(char *mime_type, void *data_id) -{ - UsedConverter *converter = RegisteredConverters; - UsedConverter *last_converter = NULL; - - if ((mime_type == NULL)||(data_id == NULL)) - { - return; - } - while (converter != NULL) - { - if ((converter->data_id == data_id)&& - (PL_strcmp(converter->mime_type, mime_type) == 0)) - { - if (last_converter == NULL) - { - RegisteredConverters = converter->next; - } - else - { - last_converter->next = converter->next; - } - PR_FREEIF(converter->mime_type); - PR_FREEIF(converter); - return; - } - last_converter = converter; - converter = converter->next; - } -} - - -extern "C" NET_StreamClass * NET_PluginStream(int fmt, void* data_obj, URL_Struct* URL_s, MWContext* w); - -extern "C" NET_StreamClass * -NET_PluginStream(int fmt, void* data_obj, URL_Struct* URL_s, MWContext* w) -{ - PRBool can_use, error = PR_FALSE; - char *mime_type; - const char *mime_type_out; - NET_StreamClass *new_stream = NULL; - NET_StreamClass *next_stream = NULL; - nsCOMPtr <nsINetPluginInstance> plugin_inst; - nsINetOStream *instance_stream; - nsINetOStream *out_stream; - nsNetConverterStream *converter_stream; - nsCID classID = {0}; - nsresult rv = NS_OK; - - if (URL_s->transfer_encoding != NULL) - { - mime_type = XP_STRDUP(URL_s->transfer_encoding); - PR_FREEIF(URL_s->transfer_encoding); - } - else if (URL_s->content_encoding != NULL) - { - mime_type = XP_STRDUP(URL_s->content_encoding); - PR_FREEIF(URL_s->content_encoding); - } - else - { - mime_type = XP_STRDUP(URL_s->content_type); - } - - can_use = register_converter(mime_type, (void *)URL_s); - if (can_use == PR_FALSE) - { - PR_FREEIF(mime_type); - return NULL; - } - - do { - if (nsComponentManager::ProgIDToCLSID(mime_type, &classID) != NS_OK) - { - error = PR_TRUE; - break; - } - - nsComponentManager::CreateInstance(classID, (nsISupports *)nsnull, kINetPluginInstanceIID, (void **) getter_AddRefs(plugin_inst)); - - if (!plugin_inst) - { - error = PR_TRUE; - break; - } - - plugin_inst->GetMIMEOutput(&mime_type_out, URL_s->address); - - if (mime_type_out != NULL) - { - PR_FREEIF(URL_s->content_type); - URL_s->content_type = XP_STRDUP(mime_type_out); - } - next_stream = NET_StreamBuilder(fmt, URL_s, w); - - converter_stream = new nsNetConverterStream(); - if (converter_stream == NULL) - { - error = PR_TRUE; - break; - } - - converter_stream->Initialize((void *)next_stream); - rv = converter_stream->QueryInterface(kINetOStreamIID, (void **)&out_stream); - if (NS_FAILED(rv)) - { - delete converter_stream; - error = PR_TRUE; - break; - } - - plugin_inst->Initialize(out_stream, URL_s->address); - rv = plugin_inst->QueryInterface(kINetOStreamIID, (void **)&instance_stream); - if (NS_FAILED(rv)) - { - delete converter_stream; - error = PR_TRUE; - break; - } - } while (0); - - if (error) - { - unregister_converter(mime_type, (void *)URL_s); - PR_FREEIF(mime_type); - return NULL; - } - - new_stream = NET_NewStream("PluginStream", plugin_stream_write, plugin_stream_complete, plugin_stream_abort, plugin_stream_write_ready, (void *)instance_stream, w); - - unregister_converter(mime_type, (void *)URL_s); - PR_FREEIF(mime_type); - return new_stream; -} - diff --git a/mozilla/network/cnvts/cvplugin.h b/mozilla/network/cnvts/cvplugin.h deleted file mode 100644 index ae00db01aa7..00000000000 --- a/mozilla/network/cnvts/cvplugin.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -#ifndef CVPLUGIN_H -#define CVPLUGIN_H - -#include "ntypes.h" - -extern NET_StreamClass * -NET_PluginStream(int format_out, void* data_obj, - URL_Struct* URL_s, MWContext* window_id); - -#endif /* CVPLUGIN_H */ diff --git a/mozilla/network/cnvts/cvproxy.c b/mozilla/network/cnvts/cvproxy.c deleted file mode 100644 index 58513908668..00000000000 --- a/mozilla/network/cnvts/cvproxy.c +++ /dev/null @@ -1,137 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "xp.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "mkstream.h" - -typedef struct _ProxyObj { - PRBool past_first_line; - PRBool definately_send_headers; - char *content_type; - char *content_encoding; -} ProxyObj; - -PRIVATE int net_proxy_write (NET_StreamClass *stream, CONST char* s, int32 len) -{ - ProxyObj *obj=stream->data_object; - /* send HTTP headers if not already getting an HTTP doc - */ - if(!obj->past_first_line) - { - if(obj->definately_send_headers || strncmp(s, "HTTP/", len >= 5 ? 5 : len)) - { - write(1, "HTTP/1.0 200 OK\r\n",17); - write(1, "Content-type: ",14); - write(1, obj->content_type, PL_strlen(obj->content_type)); - if(obj->content_encoding) - { - write(1, "\r\nContent-encoding: ",18); - write(1, obj->content_encoding, PL_strlen(obj->content_encoding)); - } - write(1, "\r\nServer: MKLib proxy agent\r\n",29); - write(1, "\r\n", 2); /* finish it */ - } - - obj->past_first_line = PR_TRUE; - } - - write(1, s, len); - return(1); -} - -PRIVATE unsigned int net_proxy_WriteReady (NET_StreamClass *stream) -{ - return(MAX_WRITE_READY); /* always ready for writing */ -} - - -PRIVATE void net_proxy_complete (NET_StreamClass *stream) -{ - ProxyObj *obj=stream->data_object; - FREEIF(obj->content_type); - FREEIF(obj->content_encoding); - FREE(obj); - return; -} - -PRIVATE void net_proxy_abort (NET_StreamClass *stream, int status) -{ - ProxyObj *obj=stream->data_object; - FREEIF(obj->content_type); - FREEIF(obj->content_encoding); - FREE(obj); - return; -} - - - -PUBLIC NET_StreamClass * -NET_ProxyConverter(int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - NET_StreamClass* stream; - ProxyObj * obj; - - TRACEMSG(("Setting up display stream. Have URL: %s \n%s\n", - URL_s->address, URL_s->content_type)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEW(ProxyObj); - if(obj == NULL) - { - FREE(stream); - return(NULL); - } - - memset(obj, 0, sizeof(ProxyObj)); - - stream->data_object = obj; - - - stream->name = "ProxyWriter"; - stream->complete = (MKStreamCompleteFunc) net_proxy_complete; - stream->abort = (MKStreamAbortFunc) net_proxy_abort; - stream->put_block = (MKStreamWriteFunc) net_proxy_write; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_proxy_WriteReady; - stream->window_id = window_id; - - TRACEMSG(("Returning stream from display_converter\n")); - - /* send HTTP headers if not already getting an HTTP doc - */ - if(PL_strncasecmp(URL_s->address,"http:",5)) - { - obj->definately_send_headers = TRUE; - } - StrAllocCopy(obj->content_type, URL_s->content_type); - StrAllocCopy(obj->content_encoding, URL_s->content_encoding); - - return stream; -} diff --git a/mozilla/network/cnvts/cvproxy.h b/mozilla/network/cnvts/cvproxy.h deleted file mode 100644 index d462d10336a..00000000000 --- a/mozilla/network/cnvts/cvproxy.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -extern NET_StreamClass* NET_ProxyConverter (FO_Present_Types format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); diff --git a/mozilla/network/cnvts/cvsimple.c b/mozilla/network/cnvts/cvsimple.c deleted file mode 100644 index a7fc8b2b3e0..00000000000 --- a/mozilla/network/cnvts/cvsimple.c +++ /dev/null @@ -1,128 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/********************************************************************** - cvsimple.c - By Daniel Malmer <malmer@netscape.com> - 1/14/98 - - Simple converter that just saves the data in a buffer. - -**********************************************************************/ - -#include "cvsimple.h" -#include "xp.h" -#include "prmem.h" - -typedef void (*simple_complete_t)(void* bytes, int32 bytes_written); - -typedef struct { - unsigned char* bytes; - int32 bytes_written; - int32 max_bytes; - simple_complete_t complete; -} NET_SimpleStreamData; - - -/* - * simple_complete - */ -PRIVATE void -simple_complete(NET_StreamClass *stream) -{ - NET_SimpleStreamData* obj = (NET_SimpleStreamData*) stream->data_object; - - if ( obj && obj->complete ) { - (obj->complete)(obj->bytes, obj->bytes_written); - } - - if ( obj && obj->bytes ) PR_Free(obj->bytes); - if ( obj ) PR_Free(obj); -} - - -/* - * simple_abort - */ -PRIVATE void -simple_abort(NET_StreamClass *stream, int status) -{ - NET_SimpleStreamData* obj = (NET_SimpleStreamData*) stream->data_object; - - if ( obj && obj->bytes ) PR_Free(obj->bytes); - if ( obj ) PR_Free(obj); -} - - -/* - * simple_write - */ -PRIVATE int -simple_write(NET_StreamClass *stream, const char* str, int32 len) -{ - NET_SimpleStreamData* obj = (NET_SimpleStreamData*) stream->data_object; - - if ( obj->bytes_written + len > obj->max_bytes ) { - /* Round to nearest 1024 */ - obj->max_bytes = ( ( ( (obj->max_bytes + len) >> 10) + 1) << 10); - obj->bytes = PR_Realloc(obj->bytes, obj->max_bytes); - } - - memcpy(obj->bytes + obj->bytes_written, str, len); - obj->bytes_written+= len; - - return MK_DATA_LOADED; -} - - -/* - * simple_write_ready - */ -PRIVATE unsigned int -simple_write_ready(NET_StreamClass *stream) -{ - return MAX_WRITE_READY; -} - - -/* - * NET_SimpleStream - * Simple stream constructor. - */ -MODULE_PRIVATE NET_StreamClass* -NET_SimpleStream(int fmt, void* data_obj, URL_Struct* URL_s, MWContext* w) -{ - NET_SimpleStreamData* obj; - - if ( (obj = PR_NEWZAP(NET_SimpleStreamData)) == NULL ) { - return NULL; - } - - obj->bytes = NULL; - obj->bytes_written = 0; - obj->max_bytes = 0; - obj->complete = (simple_complete_t) data_obj; - - return NET_NewStream("SimpleStream", simple_write, simple_complete, - simple_abort, simple_write_ready, obj, w); -} - - diff --git a/mozilla/network/cnvts/cvsimple.h b/mozilla/network/cnvts/cvsimple.h deleted file mode 100644 index 78c9ca7b8a0..00000000000 --- a/mozilla/network/cnvts/cvsimple.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/********************************************************************** - cvsimple.h - By Daniel Malmer <malmer@netscape.com> - 1/14/98 - - Simple converter that just saves the data in a buffer. - -**********************************************************************/ - - -#ifndef __cvsimple_h -#define __cvsimple_h - -#include "net.h" - -MODULE_PRIVATE NET_StreamClass* -NET_SimpleStream(int fmt, void* data_obj, URL_Struct* URL_s, MWContext* w); - -#endif diff --git a/mozilla/network/cnvts/cvunzip.c b/mozilla/network/cnvts/cvunzip.c deleted file mode 100644 index ef1918ca1c0..00000000000 --- a/mozilla/network/cnvts/cvunzip.c +++ /dev/null @@ -1,538 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Please leave outside of ifdef for windows precompiled headers */ -#include "xp.h" -#include "prmem.h" -#include "plstr.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "cvunzip.h" - -/* BEGIN NEW_STRING_LIB */ -#ifdef XP_MAC -#ifndef MOZ_NGLAYOUT -#include "allxpstr.h" -#endif -#endif -/* END NEW_STRING_LIB */ -#ifdef MOZILLA_CLIENT - -#include "mkstream.h" -#include "zlib.h" - -extern int MK_OUT_OF_MEMORY; -extern int MK_BAD_GZIP_HEADER; - -typedef struct _DataObject { - NET_StreamClass *next_stream; - z_stream d_stream; /* decompression stream */ - unsigned char *dcomp_buf; - uint32 dcomp_buf_size; - PRBool is_done; - PRBool checking_crc_footer; - unsigned char *incoming_buf; - uint32 incoming_buf_size; - PRBool header_skipped; - URL_Struct *URL_s; - uint32 crc_check; -} DataObject; - -#define DECOMP_BUF_SIZE NET_Socket_Buffer_Size*2 - -enum check_header_response { - HEADER_OK, - BAD_HEADER, - NEED_MORE_HEADER -}; - -static uint32 gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ - -/* gzip flag byte */ -#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ -#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ -#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ -#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ -#define COMMENT 0x10 /* bit 4 set: file comment present */ -#define RESERVED 0xE0 /* bits 5..7: reserved */ - -/* code copied from Zlib please see zlib.h for copyright statement */ -/* =========================================================================== - Check the gzip header of a gz_stream opened for reading. Set the stream - mode to transparent if the gzip magic header is not present; set s->err - to Z_DATA_ERROR if the magic header is present but the rest of the header - is incorrect. - IN assertion: the stream s has already been created sucessfully; - s->stream.avail_in is zero for the first time, but may be non-zero - for concatenated .gz files. -*/ -static enum check_header_response -check_header(unsigned char *header, uint32 header_length, uint32 *actual_header_size) -{ - int method; /* method byte */ - int flags; /* flags byte */ - uInt len; - uint32 c; - uint32 orig_header_size = header_length; - - /* header must be at least 10 bytes */ - if(header_length < 10) - return NEED_MORE_HEADER; - - /* Check the gzip magic header */ - for (len = 0; len < 2; len++) { - c = (uint32) *header++; - header_length--; - if (c != gz_magic[len]) { - return BAD_HEADER; - } - } - method = *header++; - header_length--; - flags = *header++; - header_length--; - if (method != Z_DEFLATED || (flags & RESERVED) != 0) { - return BAD_HEADER; - } - - /* Discard time, xflags and OS code: */ - for (len = 0; len < 6; len++) - { - header++; - header_length--; - } - - /* OK we now passed the safe 10 byte boundary, we need to check from here - * on out to make sure we have enough data - */ - - if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ - if(header_length < 2) - return NEED_MORE_HEADER; - - len = (uInt)*header++; - header_length--; - len += ((uInt)*header++)<<8; - header_length--; - - /* len is garbage if EOF but the loop below will quit anyway */ - - if(header_length < len) - return NEED_MORE_HEADER; - - while (len-- != 0) - { - header++; - header_length--; - } - } - if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ - - if(header_length < 1) - return NEED_MORE_HEADER; - - while (*header != '\0') - { - header++; - header_length--; - - if(header_length == 0) - return NEED_MORE_HEADER; - } - - /* skip null byte */ - header++; - header_length--; - } - if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ - - if(header_length < 1) - return NEED_MORE_HEADER; - - while (*header != '\0') - { - header++; - header_length--; - - if(header_length == 0) - return NEED_MORE_HEADER; - } - - /* skip null byte */ - header++; - header_length--; - - } - if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ - - if(header_length < 2) - return NEED_MORE_HEADER; - - for (len = 0; len < 2; len++) - { - header++; - header_length--; - } - } - - *actual_header_size = orig_header_size - header_length; - - return HEADER_OK; -} - -PRIVATE int -do_end_crc_check(DataObject *obj) -{ - - if(obj->incoming_buf_size >= 8) - { - uint32 crc_int; - uint32 size_int; - - obj->checking_crc_footer = PR_FALSE; - obj->is_done = PR_TRUE; - - crc_int = (uint32)obj->incoming_buf[0]; - crc_int += (uint32)obj->incoming_buf[1]<<8; - crc_int += (uint32)obj->incoming_buf[2]<<16; - crc_int += (uint32)obj->incoming_buf[3]<<24; - - size_int = (uint32)obj->incoming_buf[4]; - size_int += (uint32)obj->incoming_buf[5]<<8; - size_int += (uint32)obj->incoming_buf[6]<<16; - size_int += (uint32)obj->incoming_buf[7]<<24; - - if(obj->crc_check != crc_int - || obj->d_stream.total_out != size_int) - { - /* crc or size checksum failure */ - obj->URL_s->error_msg = NET_ExplainErrorDetails(MK_BAD_GZIP_HEADER); - return MK_BAD_GZIP_HEADER; - } - - return 1; - } - - return 0; /* need more data */ -} - -/* Free up the unzip specific stream data object. - */ -PRIVATE void net_UnZipFreeDataObject (DataObject **objp) -{ - DataObject *obj; - - PR_ASSERT(objp && *objp); - - if (objp && *objp) - { - obj = *objp; - PR_FREEIF(obj->dcomp_buf); - PR_FREEIF(obj->incoming_buf); - PR_Free(obj); - *objp = NULL; - } -} - -PRIVATE int net_UnZipWrite (NET_StreamClass *stream, CONST char* s, int32 l) -{ - int err; - uint32 prev_total_out; - uint32 new_data_total_out; - uint32 input_used_up, input_left_over; - char * tempPtr = NULL; - DataObject *obj; - - PR_ASSERT(stream); - obj = stream->data_object; - if(obj->is_done) - { - /* multipart gzip? */ - PR_ASSERT(0); - return (1); - } - - PR_ASSERT(s && l); - - tempPtr = (char *)obj->incoming_buf; - BlockAllocCat(tempPtr, obj->incoming_buf_size, s, l); - if(!tempPtr) - return MK_OUT_OF_MEMORY; - - obj->incoming_buf = (unsigned char*)tempPtr; - obj->incoming_buf_size += l; - - /* parse and skip the header */ - if(!obj->header_skipped) - { - uint32 actual_header_size; - enum check_header_response status; - - status = check_header((unsigned char *)obj->incoming_buf, obj->incoming_buf_size, &actual_header_size); - - if(status == HEADER_OK) - { - /* squash the header */ - obj->incoming_buf_size -= actual_header_size; - memmove(obj->incoming_buf, - obj->incoming_buf+actual_header_size, - obj->incoming_buf_size); - - obj->header_skipped = PR_TRUE; - } - else if(status == BAD_HEADER) - { - obj->URL_s->error_msg = NET_ExplainErrorDetails(MK_BAD_GZIP_HEADER); - return MK_BAD_GZIP_HEADER; - } - else if(status == NEED_MORE_HEADER) - { - return 1; - } - else - { - PR_ASSERT(0); - return 1; - } - } - else if(obj->checking_crc_footer) - { - return do_end_crc_check(obj); - } - - obj->d_stream.next_in = (unsigned char *)obj->incoming_buf; - obj->d_stream.avail_in = obj->incoming_buf_size; - obj->d_stream.next_out = (unsigned char *)obj->dcomp_buf; - obj->d_stream.avail_out = obj->dcomp_buf_size; - - if(obj->d_stream.avail_in <= 0) - return 1; /* wait for more data */ - - prev_total_out = obj->d_stream.total_out; - - /* need to loop to finish for small output bufs */ - while(1) - { - err = inflate(&obj->d_stream, Z_NO_FLUSH); - - /* the amount of new uncompressed data is: */ - new_data_total_out = obj->d_stream.total_out - prev_total_out; - - if(new_data_total_out > 0) - { - obj->crc_check = crc32(obj->crc_check, - obj->dcomp_buf, - new_data_total_out); - - (*obj->next_stream->put_block)(obj->next_stream, - (char *) obj->dcomp_buf, - new_data_total_out); - - - } - - obj->d_stream.avail_out = obj->dcomp_buf_size; - obj->d_stream.next_out = (unsigned char *)obj->dcomp_buf; - prev_total_out = obj->d_stream.total_out; - - if(err == Z_STREAM_END) - { - obj->checking_crc_footer = PR_TRUE; - break; - } - else if(err != Z_OK) - { - /* need to get more data on next pass - * @@@ should check for more critical errors - */ - break; - } - else if(obj->d_stream.avail_in <= 0) - { - /* need more data */ - break; - } - - } - - /* remove the part that has already been decoding from the incoming buf */ - input_left_over = obj->d_stream.avail_in; - - if(input_left_over > 0) - { - input_used_up = obj->incoming_buf_size - input_left_over; - memmove(obj->incoming_buf, obj->incoming_buf+input_used_up, input_left_over); - obj->incoming_buf_size = input_left_over; - } - else - { - obj->incoming_buf_size = 0; - } - - if(obj->checking_crc_footer == PR_TRUE) - { - return do_end_crc_check(obj); - } - - return(1); -} - -/* is the stream ready for writeing? - */ -PRIVATE unsigned int net_UnZipWriteReady (NET_StreamClass * stream) -{ - DataObject *obj=stream->data_object; - return((*obj->next_stream->is_write_ready)(obj->next_stream)); /* always ready for writing */ -} - - -PRIVATE void net_UnZipComplete (NET_StreamClass *stream) -{ - DataObject *obj=stream->data_object; - int err; - - (*obj->next_stream->complete)(obj->next_stream); - - err = inflateEnd(&(obj->d_stream)); - PR_ASSERT(err == Z_OK); - - if(!obj->is_done) - { - /* we didn't complete the crc and size checks */ - /* @@@ not sure what to do here yet */ - PR_ASSERT(0); - } - - net_UnZipFreeDataObject((DataObject **)&stream->data_object); - return; -} - -PRIVATE void net_UnZipAbort (NET_StreamClass *stream, int status) -{ - DataObject *obj=stream->data_object; - int err; - - (*obj->next_stream->abort)(obj->next_stream, status); - - err = inflateEnd(&(obj->d_stream)); - PR_ASSERT(err == Z_OK); - - net_UnZipFreeDataObject((DataObject **)&stream->data_object); - return; -} - - -PUBLIC NET_StreamClass * -NET_UnZipConverter (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - DataObject* obj; - NET_StreamClass* stream; - int err; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - PR_ASSERT(URL_s); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEWZAP(DataObject); - if (obj == NULL) - { - PR_Free(stream); - return(NULL); - } - - stream->name = "UnZiper"; - stream->complete = (MKStreamCompleteFunc) net_UnZipComplete; - stream->abort = (MKStreamAbortFunc) net_UnZipAbort; - stream->put_block = (MKStreamWriteFunc) net_UnZipWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_UnZipWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - obj->dcomp_buf = PR_Malloc(DECOMP_BUF_SIZE); - obj->dcomp_buf_size = DECOMP_BUF_SIZE; - - if(!obj->dcomp_buf) - { - net_UnZipFreeDataObject(&obj); - PR_Free(stream); - return NULL; - } - - obj->URL_s = URL_s; - - obj->d_stream.zalloc = (alloc_func)0; - obj->d_stream.zfree = (free_func)0; - obj->d_stream.opaque = (voidpf)0; - - err = inflateInit2(&obj->d_stream, -15); - - if(err != Z_OK) - { - net_UnZipFreeDataObject(&obj); - PR_Free(stream); - return NULL; - } - - /* create the next stream, but strip the compressed encoding */ - /* - * We might have been sent here from either a transfer-encoding: gzip - * or a content-encoding: gzip stream. There is no way to know for - * sure at this point. Based on knowing what NET_StreamBuilder does - * I know transfer-encoding is processed before content-encoding - * and that the only encoding currently sent here are - * ENCODING_GZIP and ENCODING_GZIP2. If this changes in the - * future it could cause an infinite recursion bug here. - */ - if ((URL_s->transfer_encoding != NULL)&& - ((!PL_strcasecmp(URL_s->transfer_encoding, ENCODING_GZIP))|| - (!PL_strcasecmp(URL_s->transfer_encoding, ENCODING_GZIP2)))) - { - PR_FREEIF(URL_s->transfer_encoding); - } - else - { - PR_FREEIF(URL_s->content_encoding); - } - obj->next_stream = NET_StreamBuilder(format_out, URL_s, window_id); - - if(!obj->next_stream) - { - inflateEnd(&obj->d_stream); - net_UnZipFreeDataObject(&obj); - PR_Free(stream); - return NULL; - } - - TRACEMSG(("Returning stream from NET_UnZipConverter\n")); - - return stream; -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cnvts/cvunzip.h b/mozilla/network/cnvts/cvunzip.h deleted file mode 100644 index 9bcba09c28e..00000000000 --- a/mozilla/network/cnvts/cvunzip.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVUNZIP_H -#define CVUNZIP_H - -NET_StreamClass * -NET_UnZipConverter (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* CVUNZIP_H */ diff --git a/mozilla/network/cnvts/cvview.c b/mozilla/network/cnvts/cvview.c deleted file mode 100644 index eb55ef6fb65..00000000000 --- a/mozilla/network/cnvts/cvview.c +++ /dev/null @@ -1,601 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Please leave outside of ifdef for windows precompiled headers */ -#include "xp.h" -#include "prmem.h" -#include "plstr.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "net_xp_file.h" -#include "mkgeturl.h" -#include <signal.h> - -#ifdef MOZILLA_CLIENT - -#include "mkstream.h" -#include "mkparse.h" -#include "cvview.h" - -#include "libmime.h" - -/* for select(), fd_set, struct timeval */ -#if defined(XP_UNIX) -#include <sys/time.h> -#include <sys/types.h> -#include <unistd.h> -#if defined(AIX) -#include <sys/select.h> -#endif -#elif defined(XP_WIN) -#include <windows.h> -#elif defined(XP_MAC) -#include "macsocket.h" -#endif - -/* for XP_GetString() */ -#include <xpgetstr.h> -extern int XP_CONFIRM_EXEC_UNIXCMD_ARE; -extern int XP_CONFIRM_EXEC_UNIXCMD_MAYBE; -extern int XP_ALERT_UNABLE_INVOKEVIEWER; -extern int MK_UNABLE_TO_OPEN_TMP_FILE; - - -typedef struct _CV_DataObject { - FILE * fp; - char * filename; - char * command; - char * url; - unsigned int stream_block_size; - int32 cur_size; - int32 tot_size; - MWContext * context; -} CV_DataObject; - - -/* -** build_viewer_cmd -** Build up the command for forking the external viewer. -** Argument list is the template for the command and the a set of -** (char,char*) pairs of characters to be recognized as '%' escapes -** and what they should expand to, terminated with a 0. -** -** Return value is a malloc'ed string, must be freed when command is done. -** -** Example: -** char* s=build_viewer(line_from_mailcap, 's', tmpFile, 'u', url, 0); -** -** I'm completely unsure what to do about security considerations and -** encodings. Should the URL get % encoded. What if it contains "bad" -** characters. etc. etc. etc -*/ - -char* -build_viewer_cmd(char *template, ...) -{ - va_list args; - char *ret, *from, *to; - int len; - - if (template == NULL) - return NULL; - - len = strlen(template); - ret = (char*) malloc(len+1); - if (ret == NULL) - return NULL; - - from = template, to = ret; - - while (*from) { - if (*from != '%' || *++from == '%') { - *to++ = *from++; - } else { - - /* - ** We have a % escape, now look through all the arguments for - ** a matching one. When one is found, substitute in the - ** passed value. If none is found, the % and following character - ** get swallowed. - */ - char argc; - char* argv; - - va_start(args, template); - while ((argc = va_arg(args, int)) != 0) { - argv = va_arg(args, char*); - if (*from == argc) { - int off = to - ret; - int arglen = strlen(argv); - - len = len + arglen - 2; - ret = (char*) realloc(ret, len + 1); - if (ret == NULL) - return NULL; - PL_strcpy(ret + off, argv); - to = ret + off + arglen; - break; - } - } - if (*from) from++; /* skip char following % unless it was last */ - va_end(args); - } - } - *to = '\0'; - return ret; -} - -PRIVATE int net_ExtViewWrite (NET_StreamClass *stream, CONST char* s, int32 l) -{ - CV_DataObject *obj=stream->data_object; - if(obj->tot_size) - { - obj->cur_size += l; - - obj->context->funcs->SetProgressBarPercent(obj->context, (obj->cur_size*100)/obj->tot_size); - } - - /* TRACEMSG(("Length of string passed to display: %d\n",l)); - */ - return(fwrite((char *) s, 1, l, obj->fp)); -} - -PRIVATE int net_ExtViewWriteReady (NET_StreamClass * stream) -{ - CV_DataObject *obj=stream->data_object; - fd_set write_fds; - struct timeval timeout; - int ret; - - if(obj->command) - { - return(MAX_WRITE_READY); /* never wait for files */ - } - - timeout.tv_sec = 0; - timeout.tv_usec = 1; /* minimum hopefully */ - - memset(&write_fds, 0, sizeof(fd_set)); - - FD_SET(fileno(obj->fp), &write_fds); - - ret = select(fileno(obj->fp)+1, NULL, &write_fds, NULL, &timeout); - - if(ret) - return(obj->stream_block_size); /* read in a max of 8000 bytes */ - else - return(0); -} - - -PRIVATE void net_ExtViewComplete (NET_StreamClass *stream) -{ - CV_DataObject *obj=stream->data_object; - obj->context->funcs->SetProgressBarPercent(obj->context, 100); - - if(obj->command) - { - char *p_tmp; - char *command; - - /* restrict to allowed url chars - * - */ - for(p_tmp = obj->url; *p_tmp != '\0'; p_tmp++) - if( (*p_tmp >= '0' && *p_tmp <= '9') - || (*p_tmp >= 'A' && *p_tmp <= 'Z') - || (*p_tmp >= 'a' && *p_tmp <= 'z') - || (*p_tmp == '_') - || (*p_tmp == '?') - || (*p_tmp == '#') - || (*p_tmp == '&') - || (*p_tmp == '%') - || (*p_tmp == '/') - || (*p_tmp == ':') - || (*p_tmp == '+') - || (*p_tmp == '.') - || (*p_tmp == '~') - || (*p_tmp == '=') - || (*p_tmp == '-')) - { - /* this is a good character. Allow it. - */ - } - else - { - *p_tmp = '\0'; - break; - } - - command=build_viewer_cmd(obj->command, - 's', obj->filename, - 'u', obj->url, 0); - - fclose(obj->fp); - TRACEMSG(("Invoking: %s", command)); - - system(command); - PR_FREEIF(obj->command); - } - else - { - pclose(obj->fp); - } - - PR_FREEIF(obj->filename); - PR_FREEIF(obj->url); - PR_Free(obj); - return; -} - -PRIVATE void net_ExtViewAbort (NET_StreamClass *stream, int status) -{ - CV_DataObject *obj=stream->data_object; - obj->context->funcs->SetProgressBarPercent(obj->context, 100); - - fclose(obj->fp); - - if(obj->filename) - { - remove(obj->filename); - PR_Free(obj->filename); - } - - PR_FREEIF(obj->url); - PR_FREEIF(obj->command); - - PR_Free(obj); - - return; -} - -#ifdef XP_UNIX -extern char **fe_encoding_extensions; /* gag! */ -#endif - - -PUBLIC NET_StreamClass * -NET_ExtViewerConverter (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - CV_DataObject* obj; - NET_StreamClass* stream; - char *tmp_filename; - char *dot; - char *path; - CV_ExtViewStruct * view_struct = (CV_ExtViewStruct *)data_obj; - char small_buf[256]; - int yes_stream=0; - - /* If this URL is a mail or news attachment, use the name of that - attachment as the URL -- this is so the temp file gets the right - extension on it (some helper apps are picky about that...) - */ - path = MimeGuessURLContentName(window_id, URL_s->address); - if (!path) - path = NET_ParseURL(URL_s->address, GET_PATH_PART); - if (!path) - return 0; - - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - memset(stream, 0, sizeof(NET_StreamClass)); - - obj = PR_NEW(CV_DataObject); - if (obj == NULL) - return(NULL); - memset(obj, 0, sizeof(CV_DataObject)); - - obj->context = window_id; - - if(URL_s->content_length) - { - obj->tot_size = URL_s->content_length; - } - else - { - /* start the progress bar cyloning - */ - obj->context->funcs->SetProgressBarPercent(window_id, -1); - } - - stream->name = "Execute external viewer"; - stream->complete = (MKStreamCompleteFunc) net_ExtViewComplete; - stream->abort = (MKStreamAbortFunc) net_ExtViewAbort; - stream->put_block = (MKStreamWriteFunc) net_ExtViewWrite; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_ExtViewWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - -#ifdef XP_UNIX - /* Some naive people may have trustingly put - - application/x-sh; sh %s - application/x-csh; csh %s - - in their mailcap files without realizing how dangerous that is. - Worse, it might be there and they might not realize it. So, if - we're about to execute a shell, pop up a dialog box first. - */ - { - char *prog = PL_strdup (view_struct->system_command); - char *s, *start, *end; - int danger = 0; - - /* strip end space */ - end = XP_StripLine(prog); - - /* Extract the leaf name of the program: " /bin/sh -foo" ==> "sh". */ - for (; *end && !NET_IS_SPACE(*end); end++) - ; - *end = 0; - - if ((start = PL_strrchr (prog, '/'))) - start++; - else - start = XP_StripLine(prog); /* start at first non-white space */ - - /* Strip off everything after the first nonalphabetic. - This is so "perl-4.0" is compared as "perl" and - "emacs19" is compared as "emacs". - */ - for (s = start; *s; s++) - if (!isalpha (*s)) - *s = 0; - - /* These are things known to be shells - very bad. */ - if (!PL_strcmp (start, "ash") || - !PL_strcmp (start, "bash") || - !PL_strcmp (start, "csh") || - !PL_strcmp (start, "jsh") || - !PL_strcmp (start, "ksh") || - !PL_strcmp (start, "pdksh") || - !PL_strcmp (start, "sh") || - !PL_strcmp (start, "tclsh") || - !PL_strcmp (start, "tcsh") || - !PL_strcmp (start, "wish") || /* a tcl thing */ - !PL_strcmp (start, "wksh") || - !PL_strcmp (start, "zsh")) - danger = 2; - - /* Remote shells are potentially dangerous, in the case of - "rsh somehost some-dangerous-program", but it's hard to - parse that out, since rsh could take arbitrarily complicated - args, like "rsh somehost -u something -pass8 /bin/sh %s". - And we don't want to squawk about "rsh somehost playulaw -". - So... allow rsh to possibly be a security hole. - */ - else if (!PL_strcmp (start, "remsh") || /* remote shell */ - !PL_strcmp (start, "rksh") || - !PL_strcmp (start, "rsh") /* remote- or restricted- */ - ) - danger = 0; - - /* These are things which aren't really shells, but can do the - same damage anyway since they can write files and/or execute - other programs. */ - else if (!PL_strcmp (start, "awk") || - !PL_strcmp (start, "e") || - !PL_strcmp (start, "ed") || - !PL_strcmp (start, "ex") || - !PL_strcmp (start, "gawk") || - !PL_strcmp (start, "m4") || - !PL_strcmp (start, "sed") || - !PL_strcmp (start, "vi") || - !PL_strcmp (start, "emacs") || - !PL_strcmp (start, "lemacs") || - !PL_strcmp (start, "xemacs") || - !PL_strcmp (start, "temacs") || - - /* Other dangerous interpreters */ - !PL_strcmp (start, "basic") || - !PL_strcmp (start, "expect") || - !PL_strcmp (start, "expectk") || - !PL_strcmp (start, "perl") || - !PL_strcmp (start, "python") || - !PL_strcmp (start, "rexx") - ) - danger = 1; - - /* Be suspicious of anything ending in "sh". */ - else if (PL_strlen (start) > 2 && - !PL_strcmp (start + PL_strlen (start) - 2, "sh")) - danger = 1; - - if (danger) - { - char msg [2048]; - PR_snprintf (msg, - sizeof(msg), - (danger > 1 ? XP_GetString(XP_CONFIRM_EXEC_UNIXCMD_ARE) : XP_GetString(XP_CONFIRM_EXEC_UNIXCMD_MAYBE)), - start - ); - if (!FE_Confirm (window_id, msg)) - { - PR_Free (stream); - PR_Free (obj); - PR_Free (path); - PR_Free (prog); - return(NULL); - } - } - PR_Free (prog); - } -#endif /* XP_UNIX */ - - if(view_struct->stream_block_size) - { - /* asks the user if they want to stream data. - * -1 cancel - * 0 No, don't stream data, play from the file - * 1 Yes, stream the data from the network - */ - if (NET_URL_Type (URL_s->address) == ABOUT_TYPE_URL) - yes_stream = 1; - else - yes_stream = FE_AskStreamQuestion(window_id); - - if(yes_stream == -1) - { - PR_Free(stream); - PR_Free(obj); - PR_Free(path); - return(NULL); - } - } - - if(yes_stream && view_struct->stream_block_size) - { - /* use popen */ - obj->fp = popen(view_struct->system_command, "w"); - - if(!obj->fp) - { - FE_Alert(window_id, XP_GetString(XP_ALERT_UNABLE_INVOKEVIEWER)); - return(NULL); - } - - obj->stream_block_size = view_struct->stream_block_size; - - signal(SIGPIPE, SIG_IGN); - - } - else - { - - dot = PL_strrchr(path, '.'); - -#ifdef XP_UNIX - /* Gag. foo.ps.gz --> tmpXXXXX.ps, not tmpXXXXX.gz. */ - if (dot && fe_encoding_extensions) - { - int i = 0; - while (fe_encoding_extensions [i]) - { - if (!PL_strcmp (dot, fe_encoding_extensions [i])) - { - *dot = 0; - dot--; - while (dot > path && *dot != '.') - dot--; - if (*dot != '.') - dot = 0; - break; - } - i++; - } - } -#endif /* XP_UNIX */ - - tmp_filename = WH_TempName(xpTemporary, "MO"); - if (!tmp_filename) { - PR_FREEIF(stream); - PR_FREEIF(obj); - return NULL; - } - if (dot) - { - char * p_tmp; - - StrAllocCopy(obj->filename, tmp_filename); - - /* restrict to ascii alphanumeric chars - * - * this fixes really bad security hole - */ - for(p_tmp = dot+1; *p_tmp != '\0'; p_tmp++) - if( (*p_tmp >= '0' && *p_tmp <= '9') - || (*p_tmp >= 'A' && *p_tmp <= 'Z') - || (*p_tmp >= 'a' && *p_tmp <= 'z') - || (*p_tmp == '_') - || (*p_tmp == '+') - || (*p_tmp == '-')) - { - /* this is a good character. Allow it. - */ - } - else - { - *p_tmp = '\0'; - break; - } - - StrAllocCat(obj->filename, dot); - } - else - { - StrAllocCopy(obj->filename, tmp_filename); - } - - PR_Free(path); - PR_Free(tmp_filename); - - obj->fp = NET_XP_FileOpen(obj->filename, xpTemporary, XP_FILE_WRITE); - - TRACEMSG(("Trying to open output file: %s\n", obj->filename)); - - if(!obj->fp) - { - char *s = NET_ExplainErrorDetails (MK_UNABLE_TO_OPEN_TMP_FILE, - obj->filename); - if (s) - { - FE_Alert (window_id, s); - PR_Free (s); - } - return(NULL); - } - - /* construct the command like this - * - * (( COMMAND ); rm %s )& - */ - StrAllocCopy(obj->command, "(("); - - /* this is a stream writable program that the user wants - * to use non streaming - */ - if(view_struct->stream_block_size) - StrAllocCat(obj->command, "cat %s | "); - - StrAllocCat(obj->command, view_struct->system_command); - - PR_snprintf(small_buf, sizeof(small_buf), "); rm %.200s )&", obj->filename); - StrAllocCat(obj->command, small_buf); - } - - StrAllocCopy(obj->url, URL_s->address); - - TRACEMSG(("Returning stream from NET_ExtViewer\n")); - - return stream; -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/cnvts/cvview.h b/mozilla/network/cnvts/cvview.h deleted file mode 100644 index 10ffa95cab0..00000000000 --- a/mozilla/network/cnvts/cvview.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef CVVIEW_H -#define CVVIEW_H - -extern NET_StreamClass* NET_ExtViewerConverter ( FO_Present_Types format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - -typedef struct _CV_ExtViewStruct { - char * system_command; - unsigned int stream_block_size; -} CV_ExtViewStruct; - -#endif /* CVVIEW_H */ diff --git a/mozilla/network/cnvts/makefile.win b/mozilla/network/cnvts/makefile.win deleted file mode 100644 index e54fc9d6ad7..00000000000 --- a/mozilla/network/cnvts/makefile.win +++ /dev/null @@ -1,130 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network protocol converters LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\cvplugin.obj \ - .\$(OBJDIR)\nsNetConverterStream.obj \ - .\$(OBJDIR)\cvactive.obj \ - .\$(OBJDIR)\cvchunk.obj \ - .\$(OBJDIR)\cvcolor.obj \ - .\$(OBJDIR)\cvdisk.obj \ - .\$(OBJDIR)\cvsimple.obj \ - .\$(OBJDIR)\cvunzip.obj \ - .\$(OBJDIR)\cvjscfg.obj \ - .\$(OBJDIR)\txview.obj \ - .\$(OBJDIR)\cvmime.obj \ - $(NULL) - -CPPSRCS = \ - cvplugin.cpp \ - nsNetConverterStream.cpp \ - $(NULL) - -TMP_CSRCS = \ - cvactive.c \ - cvchunk.c \ - cvcolor.c \ - cvmime.c \ - cvdisk.c \ - cvsimple.c \ - cvunzip.c \ - cvjscfg.c \ - txview.c \ - $(NULL) - - -LIBRARY_NAME=netcnvts -MODULE=netcnvts -DEPTH=..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network ldap -EXPORTS= \ - cvactive.h \ - cvchunk.h \ - cvcolor.h \ - cvdisk.h \ - cvmime.h \ - cvpics.h \ - cvplugin.h \ - cvsimple.h \ - cvunzip.h \ - cvjscfg.h \ - nsINetPlugin.h \ - nsINetPluginInstance.h \ - nsINetOStream.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\parse \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\marimurl \ - -I$(PUBLIC)\lay \ - -I$(PUBLIC)\style \ - -I$(PUBLIC)\zlib \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\mimetype \ - -I$(PUBLIC)\plugin \ - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\raptor \ - -I$(PUBLIC)\xpcom \ - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/cnvts/nsINetOStream.h b/mozilla/network/cnvts/nsINetOStream.h deleted file mode 100644 index f3decd1f8fa..00000000000 --- a/mozilla/network/cnvts/nsINetOStream.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsINetOStream_h___ -#define nsINetOStream_h___ - -#include "nsIOutputStream.h" - -class nsINetOStream : public nsIOutputStream { -public: - - NS_IMETHOD - Complete(void) = 0; - - NS_IMETHOD - Abort(PRInt32 status) = 0; - - NS_IMETHOD - WriteReady(PRUint32 *aReadyCount) = 0; -}; - - - - - -/* 7f13b870-e95f-11d2-beae-00805f8a66dc */ -#define NS_INETOSTREAM_IID \ -{ 0x7f13b870, 0xe95f, 0x11d2, \ - {0xbe, 0xae, 0x00, 0x80, 0x5f, 0x8a, 0x66, 0xdc} } - -#endif /* nsINetOStream_h___ */ diff --git a/mozilla/network/cnvts/nsINetPlugin.h b/mozilla/network/cnvts/nsINetPlugin.h deleted file mode 100644 index 77eb7a2951a..00000000000 --- a/mozilla/network/cnvts/nsINetPlugin.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -//////////////////////////////////////////////////////////////////////////////// -/** - * <B>INTERFACE TO NETSCAPE COMMUNICATOR PLUGINS (NEW C++ API).</B> - * - * <P>This superscedes the old plugin API (npapi.h, npupp.h), and - * eliminates the need for glue files: npunix.c, npwin.cpp and npmac.cpp that - * get linked with the plugin. You will however need to link with the "backward - * adapter" (badapter.cpp) in order to allow your plugin to run in pre-5.0 - * browsers. - * - * <P>See nsplugin.h for an overview of how this interface fits with the - * overall plugin architecture. - */ -//////////////////////////////////////////////////////////////////////////////// - -#ifndef nsINetPlugin_h___ -#define nsINetPlugin_h___ - -#include "nsplugindefs.h" -#include "nsIFactory.h" - -/** - * The nsIPlugin interface is the minimum interface plugin developers need to - * support in order to implement a plugin. The plugin manager may QueryInterface - * for more specific plugin types, e.g. nsILiveConnectPlugin. - * - * The old NPP_New plugin operation is now subsumed by two operations: - * - * CreateInstance -- called once, after the plugin instance is created. This - * method is used to initialize the new plugin instance (although the actual - * plugin instance object will be created by the plugin manager). - * - * nsIPluginInstance::Start -- called when the plugin instance is to be - * started. This happens in two circumstances: (1) after the plugin instance - * is first initialized, and (2) after a plugin instance is returned to - * (e.g. by going back in the window history) after previously being stopped - * by the Stop method. - */ -struct nsINetPlugin : public nsIFactory { -public: - - /** - * Initializes the plugin and will be called before any new instances are - * created. It is passed browserInterfaces on which QueryInterface - * may be used to obtain an nsIPluginManager, and other interfaces. - * - * @param browserInterfaces - an object that allows access to other browser - * interfaces via QueryInterface - * @result - NS_OK if this operation was successful - */ - NS_IMETHOD - Initialize() = 0; - - /** - * Called when the browser is done with the plugin factory, or when - * the plugin is disabled by the user. - * - * (Corresponds to NPP_Shutdown.) - * - * @result - NS_OK if this operation was successful - */ - NS_IMETHOD - Shutdown(void) = 0; - - /** - * Returns the MIME description for the plugin. The MIME description - * is a colon-separated string containg the plugin MIME type, plugin - * data file extension, and plugin name, e.g.: - * - * "application/x-simple-plugin:smp:Simple LiveConnect Sample Plug-in" - * - * (Corresponds to NPP_GetMIMEDescription.) - * - * @param resultingDesc - the resulting MIME description - * @result - NS_OK if this operation was successful - */ - NS_IMETHOD - GetMIMEDescription(const char* *resultingDesc) = 0; - -}; - -#define NS_INET_PLUGIN_IID \ -{ /* df773070-0199-11d2-815b-006008119d7b */ \ - 0xdf773070, \ - 0x0199, \ - 0x11d2, \ - {0x81, 0x5b, 0x00, 0x60, 0x08, 0x11, 0x9d, 0x7b} \ -} - -#define NS_INET_PLUGIN_CID \ -{ /* dc26e0e0-0199-11d2-815b-006008119d7b */ \ - 0xdc26e0e0, \ - 0x0199, \ - 0x11d2, \ - {0x81, 0x5b, 0x00, 0x60, 0x08, 0x11, 0x9d, 0x7b} \ -} - -//////////////////////////////////////////////////////////////////////////////// - -#endif /* nsINetPlugin_h___ */ diff --git a/mozilla/network/cnvts/nsINetPluginInstance.h b/mozilla/network/cnvts/nsINetPluginInstance.h deleted file mode 100644 index e63a01713d5..00000000000 --- a/mozilla/network/cnvts/nsINetPluginInstance.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsINetPluginInstance_h___ -#define nsINetPluginInstance_h___ - -#include "nsINetOStream.h" -#include "nsISupports.h" -#include "nsplugindefs.h" - - -#define NS_INETPLUGININSTANCE_IID \ -{ /* ebe00f40-0199-11d2-815b-006008219d7a */ \ - 0xebe00f40, \ - 0x0199, \ - 0x11d2, \ - {0x81, 0x5b, 0x00, 0x60, 0x08, 0x21, 0x9d, 0x7a} \ -} - -class nsINetPluginInstance : public nsISupports { -public: - static const nsIID& GetIID() { static nsIID iid = NS_INETPLUGININSTANCE_IID; return iid; } - - NS_IMETHOD - Initialize(nsINetOStream* out_stream, const char *stream_name) = 0; - - NS_IMETHOD - GetMIMEOutput(const char* *result, const char *stream_name) = 0; - - NS_IMETHOD - Start(void) = 0; - - NS_IMETHOD - Stop(void) = 0; - - NS_IMETHOD - Destroy(void) = 0; - -}; - - -//////////////////////////////////////////////////////////////////////////////// - -#endif /* nsINetPluginInstance_h___ */ diff --git a/mozilla/network/cnvts/nsNetConverterStream.cpp b/mozilla/network/cnvts/nsNetConverterStream.cpp deleted file mode 100644 index 0ad2f9c6910..00000000000 --- a/mozilla/network/cnvts/nsNetConverterStream.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsNetConverterStream.h" -#include <stdio.h> -#include "net.h" -#include "nscore.h" - - -static NS_DEFINE_IID(kINetOStreamIID, NS_INETOSTREAM_IID); -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); - - -nsNetConverterStream :: nsNetConverterStream() -{ - NS_INIT_REFCNT(); - - mNextStream = nsnull; -} - - -nsNetConverterStream :: ~nsNetConverterStream() -{ - mNextStream = nsnull; -} - - -NS_IMPL_ADDREF(nsNetConverterStream); -NS_IMPL_RELEASE(nsNetConverterStream); - - -nsresult nsNetConverterStream :: QueryInterface(const nsIID& aIID, - void** aInstancePtrResult) -{ - if (!aInstancePtrResult) - { - return NS_ERROR_NULL_POINTER; - } - - if (aIID.Equals(kISupportsIID)) - { - *aInstancePtrResult = (void *)((nsISupports *)this); - AddRef(); - return NS_OK; - } - - if (aIID.Equals(kINetOStreamIID)) - { - *aInstancePtrResult = (void *)((nsINetOStream *)this); - AddRef(); - return NS_OK; - } - - return NS_NOINTERFACE; -} - - -nsresult nsNetConverterStream :: Initialize(void *aStream) -{ - mNextStream = aStream; - return NS_OK; -} - - -nsresult nsNetConverterStream :: Complete(void) -{ - NET_StreamClass *stream; - - stream = (NET_StreamClass *)mNextStream; - if (stream != NULL) - { - stream->complete(stream); - return NS_OK; - } - - return NS_OK; -} - - -nsresult nsNetConverterStream :: Abort(PRInt32 status) -{ - NET_StreamClass *stream; - - stream = (NET_StreamClass *)mNextStream; - if (stream != NULL) - { - stream->abort(stream, status); - return NS_OK; - } - - return NS_OK; -} - - -nsresult nsNetConverterStream :: WriteReady(PRUint32 *aReadyCount) -{ - NET_StreamClass *stream; - - stream = (NET_StreamClass *)mNextStream; - if (stream != NULL) - { - unsigned int ready; - - ready = stream->is_write_ready(stream); - *aReadyCount = ready; - return NS_OK; - } - *aReadyCount = 0; - return NS_OK; -} - - -nsresult nsNetConverterStream :: Write(const char* aBuf, PRUint32 aCount, PRUint32 *aWriteCount) -{ - NET_StreamClass *stream; - - stream = (NET_StreamClass *)mNextStream; - if (stream != NULL) - { - int ret; - - ret = stream->put_block(stream, (char *)aBuf, aCount); - - *aWriteCount = aCount; - return NS_OK; - } - *aWriteCount = 0; - return NS_OK; -} - - -nsresult nsNetConverterStream::Close(void) -{ - return NS_OK; -} - diff --git a/mozilla/network/cnvts/nsNetConverterStream.h b/mozilla/network/cnvts/nsNetConverterStream.h deleted file mode 100644 index 49b52ccb973..00000000000 --- a/mozilla/network/cnvts/nsNetConverterStream.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsNetConverterStream_h___ -#define nsNetConverterStream_h___ - -#include "nsINetOStream.h" - - -class nsNetConverterStream : public nsINetOStream { -public: - nsNetConverterStream(); - virtual ~nsNetConverterStream(); - - NS_DECL_ISUPPORTS - - - //nsINetOStream interface - - NS_IMETHOD - Complete(void); - - NS_IMETHOD - Abort(PRInt32 status); - - NS_IMETHOD - WriteReady(PRUint32 *aReadyCount); - - - // nsIOutputStream interface - - NS_IMETHOD Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteLength); - - NS_IMETHOD Flush(void) { - return NS_OK; - } - - // nsIBaseStream interface - - NS_IMETHOD Close(void); - - - //locals - - nsresult Initialize(void *next_stream); - - -private: - void *mNextStream; - -}; - -#endif /* nsNetConverterStream_h___ */ diff --git a/mozilla/network/cnvts/txview.c b/mozilla/network/cnvts/txview.c deleted file mode 100644 index 4ec827944e2..00000000000 --- a/mozilla/network/cnvts/txview.c +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "xp.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "mkformat.h" - - -PUBLIC NET_StreamClass * -NET_PlainTextConverter (FO_Present_Types format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id) -{ - NET_StreamClass * stream; - char plaintext [] = "<plaintext>"; /* avoid writable string lossage... */ - - StrAllocCopy(URL_s->content_type, TEXT_HTML); - - /* stuff for text fe */ - if(format_out == FO_VIEW_SOURCE) - { - format_out = FO_PRESENT; - } - - stream = NET_StreamBuilder(format_out, URL_s, window_id); - - if(stream) - (*stream->put_block)(stream, plaintext, 11); - - return stream; -} diff --git a/mozilla/network/cnvts/txview.h b/mozilla/network/cnvts/txview.h deleted file mode 100644 index ee072da2089..00000000000 --- a/mozilla/network/cnvts/txview.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef TXVIEW_H -#define TXVIEW_H - -PUBLIC NET_StreamClass * -NET_PlainTextConverter (FO_Present_Types format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *window_id); - - -#endif /* TXVIEW_H */ diff --git a/mozilla/network/cstream/MANIFEST b/mozilla/network/cstream/MANIFEST deleted file mode 100644 index a074a5a6314..00000000000 --- a/mozilla/network/cstream/MANIFEST +++ /dev/null @@ -1,6 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -cstream.h -strmutil.h diff --git a/mozilla/network/cstream/Makefile.in b/mozilla/network/cstream/Makefile.in deleted file mode 100644 index 2de03177ae1..00000000000 --- a/mozilla/network/cstream/Makefile.in +++ /dev/null @@ -1,40 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = cstream -LIBRARY_NAME = cstream - -REQUIRES = network dbm util pref js java fileurl security layer img jtools netcnvts - -CSRCS = cstream.c - -EXPORTS = cstream.h strmutil.h -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/cstream/cstream.c b/mozilla/network/cstream/cstream.c deleted file mode 100644 index dee9bd07833..00000000000 --- a/mozilla/network/cstream/cstream.c +++ /dev/null @@ -1,1250 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * Do stream related stuff like push data down the - * stream and determine which converter to use to - * set up the stream. - * Additions/Changes by Judson Valeski 1998 - */ -#include "mkutils.h" -#include "cstream.h" -#include "plstr.h" -#include "prmem.h" -#include "mkgeturl.h" -#include "netstream.h" -#include "strmutil.h" -#include "mktcp.h" - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_ALERT_CANTFIND_CONVERTER; - - -#ifdef PROFILE -#pragma profile on -#endif - -typedef struct _net_ConverterStruct { - XP_List * converter_stack; /* the ordered list of converters; - * elements are net_ConverterElement's - */ - char * format_in; /* the input (mime) type that the - * function accepts - */ - char * encoding_in; /* the input content-encoding that the - * function accepts, or 0 for `any'. - */ - FO_Present_Types format_out; /* the output type of the function */ - Bool bAutomated; /* this flag currently only used by Window on the - client side. */ -} net_ConverterStruct; - -typedef struct _net_ConverterElement { - NET_Converter * converter; /* the converter function */ - void * data_obj; /* a converter specific data object - * passed in at the - * time of registration - */ -} net_ConverterElement; - -/* MWH - this is an ugly implement to get get around the following: I need to pass - a flag to NET_RegisterContentTypeConverter(), but I don't want to change the API. - If we changed this API please fixed this problem. -*/ - -static Bool autoFlag = 0; - -#define MAX_FORMATS_OUT FO_ONLY_FROM_CACHE_AND_LOAD_HTML_HELP_MAP_FILE +1 - -static Bool needInit = TRUE; /* this is the flag to tell us that we need to initialize - net_converter_list, and net_decoder_list. */ - -PRIVATE XP_List * net_converter_list[MAX_FORMATS_OUT]; /* a list of converters */ -PRIVATE XP_List * net_decoder_list[MAX_FORMATS_OUT]; /* a list of decoders */ - -#define NET_MIME_EXACT_MATCH 1 -#define NET_MIME_PARTIAL_MATCH 2 -#define NET_WILDCARD_MATCH 3 - -/* will compare two mime times and return - * NET_MIME_EXACT_MATCH if they match exactly - * or NET_MIME_PARTIAL_MATCH if they match due - * to a wildcard entry (image.*, or movie.*). - * - * if 'partial' equals '*' then - * NET_WILDCARD_MATCH is returned - * - * If there is no match then 0(zero) is returned - */ -PRIVATE int -net_compare_mime_types(char * absolute, char * partial) -{ - char *star; - - TRACEMSG(("StreamBuilder: Comparing %s and %s\n",absolute, partial)); - - if(!PL_strcasecmp(absolute, partial)) - return(NET_MIME_EXACT_MATCH); - - if(!PL_strcmp(partial, "*")) - return(NET_WILDCARD_MATCH); - - if((star = PL_strchr(partial, '*')) == 0) - return(0); /* not a wildcard mime type */ - - /* compare just the part before the slash star - * - */ - if(!PL_strncasecmp(absolute, partial, (star-1)-partial)) - return(NET_MIME_PARTIAL_MATCH); - - return(0); /* no match */ -} - -PUBLIC XP_Bool -NET_HaveConverterForMimeType(char *content_type) -{ - net_ConverterStruct * cs_ptr; - XP_List * ct_list_ptr = net_converter_list[FO_PRESENT]; - - while ((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ct_list_ptr)) - != 0) - { - if (FO_PRESENT == cs_ptr->format_out) - { - int compare_val = net_compare_mime_types (content_type, cs_ptr->format_in); - if (compare_val == NET_MIME_PARTIAL_MATCH || compare_val == NET_MIME_EXACT_MATCH) - return TRUE; - } - } - - return FALSE; -} - -/* Find a converter routine to create a stream and return the stream struct -*/ -PUBLIC NET_StreamClass * -NET_StreamBuilder (FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *context) -{ - net_ConverterStruct * cs_ptr; - XP_List * ct_list_ptr = net_converter_list[format_out]; - - - - XP_List * ce_list_ptr = net_decoder_list[format_out]; - - assert (URL_s->content_type); - - TRACEMSG(("Entering StreamBuilder:\n\ - F-in: %s\n\ - F-out: %d\n\ - Enc: %s\n",URL_s->content_type,format_out, - (URL_s->content_encoding ? URL_s->content_encoding : "None Specified"))); - -#if 0 - /* First, determine whether there is a content-type converter for this - document; if there isn't one, then the only way to handle it is to - send it straight to disk, so try that. - */ - if (format_out != FO_SAVE_TO_DISK) - { - while ((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ct_list_ptr)) - != 0) - { - if (format_out == cs_ptr->format_out && - net_compare_mime_types (URL_s->content_type, - cs_ptr->format_in)) - break; - } - - if (! cs_ptr) /* There is no content-type converter; save it. */ - format_out = FO_SAVE_TO_DISK; - ct_list_ptr = net_converter_list; /* Reset for next traversal. */ - } -#endif - - - /* if there are content encodings then - * execute decoders first - */ - /* go through list of converters and choose - * the first exact or partial match we - * find. The order of the list - * is guarenteed by the registration - * routines - * - * the format-out is compared as well. - * - * if there are transfer_encodings use them even before - * content_encodings - */ - if ((URL_s->transfer_encoding && *URL_s->transfer_encoding) - || (URL_s->content_encoding && *URL_s->content_encoding)) - { - char *encoding; - - if(URL_s->transfer_encoding && *URL_s->transfer_encoding) - encoding = URL_s->transfer_encoding; - else - encoding = URL_s->content_encoding; - - - while ((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ce_list_ptr)) - != 0) - { - if (format_out == cs_ptr->format_out && - net_compare_mime_types (URL_s->content_type, - cs_ptr->format_in) && - net_compare_mime_types (encoding, - cs_ptr->encoding_in)) - { - net_ConverterElement *elem = XP_ListPeekTopObject(cs_ptr->converter_stack); - PR_ASSERT(elem != (net_ConverterElement *)0); - return ((NET_StreamClass *) - ((*elem->converter) - (format_out, elem->data_obj, URL_s, context))); - } - } - } - - /* now search for content-type converters - */ - /* go through list of converters and choose - * the first exact or partial match we - * find. The order of the list - * is guarenteed by the registration - * routines - */ - while((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ct_list_ptr)) != 0) - { - if(format_out == cs_ptr->format_out) - if(net_compare_mime_types(URL_s->content_type, cs_ptr->format_in)) - { - net_ConverterElement *elem = XP_ListPeekTopObject(cs_ptr->converter_stack); - PR_ASSERT(elem != (net_ConverterElement *)0); - return( (NET_StreamClass *) (*elem->converter) (format_out, - elem->data_obj, URL_s, context)); - } - } - -#ifdef DEBUG_pnunn - TRACEMSG(("Alert! did not find a converter or decoder\n")); - FE_Alert(context, XP_GetString(XP_ALERT_CANTFIND_CONVERTER)); -#endif - - return(0); /* Uh-oh. didn't find a converter. VERY VERY BAD! */ -} - -/* prints out all presentation mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -MODULE_PRIVATE char * -XP_ListNextPresentationType(PRBool first) -{ - static XP_List * converter_list_ptr; - net_ConverterStruct * converter; - - /* reset list pointers - */ - if(first) - converter_list_ptr = net_converter_list[FO_PRESENT]; - - /* print out next converter if there are any more - */ - converter = (net_ConverterStruct *) XP_ListNextObject(converter_list_ptr); - - if(converter && converter->format_out == FO_PRESENT) - return(converter->format_in); - - /* else */ - return(NULL); -} - -/* prints out all encoding mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -MODULE_PRIVATE char * -XP_ListNextEncodingType(PRBool first) -{ - static XP_List * decoder_list_ptr; - net_ConverterStruct * converter; - static int count; - static index = 0; - static int curArrayIndex = 0; - - - while ((index < count) && (curArrayIndex < MAX_FORMATS_OUT)) { - decoder_list_ptr = net_decoder_list[curArrayIndex]; - count = XP_ListCount(decoder_list_ptr); - if (count > 0) { - index = 0; - break; - } - else count++; - } -#if 0 - /* reset list pointers - */ - if(first) - { - decoder_list_ptr = net_decoder_list; - } -#endif - converter = (net_ConverterStruct *) XP_ListNextObject(decoder_list_ptr); - if(converter) { - index++; - return(converter->format_in); - } - - /* else */ - return(NULL); -} - -PRIVATE void -net_RegisterGenericConverterOrDecoder(XP_List ** conv_list, - char * format_in, - char * encoding_in, - FO_Present_Types format_out, - void * data_obj, - NET_Converter * converter_func) -{ - XP_List * list_ptr = *conv_list; - net_ConverterStruct * converter_struct_ptr; - net_ConverterStruct * new_converter_struct; - net_ConverterElement *elem; - int f_in_type; - XP_List *pList; - int i; - - if (needInit) { /* MWH - this will only happen once. It is pretty ugly, - but I don't know how to get around it. */ - needInit = FALSE; - - for (i = 0; i <MAX_FORMATS_OUT;i++) { - net_converter_list[i] = net_decoder_list[i] = 0; - } - - } - - pList = list_ptr = conv_list[format_out]; - /* check for an existing converter with the same format_in and format_out - * and add this to the list if found. - * - * if the list is NULL XP_ListNextObject will return 0 - */ - while((converter_struct_ptr = (net_ConverterStruct *) XP_ListNextObject(list_ptr)) != 0){ - if(format_out == converter_struct_ptr->format_out) - /* Rewritten to logic equivalent but should-be-faster version:*/ - if (((!encoding_in && !converter_struct_ptr->encoding_in) || - (encoding_in && converter_struct_ptr->encoding_in && - !PL_strcmp (encoding_in, - converter_struct_ptr->encoding_in))) - && !PL_strcasecmp(format_in, converter_struct_ptr->format_in) -#ifdef XP_WIN - && (converter_struct_ptr->bAutomated == autoFlag) -#endif - ) - { - /* Add a new converter element to the list */ - net_ConverterElement *elem = PR_NEWZAP(net_ConverterElement); - if( elem == (net_ConverterElement *)0 ) return; - elem->converter = converter_func; - elem->data_obj = data_obj; - XP_ListAddObject(converter_struct_ptr->converter_stack, elem); - return; - } - } - /* find out the type of entry format_in is - */ - f_in_type = NET_MIME_EXACT_MATCH; - if(PL_strchr(format_in, '*')) - { - if(!PL_strcmp(format_in, "*")) - f_in_type = NET_WILDCARD_MATCH; - else - f_in_type = NET_MIME_PARTIAL_MATCH; - } - - /* if existing converter not found/replaced - * add this converter to the list in - * its order of importance so that we can - * take the first exact or partial fit - */ - new_converter_struct = PR_NEW(net_ConverterStruct); - if(!new_converter_struct) { - return; - } - - new_converter_struct->converter_stack = XP_ListNew(); - if( new_converter_struct->converter_stack == (XP_List *)0 ) - { - PR_Free(new_converter_struct); - return; - } - - elem = PR_NEWZAP(net_ConverterElement); - if( elem == (net_ConverterElement *)0 ) - { - XP_ListDestroy(new_converter_struct->converter_stack); - PR_Free(new_converter_struct); - return; - } - - elem->converter = converter_func; - elem->data_obj = data_obj; - new_converter_struct->format_in = 0; - StrAllocCopy(new_converter_struct->format_in, format_in); - new_converter_struct->encoding_in = (encoding_in - ? PL_strdup (encoding_in) : 0); - new_converter_struct->format_out = format_out; - XP_ListAddObject(new_converter_struct->converter_stack, elem); - new_converter_struct->bAutomated = autoFlag; - - - if(!pList) { -/* if(!*conv_list) */ - /* create the list and add this object - * don't worry about order since there - * can't be any - */ - pList = XP_ListNew(); - if(!pList) - return; /* big error */ - conv_list[format_out] = pList; - XP_ListAddObject(pList, new_converter_struct); - return; - } - if(f_in_type == NET_MIME_EXACT_MATCH) - { -#if defined(XP_WIN) && defined (MOZILLA_CLIENT) - net_ConverterStruct *pRegistered; - XP_List *tempList = pList; - int count = XP_ListCount(tempList); - for (i = 0; i < count; i++) { - pRegistered = (net_ConverterStruct *) XP_ListNextObject(tempList); - - if(new_converter_struct->bAutomated == TRUE) { - if(pRegistered->bAutomated == FALSE) { - XP_ListInsertObject (pList, pRegistered, new_converter_struct); - return; - } - } - - /* if it is an exact match type - * then we can just add it to the beginning - * of the list - */ - if (!PL_strcasecmp(pRegistered->format_in, new_converter_struct->format_in) - && ((!pRegistered->encoding_in && !new_converter_struct->format_in) - || !PL_strcasecmp(pRegistered->encoding_in, new_converter_struct->encoding_in))) { - if(new_converter_struct->bAutomated == TRUE) { - PR_Free( new_converter_struct); - return; - } - - // Overwrite - memcpy(pRegistered, new_converter_struct, sizeof(net_ConverterStruct)); - PR_Free( new_converter_struct); - return; - } - } - - - - - - - - XP_ListInsertObject (pList, pRegistered, new_converter_struct); -#else - XP_ListAddObject(pList, new_converter_struct); - TRACEMSG(("Adding Converter to Beginning of list")); -#endif - } - else if(f_in_type == NET_MIME_PARTIAL_MATCH) - { - /* this is a partial wildcard of the form (image/(star)) - * store it at the end of all the exact match pairs - */ - list_ptr = pList; - while((converter_struct_ptr = (net_ConverterStruct *) XP_ListNextObject(list_ptr)) != 0) - { - if(PL_strchr(converter_struct_ptr->format_in, '*')) - { - XP_ListInsertObject (pList, - converter_struct_ptr, - new_converter_struct); - return; - } - } - /* else no * objects in list */ - XP_ListAddObjectToEnd(pList, new_converter_struct); - TRACEMSG(("Adding Converter to Middle of list")); - } - else - { - /* this is a very wild wildcard match of the form "*" only. - * It has the least precedence so store it at the end - * of the list. (There must always be at least one - * item in the list (see above)) - */ - XP_ListAddObjectToEnd(pList, new_converter_struct); - TRACEMSG(("Adding Converter to end of list")); - } -} - -struct net_encoding_converter -{ - char *encoding_in; - void *data_obj; - NET_Converter * converter_func; -}; - -static struct net_encoding_converter *net_all_encoding_converters; -static int net_encoding_converter_size = 0; -static int net_encoding_converter_fp = 0; - -PUBLIC void* NET_GETDataObject(XP_List* list, char* mineType, void** obj) -{ - net_ConverterStruct* converter_struct_ptr; - - *obj = (void*)0; - - while((converter_struct_ptr = (net_ConverterStruct *)XP_ListNextObject(list)) != NULL) { - if(converter_struct_ptr->bAutomated) { - if(!PL_strcmp(converter_struct_ptr->format_in, mineType)) { - net_ConverterElement *elem = XP_ListPeekTopObject(converter_struct_ptr->converter_stack); - *obj = (void*)converter_struct_ptr; - return elem->data_obj; - } - } - } - - return (void*)0; -} - -PUBLIC XP_List* NET_GetRegConverterList(FO_Present_Types iFormatOut) -{ - return net_converter_list[iFormatOut]; - -} -/* register a routine to decode a stream - */ - -PUBLIC void -NET_RegisterEncodingConverter(char *encoding_in, - void * data_obj, - NET_Converter * converter_func) -{ - - /* Don't register anything right now, but remember that we have a - decoder for this so that we can register it hither and yon at - a later date. - */ - if (net_encoding_converter_size <= net_encoding_converter_fp) - { - net_encoding_converter_size += 10; - if (net_all_encoding_converters) - net_all_encoding_converters = (struct net_encoding_converter *) - PR_Realloc (net_all_encoding_converters, - net_encoding_converter_size - * sizeof (*net_all_encoding_converters)); - else - net_all_encoding_converters = (struct net_encoding_converter *) - PR_Calloc (net_encoding_converter_size, - sizeof (*net_all_encoding_converters)); - } - - { /* Don't register the same decoder twice; having too many - decoders is multiplicatively expensive with respect to the number of - calls to net_RegisterGenericConverterOrDecoder() from the loop inside - NET_RegisterAllEncodingConverters(). */ - int i; - for (i=0; i < net_encoding_converter_fp; i++) - if ((net_all_encoding_converters[i].data_obj == data_obj) - && (net_all_encoding_converters[i].converter_func == converter_func) - && (strcmp(net_all_encoding_converters[i].encoding_in,encoding_in) - == 0)) - return; - } - - net_all_encoding_converters [net_encoding_converter_fp].encoding_in - = PL_strdup (encoding_in); - net_all_encoding_converters [net_encoding_converter_fp].data_obj - = data_obj; - net_all_encoding_converters [net_encoding_converter_fp].converter_func - = converter_func; - net_encoding_converter_fp++; - -} - - -#ifdef MOZILLA_CLIENT - -void -NET_DumpDecoders() -{ -#ifdef DEBUG - net_ConverterStruct * cs_ptr; - XP_List *list_ptr = net_decoder_list[FO_PRESENT]; - - while((cs_ptr = XP_ListNextObject(list_ptr))) - { - char *msg = PR_smprintf("in: %s out: %d\n",cs_ptr->encoding_in, cs_ptr->format_out); - - TRACEMSG(("%s", msg)); - FREE(msg); - } -#endif /* DEBUG */ -} - -/* register an encoding converter that is used for everything, - * no exeptions - * this is necessary for chunked encoding - */ -MODULE_PRIVATE void -NET_RegisterUniversalEncodingConverter(char *encoding_in, - void * data_obj, - NET_Converter * converter_func) -{ - int i; - - /* for each list in the net_decoder_list array */ - for (i = 0; i < MAX_FORMATS_OUT; i++) - { - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - "*", - encoding_in, - i, /* format out */ - data_obj, - converter_func); - } - -} - -void -NET_RegisterAllEncodingConverters (char *format_in, - FO_Present_Types format_out) -{ - int i; - -#ifdef XP_UNIX - /* On Unix at least, there should be *some* registered... */ - assert (net_encoding_converter_fp > 0); -#endif - - for (i = 0; i < net_encoding_converter_fp; i++) - { - char *encoding_in = net_all_encoding_converters [i].encoding_in; - void *data_obj = net_all_encoding_converters [i].data_obj; - NET_Converter *func = net_all_encoding_converters [i].converter_func; - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - format_in, - encoding_in, - format_out, - data_obj, - func); - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - format_in, - encoding_in, - format_out | FO_CACHE_ONLY, - data_obj, - func); - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - format_in, - encoding_in, - format_out | FO_ONLY_FROM_CACHE, - data_obj, - func); - } -} - -#endif /* MOZILLA_CLIENT */ - - - - -/* Register a routine to convert between format_in and format_out - * - */ -#if (defined(XP_WIN) || defined(XP_OS2)) && defined(MOZILLA_CLIENT) -/* Reroute XP handling of streams for windows. - * MWH -This routine should not be called recursively. - It rely on the static global variable to set the - * automatedflag. The reason for this is I don't to - change the API on NET_RegisterContentTypeConverter - because some other group still depend on this API. - * If we decided to change API, please fix this. - */ -PUBLIC void -NET_RegContentTypeConverter (char * format_in, - FO_Present_Types format_out, - void * data_obj, - NET_Converter * converter_func, - Bool bAutomated) -{ - autoFlag = bAutomated; - NET_RegisterContentTypeConverter (format_in, format_out, - data_obj, - converter_func); - autoFlag = FALSE; - -} - -#endif - -PUBLIC void -NET_RegisterContentTypeConverter (char * format_in, - FO_Present_Types format_out, - void * data_obj, - NET_Converter * converter_func) -{ - net_RegisterGenericConverterOrDecoder(net_converter_list, - format_in, - 0, - format_out, - data_obj, - converter_func); - -} - -#ifdef MOZILLA_CLIENT -#ifdef XP_UNIX - -#include "cvview.h" -#include "cvextcon.h" - -/* register a mime type and a command to be executed - * - * if stream_block_size is zero then the data will be completely - * pooled and the external viewer called with the filename. - * if stream_block_size is greater than zero the viewer will be - * called with a popen and the stream_block_size will be used as - * the maximum size of each buffer to pass to the viewer - */ -MODULE_PRIVATE void -NET_RegisterExternalViewerCommand(char * format_in, - char * system_command, - unsigned int stream_block_size) -{ - CV_ExtViewStruct * new_obj = PR_NEW(CV_ExtViewStruct); - - if(!new_obj) - return; - - memset(new_obj, 0, sizeof(CV_ExtViewStruct)); - - /* make a new copy of the command so it can be passed - * as the data object - */ - StrAllocCopy(new_obj->system_command, system_command); - new_obj->stream_block_size = stream_block_size; - - /* register the routine - */ - NET_RegisterContentTypeConverter(format_in, FO_PRESENT, new_obj, NET_ExtViewerConverter); - - /* Also register the content-encoding converters on this type. - Those get registered only on types we know how to display, - either internally or externally - and don't get registered - on types we know nothing about. - */ - NET_RegisterAllEncodingConverters (format_in, FO_PRESENT); -} - -/* removes all external viewer commands - */ -PUBLIC void -NET_ClearExternalViewerConverters(void) -{ - XP_List * list_ptr; - XP_List *temp_list; - net_ConverterStruct * converter_struct_ptr; - int i; - - for (i = 0; i <MAX_FORMATS_OUT; i++) { - list_ptr = temp_list = net_converter_list[i]; - while((converter_struct_ptr = - (net_ConverterStruct *) XP_ListNextObject(list_ptr))) - { - XP_List *new; - net_ConverterElement *elem; - - new = XP_ListNew(); - if( new == (XP_List *)0 ) return; - - while( (elem = XP_ListRemoveTopObject(converter_struct_ptr->converter_stack)) != (net_ConverterElement *)0 ) - { - if( elem->converter == NET_ExtViewerConverter ) - { - PR_FREEIF(elem->data_obj); - PR_Free(elem); - continue; - } - else - { - XP_ListAddObjectToEnd(new, elem); - } - } - - XP_ListDestroy(converter_struct_ptr->converter_stack); - - if( XP_ListCount(new) > 0 ) - { - converter_struct_ptr->converter_stack = new; - } - else - { - XP_ListDestroy(new); - XP_ListRemoveObject(temp_list, converter_struct_ptr); - PR_Free(converter_struct_ptr->format_in); - PR_Free(converter_struct_ptr->encoding_in); - PR_Free(converter_struct_ptr); - } - } - } -} - -/* removes all registered converters of any kind - */ -PUBLIC void -NET_ClearAllConverters(void) -{ - net_ConverterStruct * aConverter; - net_ConverterElement * aConverterStackElement; - XP_List * theList; - int i; - - /* for each list in the net_converter_list array */ - for (i = 0; i < MAX_FORMATS_OUT; i++) { - theList = net_converter_list[i]; - /* Traverse it, removing each converter, and freeing its data */ - while( aConverter = (net_ConverterStruct *) XP_ListRemoveTopObject(theList) ) - { - FREEIF(aConverter->format_in); - FREEIF(aConverter->encoding_in); - while( aConverterStackElement = XP_ListRemoveTopObject(aConverter->converter_stack) ) - { -#ifdef XP_UNIX - if(aConverterStackElement->converter == NET_ExtViewerConverter) - PR_FREEIF(aConverterStackElement->data_obj); -#endif /* XP_UNIX */ - PR_Free(aConverterStackElement); - } - XP_ListDestroy(aConverter->converter_stack); - FREE(aConverter); - } - XP_ListDestroy(theList); - net_converter_list[i] = NULL; - } - - /* for each list in the net_decoder_list array */ - for (i = 0; i < MAX_FORMATS_OUT; i++) { - theList = net_decoder_list[i]; - /* Traverse it, removing each converter, and freeing its data */ - while( aConverter = (net_ConverterStruct *) XP_ListRemoveTopObject(theList) ) - { - FREEIF(aConverter->format_in); - FREEIF(aConverter->encoding_in); - while( aConverterStackElement = XP_ListRemoveTopObject(aConverter->converter_stack) ) - { -#ifdef XP_UNIX - if(aConverterStackElement->converter == NET_ExtViewerConverter) - PR_FREEIF(aConverterStackElement->data_obj); -#endif /* XP_UNIX */ - PR_Free(aConverterStackElement); - } - XP_ListDestroy(aConverter->converter_stack); - FREE(aConverter); - } - XP_ListDestroy(theList); - net_decoder_list[i] = NULL; - } -} - -/* register an external program to act as a content-type - * converter - */ -MODULE_PRIVATE void -NET_RegisterExternalConverterCommand(char * format_in, - int format_out, - char * system_command, - char * new_format) -{ - CV_ExtConverterStruct * new_obj = PR_NEW(CV_ExtConverterStruct); - - if(!new_obj) - return; - - memset(new_obj, 0, sizeof(CV_ExtConverterStruct)); - - /* make a new copy of the command so it can be passed - * as the data object - */ - StrAllocCopy(new_obj->command, system_command); - StrAllocCopy(new_obj->new_format, new_format); - new_obj->is_encoding_converter = FALSE; - - /* register the routine - */ - NET_RegisterContentTypeConverter(format_in, format_out, new_obj, NET_ExtConverterConverter); -} - -/* register an external program to act as a content-encoding - * converter - */ -PUBLIC void -NET_RegisterExternalDecoderCommand (char * format_in, - char * format_out, - char * system_command) -{ - CV_ExtConverterStruct * new_obj = PR_NEW(CV_ExtConverterStruct); - - if(!new_obj) - return; - - memset(new_obj, 0, sizeof(CV_ExtConverterStruct)); - - /* make a new copy of the command so it can be passed - * as the data object - */ - StrAllocCopy(new_obj->command, system_command); - StrAllocCopy(new_obj->new_format, format_out); - new_obj->is_encoding_converter = TRUE; - - /* register the routine - */ - NET_RegisterEncodingConverter (format_in, new_obj, - NET_ExtConverterConverter); -} - - -#endif /* XP_UNIX */ -#endif /* MOZILLA_CLIENT */ - -/* NewMKStream - * Utility to create a new initialized NET_StreamClass object - */ -NET_StreamClass * -NET_NewStream (char *name, - MKStreamWriteFunc process, - MKStreamCompleteFunc complete, - MKStreamAbortFunc abort, - MKStreamWriteReadyFunc ready, - void *streamData, - MWContext *windowID) -{ - NET_StreamClass *stream = PR_NEW (NET_StreamClass); - if (!stream) - return nil; - - stream->name = name; - stream->window_id = windowID; - stream->data_object = streamData; - stream->put_block = process; - stream->complete = complete; - stream->abort = abort; - stream->is_write_ready = ready; - - return stream; -} - -PRIVATE XP_List * -net_GetConverterOrDecoderList(XP_List ** conv_list, - char * format_in, - char * encoding_in, - FO_Present_Types format_out) -{ - XP_List * list_ptr = *conv_list; - net_ConverterStruct * converter_struct_ptr; - - while((converter_struct_ptr = (net_ConverterStruct *) XP_ListNextObject(list_ptr)) != 0) - if(format_out == converter_struct_ptr->format_out) - if(!PL_strcasecmp(format_in, converter_struct_ptr->format_in) - && ((!encoding_in && !converter_struct_ptr->encoding_in) || - (encoding_in && converter_struct_ptr->encoding_in && - !PL_strcmp (encoding_in, - converter_struct_ptr->encoding_in))) - ) - { - return converter_struct_ptr->converter_stack; - } - - return (XP_List *)0; -} - -PUBLIC void -NET_DeregisterContentTypeConverter(char *format_in, FO_Present_Types format_out) -{ - XP_List *l; - net_ConverterElement *elem; - - l = net_GetConverterOrDecoderList(net_converter_list, format_in, 0, format_out); - if( l == (XP_List *)0 ) return; - - elem = XP_ListRemoveTopObject(l); -# ifdef XP_UNIX - /* total kludge!! */ - if( elem->converter == NET_ExtViewerConverter ) - PR_FREEIF(elem->data_obj); -# endif - PR_Free(elem); - - return; -} - -#ifdef DEBUG -MODULE_PRIVATE void -NET_DisplayStreamInfoAsHTML(ActiveEntry *cur_entry) -{ - char *buffer = (char*)PR_Malloc(2048); - NET_StreamClass * stream; - int i; - - static char *fo_names[] = { - /* 0 */ "(unknown)", - /* 1 */ "Present", - /* 2 */ "Internal Image", - /* 3 */ "Out to Proxy Client", - /* 4 */ "View Source", - /* 5 */ "Save As", - /* 6 */ "Save as Text", - /* 7 */ "Save as Postscript", - /* 8 */ "Quote Message", - /* 9 */ "Mail To", - /* 10 */ "OLE Network", - /* 11 */ "Multipart Image", - /* 12 */ "Embed", - /* 13 */ "Print", - /* 14 */ "Plugin", - /* 15 */ "Append to Folder", - /* 16 */ "Do Java", - /* 17 */ "Byterange", - /* 18 */ "EDT Save Image", - /* 19 */ "Edit", - /* 20 */ "Load HTML Help Map File", - /* 21 */ "Save to News DB", - /* 22 */ "Open Draft", - }; - - if(!buffer) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - return; - } - - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, - cur_entry->window_id); - - if(!stream) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - FREE(buffer); - return; - } - - - /* define a macro to push a string up the stream - * and handle errors - */ -#define PUT_PART(part) \ -cur_entry->status = (*stream->put_block)(stream, \ - part ? part : "Unknown", \ - part ? PL_strlen(part) : 7); \ -if(cur_entry->status < 0) \ - goto END; - - sprintf(buffer, -"<html><head><title>Information about the Netscape streams configuration</title></head>\n" -"<body><h1>Information about the Netscape streams configuration</h1>\n" -); - - PUT_PART(buffer); - - sprintf(buffer, "<h2>Converter List</h2>\n<ul>"); - PUT_PART(buffer); - - for( i = 0; i < MAX_FORMATS_OUT; i++ ) - { - int j = i & ~FO_CACHE_ONLY & ~FO_ONLY_FROM_CACHE; - XP_List *list_ptr = net_converter_list[i]; - net_ConverterStruct *csp; - - sprintf(buffer, "<li><ul><p>%s", j < sizeof(fo_names)/sizeof(fo_names[0]) ? - fo_names[j] : fo_names[0]); - PUT_PART(buffer); - - if( i & FO_CACHE_ONLY ) - { - sprintf(buffer, " | Cache Only"); - PUT_PART(buffer); - } - - if( i & FO_ONLY_FROM_CACHE ) - { - sprintf(buffer, " | Only From Cache"); - PUT_PART(buffer); - } - - sprintf(buffer, " [%d]</p>", i); - PUT_PART(buffer); - - while( (csp = (net_ConverterStruct *)XP_ListNextObject(list_ptr)) != (net_ConverterStruct *)0 ) - { - XP_List *stack = csp->converter_stack; - int stack_count = XP_ListCount(stack); - net_ConverterElement *elem; - sprintf(buffer, - "<li>Format In: %s<br>\n" - "Encoding In: %s<br>\n" - "Present Type: %d<br>\n" - "%s<br><ol>%d Converter%s:\n", - (csp->format_in != (char *)0) ? csp->format_in : "(null)", - (csp->encoding_in != (char *)0) ? csp->encoding_in : "(null)", - csp->format_out, - csp->bAutomated ? "Automated" : "Not automated", - stack_count, (stack_count == 1) ? "" : "s"); - PUT_PART(buffer); - - while( (elem = (net_ConverterElement *)XP_ListNextObject(stack)) != (net_ConverterElement *)0 ) - { -#if defined(__sun) && !defined(SVR4) - sprintf(buffer, "<li>Converter: %lu<br>Object: %lu<br>\n", - elem->converter, elem->data_obj); -#else - sprintf(buffer, "<li>Converter: %p<br>Object: %p<br>\n", - elem->converter, elem->data_obj); -#endif - PUT_PART(buffer); - } - - sprintf(buffer, "<br></ol>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - - sprintf(buffer, "<h2>Decoder List</h2>\n<ul>"); - PUT_PART(buffer); - - for( i = 0; i < MAX_FORMATS_OUT; i++ ) - { - int j = i & ~FO_CACHE_ONLY & ~FO_ONLY_FROM_CACHE; - XP_List *list_ptr = net_decoder_list[i]; - net_ConverterStruct *csp; - - sprintf(buffer, "<li><ul><p>%s", j < sizeof(fo_names)/sizeof(fo_names[0]) ? - fo_names[j] : fo_names[0]); - PUT_PART(buffer); - - if( i & FO_CACHE_ONLY ) - { - sprintf(buffer, " | Cache Only"); - PUT_PART(buffer); - } - - if( i & FO_ONLY_FROM_CACHE ) - { - sprintf(buffer, " | Only From Cache"); - PUT_PART(buffer); - } - - sprintf(buffer, " [%d]</p>", i); - PUT_PART(buffer); - - while( (csp = (net_ConverterStruct *)XP_ListNextObject(list_ptr)) != (net_ConverterStruct *)0 ) - { - XP_List *stack = csp->converter_stack; - int stack_count = XP_ListCount(stack); - net_ConverterElement *elem; - sprintf(buffer, - "<li>Format In: %s<br>\n" - "Encoding In: %s<br>\n" - "Present Type: %d<br>\n" - "%s<br><ol>%d Converter%s:\n", - (csp->format_in != (char *)0) ? csp->format_in : "(null)", - (csp->encoding_in != (char *)0) ? csp->encoding_in : "(null)", - csp->format_out, - csp->bAutomated ? "Automated" : "Not automated", - stack_count, (stack_count == 1) ? "" : "s"); - PUT_PART(buffer); - - while( (elem = (net_ConverterElement *)XP_ListNextObject(stack)) != (net_ConverterElement *)0 ) - { -#if defined(__sun) && !defined(SVR4) - sprintf(buffer, "<li>Converter: %lu<br>Object: %lu<br>\n", - elem->converter, elem->data_obj); -#else - sprintf(buffer, "<li>Converter: %p<br>Object: %p<br>\n", - elem->converter, elem->data_obj); -#endif - PUT_PART(buffer); - } - - sprintf(buffer, "<br></ol>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - - END: - PR_Free(buffer); - if( cur_entry->status < 0 ) - (*stream->abort)(stream, cur_entry->status); - else - (*stream->complete)(stream); - - return; -} - -#endif /* DEBUG */ - -#ifdef PROFILE -#pragma profile off -#endif - diff --git a/mozilla/network/cstream/cstream.h b/mozilla/network/cstream/cstream.h deleted file mode 100644 index eb0e08f631b..00000000000 --- a/mozilla/network/cstream/cstream.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef CSTREAM_H -#define CSTREAM_H - -XP_BEGIN_PROTOS - -/* builds an outgoing stream and returns a stream class structure - * containing a stream function table - */ -extern NET_StreamClass * NET_StreamBuilder ( - FO_Present_Types format_out, - URL_Struct * anchor, - MWContext * window_id); - -/* stream functions - */ -typedef unsigned int -(*MKStreamWriteReadyFunc) (NET_StreamClass *stream); - -#define MAX_WRITE_READY (((unsigned) (~0) << 1) >> 1) /* must be <= than MAXINT */ - -typedef int -(*MKStreamWriteFunc) (NET_StreamClass *stream, const char *str, int32 len); - -typedef void -(*MKStreamCompleteFunc) (NET_StreamClass *stream); - -typedef void -(*MKStreamAbortFunc) (NET_StreamClass *stream, int status); - -/* - * NewMKStream - * Utility to create a new initialized NET_StreamClass object - */ -extern NET_StreamClass * NET_NewStream(char *, - MKStreamWriteFunc, - MKStreamCompleteFunc, - MKStreamAbortFunc, - MKStreamWriteReadyFunc, - void *, - MWContext *); -/* streamclass function - */ -struct _NET_StreamClass { - - char * name; /* Just for diagnostics */ - - MWContext * window_id; /* used for progress messages, etc. */ - - void * data_object; /* a pointer to whatever - * structure you wish to have - * passed to the routines below - * during writes, etc... - * - * this data object should hold - * the document, document - * structure or a pointer to the - * document. - */ - - MKStreamWriteReadyFunc is_write_ready; /* checks to see if the stream is ready - * for writing. Returns 0 if not ready - * or the number of bytes that it can - * accept for write - */ - - MKStreamWriteFunc put_block; /* writes a block of data to the stream */ - MKStreamCompleteFunc complete; /* normal end */ - MKStreamAbortFunc abort; /* abnormal end */ - - Bool is_multipart; /* is the stream part of a multipart sequence */ -}; - - - -/* prints out all converter mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -extern char * -XP_ListNextPresentationType(PRBool first); - -/* prints out all encoding mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -extern char * -XP_ListNextEncodingType(PRBool first); - -/* register a mime type and a command to be executed - */ -extern void -NET_RegisterExternalViewerCommand(char * format_in, - char * system_command, - unsigned int stream_block_size); - -/* removes all external viewer commands - */ -extern void NET_ClearExternalViewerConverters(void); - -MODULE_PRIVATE void -NET_RegisterExternalConverterCommand(char * format_in, - FO_Present_Types format_out, - char * system_command, - char * new_format); - -void -NET_RegisterAllEncodingConverters (char *format_in, - FO_Present_Types format_out); - -/* register an encoding converter that is used for everything, - * no exeptions - * this is necessary for chunked encoding - */ -void -NET_RegisterUniversalEncodingConverter(char *encoding_in, - void * data_obj, - NET_Converter * converter_func); - -XP_END_PROTOS - -#endif /* CSTREAM.h */ diff --git a/mozilla/network/cstream/makefile.win b/mozilla/network/cstream/makefile.win deleted file mode 100644 index c11882548d0..00000000000 --- a/mozilla/network/cstream/makefile.win +++ /dev/null @@ -1,92 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the cstream LIB -# -#------------------------------------------------------------------------ - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -LLIBS= \ - $(NULL) -OBJS= \ - .\$(OBJDIR)\cstream.obj \ - $(NULL) - - -CSRCS = \ - cstream.c \ - $(NULL) - - -LIBRARY_NAME=cstream - -MODULE=cstream -DEPTH=..\.. - -EXTRA_LIBS= - -REQUIRES= network nspr2 -EXPORTS= cstream.h strmutil.h - -C_OBJS = \ - $(NULL) - - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\dbm \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\network \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\fileurl \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\jtools -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - -install:: - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/cstream/strmutil.h b/mozilla/network/cstream/strmutil.h deleted file mode 100644 index 2bd582b8403..00000000000 --- a/mozilla/network/cstream/strmutil.h +++ /dev/null @@ -1,9 +0,0 @@ - -#ifndef STRMUTIL_H -#define STRMUTIL_H - -#ifdef DEBUG -extern void NET_DisplayStreamInfoAsHTML(ActiveEntry *cur_entry); -#endif /* DEBUG */ - -#endif /* STRMUTIL_H */ diff --git a/mozilla/network/macbuild/NetworkSharedPrefix.h b/mozilla/network/macbuild/NetworkSharedPrefix.h deleted file mode 100644 index bee2ada20bb..00000000000 --- a/mozilla/network/macbuild/NetworkSharedPrefix.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Defining the following causes NS_NET to be defined as NS_EXPORT. */ -#define _IMPL_NS_NET - -#include "MacSharedPrefix.h" diff --git a/mozilla/network/macbuild/NetworkSharedPrefix_debug.h b/mozilla/network/macbuild/NetworkSharedPrefix_debug.h deleted file mode 100644 index a96b83a0d58..00000000000 --- a/mozilla/network/macbuild/NetworkSharedPrefix_debug.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Defining the following causes NS_NET to be defined as NS_EXPORT. */ -#define _IMPL_NS_NET - -#include "MacSharedPrefix_debug.h" diff --git a/mozilla/network/macbuild/network.mcp b/mozilla/network/macbuild/network.mcp deleted file mode 100644 index 1f7fd7c8ee7..00000000000 Binary files a/mozilla/network/macbuild/network.mcp and /dev/null differ diff --git a/mozilla/network/macbuild/network.toc b/mozilla/network/macbuild/network.toc deleted file mode 100644 index 4261b5be7d6..00000000000 --- a/mozilla/network/macbuild/network.toc +++ /dev/null @@ -1,64 +0,0 @@ -# target: NetworkModularDebug.shlb -mozilla/cmd/macfe/central/PascalString.cp -mozilla/cmd/macfe/central/ufilemgr.cp -mozilla/lib/libpwcac/pwcacapi.c -mozilla/lib/mac/Misc/mactime.c -mozilla/lib/xp/allxpstr.c -mozilla/lib/xp/xp_hash.c -mozilla/lib/xp/xp_list.c -mozilla/lib/xp/xp_qsort.c -mozilla/lib/xp/xp_regexp.c -mozilla/lib/xp/xp_str.c -mozilla/lib/xp/xp_stub.c -mozilla/lib/xp/xp_trace.c -mozilla/network/cache/extcache.c -mozilla/network/cache/mkcache.c -mozilla/network/cache/mkextcac.c -mozilla/network/cache/mkmemcac.c -mozilla/network/cnvts/cvactive.c -mozilla/network/cnvts/cvchunk.c -mozilla/network/cnvts/cvcolor.c -mozilla/network/cnvts/cvjscfg.c -mozilla/network/cnvts/cvmime.c -mozilla/network/cnvts/cvsimple.c -mozilla/network/cnvts/cvunzip.c -mozilla/network/cnvts/txview.c -mozilla/network/main/jsautocf.c -mozilla/network/main/jscookie.c -mozilla/network/main/MacBinSupport.c -mozilla/network/main/mkautocf.c -mozilla/network/main/mkconect.c -mozilla/network/main/mkfsort.c -mozilla/network/main/mkgeturl.c -mozilla/network/main/mkinit.c -mozilla/network/main/mkmessag.c -mozilla/network/main/mkpadpac.c -mozilla/network/main/mkparse.c -mozilla/network/main/mkselect.c -mozilla/network/main/mksockrw.c -mozilla/network/main/mksort.c -mozilla/network/main/mkstream.c -mozilla/network/main/mktrace.c -mozilla/network/main/mkutils.c -mozilla/network/main/prefetch.c -mozilla/network/main/singsign.c -mozilla/network/mimetype/mkformat.c -mozilla/network/module/nsHttpUrl.cpp -mozilla/network/module/nsLoadAttribs.cpp -mozilla/network/module/nsNetFactory.cpp -mozilla/network/module/nsNetService.cpp -mozilla/network/module/nsNetStream.cpp -mozilla/network/module/nsNetStubs.cpp -mozilla/network/module/nsNetThread.cpp -mozilla/network/module/nsRelatedLinks.cpp -mozilla/network/module/nsStubContext.cpp -mozilla/network/module/nsURL.cpp -mozilla/network/protocol/about/mkabout.c -mozilla/network/protocol/file/mkfile.c -mozilla/network/protocol/ftp/mkftp.c -mozilla/network/protocol/gopher/mkgopher.c -mozilla/network/protocol/http/mkaccess.c -mozilla/network/protocol/http/mkhttp.c -mozilla/network/protocol/remote/mkremote.c -mozilla/webshell/tests/viewer/macToBeImplemented.cp -mozilla/webshell/tests/viewer/nsMacFile.cp diff --git a/mozilla/network/main/MANIFEST b/mozilla/network/main/MANIFEST deleted file mode 100644 index 0964c1365de..00000000000 --- a/mozilla/network/main/MANIFEST +++ /dev/null @@ -1,19 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mkstream.h -mkparse.h -mkfsort.h -mksort.h -mkgeturl.h -mkselect.h -mktcp.h -netutils.h -mkpadpac.h -mkautocf.h -mkutils.h -mktrace.h -mkhelp.h -net_xp_file.h -mkprefs.h \ No newline at end of file diff --git a/mozilla/network/main/MacBinSupport.c b/mozilla/network/main/MacBinSupport.c deleted file mode 100644 index 720e8708467..00000000000 --- a/mozilla/network/main/MacBinSupport.c +++ /dev/null @@ -1,467 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* MacBinary support.c - -This file implements MacBinary (actually MacBinary II) support for the following: - - -Determine the size of a file when encoded in MacBinary - - -Inline encoding of a file in MacBinary format - -The MacBinary II format consists of a 128-byte header containing all the -information necessary to reproduce the document's directory entry on the -receiving Macintosh; followed by the document's Data Fork (if it has one), -padded with nulls to a multiple of 128 bytes (if necessary); followed by the -document's Resource Fork (again, padded if necessary). The lengths of these -forks (either or both of which may be zero) are contained in the header. - -The format of the header for MacBinary II is as follows: - - Offset 000 Byte old version number, must be kept at zero for compatibility - Offset 001 Byte Length of filename (must be in the range 1-63) - Offset 002 1 to 63 chars, filename (only "length" bytes are significant). - Offset 065 Long file type (normally expressed as four characters) - Offset 069 Long file creator (normally expressed as four characters) - Offset 073 Byte original Finder flags - Bit 7 - Locked. - Bit 6 - Invisible. - Bit 5 - Bundle. - Bit 4 - System. - Bit 3 - Bozo. - Bit 2 - Busy. - Bit 1 - Changed. - Bit 0 - Inited. - Offset 074 Byte zero fill, must be zero for compatibility - Offset 075 Short file's vertical position within its window. - Offset 077 Short file's horizontal position within its window. - Offset 079 Short file's window or folder ID. - Offset 081 Byte "Protected" flag (in low order bit). - Offset 082 Byte zero fill, must be zero for compatibility - Offset 083 Long Data Fork length (bytes, zero if no Data Fork). - Offset 087 Long Resource Fork length (bytes, zero if no R.F.). - Offset 091 Long File's creation date - Offset 095 Long File's "last modified" date. - Offset 099 Short zero fill (was file comment length which is not supported) - Offset 101 Byte Finder Flags, bits 0-7. (Bits 8-15 are already in byte 73) - Offset 116 Long Length of total files when packed files are unpacked. - This is only used by programs that pack and unpack on the fly, - mimicing a standalone utility such as PackIt. A program that is - uploading a single file must zero this location when sending a - file. Programs that do not unpack/uncompress files when - downloading may ignore this value. - Offset 120 Short zero fill (was length of a secondary header which is not supported) - Offset 122 Byte Version number of Macbinary II that the uploading program - is written for (the version begins at 129) - Offset 123 Byte Minimum MacBinary II version needed to read this file - (start this value at 129) - Offset 124 Short CRC of previous 124 bytes - -All values are stored in normal 68000 order, with Most Significant Byte -appearing first then the file. Any bytes in the header not defined above -should be set to zero. - - -MacBinary header creation and CRC calculation based on Erny Tontlinger's free 'Terminal' source - -*/ - -#include "xp.h" - -#include "MacBinSupport.h" - -#include "MoreFilesExtras.h" - -#include <Errors.h> - -enum -{ - kMB_SendingHeader, /* Data from read is MB header */ - kMB_SetupDataFork, /* Finished sending MB header so prepare data fork */ - kMB_SendingDataFork, /* Data from read is file's data fork */ - kMB_SetupResFork, /* Finished sending data fork so prepare res fork */ - kMB_SendingResFork, /* Data from read is file's data fork */ - kMB_FinishedFile /* Nothing left to send - file finished */ - -}; - -static Byte fillerBuf[kMBHeaderLength]; - -static unsigned short CalcMacBinaryCRC(Byte *ptr, unsigned long count) -{ - unsigned short crc; - unsigned short i; - - crc = 0; - while (count-- > 0) { - crc = crc ^ (unsigned short)*ptr++ << 8; - for (i = 0; i < 8; ++i) - if (crc & 0x8000) - crc = crc << 1 ^ 0x1021; - else - crc = crc << 1; - } - return crc; -} - -static OSErr InitMacBinaryHeader(MB_FileSpec *mbFileSpec) -{ -#define MB_VersionNumber 129 -#define MBH_name 1 -#define MBH_info1 65 -#define MBH_protected 81 -#define MBH_dLength 83 -#define MBH_rLength 87 -#define MBH_creation 91 -#define MBH_modification 95 -#define MBH_getInfoLength 99 -#define MBH_info2 101 -#define MBH_filesLength 116 -#define MBH_sHeaderLength 120 -#define MBH_newVersion 122 -#define MBH_minimumVersion 123 -#define MBH_crc 124 - - OSErr theErr; - unsigned short crc; - HParamBlockRec param; - - XP_MEMSET(&param, 0, sizeof(param)); - param.fileParam.ioNamePtr = (StringPtr)mbFileSpec->theFileSpec.name; - param.fileParam.ioVRefNum = mbFileSpec->theFileSpec.vRefNum; - param.fileParam.ioDirID = mbFileSpec->theFileSpec.parID; - theErr = PBHGetFInfoSync(&param); - if (theErr != noErr) - return (theErr); - - XP_MEMSET(mbFileSpec->mbHeader, 0, kMBHeaderLength); - - XP_MEMCPY( - &mbFileSpec->mbHeader[MBH_name], - mbFileSpec->theFileSpec.name, mbFileSpec->theFileSpec.name[0] + 1); - mbFileSpec->mbHeader[MBH_info2] = param.fileParam.ioFlFndrInfo.fdFlags & 0x00FF; - param.fileParam.ioFlFndrInfo.fdFlags &= 0xFF00; - *(long *)&param.fileParam.ioFlFndrInfo.fdLocation = 0; - param.fileParam.ioFlFndrInfo.fdFldr = 0; - XP_MEMCPY(&mbFileSpec->mbHeader[MBH_info1], (void *)&param.fileParam.ioFlFndrInfo, 16); - mbFileSpec->mbHeader[MBH_protected] = (Byte)(param.fileParam.ioFlAttrib) & 0x01; - XP_MEMCPY(&mbFileSpec->mbHeader[MBH_dLength], (void *)&param.fileParam.ioFlLgLen, 4); - XP_MEMCPY(&mbFileSpec->mbHeader[MBH_rLength], (void *)&param.fileParam.ioFlRLgLen, 4); - XP_MEMCPY(&mbFileSpec->mbHeader[MBH_creation], (void *)&param.fileParam.ioFlCrDat, 4); - XP_MEMCPY(&mbFileSpec->mbHeader[MBH_modification], (void *)&param.fileParam.ioFlMdDat, 4); - mbFileSpec->mbHeader[MBH_newVersion] = MB_VersionNumber; - mbFileSpec->mbHeader[MBH_minimumVersion] = MB_VersionNumber; - crc = CalcMacBinaryCRC(mbFileSpec->mbHeader, 124); - XP_MEMCPY(&mbFileSpec->mbHeader[MBH_crc], (void *)&crc, 2); - - mbFileSpec->dataForkLength = param.fileParam.ioFlLgLen; - mbFileSpec->resForkLength = param.fileParam.ioFlRLgLen; - - return (noErr); -} - -static long PadBufferToMacBinBlock(char *buf, long bytesInBuf) -{ - long paddingNeeded = 0; - - if (bytesInBuf % kMBHeaderLength) - { - paddingNeeded = kMBHeaderLength - (bytesInBuf % kMBHeaderLength); - XP_MEMCPY(&buf[bytesInBuf], fillerBuf, paddingNeeded); - } - - return (bytesInBuf + paddingNeeded); -} - -/* MB_Stat - - Returns the size of the file when encoded in MacBinary format - - This is computed as 128 bytes for the MacBinary header + the size of the data fork - rounded up to a multiple of 128 bytes + the size of the resource fork rounded up to - a multiple of 128 bytes. -*/ - -int MB_Stat( const char* name, XP_StatStruct * outStat, XP_FileType type ) -{ - int result = -1; - long totalFileSize = 0; - char *newName = WH_FileName( name, type ); - FSSpec fileSpec = {0, 0, "\p"}; - OSErr theErr; - long dataSize; - long rsrcSize; - long sizeRemainder; - - /* See if we managed to copy the name */ - if (!newName) - return (result); - - /* Now see if we can find out something about the file */ - theErr = FSSpecFromPathname_CWrapper(newName, &fileSpec); - if (theErr == noErr) - { - theErr = FSpGetFileSize(&fileSpec, &dataSize, &rsrcSize); - if (theErr == noErr) - { - result = 0; /* Set the result code to success */ - - totalFileSize = kMBHeaderLength; /* 128 bytes for the MacBin header */ - - /* Make sure data and rsrc sizes are multiples of 128 bytes - before adding them to totalFileSize */ - sizeRemainder = dataSize % kMBHeaderLength; - if (sizeRemainder) - { - dataSize += (kMBHeaderLength - sizeRemainder); - } - totalFileSize += dataSize; - - sizeRemainder = rsrcSize % kMBHeaderLength; - if (sizeRemainder) - { - rsrcSize += (kMBHeaderLength - sizeRemainder); - } - totalFileSize += rsrcSize; - - /* Stuff the calculated file size into the appropriate stat field */ - outStat->st_size = totalFileSize; - } - } - - XP_FREE(newName); - - return (result); -} - -/* MB_Open - - Prepares a file for inline encoding in the MacBinary format. It builds the - MacBinary header and initializes the state machine for the encoding process. - - - Get file info - Build MacBinary header - Set state machine to kMB_SendingHeader - -*/ - -OSErr MB_Open(const char *name, MB_FileSpec *mbFileSpec) -{ - char *newName = WH_FileName( name, xpFileToPost ); - OSErr theErr = noErr; - - /* See if we managed to copy the name */ - if (!newName) - return (fnfErr); - - /* Now see if we can find make an FSSpec for the file */ - theErr = FSSpecFromPathname_CWrapper(newName, &mbFileSpec->theFileSpec); - if (theErr == noErr) - { - theErr = InitMacBinaryHeader(mbFileSpec); - if (theErr == noErr) - { - // Set up the rest of the MB_FileSpec info - mbFileSpec->fileState = kMB_SendingHeader; - mbFileSpec->fileRefNum = -1; - mbFileSpec->dataBytesRead = 0; - mbFileSpec->resBytesRead = 0; - } - } - - /* Make sure our filler buffer is cleared */ - XP_MEMSET(fillerBuf, 0, kMBHeaderLength); - - return (theErr); -} - -/* MB_Read - - Provides a MacBinary encoded version of a file. All reads are done to the supplied - buffer. The MB_Read function just returns how many bytes have been placed in the - buffer. - - Switch on state - kMB_SendingHeader - set state to kMB_SetupDataFork - Return the # of bytes in an MB header - kMB_SetupDataFork - If hasDataFork - Open the data fork of the file - Set the state to kMB_SendingDataFork - GOTO kMB_SendingDataFork - else - GOTO kMB_SetupResFork - kMB_SendingDataFork - Read a buffer's worth of data - Make sure buffer is padded to MB block boundary - If EOF set state to kMB_SetupResFork - Return the # of bytes in buffer - kMB_SetupResFork - Close data fork if open - If hasResFork - Open the resource fork of the file - Set the state to kMB_SendingResFork - GOTO kMB_SendingResFork - else - GOTO kMB_FinishedFile - kMB_SendingResFork - Read a buffer's worth of data - Make sure buffer is padded to MB block boundary - If EOF set state to kMB_FinishedFile - Return the # of bytes in buffer - kMB_FinishedFile - Close resource fork if open - Set the state to kMB_FinishedFile - -*/ -int32 MB_Read(char *buf, int bufSize, MB_FileSpec *mbFileSpec) -{ - long bytesInBuf = 0; - OSErr theErr = noErr; - long count = bufSize; - - switch (mbFileSpec->fileState) - { - case kMB_SendingHeader: - XP_MEMCPY(buf, mbFileSpec->mbHeader, kMBHeaderLength); - bytesInBuf = kMBHeaderLength; - mbFileSpec->fileState = kMB_SetupDataFork; - break; - - case kMB_SetupDataFork: - if (mbFileSpec->dataForkLength) - { - theErr = FSpOpenDF(&mbFileSpec->theFileSpec, fsRdPerm, &mbFileSpec->fileRefNum); - if (theErr == noErr) - { - mbFileSpec->fileState = kMB_SendingDataFork; - - /* Now that the data fork is open jump into the read state */ - goto SendingDataFork; - } - else - { /* Couldn't open the data fork so exit the state machine */ - goto FinishedFile; - } - } - else - { /* Apparently no data fork so go ahead and try the res fork */ - goto SetupResFork; - } - break; - - case kMB_SendingDataFork: -SendingDataFork: - theErr = FSRead(mbFileSpec->fileRefNum, &count, buf); - if (theErr == noErr || theErr == eofErr) - { - bytesInBuf = PadBufferToMacBinBlock(buf, count); - mbFileSpec->dataBytesRead += count; - - /* See if we've reached EOF for the data */ - if (mbFileSpec->dataBytesRead == mbFileSpec->dataForkLength) - mbFileSpec->fileState = kMB_SetupResFork; - } - else - { /* Got some sort of error reading the data fork so exit the state machine */ - goto FinishedFile; - } - break; - - case kMB_SetupResFork: -SetupResFork: - /* Close the data fork */ - if (mbFileSpec->fileRefNum != -1) - { - FSClose(mbFileSpec->fileRefNum); - mbFileSpec->fileRefNum = -1; - } - - /* See if we have a res fork to send */ - if (mbFileSpec->resForkLength) - { - theErr = FSpOpenRF(&mbFileSpec->theFileSpec, fsRdPerm, &mbFileSpec->fileRefNum); - if (theErr == noErr) - { - mbFileSpec->fileState = kMB_SendingResFork; - /* Now that the res fork is open jump into the read state */ - goto SendingResFork; - } - else - { /* Couldn't open the res fork so exit the state machine */ - goto FinishedFile; - } - } - else - { /* Apparently no res fork so go ahead and exite the state machine */ - goto FinishedFile; - } - - case kMB_SendingResFork: -SendingResFork: - theErr = FSRead(mbFileSpec->fileRefNum, &count, buf); - if (theErr == noErr || theErr == eofErr) - { - bytesInBuf = PadBufferToMacBinBlock(buf, count); - mbFileSpec->resBytesRead += count; - - /* See if we've reached EOF for the res fork */ - if (mbFileSpec->resBytesRead == mbFileSpec->resForkLength) - mbFileSpec->fileState = kMB_FinishedFile; - } - else - { /* Got some sort of error reading the res fork so exit the state machine */ - goto FinishedFile; - } - break; - - case kMB_FinishedFile: -FinishedFile: - /* If we're here then we're done with the file */ - mbFileSpec->fileState = kMB_FinishedFile; - - /* If we have a fork open, close it */ - if (mbFileSpec->fileRefNum != -1) - { - FSClose(mbFileSpec->fileRefNum); - mbFileSpec->fileRefNum = -1; - } - break; - } - - return ((int32)bytesInBuf); -} - -/* MB_Close - - Nothing really to do since the file forks are actually closed in the MB_Read - routine after they have been sent. -*/ -void MB_Close(MB_FileSpec *mbFileSpec) -{ - if (mbFileSpec->fileRefNum != -1) - FSClose(mbFileSpec->fileRefNum); - - mbFileSpec->fileState = kMB_FinishedFile; -} diff --git a/mozilla/network/main/MacBinSupport.h b/mozilla/network/main/MacBinSupport.h deleted file mode 100644 index a16b6bb16bb..00000000000 --- a/mozilla/network/main/MacBinSupport.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* MacBinSupport.h */ - -#include "xp_file.h" - -#define kMBHeaderLength 128L - -typedef struct -{ - short fileState; /* Current phase of MB read */ - short fileRefNum; - long dataForkLength; - long dataBytesRead; - long resForkLength; - long resBytesRead; - FSSpec theFileSpec; - Byte mbHeader[kMBHeaderLength]; /* The actual MacBinary header info */ -} MB_FileSpec; - - -#ifdef __cplusplus -extern "C" { -#endif - -/* NOTE!! - FSSpecFromPathname_CWrapper is declared in ufilemgr.cp as an - extern "C" function. This prototype must match the declaration in - ufilemgr.cp or bad things will happen -*/ -OSErr FSSpecFromPathname_CWrapper(char * path, FSSpec * outSpec); - -int MB_Stat( const char* name, XP_StatStruct * outStat, XP_FileType type ); - -OSErr MB_Open(const char *name, MB_FileSpec *mbFileSpec); - -int32 MB_Read(char *buf, int bufSize, MB_FileSpec *mbFileSpec); - -void MB_Close(MB_FileSpec *mbFileSpec); - -#ifdef __cplusplus -} -#endif diff --git a/mozilla/network/main/Makefile.in b/mozilla/network/main/Makefile.in deleted file mode 100644 index 3de9b015011..00000000000 --- a/mozilla/network/main/Makefile.in +++ /dev/null @@ -1,122 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = network -LIBRARY_NAME = network - -REQUIRES = \ - ldapurl \ - imap4url \ - jtools \ - progress \ - dbm \ - util \ - js \ - parse \ - lay \ - style \ - pref \ - htmldlgs \ - java \ - libfont \ - netcache \ - httpurl \ - cnetinit \ - security \ - img \ - layer \ - netcnvts \ - network \ - mimetype \ - ldap \ - net \ - sockstuburl \ - cache \ - progress \ - $(NULL) - -CSRCS = \ - jscookie.c \ - mkautocf.c \ - mkconect.c \ - mkfsort.c \ - mkgeturl.c \ - mkhelp.c \ - mkmessag.c \ - mkpadpac.c \ - mkparse.c \ - mkselect.c \ - mksockrw.c \ - mksort.c \ - mkstream.c \ - mktrace.c \ - mkutils.c \ - prefetch.c \ - unix-dns.c \ - $(NULL) - -CPPSRCS = singsignStub.cpp - -EXPORTS = \ - mkstream.h \ - mkparse.h \ - mkfsort.h \ - mksort.h \ - mkgeturl.h \ - netstream.h \ - mkselect.h \ - mktcp.h \ - netutils.h \ - mkpadpac.h \ - mkautocf.h \ - mkhelp.h \ - mkutils.h \ - mktrace.h \ - net_xp_file.h \ - mkprefs.h \ - $(NULL) - -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - -TEST_LIBS = \ - $(LIBRARY) \ - $(DIST)/lib/liburl.$(LIB_SUFFIX) \ - $(DIST)/lib/libsec-us.$(LIB_SUFFIX) \ - $(DIST)/lib/libdbm.$(LIB_SUFFIX) \ - $(DIST)/lib/libxp.$(LIB_SUFFIX) \ - $(NSPR_LIBS) \ - $(NULL) - -test: - $(CC) -g -o style_test $(CFLAGS) -DSS_TEST stystruc.c $(TEST_LIBS) - $(CC) -g -o stack_test $(CFLAGS) -DTEST_STYLESTACK stystack.c $(TEST_LIBS) - diff --git a/mozilla/network/main/autoupdt.c b/mozilla/network/main/autoupdt.c deleted file mode 100644 index dfaef4fa178..00000000000 --- a/mozilla/network/main/autoupdt.c +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* NEED TO REMOVE. Contact dougt@netscape.com. */ \ No newline at end of file diff --git a/mozilla/network/main/autoupdt.h b/mozilla/network/main/autoupdt.h deleted file mode 100644 index dfaef4fa178..00000000000 --- a/mozilla/network/main/autoupdt.h +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* NEED TO REMOVE. Contact dougt@netscape.com. */ \ No newline at end of file diff --git a/mozilla/network/main/crawler.c b/mozilla/network/main/crawler.c deleted file mode 100644 index 1e223bd1000..00000000000 --- a/mozilla/network/main/crawler.c +++ /dev/null @@ -1,1463 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** crawler.c ****************************************************/ -/* description: implementation for the html crawler. */ - - - /******************************************************************** - - 15.Jan.98 mchung - The crawler sometimes has the annoying behavior of thrashing when the cache is getting - full. When the available space is less than a threshold (sizeSlop) crawling will stop, - but the situation arises where we are outside the threshold and each file that comes - in is larger. Netlib will pull down the file and immediately remove it because it would - exceed the cache size. There are a couple of strategies for fixing this: increase the - sizeSlop when a file is not cached, so we cross the threshold sooner, or stop caching - after a certain number of files have not been cached, or some combination of these. - In any case, crawling should _not_ stop if no cache has been specified. - - The approach I am taking for now is to increase the sizeSlop (which lowers the threshold - for the cache to be considered full) by SIZE_SLOP every time a file fails to be cached. - This would alleviate the thrashing problem but would result in the threshold being - lowered prematurely if the crawler encounters several large files which would exceed the cache, - before the cache is nearly full, but the remainder of the files are "normal" size. The - appropriate strategy really depends on how accurately the max cache size reflects the total - content size (if not accurate we need to be more aggressive about lowering the threshold), - and how close to the cache limit we need to go. - - To do - (maybe) One service the crawler might provide is informing its client that a url has - changed. For a page this could also mean that one or more of its images or resources - has changed. In order to do this it would be necessary to track which images and resources - belong to which page(s) (or crawl them right after the page), find the url in the cache - and store their last modified date and content length before calling netlib to get the url. - On return if the last modified date is later or the content length is different, the - url has changed. - - (definitely) i18n of the parser - - $Revision: 1.3 $ - $Date: 1999-11-06 02:32:27 $ - - *********************************************************************/ - -#include "xp.h" -#include "xp_str.h" -#include "xpassert.h" -#include "prio.h" -#include "prmem.h" -#include "plhash.h" -#include "prprf.h" -#include "robotxt.h" -#include "pagescan.h" -#include "crawler.h" - -/* #define CRAWLERTEST */ - -#ifdef CRAWLERTEST -#include "fe_proto.h" /* FE_GetNetHelpContext */ -#include "prinrval.h" -#include "mkextcac.h" -#endif - -#define SIZE_SLOP ((uint32)2000) - -typedef uint8 CRAWL_Status; -#define CRAWL_STOPPED ((CRAWL_Status)0x00) -#define CRAWL_STOP_REQUESTED ((CRAWL_Status)0x01) -#define CRAWL_RUNNING ((CRAWL_Status)0x02) - -typedef uint8 CRAWL_CrawlerItemType; -#define CRAWLER_ITEM_TYPE_PAGE ((CRAWL_CrawlerItemType)0x00) -#define CRAWLER_ITEM_TYPE_IMAGE ((CRAWL_CrawlerItemType)0x01) -#define CRAWLER_ITEM_TYPE_RESOURCE ((CRAWL_CrawlerItemType)0x02) - -typedef uint8 CRAWL_LinkStatus; - -#define NEW_LINK ((CRAWL_LinkStatus)0x01) -#define REPLACED_LINK ((CRAWL_LinkStatus)0x02) -#define OLD_LINK ((CRAWL_LinkStatus)0x03) - -typedef struct _CRAWL_LinkInfoStruc { - time_t lastModifiedDate; - CRAWL_LinkStatus status; -} CRAWL_LinkInfoStruc; - -/* - * Typedef for function callback (used internally) - */ - typedef void -(*CRAWL_ProcessItemFunc)(CRAWL_Crawler crawler, char *url, CRAWL_RobotControl control, CRAWL_CrawlerItemType type); - -typedef struct _CRAWL_ItemTable { - CRAWL_ItemList items; - uint16 count; -} CRAWL_ItemTable; - -typedef struct _CRAWL_CrawlerStruct { - char *siteName; - char *siteHost; - uint8 depth; /* how many levels to crawl */ - uint32 sizeSlop; /* size in bytes of the amount of space left in the cache for the cache - to be considered full */ - - CRAWL_ItemTable *linkedPagesTable; /* has entry for each depth containing all the page URLs */ - CRAWL_ItemTable *linkedImagesTable; /* has entry for each depth containing all the image URLs*/ - CRAWL_ItemTable *linkedResourcesTable; /* has entry for each depth containing all the resource URLs*/ - - PLHashTable *pagesParsed; /* key is a url, value is last modified time */ - PLHashTable *imagesCached; /* key is a url, value is last modified time */ - PLHashTable *resourcesCached; /* key is a url, value is last modified time */ - - CRAWL_Status status; /* is the crawler running? */ - CRAWL_Error error; - - uint8 currentDepth; /* starts at 1 */ - CRAWL_CrawlerItemType currentType; /* which type of item we're working on */ - uint16 itemIndex; /* which item in the table we're working on */ - CRAWL_ItemList requiredResources; - uint16 numRequiredResources; - - /* determines what items crawler is allowed or disallowed to crawl at a given site. - key is a site name, value is RobotControl */ - PLHashTable *robotControlTable; - - CRAWL_ItemList keys; /* keeps track of the hashtable keys (so they can be freed) */ - uint16 numKeys; - uint16 sizeKeys; - - PRBool stayInSite; - PRBool manageCache; /* maintain a file which lists the cached items so links unreferenced in the next update may be removed */ - MWContext *context; /* dummy context */ - ExtCacheDBInfo *cache; /* external cache */ - CRAWL_PostProcessItemFn postProcessItemFn; - void *postProcessItemData; - CRAWL_ExitFn exitFn; - void *exitData; -} CRAWL_CrawlerStruct; - -typedef struct _Crawl_DoProcessItemRecordStruct { - CRAWL_Crawler crawler; - CRAWL_CrawlerItemType type; /* which type of item we're working on */ - char *url; - CRAWL_RobotControl control; - CRAWL_ProcessItemFunc func; -} Crawl_DoProcessItemRecordStruct; - -typedef Crawl_DoProcessItemRecordStruct *Crawl_DoProcessItemRecord; - -extern void crawl_stringToLower(char *str); -extern int crawl_appendStringList(char ***list, uint16 *len, uint16 *size, char *str); - -/* prototypes */ -static PRBool crawl_hostEquals(char *pagehost, char *sitehost); -static void crawl_destroyItemTable(CRAWL_ItemTable *table); -static int crawl_appendToItemList(CRAWL_ItemList *list1, - uint16 *numList1, - const CRAWL_ItemList list2, - uint16 numList2); -static int crawl_insertInItemList(CRAWL_ItemList *list1, - uint16 *numList1, - const CRAWL_ItemList list2, - uint16 numList2, - uint16 pos); -static int crawl_destroyRobotControl(PLHashEntry *he, int i, void *arg); -static int crawl_destroyLinkInfo(PLHashEntry *he, int i, void *arg); -static PRBool crawl_cacheNearlyFull(CRAWL_Crawler crawler); -static void crawl_processLinkWithRobotControl(CRAWL_Crawler crawler, - char *url, - CRAWL_RobotControl control, - CRAWL_CrawlerItemType type); -static int crawl_addCacheTableEntry(PLHashTable *ht, const char *key, time_t lastModifiedDate); -static void crawl_executePostProcessItemFn(CRAWL_Crawler crawler, URL_Struct *URL_s, PRBool isCached); -static void crawl_nonpage_exit(URL_Struct *URL_s, - int status, - MWContext *window_id, - CRAWL_CrawlerItemType type); -static void crawl_cache_image_exit(URL_Struct *URL_s, int status, MWContext *window_id); -static void crawl_cache_resource_exit(URL_Struct *URL_s, int status, MWContext *window_id); -static void crawl_processItemWithRobotControl(CRAWL_Crawler crawler, - char *url, - CRAWL_RobotControl control, - CRAWL_CrawlerItemType type); -static void crawl_processNextLink(CRAWL_Crawler crawler); -static void crawl_scanPageComplete(void *data, CRAWL_PageInfo pageInfo); -static PRBool crawl_isCrawlableURL(char *url); -static Crawl_DoProcessItemRecord crawl_makeDoProcessItemRecord(CRAWL_Crawler crawler, - char *url, - CRAWL_RobotControl control, - CRAWL_CrawlerItemType type, - CRAWL_ProcessItemFunc func); -static void crawl_doProcessItem(void *data); -static void crawl_processLink(CRAWL_Crawler crawler, - PLHashTable *ht, - char *url, - CRAWL_ProcessItemFunc func, - CRAWL_CrawlerItemType type); -static int crawl_writeCachedLinks(PLHashEntry *he, int i, void *arg); -static int crawl_writeCachedImages(PLHashEntry *he, int i, void *arg); -static int crawl_writeCachedResources(PLHashEntry *he, int i, void *arg); -static char* crawl_makeCacheInfoFilename(CRAWL_Crawler crawler); -static void crawl_writeCacheList(CRAWL_Crawler crawler); -static int crawl_processCacheInfoEntry(CRAWL_Crawler crawler, char *line, PLHashTable *ht); -static int crawl_processCacheInfoLine(CRAWL_Crawler crawler, char *line); -static void crawl_removeDanglingLinksFromCache(CRAWL_Crawler crawler); -static int crawl_updateCrawlerErrors(PLHashEntry *he, int i, void *arg); -static void crawl_crawlerFinish(CRAWL_Crawler crawler); -static void crawl_outOfMemory(CRAWL_Crawler crawler); -#ifdef CRAWLERTEST -void testCrawler(char *name, char *inURL, uint8 depth, uint32 maxSize, PRBool stayInSite); -static void myPostProcessFn(CRAWL_Crawler crawler, URL_Struct *url_s, PRBool isCached, void *data); -static void myExitFn(CRAWL_Crawler crawler, void *data); -#endif - -PR_IMPLEMENT(PRBool) CRAWL_IsStopped(CRAWL_Crawler crawler) { - return((crawler->status == CRAWL_STOPPED) ? PR_TRUE : PR_FALSE); -} - -PR_IMPLEMENT(CRAWL_Error) CRAWL_GetError(CRAWL_Crawler crawler) { - return(crawler->error); -} - -/* returns true if the host names are the same. - - The arguments are assumed to be already converted to lower case. - - If the hostname of the page is a substring of the hostname of the site, or - vice versa, return true. For example, w3 and w3.mcom.com - - This would fail if for example an intranet had a server called netscape. Then any - pages www.netscape.com would be considered to be on that server. - - If the domain names are the same, return true. The domain name is extracted by taking the - substring after the first dot. The domain name must contain another dot (www.yahoo.com and - search.yahoo.com are considered equivalent, but foo.org and bar.org are not). - - This fails to compare id addresses to host names -*/ -static PRBool -crawl_hostEquals(char *pagehost, char *sitehost) { - if ((PL_strstr(sitehost, pagehost) != NULL) || (PL_strstr(pagehost, sitehost) != NULL)) - return PR_TRUE; - else { - char *pageDomain = PL_strchr(pagehost, '.'); - char *siteDomain = PL_strchr(sitehost, '.'); - if ((pageDomain != NULL) && (siteDomain != NULL)) { - char *pageDomainType = PL_strchr(pageDomain+1, '.'); - char *siteDomainType = PL_strchr(siteDomain+1, '.'); - if ((pageDomainType != NULL) && - (siteDomainType != NULL) && - (PL_strcmp(pageDomain+1, siteDomain+1) == 0)) { - return PR_TRUE; - } - } - } - return PR_FALSE; -} - -static void -crawl_destroyItemTable(CRAWL_ItemTable *table) { - uint16 count; - for (count = 0; count < table->count; count++) { - char *item = *(table->items + count); - if (item != NULL) PR_Free(item); - } - if (table->items != NULL) PR_Free(table->items); -} - -/* appends list2 to the end of list1. Returns -1 if no memory */ -static int -crawl_appendToItemList(CRAWL_ItemList *list1, - uint16 *numList1, - const CRAWL_ItemList list2, - uint16 numList2) { - /* this memory freed in CRAWL_DestroyCrawler */ - CRAWL_ItemList newList = (CRAWL_ItemList)PR_Malloc(sizeof(CRAWL_Item) * (*numList1 + numList2)); - CRAWL_ItemList old = *list1; - if (newList == NULL) return -1; - memcpy((char*)newList, (char*)*list1, sizeof(CRAWL_Item) * (*numList1)); /* copy first list */ - memcpy((char*)(newList + *numList1), (char*)list2, sizeof(CRAWL_Item) * numList2); - *list1 = newList; - *numList1 += numList2; - if (old != NULL) PR_Free(old); - return 0; -} - -/* inserts list2 at (zero-indexed) position in list1. Returns -1 if no memory. */ -static int -crawl_insertInItemList(CRAWL_ItemList *list1, - uint16 *numList1, - const CRAWL_ItemList list2, - uint16 numList2, - uint16 pos) { - /* this memory freed in CRAWL_DestroyCrawler */ - CRAWL_ItemList newList = (CRAWL_ItemList)PR_Malloc(sizeof(CRAWL_Item) * (*numList1 + numList2)); - CRAWL_ItemList old = *list1; - if (newList == NULL) return -1; - memcpy((char*)newList, (char*)*list1, sizeof(CRAWL_Item) * pos); /* copy first list up to pos */ - memcpy((char*)(newList + pos), (char*)list2, sizeof(CRAWL_Item) * numList2); /* copy second list */ - memcpy((char*)(newList + pos + numList2), (char*)(*list1 + pos), sizeof(CRAWL_Item) * (*numList1 - pos)); - *list1 = newList; - *numList1 += numList2; - if (old != NULL) PR_Free(old); - return 0; -} - -PR_IMPLEMENT(CRAWL_Crawler) -CRAWL_MakeCrawler(MWContext *context, - char *siteName, - uint8 depth, - PRBool stayInSite, - PRBool manageCache, - ExtCacheDBInfo *cache, - CRAWL_PostProcessItemFn postProcessItemFn, - void *postProcessItemData, - CRAWL_ExitFn exitFn, - void *exitData) { - CRAWL_Crawler crawler; - if (depth < 1) return NULL; - crawler = PR_NEWZAP(CRAWL_CrawlerStruct); - if (crawler == NULL) return NULL; - crawler->siteName = PL_strdup(siteName); - crawl_stringToLower(crawler->siteName); - crawler->siteHost = NET_ParseURL(crawler->siteName, GET_PROTOCOL_PART | GET_HOST_PART); - crawler->depth = depth; - crawler->sizeSlop = SIZE_SLOP; - crawler->stayInSite = stayInSite; - crawler->manageCache = manageCache; - /* this memory freed in CRAWL_DestroyCrawler */ - crawler->linkedPagesTable = (CRAWL_ItemTable*)PR_Calloc(depth+1, sizeof(CRAWL_ItemTable)); - crawler->linkedImagesTable = (CRAWL_ItemTable*)PR_Calloc(depth+1, sizeof(CRAWL_ItemTable)); - crawler->linkedResourcesTable = (CRAWL_ItemTable*)PR_Calloc(depth+1, sizeof(CRAWL_ItemTable)); - if (crawler->linkedPagesTable == NULL || - crawler->linkedImagesTable == NULL || - crawler->linkedResourcesTable == NULL) - return NULL; - crawler->pagesParsed = PL_NewHashTable(100, PL_HashString, PL_CompareStrings, PL_CompareValues, NULL, NULL); - crawler->imagesCached = PL_NewHashTable(100, PL_HashString, PL_CompareStrings, PL_CompareValues, NULL, NULL); - crawler->resourcesCached = PL_NewHashTable(100, PL_HashString, PL_CompareStrings, PL_CompareValues, NULL, NULL); - crawler->robotControlTable = PL_NewHashTable(50, PL_HashString, PL_CompareStrings, PL_CompareValues, NULL, NULL); - crawler->context = context; - crawler->cache = cache; - crawler->status = CRAWL_STOPPED; - crawler->postProcessItemFn = postProcessItemFn; - crawler->postProcessItemData = postProcessItemData; - crawler->exitFn = exitFn; - crawler->exitData = exitData; - return crawler; -} - -/* an enumerator function for the robotControlTable hashtable - maybe this should be moved to an allocator op */ -static int -crawl_destroyRobotControl(PLHashEntry *he, int i, void *arg) { -#if defined(XP_MAC) -#pragma unused(i, arg) -#endif - CRAWL_DestroyRobotControl((CRAWL_RobotControl)he->value); - return HT_ENUMERATE_NEXT; -} - -/* an enumerator function for the cache tables */ -static int -crawl_destroyLinkInfo(PLHashEntry *he, int i, void *arg) { -#if defined(XP_MAC) -#pragma unused(i, arg) -#endif - if (he->value != NULL) PR_Free(he->value); - return HT_ENUMERATE_NEXT; -} - -PR_IMPLEMENT(void) -CRAWL_DestroyCrawler(CRAWL_Crawler crawler) { - int i; - if (crawler->siteName != NULL) PR_DELETE(crawler->siteName); - if (crawler->siteHost != NULL) PR_DELETE(crawler->siteHost); - PL_HashTableEnumerateEntries(crawler->pagesParsed, crawl_destroyLinkInfo, NULL); - PL_HashTableEnumerateEntries(crawler->imagesCached, crawl_destroyLinkInfo, NULL); - PL_HashTableEnumerateEntries(crawler->resourcesCached, crawl_destroyLinkInfo, NULL); - PL_HashTableEnumerateEntries(crawler->robotControlTable, crawl_destroyRobotControl, NULL); - for (i = 0; i < crawler->depth; i++) { - crawl_destroyItemTable(crawler->linkedPagesTable + i); - crawl_destroyItemTable(crawler->linkedImagesTable + i); - crawl_destroyItemTable(crawler->linkedResourcesTable + i); - } - PR_DELETE(crawler->linkedPagesTable); - PR_DELETE(crawler->linkedImagesTable); - PR_DELETE(crawler->linkedResourcesTable); - PL_HashTableDestroy(crawler->pagesParsed); - PL_HashTableDestroy(crawler->imagesCached); - PL_HashTableDestroy(crawler->resourcesCached); - PL_HashTableDestroy(crawler->robotControlTable); - for (i = 0; i < crawler->numKeys; i++) { - PR_Free(crawler->keys[i]); /* these were created with PL_strdup so use PR_Free */ - } - if (crawler->keys != NULL) PR_DELETE(crawler->keys); - PR_DELETE(crawler); -} - -/* returns true if the cache is almost full (libnet insures that DiskCacheSize won't exceed MaxSize) -*/ -static PRBool -crawl_cacheNearlyFull(CRAWL_Crawler crawler) { - if ((crawler->cache != NULL) && - (crawler->cache->MaxSize - crawler->cache->DiskCacheSize <= crawler->sizeSlop)) - return PR_TRUE; - else return PR_FALSE; -} - -/* error handling for no memory, for situations where we want to exit right away. */ -static void -crawl_outOfMemory(CRAWL_Crawler crawler) { - crawler->error |= CRAWL_NO_MEMORY; - crawl_crawlerFinish(crawler); -} - -/* scans a page if robots.txt allows it */ -static void -crawl_processLinkWithRobotControl(CRAWL_Crawler crawler, - char *url, - CRAWL_RobotControl control, - CRAWL_CrawlerItemType type) { - PR_ASSERT(type == CRAWLER_ITEM_TYPE_PAGE); - if (CRAWL_GetRobotControl(control, url) == CRAWL_ROBOT_DISALLOWED) { - crawl_processNextLink(crawler); - } else { - CRAWL_PageInfo pageInfo = crawl_makePage(crawler->siteName, url, crawler->cache); - if (pageInfo != NULL) { - crawl_scanPage(pageInfo, crawler->context, crawl_scanPageComplete, crawler); - } else crawl_outOfMemory(crawler); - } -} - -/* add an entry to the table of items cached with the last modified time */ -static int -crawl_addCacheTableEntry(PLHashTable *ht, const char *key, time_t lastModifiedDate) { - CRAWL_LinkInfoStruc *info = PR_NEWZAP(CRAWL_LinkInfoStruc); - if (info == NULL) return -1; - info->lastModifiedDate = lastModifiedDate; - info->status = NEW_LINK; - PL_HashTableAdd(ht, key, (void*)info); - return 0; -} - -static void crawl_executePostProcessItemFn(CRAWL_Crawler crawler, URL_Struct *URL_s, PRBool isCached) { - if (!isCached) crawler->sizeSlop += SIZE_SLOP; /* lower the threshold for cache fullness */ - if (crawler->postProcessItemFn != NULL) - (crawler->postProcessItemFn)(crawler, URL_s, isCached, crawler->postProcessItemData); -} - -/* common completion code for images and resources */ -static void -crawl_nonpage_exit(URL_Struct *URL_s, int status, MWContext *window_id, CRAWL_CrawlerItemType type) { -#if defined(XP_MAC) -#pragma unused(window_id) -#endif - int err = 0; - CRAWL_Crawler crawler = (CRAWL_Crawler)URL_s->owner_data; - PLHashTable *table = NULL; - switch(type) { - case CRAWLER_ITEM_TYPE_IMAGE: - table = crawler->imagesCached; - break; - case CRAWLER_ITEM_TYPE_RESOURCE: - table = crawler->resourcesCached; - break; - default: - break; - } - PR_ASSERT(table != NULL); - - if (URL_s->server_status >= 400) crawler->error |= CRAWL_SERVER_ERR; - /* add to the images cached if we are in fact caching and the cache_file is set */ - if ((status >= 0) && ((crawler->cache == NULL) || (URL_s->cache_file != NULL))) { - char *url = PL_strdup(URL_s->address); - if (url == NULL) { - crawl_outOfMemory(crawler); - return; - } - err = crawl_addCacheTableEntry(table, url, URL_s->last_modified); - crawl_executePostProcessItemFn(crawler, URL_s, PR_TRUE); - if (err == 0) - err = crawl_appendStringList(&crawler->keys, &crawler->numKeys, &crawler->sizeKeys, url); - } else { - crawl_executePostProcessItemFn(crawler, URL_s, PR_FALSE); - } - - if (status != MK_CHANGING_CONTEXT) - NET_FreeURLStruct(URL_s); - - if (err == 0) crawl_processNextLink(crawler); - else crawl_outOfMemory(crawler); /* alert! assumes any error code returned means out of memory */ -} - -/* exit routine for NET_GetURL for images */ -static void -crawl_cache_image_exit(URL_Struct *URL_s, int status, MWContext *window_id) -{ - crawl_nonpage_exit(URL_s, status, window_id, CRAWLER_ITEM_TYPE_IMAGE); -} - -/* exit routine for NET_GetURL for resources */ -static void -crawl_cache_resource_exit(URL_Struct *URL_s, int status, MWContext *window_id) -{ - crawl_nonpage_exit(URL_s, status, window_id, CRAWLER_ITEM_TYPE_RESOURCE); -} - -/* caches an image or resource if robots.txt allows it */ -static -void crawl_processItemWithRobotControl(CRAWL_Crawler crawler, - char *url, - CRAWL_RobotControl control, - CRAWL_CrawlerItemType type) { - if (CRAWL_GetRobotControl(control, url) == CRAWL_ROBOT_DISALLOWED) { - crawl_processNextLink(crawler); - } else if (crawler->cache != NULL) { - URL_Struct *url_s; - url_s = NET_CreateURLStruct(url, NET_NORMAL_RELOAD); - if (url_s == NULL) crawl_outOfMemory(crawler); - url_s->load_background = PR_TRUE; - url_s->SARCache = crawler->cache; - url_s->owner_data = crawler; - switch (type) { - case CRAWLER_ITEM_TYPE_IMAGE: - NET_GetURL(url_s, FO_CACHE_AND_CRAWL_RESOURCE, crawler->context, crawl_cache_image_exit); - break; - case CRAWLER_ITEM_TYPE_RESOURCE: - NET_GetURL(url_s, FO_CACHE_AND_CRAWL_RESOURCE, crawler->context, crawl_cache_resource_exit); - break; - } - } -} - -/* Process the next link in the table at the current depth. - Pages at the previous depth are scanned, and then images and resources at the current depth - are cached. -*/ -#ifndef DEFER_RESOURCE_SCAN - -static -void crawl_processNextLink(CRAWL_Crawler crawler) { - PRBool allDone = PR_FALSE; - PLHashTable *completedTable; - CRAWL_ProcessItemFunc func = NULL; - static uint16 requiredIndex = 0; - - /* parse all the pages at the previous depth, (this includes also frames and layers for - the most recently scanned page) and then process the images and resources - at the current depth. - */ - if (crawler->currentDepth <= crawler->depth) { - CRAWL_ItemTable *table; - switch (crawler->currentType) { - case CRAWLER_ITEM_TYPE_PAGE: - /* if the previous page had any required resources, cache them now. */ - if (crawler->requiredResources != NULL) { - PR_LogPrint(("required resources")); - if (requiredIndex < crawler->numRequiredResources) { - crawl_processLink(crawler, - crawler->resourcesCached, - *(crawler->requiredResources + requiredIndex++), - crawl_processItemWithRobotControl, - CRAWLER_ITEM_TYPE_RESOURCE); - return; /* wait for callback */ - } else { - uint16 i; - for (i = 0; i < crawler->numRequiredResources; i++) { - PR_Free(*(crawler->requiredResources + i)); - } - requiredIndex = crawler->numRequiredResources = 0; - PR_DELETE(crawler->requiredResources); - } - } - /* process the pages at the previous level */ - table = crawler->linkedPagesTable + crawler->currentDepth - 1; - func = crawl_processLinkWithRobotControl; - completedTable = crawler->pagesParsed; - if (crawler->itemIndex == table->count) { /* no more items */ - /* done with the pages, now do the images */ - PR_LogPrint(("finished pages")); - func = crawl_processItemWithRobotControl; - crawler->currentType = CRAWLER_ITEM_TYPE_IMAGE; - completedTable = crawler->imagesCached; - table = crawler->linkedImagesTable + crawler->currentDepth; - crawler->itemIndex = 0; - } - break; - case CRAWLER_ITEM_TYPE_IMAGE: - table = crawler->linkedImagesTable + crawler->currentDepth; - func = crawl_processItemWithRobotControl; - completedTable = crawler->imagesCached; - if (crawler->itemIndex == table->count) { /* no more items */ - PR_LogPrint(("finished images")); - /* done with the images, now do the resources */ - func = crawl_processItemWithRobotControl; - crawler->currentType = CRAWLER_ITEM_TYPE_RESOURCE; - completedTable = crawler->resourcesCached; - table = crawler->linkedResourcesTable + crawler->currentDepth; - crawler->itemIndex = 0; - } - break; - case CRAWLER_ITEM_TYPE_RESOURCE: - table = crawler->linkedResourcesTable + crawler->currentDepth; - func = crawl_processItemWithRobotControl; - completedTable = crawler->resourcesCached; - if (crawler->itemIndex == table->count) { /* no more items */ - PR_LogPrint(("finished resources")); - if (crawler->currentDepth == crawler->depth) { - allDone = PR_TRUE; - break; - } - /* done with the resources, now go to next level */ - func = crawl_processLinkWithRobotControl; - crawler->currentType = CRAWLER_ITEM_TYPE_PAGE; - completedTable = crawler->pagesParsed; - crawler->currentDepth++; - PR_LogPrint(("depth = %d", crawler->currentDepth)); - crawler->itemIndex = 0; - table = crawler->linkedPagesTable + crawler->currentDepth - 1; - } - break; - } - if (!allDone) { - if (table->count == crawler->itemIndex) crawl_processNextLink(crawler); /* new table is empty */ - else { - crawl_processLink(crawler, - completedTable, - *(table->items + (crawler->itemIndex++)), - func, - crawler->currentType); - } - } else { - crawl_crawlerFinish(crawler); - } - } -} - -#else - -/* this version traverses the tree like Netcaster 1.0: all the pages at all the depths, then all the - images at all the depths, and then all the resources at all the depths. -*/ -static -void crawl_processNextLink(CRAWL_Crawler crawler) { - PRBool allDone = PR_FALSE; - PLHashTable *completedTable; - CRAWL_ProcessItemFunc func = NULL; - static uint16 requiredIndex = 0; - - /* parse all the pages at the previous depth, (this includes also frames and layers for - the most recently scanned page) and then process the images and resources - at the current depth. - */ - if (crawler->currentDepth <= crawler->depth) { - CRAWL_ItemTable *table; - switch (crawler->currentType) { - case CRAWLER_ITEM_TYPE_PAGE: - /* if the previous page had any required resources, cache them now. */ - if (crawler->requiredResources != NULL) { - PR_LogPrint(("required resources")); - if (requiredIndex < crawler->numRequiredResources) { - crawl_processLink(crawler, - crawler->resourcesCached, - *(crawler->requiredResources + requiredIndex++), - crawl_processItemWithRobotControl, - CRAWLER_ITEM_TYPE_RESOURCE); - return; /* wait for callback */ - } else { - uint16 i; - for (i = 0; i < crawler->numRequiredResources; i++) { - PR_Free(*(crawler->requiredResources + i)); - } - requiredIndex = crawler->numRequiredResources = 0; - PR_DELETE(crawler->requiredResources); - } - } - /* process the pages at the previous level */ - table = crawler->linkedPagesTable + crawler->currentDepth - 1; - func = crawl_processLinkWithRobotControl; - completedTable = crawler->pagesParsed; - if (crawler->itemIndex == table->count) { /* no more items */ - /* done with the pages at this level, now go to next level */ - if (crawler->currentDepth < crawler->depth) { - crawler->currentDepth++; - PR_LogPrint(("depth = %d", crawler->currentDepth)); - crawler->itemIndex = 0; - } else { - /* done with pages, now do images */ - crawler->currentDepth = 1; - crawler->itemIndex = 0; - func = crawl_processItemWithRobotControl; - crawler->currentType = CRAWLER_ITEM_TYPE_IMAGE; - completedTable = crawler->imagesCached; - table = crawler->linkedImagesTable + crawler->currentDepth; - } - } - break; - case CRAWLER_ITEM_TYPE_IMAGE: - table = crawler->linkedImagesTable + crawler->currentDepth; - func = crawl_processItemWithRobotControl; - completedTable = crawler->imagesCached; - if (crawler->itemIndex == table->count) { /* no more items */ - if (crawler->currentDepth < crawler->depth) { - crawler->currentDepth++; - PR_LogPrint(("depth = %d", crawler->currentDepth)); - crawler->itemIndex = 0; - } else { - /* done with the images, now do the resources */ - crawler->currentDepth = 1; - crawler->itemIndex = 0; - func = crawl_processItemWithRobotControl; - crawler->currentType = CRAWLER_ITEM_TYPE_RESOURCE; - completedTable = crawler->resourcesCached; - table = crawler->linkedResourcesTable + crawler->currentDepth; - crawler->itemIndex = 0; - } - } - break; - case CRAWLER_ITEM_TYPE_RESOURCE: - table = crawler->linkedResourcesTable + crawler->currentDepth; - func = crawl_processItemWithRobotControl; - completedTable = crawler->resourcesCached; - if (crawler->itemIndex == table->count) { /* no more items */ - if (crawler->currentDepth < crawler->depth) { - crawler->currentDepth++; - PR_LogPrint(("depth = %d", crawler->currentDepth)); - crawler->itemIndex = 0; - } else { - allDone = PR_TRUE; - break; - } - } - break; - } - if (!allDone) { - if (table->count == crawler->itemIndex) crawl_processNextLink(crawler); /* new table is empty */ - else { - crawl_processLink(crawler, - completedTable, - *(table->items + (crawler->itemIndex++)), - func, - crawler->currentType); - } - } else { - crawl_crawlerFinish(crawler); - } - } -} -#endif - -/* adds links from the page just parsed to the appropriate table, and continue. - This is a completion routine for the page scan. -*/ -static -void crawl_scanPageComplete(void *data, CRAWL_PageInfo pageInfo) { - int err = 0; - CRAWL_Crawler crawler = (CRAWL_Crawler)data; - URL_Struct *url_s = crawl_getPageURL_Struct(pageInfo); - char *url = PL_strdup(crawl_getPageURL(pageInfo)); - - if (url == NULL) crawl_outOfMemory(crawler); - - if (url_s->server_status >= 400) crawler->error |= CRAWL_SERVER_ERR; - - /* add url to pages parsed only if it was actually cached - this might mean that - we would parse the url again if encountered, but this should only be encountered - when the cache is full, and we're about to quit. - */ - if (crawl_pageCanBeIndexed(pageInfo)) { /* no meta robots tag directing us not to index, i.e. cache */ - if ((crawler->cache == NULL) || (url_s->cache_file != NULL)) { /* was cached, or not cache specified */ - err = crawl_addCacheTableEntry(crawler->pagesParsed, url, crawl_getPageLastModified(pageInfo)); - crawl_executePostProcessItemFn(crawler, url_s, PR_TRUE); - if (err == 0) - err = crawl_appendStringList(&crawler->keys, &crawler->numKeys, &crawler->sizeKeys, url); - } else { /* wasn't cached */ - crawl_executePostProcessItemFn(crawler, url_s, PR_FALSE); - } - } else { /* obey meta robots tag and remove from cache. */ - NET_RemoveURLFromCache(url_s); - if (crawler->postProcessItemFn != NULL) - (crawler->postProcessItemFn)(crawler, url_s, PR_FALSE, crawler->postProcessItemData); - } - - if ((crawl_getPageLinks(pageInfo) != NULL) && (err == 0)) { - /* add links to pages at depth */ - err = crawl_appendToItemList(&(crawler->linkedPagesTable + crawler->currentDepth)->items, - &(crawler->linkedPagesTable + crawler->currentDepth)->count, - crawl_getPageLinks(pageInfo), - crawl_getPageLinkCount(pageInfo)); - } - if ((crawl_getPageImages(pageInfo) != NULL) && (err == 0)) { - /* add images to images at depth */ - err = crawl_appendToItemList(&(crawler->linkedImagesTable + crawler->currentDepth)->items, - &(crawler->linkedImagesTable + crawler->currentDepth)->count, - crawl_getPageImages(pageInfo), - crawl_getPageImageCount(pageInfo)); - } - if ((crawl_getPageResources(pageInfo) != NULL) && (err == 0)) { - /* add resources to resources at depth */ - err = crawl_appendToItemList(&(crawler->linkedResourcesTable + crawler->currentDepth)->items, - &(crawler->linkedResourcesTable + crawler->currentDepth)->count, - crawl_getPageResources(pageInfo), - crawl_getPageResourceCount(pageInfo)); - } - if ((crawl_getPageFrames(pageInfo) != NULL) && (err == 0)) { - /* add frames to pages currently being processed (next link will be a frame) */ - err = crawl_insertInItemList(&(crawler->linkedPagesTable + crawler->currentDepth - 1)->items, - &(crawler->linkedPagesTable + crawler->currentDepth - 1)->count, - crawl_getPageFrames(pageInfo), - crawl_getPageFrameCount(pageInfo), - crawler->itemIndex); - } - if ((crawl_getPageLayers(pageInfo) != NULL) && (err == 0)){ - /* add layers to pages currently being processed */ - err = crawl_insertInItemList(&(crawler->linkedPagesTable + crawler->currentDepth - 1)->items, - &(crawler->linkedPagesTable + crawler->currentDepth - 1)->count, - crawl_getPageLayers(pageInfo), - crawl_getPageLayerCount(pageInfo), - crawler->itemIndex); - } - if ((crawl_getPageRequiredResources(pageInfo) != NULL) && (err == 0)) { - err = crawl_appendToItemList(&crawler->requiredResources, - &crawler->numRequiredResources, - crawl_getPageRequiredResources(pageInfo), - crawl_getPageRequiredResourceCount(pageInfo)); - } - /* crawler->currentPage = pageInfo; */ - if (err == 0) crawl_processNextLink(crawler); - else crawl_outOfMemory(crawler); -} - -/* returns false if the url is empty or contains any entities */ -static -PRBool crawl_isCrawlableURL(char *url) { - char *amp, *semicolon; - if (*url == '\0') return PR_FALSE; - amp = PL_strchr(url, '&'); - if (amp != NULL) { - semicolon = PL_strchr(amp, ';'); - if (semicolon != NULL) return PR_FALSE; /* don't crawl any url with entities */ - } - return PR_TRUE; -} - -/* callback structure for the robots.txt parser, freed in robotxt.c */ -static Crawl_DoProcessItemRecord -crawl_makeDoProcessItemRecord(CRAWL_Crawler crawler, char *url, CRAWL_RobotControl control, CRAWL_CrawlerItemType type, CRAWL_ProcessItemFunc func) { - Crawl_DoProcessItemRecord rec; - rec = (Crawl_DoProcessItemRecord)PR_Malloc(sizeof(Crawl_DoProcessItemRecordStruct)); - rec->crawler = crawler; - rec->control = control; - rec->url = url; - rec->type = type; - rec->func = func; - return rec; -} - -/* callback for the robots.txt parser */ -static void -crawl_doProcessItem(void *data) { - Crawl_DoProcessItemRecord rec = (Crawl_DoProcessItemRecord)data; - rec->func(rec->crawler, rec->url, rec->control, rec->type); -} - -/* processes a link (page, image, or resource). -*/ -static void -crawl_processLink(CRAWL_Crawler crawler, - PLHashTable *ht, - char *url, - CRAWL_ProcessItemFunc func, - CRAWL_CrawlerItemType type) { - CRAWL_RobotControl control; - char *siteURL; - PLHashNumber keyHash; - PLHashEntry *he, **hep; - - if (crawler->status == CRAWL_STOP_REQUESTED) { - crawler->error |= CRAWL_INTERRUPTED; - crawl_crawlerFinish(crawler); /* stop update */ - return; - } - - if (crawl_cacheNearlyFull(crawler)) { - PR_LogPrint(("crawl_processLink: cache is full, stopping")); - crawler->error |= CRAWL_CACHE_FULL; - crawl_crawlerFinish(crawler); /* stop update */ - return; - } - - if (!crawl_isCrawlableURL(url)) { - crawl_processNextLink(crawler); - return; - } - - /* check if already processed - use raw lookup because value can be 0 */ - keyHash = (*ht->keyHash)(url); - hep = PL_HashTableRawLookup(ht, keyHash, url); - if ((he = *hep) != 0) { - crawl_processNextLink(crawler); - return; - } - - siteURL = NET_ParseURL(url, GET_PROTOCOL_PART | GET_HOST_PART); /* PR_Malloc'd */ - crawl_stringToLower(siteURL); - - if (crawler->stayInSite && !crawl_hostEquals(siteURL, crawler->siteHost)) { - PR_Free(siteURL); - crawl_processNextLink(crawler); /* skip this item */ - return; - } - - /* get robot directives for this site, creating if it doesn't exist */ - control = PL_HashTableLookup(crawler->robotControlTable, siteURL); - if (control == NULL) { - control = CRAWL_MakeRobotControl(crawler->context, siteURL); - if (control != NULL) { - Crawl_DoProcessItemRecord rec; - PL_HashTableAdd(crawler->robotControlTable, siteURL, control); - /* keep a separate list of the hosts around so we can free them later on */ - if (crawl_appendStringList(&crawler->keys, &crawler->numKeys, &crawler->sizeKeys, siteURL) < 0) { - crawl_outOfMemory(crawler); - return; - } - /* if we successfully issue request for robots.txt, return (link processed in callback), - , otherwise process it now. */ - rec = crawl_makeDoProcessItemRecord(crawler, url, control, type, func); - if (rec == NULL) { - crawl_outOfMemory(crawler); - return; - } - if (CRAWL_ReadRobotControlFile(control, crawl_doProcessItem, rec, PR_TRUE)) return; /* wait for the callback */ - } else { - PR_Free(siteURL); - crawl_outOfMemory(crawler); - return; - } - } else PR_Free(siteURL); /* we found a robot control */ - - if (control != NULL) { - func(crawler, url, control, type); - } -} - -/* starts crawling from the url specified */ -PR_IMPLEMENT(void) -CRAWL_StartCrawler(CRAWL_Crawler crawler, char *url) { - crawler->currentDepth = 1; - crawler->status = CRAWL_RUNNING; - /* just assume it's a page for now. The crawler converter won't attempt to - parse it if the mime type is not text/html. */ - crawl_processLink(crawler, - crawler->pagesParsed, - url, - crawl_processLinkWithRobotControl, - CRAWLER_ITEM_TYPE_PAGE); -} - -/* stops crawling safely */ -PR_IMPLEMENT(void) -CRAWL_StopCrawler(CRAWL_Crawler crawler) { - crawler->status = CRAWL_STOP_REQUESTED; -} - -/****************************************************************************************/ -/* cache management using .dat file */ -/****************************************************************************************/ - -static int -crawl_writeCachedLinks(PLHashEntry *he, int i, void *arg) { -#if defined(XP_MAC) -#pragma unused(i) -#endif - PRFileDesc *fd = (PRFileDesc *)arg; - PR_fprintf(fd, "L>%s/%lu\n", he->key, he->value); - return HT_ENUMERATE_NEXT; -} - -static int -crawl_writeCachedImages(PLHashEntry *he, int i, void *arg) { -#if defined(XP_MAC) -#pragma unused(i) -#endif - PRFileDesc *fd = (PRFileDesc *)arg; - PR_fprintf(fd, "I>%s/%lu\n", he->key, he->value); - return HT_ENUMERATE_NEXT; -} - -static int -crawl_writeCachedResources(PLHashEntry *he, int i, void *arg) { -#if defined(XP_MAC) -#pragma unused(i) -#endif - PRFileDesc *fd = (PRFileDesc *)arg; - PR_fprintf(fd, "R>%s/%lu\n", he->key, he->value); - return HT_ENUMERATE_NEXT; -} - -/* result is malloc'd on Windows, not on Mac or UNIX. - crawler->cache is assumed to be non-null. */ -static char* -crawl_makeCacheInfoFilename(CRAWL_Crawler crawler) { -#if defined(XP_MAC) - OSErr ConvertMacPathToUnixPath(const char *macPath, char **unixPath); -#endif - char *tmp = NULL, *tmpName, *dot, *filename; - - tmp = (char *)PR_MALLOC(PL_strlen(crawler->cache->filename) + 5); /* +5 for .dat and null termination */ - PL_strcpy(tmp, crawler->cache->filename); - if (tmp == NULL) return NULL; - dot = PL_strchr(tmp, '.'); - if (dot != NULL) *dot = '\0'; - PL_strcat(tmp, ".dat"); - tmpName = WH_FileName(tmp, xpSARCache); -#ifndef XP_MAC - filename = WH_FilePlatformName(tmpName); -#else - /* unfortunately PR_Open doesn't like the output of WH_FileName, we have to - convert it to a Unix path, or use the XP_File routines. - */ - /* filename = tmpName; */ - ConvertMacPathToUnixPath(tmpName, &filename); -#endif - PR_Free(tmp); - return filename; -} - -/* Writes list of all links, images, and resources that were cached by the crawler. - crawler->cache is assumed to be non-null. -*/ -static void -crawl_writeCacheList(CRAWL_Crawler crawler) { - PRFileDesc *fd; - char *filename = crawl_makeCacheInfoFilename(crawler); - if (filename != NULL) { - PR_Delete(filename); - fd = PR_Open(filename, PR_CREATE_FILE | PR_RDWR, 0644); - if(fd == NULL) return; - /* write here */ - PL_HashTableEnumerateEntries(crawler->pagesParsed, crawl_writeCachedLinks, fd); - PL_HashTableEnumerateEntries(crawler->imagesCached, crawl_writeCachedImages, fd); - PL_HashTableEnumerateEntries(crawler->resourcesCached, crawl_writeCachedResources, fd); - PR_Close(fd); -#ifdef XP_WIN - PR_Free(filename); /* WH_FilePlatformName malloc's on Win but not Mac and X */ -#endif - } else crawler->error |= CRAWL_NO_MEMORY; -} - -/* if the cache item specified in the line does not exist in the table, remove it from the cache - returns -1 if no memory, 0 for no error. */ -static int -crawl_processCacheInfoEntry(CRAWL_Crawler crawler, char *line, PLHashTable *ht) { - PLHashNumber keyHash; - PLHashEntry *he, **hep; - char old; - char *slash = PL_strrchr(line, '/'); - char *gt = PL_strchr(line, '>'); - if ((slash != NULL) && (gt != NULL)) { - char *url = gt + 1; - char *date = slash + 1; - old = *slash; - *slash = '\0'; /* temporarily null terminate url */ - /* check if exists - use raw lookup because value can be 0 */ - keyHash = (*ht->keyHash)(url); - hep = PL_HashTableRawLookup(ht, keyHash, url); - if ((he = *hep) == 0) { - URL_Struct *url_s = NET_CreateURLStruct(url, NET_DONT_RELOAD); - if (url_s != NULL) { - url_s->SARCache = crawler->cache; - NET_RemoveURLFromCache(url_s); - crawler->error |= CRAWL_REMOVED_LINK; - NET_FreeURLStruct(url_s); - } else { - crawler->error |= CRAWL_NO_MEMORY; - return(-1); - } - } else { - /* there is an entry in the table so check the modified date */ - char *end = NULL; - CRAWL_LinkInfoStruc *info = (CRAWL_LinkInfoStruc*)he->value; - time_t oldDate = strtoul(date, &end, 10); - if (info->lastModifiedDate > oldDate) { - info->status = REPLACED_LINK; - } else { - info->status = OLD_LINK; /* could either be old or a new one with no last modified date reported */ - } - } - *slash = old; - } - return(0); -} - -/* returns -1 on error, 0 for no error */ -static int -crawl_processCacheInfoLine(CRAWL_Crawler crawler, char *line) { - if (line != NULL) { - switch (*line) { - case 'L': - return(crawl_processCacheInfoEntry(crawler, line, crawler->pagesParsed)); - case 'I': - return(crawl_processCacheInfoEntry(crawler, line, crawler->imagesCached)); - case 'R': - return(crawl_processCacheInfoEntry(crawler, line, crawler->resourcesCached)); - default: - return(-1); - } - } - return(-1); -} - -#define CACHE_INFO_BUF_SIZE 10 -/* Reads the existing cache info file and for each entry, does a lookup in the appropriate table - of pages, images, or resources cached. If not found, removes the file from the cache. -*/ -static void -crawl_removeDanglingLinksFromCache(CRAWL_Crawler crawler) { - static char buf[CACHE_INFO_BUF_SIZE]; - char *line = NULL; - char *eol; - int32 n = 0, status; - char *filename = crawl_makeCacheInfoFilename(crawler); - if (filename != NULL) { - PRFileDesc *fd; - fd = PR_Open(filename, PR_RDONLY, 0644); - if (fd == NULL) return; - while ((status = PR_Read(fd, buf, CACHE_INFO_BUF_SIZE)) > 0) { - while (n < status) { - if ((eol = PL_strchr(buf + n, '\n')) == NULL) { - /* no end of line detected so add to line and continue */ - if (line == NULL) line = (char *)PR_CALLOC(status+1); - else line = (char *)PR_REALLOC(line, PL_strlen(line) + status + 1); - if (line == NULL) { - PR_Close(fd); - return; - } - PL_strcat(line, buf + n, status); - n += status; - } else { - /* end of line detected so copy line up to there */ - int32 len = eol - (buf + n); - if (line == NULL) line = (char *)PR_CALLOC(len + 1); - else line = (char *)PR_REALLOC(line, PL_strlen(line) + len + 1); - if (line == NULL) { - PR_Close(fd); - return; - } - PL_strcat(line, buf + n, len); - if (crawl_processCacheInfoLine(crawler, line) != 0) { - PR_Close(fd); /* abort on bad data */ - return; - } - PR_Free(line); - line = NULL; - n += (len + 1); - } - } - n = 0; - } - PR_Close(fd); - } else crawler->error |= CRAWL_NO_MEMORY; -} - -static int -crawl_updateCrawlerErrors(PLHashEntry *he, int i, void *arg) { -#if defined(XP_MAC) -#pragma unused(i) -#endif - CRAWL_LinkInfoStruc *info = (CRAWL_LinkInfoStruc *)he->value; - CRAWL_Crawler crawler = (CRAWL_Crawler)arg; - switch (info->status) { - case NEW_LINK: - crawler->error |= CRAWL_NEW_LINK; - break; - case REPLACED_LINK: - crawler->error |= CRAWL_REPLACED_LINK; - break; - case OLD_LINK: - default: - break; - } - return HT_ENUMERATE_NEXT; -} - -/* called when we're done processing all the items */ -static void -crawl_crawlerFinish(CRAWL_Crawler crawler) { - /* remove old cache items */ - if (crawler->manageCache && - (crawler->cache != NULL) && - ((crawler->error & CRAWL_NO_MEMORY) == 0) && - (crawler->pagesParsed->nentries > 0)) { - crawl_removeDanglingLinksFromCache(crawler); - PL_HashTableEnumerateEntries(crawler->pagesParsed, crawl_updateCrawlerErrors, (void*)crawler); - PL_HashTableEnumerateEntries(crawler->imagesCached, crawl_updateCrawlerErrors, (void*)crawler); - PL_HashTableEnumerateEntries(crawler->resourcesCached, crawl_updateCrawlerErrors, (void*)crawler); - crawl_writeCacheList(crawler); - } - crawler->status = CRAWL_STOPPED; - crawler->sizeSlop = SIZE_SLOP; /* reset, in case someone decides to use this crawler again (although docs say not to use again) */ - if (crawler->exitFn != NULL) (crawler->exitFn)(crawler, crawler->exitData); -} - -/****************************************************************************************/ -/* stream routines for images and resources */ -/****************************************************************************************/ - -/* prototypes */ -PRIVATE int crawl_ResourceConvPut(NET_StreamClass *stream, char *s, int32 l); -PRIVATE int crawl_ResourceConvWriteReady(NET_StreamClass *stream); -PRIVATE void crawl_ResourceConvComplete(NET_StreamClass *stream); -PRIVATE void crawl_ResourceConvAbort(NET_StreamClass *stream, int status); - -PRIVATE int -crawl_ResourceConvPut(NET_StreamClass *stream, char *s, int32 l) -{ -#if defined(XP_MAC) -#pragma unused(stream, s, l) -#endif - return(0); -} - -PRIVATE int -crawl_ResourceConvWriteReady(NET_StreamClass *stream) -{ -#if defined(XP_MAC) -#pragma unused(stream) -#endif - return(MAX_WRITE_READY); -} - -PRIVATE void -crawl_ResourceConvComplete(NET_StreamClass *stream) -{ -#if defined(XP_MAC) -#pragma unused(stream) -#endif - /* do nothing */ -} - -PRIVATE void -crawl_ResourceConvAbort(NET_StreamClass *stream, int status) -{ -#if defined(XP_MAC) -#pragma unused(stream, status) -#endif - /* do nothing */ -} - -/* - The reason for using a converter for images and resources is efficiency - - to prevent netlib from getting a url if we can tell in advance that - it will exceed the cache size. Otherwise netlib will get the url, determine - that it has exceeded the cache size and immediately delete it. - - I haven't done enough testing to determine if this is a big win or not. -*/ -PUBLIC NET_StreamClass * -CRAWL_CrawlerResourceConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id) -{ -#if defined(XP_MAC) -#pragma unused(format_out) -#endif - NET_StreamClass *stream = NULL; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - PR_LogPrint(("CRAWL_CrawlerResourceConverter: %d %s", URL_s->server_status, URL_s->address)); - - if (URL_s->SARCache != NULL) { - /* if the content length would exceed the cache limit, don't convert this */ - if (((uint32)URL_s->content_length >= (URL_s->SARCache->MaxSize - URL_s->SARCache->DiskCacheSize)) && - ((uint32)URL_s->content_length < BOGUS_CONTENT_LENGTH)) { - PR_LogPrint(("not converting %s", URL_s->address)); - return(NULL); - } - } - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - stream->name = "Crawler Resource Converter"; - stream->complete = (MKStreamCompleteFunc) crawl_ResourceConvComplete; - stream->abort = (MKStreamAbortFunc) crawl_ResourceConvAbort; - stream->put_block = (MKStreamWriteFunc) crawl_ResourceConvPut; - stream->is_write_ready = (MKStreamWriteReadyFunc) crawl_ResourceConvWriteReady; - stream->data_object = data_object; /* document info object */ - stream->window_id = window_id; - return(stream); -} - -#ifdef CRAWLERTEST -static void myPostProcessFn(CRAWL_Crawler crawler, URL_Struct *url_s, PRBool isCached, void *data) { - if (isCached) PR_LogPrint(("%s was cached, content length=%d", url_s->address, url_s->content_length)); - else PR_LogPrint(("%s wasn't cached, content length=%d", url_s->address, url_s->content_length)); - PR_LogPrint(("cache size=%d, size slop=%d", crawler->cache->DiskCacheSize, crawler->sizeSlop)); -} - -static void myExitFn(CRAWL_Crawler crawler, void *data) { - char *msg; - PRIntervalTime startTime = (PRIntervalTime)data; - msg = PR_smprintf("Crawler finished in %lu milliseconds - cache full=%d", - PR_IntervalToMilliseconds(PR_IntervalNow() - startTime), - (crawler->error & CRAWL_CACHE_FULL)); - FE_Alert(crawler->context, msg); - PR_smprintf_free(msg); - CRAWL_DestroyCrawler(crawler); -} - -void testCrawler(char *name, char *inURL, uint8 depth, uint32 maxSize, PRBool stayInSite) { - CRAWL_Crawler crawler; - char *url = PL_strdup(inURL); -#ifdef XP_MAC - MWContext *context = XP_FindSomeContext(); /* FE_GetNetHelpContext didn't work with netlib on Mac */ -#else - MWContext *context = FE_GetNetHelpContext(); -#endif - ExtCacheDBInfo *cache = PR_NEWZAP(ExtCacheDBInfo); - - cache->name = "test cache"; - cache->filename = name; - cache->path = "\\"; /* ignored */ - cache->MaxSize = maxSize; - - cache = CACHE_GetCache(cache); - crawler = CRAWL_MakeCrawler(context, - url, - depth, - stayInSite, - PR_TRUE, - cache, - myPostProcessFn, - NULL, - myExitFn, - (void*)PR_IntervalNow()); - CRAWL_StartCrawler(crawler, url); -} -#endif - -#if 0 -/****************************************************************************************/ -/* test harness code fragment */ -/****************************************************************************************/ - -/* - Here is a code fragment which may be helpful for testing inside of the client. - You can modify NET_GetURL so it will recognize about:crawler and invoke the crawler. - Also modify net_output_about_url so it returns -1 for about:crawler. - These functions are defined in ns/lib/libnet/mkgeturl.c - - The following parameters are available - url - starting url to crawl from (defaults to http://w3.mcom.com/) - depth - how many levels to crawl (defaults to 1) - maxsize - maximum cache size in bytes (defaults to 200000) - stayinsite - if 1, restricts crawling to the site of the initial url (defaults to 1), - otherwise crawling is unrestricted. - name - name of the cache (defaults to test.db) - - The parameters are separated by &. - - Example: - - about:crawler?url=http://home&depth=2&stayinsite=0 - -*/ - -NET_GetURL (URL_Struct *URL_s, - FO_Present_Types output_format, - MWContext *window_id, - Net_GetUrlExitFunc* exit_routine) -{ - ... - - case ABOUT_TYPE_URL: - ... - - if (URL_s && PL_strncmp(URL_s->address, "about:crawler?", 14) == 0) - { - uint8 depth = 1; - uint32 maxsize = 200000; - PRBool stayInSite = PR_TRUE; - char temp; - char * end; - char * item; - char * url = "http://w3.mcom.com/"; - char * name = "test.db"; - item = PL_strstr(URL_s->address, "url="); - if (item != NULL) { - item += 4; - end = PL_strchr(item, '&'); - if (end != NULL) { - temp = *end; - *end = '\0'; - url = PL_strdup(item); - *end = temp; - } else url = PL_strdup(item); - } - item = PL_strstr(URL_s->address, "name="); - if (item != NULL) { - item += 5; - end = PL_strchr(item, '&'); - if (end != NULL) { - temp = *end; - *end = '\0'; - name = PL_strdup(item); - *end = temp; - } else name = PL_strdup(item); - } - item = PL_strstr(URL_s->address, "depth="); - if (item != NULL) { - item += 6; - depth = (uint8)strtoul(item, &end, 10); - } - item = PL_strstr(URL_s->address, "maxsize="); - if (item != NULL) { - item += 8; - maxsize = strtoul(item, &end, 10); - } - item = PL_strstr(URL_s->address, "stayinsite="); - if (item != NULL) { - item += 8; - if (strtoul(item, &end, 10) == 0) stayInSite = PR_FALSE; - else stayInSite = PR_TRUE; - } - testCrawler(name, url, (uint8)depth, (uint32)maxsize, stayInSite); - - ... - - } - ... -} - -PRIVATE int net_output_about_url(ActiveEntry * cur_entry) -{ - ... - else if (!PL_strncasecmp(which, "crawler", 7)) - { - return (-1); - } -} -#endif diff --git a/mozilla/network/main/crawler.h b/mozilla/network/main/crawler.h deleted file mode 100644 index e2b1214335e..00000000000 --- a/mozilla/network/main/crawler.h +++ /dev/null @@ -1,183 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** crawler.h ****************************************************/ -/* description: html crawler */ - - - /******************************************************************** - - The crawler scans html pages and the links in those pages to a specified - depth in a breadth first manner, optionally caching them in an external cache. - Items are crawled sequentially - an item must finish being crawled or cached - before the next item is crawled. Multiple instances of the crawler may be running - at the same time. - - Depth = 1 means that only the initial page, and any images and resources that - it contains, are cached. - - Depth = n means that the crawler will crawl to n levels deep. Assuming the - maximum cache size is sufficient, the crawler will cache images and resources - for each page it encounters. Normally, resources are cached after all the pages - for a given level have been processed, but some resources are considered "required", - meaning they will be cached immediately after the page containing them has been - processed. An example of a "required" resource is a stylesheet. - - The crawler obeys the robots.txt directives on a site, which may allow or deny access - to specific urls or directories. The robots.txt file is by convention at the top level - of a site. - - The type of links that are crawled are determined in pagescan.c. - The parsing code is in htmparse.c - The robots.txt parser is in robotxt.c - - $Revision: 1.2 $ - $Date: 1999-11-06 02:32:27 $ - - *********************************************************************/ - -#ifndef crawler_h___ -#define crawler_h___ - -#include "ntypes.h" /* for MWContext */ -#include "prtypes.h" /* for PRBool */ -#include "net.h" /* for ExtCacheDBInfo, URL_Struct */ - -/* Error codes */ -typedef PRUint16 CRAWL_Error; - -#define CRAWL_CACHE_FULL ((CRAWL_Error)0x0001) -#define CRAWL_NO_MEMORY ((CRAWL_Error)0x0002) -#define CRAWL_SERVER_ERR ((CRAWL_Error)0x0004) -#define CRAWL_INTERRUPTED ((CRAWL_Error)0x0008) - -/* these error codes indicate if and how the cache has been updated and are only - set if CRAWL_MakeCrawler was called with manageCache set to true. Note that replaced - links may not have been reported as such if the server does not provide a last - modified date. -*/ -#define CRAWL_NEW_LINK ((CRAWL_Error)0x0010) -#define CRAWL_REPLACED_LINK ((CRAWL_Error)0x0020) -#define CRAWL_REMOVED_LINK ((CRAWL_Error)0x0040) - -/* Most of the APIs require a reference to CRAWL_Crawler, which is created by CRAWL_MakeCrawler. */ -typedef struct _CRAWL_CrawlerStruct *CRAWL_Crawler; - -/* - * Typedef for a callback executed when an item has been processed. - */ - typedef void -(PR_CALLBACK *CRAWL_PostProcessItemFn)(CRAWL_Crawler crawler, URL_Struct *url_s, PRBool isCached, void *data); - -/* - * Typedef for a callback executed when the crawler is done. - */ - typedef void -(PR_CALLBACK *CRAWL_ExitFn)(CRAWL_Crawler crawler, void *data); - -/****************************************************************************************/ -/* public API */ -/****************************************************************************************/ - -NSPR_BEGIN_EXTERN_C - -/* - Creates a crawler which may be used for one crawling request. Subsequent requests - to crawl urls should use a separate crawler instance. Returns NULL if not enough - memory is available, or the depth is less than 1. - - Parameters: - context - needed by netlib (the crawler does not check this parameter) - siteName - url of the site - stayInSite - whether to restrict crawling to the site named. - manageCache - whether to maintain a local file describing the cache contents. - If true, the crawler uses the file to remove dangling links from the cache - the next time it is invoked with the same cache. This is not guaranteed to - work correctly if another crawling instance uses the same cache simultaneously. - cache - the external cache. This may be NULL if the crawled items do not need - to be put in an external cache. - postProcessItemFn - a function which is called after each item has been handled - by netlib. This may be NULL. - postProcessItemData - this data is supplied as a parameter to the postProcessItemFn - and is opaque to the crawler. This may be NULL. - exitFn - a function which is called when the crawler is done or has terminated - prematurely (because the cache is full, or no memory is available). This may be NULL. - exitData - this data is supplied as a parameter to the exitFn and is opaque to - the crawler. This may be NULL. -*/ -PR_EXTERN(CRAWL_Crawler) -CRAWL_MakeCrawler(MWContext *context, - char *siteName, - uint8 depth, - PRBool stayInSite, - PRBool manageCache, - ExtCacheDBInfo *cache, - CRAWL_PostProcessItemFn postProcessItemFn, - void *postProcessItemData, - CRAWL_ExitFn exitFn, - void *exitData); - -/* - Destroys the crawler and all memory associated with it. The crawler instance should not be - used after calling this function. -*/ -PR_EXTERN(void) -CRAWL_DestroyCrawler(CRAWL_Crawler crawler); - -/* - Starts crawling from the url. If its content type is text/html, links may be traversed. This function - returns as soon as the first network request is issued. -*/ -PR_EXTERN(void) -CRAWL_StartCrawler(CRAWL_Crawler crawler, char *url); - -/* - Stops crawling at the next link. This function returns immediately and cannot fail. -*/ -PR_EXTERN(void) -CRAWL_StopCrawler(CRAWL_Crawler crawler); - -/* - Returns the crawler error code. This function returns immediately and cannot fail. -*/ -PR_EXTERN(CRAWL_Error) -CRAWL_GetError(CRAWL_Crawler crawler); - -/* - Returns true if the crawler has stopped, which is the case before and after crawling. Returns - immediately and cannot fail. -*/ -PR_EXTERN(PRBool) -CRAWL_IsStopped(CRAWL_Crawler crawler); - -NSPR_END_EXTERN_C - -/* - Stream function for crawling resources. Resources are not parsed, but the crawler checks the - content length to see if the cache would be exceeded. -*/ -PUBLIC NET_StreamClass* -CRAWL_CrawlerResourceConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* crawler_h___ */ diff --git a/mozilla/network/main/htmparse.c b/mozilla/network/main/htmparse.c deleted file mode 100644 index fc95f1c42d8..00000000000 --- a/mozilla/network/main/htmparse.c +++ /dev/null @@ -1,514 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** htmparse.c ***************************************************/ -/* description: html parser */ - - - /******************************************************************** - - $Revision: 1.3 $ - $Date: 1999-11-06 02:32:28 $ - - *********************************************************************/ - -#include "xp.h" -#include "xp_str.h" -#include "htmparse.h" -#include "prtypes.h" -#include "pa_tags.h" -#include "pa_parse.h" /* for pa_tokenize_tag */ -#include "prmem.h" -#if 0 -#include "prio.h" /* for test only */ -#include <stdio.h> /* for test only */ -#endif - -typedef char ParseState; - -/* states of the parser */ -#define PS_START 0 /* starting state */ -#define PS_BETWEEN_TAGS 1 /* characters not enclosed by < > */ -#define PS_TAG_NAME 2 -#define PS_EMPTY_TAG 3 -#define PS_CLOSE_BRACKET 4 -#define PS_ATTRIBUTE 5 -#define PS_EQUALS 6 -#define PS_VALUE 7 -#define PS_START_COMMENT 8 -#define PS_END_COMMENT 9 - -typedef struct _CRAWL_TagStruc { - char *name; - intn token; - char **attributeNames; - char **attributeValues; /* max length of html attribute is 1024 chars */ - uint16 sizeNames; - uint16 numNames; - uint16 sizeValues; - uint16 numValues; - PRBool emptyTagp; - PRBool endTagp; -} CRAWL_TagStruc; - -/* maintains state of parser */ -typedef struct _CRAWL_ParseObjStruc { - ParseState state; - CRAWL_Tag tag; - char *data; - uint16 dataLen; - uint16 dataSize; - char *str; - uint16 strLen; - uint16 strSize; - char prev1; - char prev2; - char inQuote; /* current quote character. when not in quote, value is '\0' */ - PRBool inComment; /* we don't support comment nesting anymore */ - PRBool inScript; /* inside <SCRIPT> and </SCRIPT> */ - PRBool skipWhitespace; - PRBool isRDF; -} CRAWL_ParseObjStruc; - -/* prototypes */ -static CRAWL_Tag crawl_makeTag(); -static void crawl_recycleTag(CRAWL_Tag tag); -static void crawl_destroyTag(CRAWL_Tag tag); -static void crawl_recycleParseObj(CRAWL_ParseObj obj); - -int crawl_appendString(char **str, uint16 *len, uint16 *size, char c); -int crawl_appendStringList(char ***list_p, uint16 *len, uint16 *size, char *str); - -/* accessors */ -PR_IMPLEMENT(CRAWL_Tag) CRAWL_GetTagParsed(CRAWL_ParseObj obj) { - if (obj->data != NULL) return NULL; - else return obj->tag; -} - -PR_IMPLEMENT(char*) CRAWL_GetDataParsed(CRAWL_ParseObj obj) { - if (obj->data != NULL) return obj->data; - else return NULL; -} - -PR_IMPLEMENT(char*) CRAWL_GetTagName(CRAWL_Tag tag) { - return tag->name; -} - -PR_IMPLEMENT(intn) CRAWL_GetTagToken(CRAWL_Tag tag) { - return tag->token; -} - -PR_IMPLEMENT(PRBool) CRAWL_IsEmptyTag(CRAWL_Tag tag) { - return tag->emptyTagp; -} - -PR_IMPLEMENT(PRBool) CRAWL_IsEndTag(CRAWL_Tag tag) { - return tag->endTagp; -} - -PR_IMPLEMENT(uint16) CRAWL_GetNumberOfAttributes(CRAWL_Tag tag) { - return tag->numNames; -} - -PR_IMPLEMENT(char*) CRAWL_GetNthAttributeName(CRAWL_Tag tag, uint16 n) { - return *(tag->attributeNames + n); -} - -PR_IMPLEMENT(char*) CRAWL_GetNthAttributeValue(CRAWL_Tag tag, uint16 n) { - return *(tag->attributeValues + n); -} - -PR_IMPLEMENT(char*) CRAWL_GetAttributeValue(CRAWL_Tag tag, char *attributeName) { - int count = 0; - while (count < tag->numNames) { - if (PL_strcasecmp(attributeName, *(tag->attributeNames + count)) == 0) - return *(tag->attributeValues + count); - count++; - } - return NULL; -} - -static CRAWL_Tag crawl_makeTag() { - CRAWL_Tag tag = PR_NEWZAP(CRAWL_TagStruc); - if (tag == NULL) return NULL; - tag->sizeNames = tag->sizeValues = 4; - tag->attributeNames = (char**)PR_MALLOC(sizeof(char*) * tag->sizeNames); - if (tag->attributeNames == NULL) return NULL; - tag->attributeValues = (char**)PR_MALLOC(sizeof(char*) * tag->sizeValues); - if (tag->attributeValues == NULL) return NULL; - return tag; -} - -static void crawl_recycleTag(CRAWL_Tag tag) { - int count; - if (tag->name != NULL) PR_Free(tag->name); - tag->name = NULL; - for (count = 0; count < tag->numNames; count++) { - PR_Free(*(tag->attributeNames + count)); - } - tag->numNames = 0; - for (count = 0; count < tag->numValues; count++) { - PR_Free(*(tag->attributeValues + count)); - } - tag->numValues = 0; - tag->emptyTagp = PR_FALSE; - tag->endTagp = PR_FALSE; -} - -static void crawl_destroyTag(CRAWL_Tag tag) { - crawl_recycleTag(tag); - if (tag->attributeNames != NULL) PR_Free(tag->attributeNames); - if (tag->attributeValues != NULL) PR_Free(tag->attributeValues); - PR_Free(tag); -} - -static void crawl_recycleParseObj(CRAWL_ParseObj obj) { - crawl_recycleTag(obj->tag); - if (obj->data != NULL) PR_Free(obj->data); - obj->data = NULL; - obj->dataLen = obj->dataSize = 0; -} - -PR_IMPLEMENT(CRAWL_ParseObj) CRAWL_MakeParseObj() { - CRAWL_ParseObj obj = PR_NEWZAP(CRAWL_ParseObjStruc); - if (obj == NULL) return NULL; - obj->tag = crawl_makeTag(); - if (obj->tag == NULL) { - PR_Free(obj); - return NULL; - } - return obj; -} - -PR_IMPLEMENT(void) CRAWL_DestroyParseObj(CRAWL_ParseObj obj) { - crawl_destroyTag(obj->tag); - if (obj->data != NULL) PR_Free(obj->data); - obj->data = NULL; - obj->dataLen = obj->dataSize = 0; - if (obj->str != NULL) PR_Free(obj->str); - obj->str = NULL; - obj->strLen = obj->strSize = 0; - PR_Free(obj); -} - -#define STRING_EXPANSION_INCREMENT 16 -/* returns 0 if no error, -1 if no memory */ -int crawl_appendString(char **str, uint16 *len, uint16 *size, char c) { - if (*len == *size) { - char *newName = (char*)PR_MALLOC(*size + STRING_EXPANSION_INCREMENT); - char *old = *str; - if (newName == NULL) return -1; - memcpy(newName, *str, *size); - *str = newName; - if (old != NULL) PR_Free(old); - *size += STRING_EXPANSION_INCREMENT; - } - *(*str + *len) = c; - ++(*len); - return 0; -} - -#define STRINGLIST_EXPANSION_INCREMENT 8 - -/* returns 0 if no error, -1 if no memory */ -int crawl_appendStringList(char ***list_p, uint16 *len, uint16 *size, char *str) { - char **list = *list_p; - if (*len == *size) { - char **newList = (char**)PR_MALLOC(sizeof(char*) * (*size + STRINGLIST_EXPANSION_INCREMENT)); - char **old = list; - if (newList == NULL) return -1; - memcpy(newList, list, (sizeof(char*) * (*size))); - list = newList; - if (old != NULL) PR_Free(old); - *size += STRINGLIST_EXPANSION_INCREMENT; - } - *(list + *len) = str; - ++(*len); - *list_p = list; - return 0; -} - -/* returns index to last character of buffer parsed */ -PR_IMPLEMENT(int) CRAWL_ParserPut(CRAWL_ParseObj obj, char *str, uint32 len, CRAWL_ParseFunc func, void *data) { - uint32 n = 0; /* where we are in the buffer */ - uint32 lastn = 0; /* position the last time in the loop */ - char c; - - while (n < len) { - if (lastn < n) { /* we advanced a character */ - obj->prev1 = obj->prev2; - obj->prev2 = c; - } - lastn = n; - c = *(str + n); - if (obj->inComment) { - /* if we're in a comment, ignore everything until we detect end of comment */ - if ((obj->prev1 == '-') && (obj->prev2 == '-') && (c == '>')) obj->inComment = PR_FALSE; - n++; - } else if (obj->skipWhitespace) { - if ((c == ' ') || (c == '\n') || (c == '\r')) { - n++; - } else obj->skipWhitespace = PR_FALSE; - } else { - PRBool endOfString = PR_FALSE; - switch (obj->state) { - case PS_START: - /* PS_START - expecting open bracket or character data */ - if (c == '<') { - obj->state = PS_TAG_NAME; - n++; - } else { - obj->state = PS_BETWEEN_TAGS; - } - break; - case PS_BETWEEN_TAGS: - /* PS_BETWEEN_TAGS - expecting open bracket (terminating character data) or more character data */ - if (obj->inQuote == c) { - obj->inQuote = '\0'; /* close quote */ - } else if ((c == '"') || (obj->inScript && (c == '\''))) { /* start a quote, only double quotes significant in between tags */ - obj->inQuote = c; - } - /* open bracket not in quoted section indicates end of data */ - if ((obj->inQuote == '\0') && (c == '<')) { - obj->state = PS_START; - if (crawl_appendString(&obj->data, &obj->dataLen, &obj->dataSize, '\0') != 0) /* null terminate string */ - return CRAWL_PARSE_OUT_OF_MEMORY; - if (func(obj, PR_FALSE, data) == PARSE_STOP) return CRAWL_PARSE_TERMINATE; - crawl_recycleParseObj(obj); - } else { - if (crawl_appendString(&obj->data, &obj->dataLen, &obj->dataSize, c) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - n++; - } - break; - case PS_TAG_NAME: - /* PS_TAG_NAME - terminated by space, \r, \n, >, / */ - if ((c == '"') || (c == '\'')) return CRAWL_PARSE_ERROR; /* error - these are not allowed in tagname */ - else if (c == ' ') { - /* Note: Both mozilla and XML don't allow any spaces between < and tagname. - Need to check for zero-length tagname. - */ - if (obj->str == NULL) return CRAWL_PARSE_ERROR; /* obj->str is the buffer we're working on */ - endOfString = PR_TRUE; - obj->state = PS_ATTRIBUTE; - obj->skipWhitespace = PR_TRUE; - n++; - } else if (c == '/') { - if (obj->tag->name == NULL) obj->tag->endTagp = PR_TRUE; /* indicates end tag if no tag name read yet */ - else if (obj->isRDF) { /* otherwise its an empty tag (RDF only) */ - endOfString = PR_TRUE; - obj->tag->emptyTagp = PR_TRUE; - obj->state = PS_CLOSE_BRACKET; - } else return CRAWL_PARSE_ERROR; - n++; - } else if (c == '>') { - endOfString = PR_TRUE; - obj->state = PS_CLOSE_BRACKET; - } else if ((c != '\r') && (c != '\n')) { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, c) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - n++; - } else { - endOfString = PR_TRUE; - obj->state = PS_ATTRIBUTE; /* note - mozilla allows newline after tag name */ - obj->skipWhitespace = PR_TRUE; - n++; - } - if (endOfString) { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, '\0') != 0) /* null terminate string */ - return CRAWL_PARSE_OUT_OF_MEMORY; - if (strcmp(obj->str, "!--") == 0) { /* html comment */ - obj->inComment = PR_TRUE; - obj->state = PS_START; - } else { - obj->tag->name = obj->str; - obj->tag->token = pa_tokenize_tag(obj->str); - } - obj->str = NULL; - obj->strLen = obj->strSize = 0; - endOfString = PR_FALSE; - } - break; - case PS_CLOSE_BRACKET: - /* PS_CLOSE_BRACKET - expecting a close bracket, anything else is an error */ - if (c == '>') { - if (!obj->isRDF && (obj->tag->token == P_SCRIPT)) { - /* we're inside a script tag (not RDF) */ - if (obj->tag->endTagp) obj->inScript = PR_FALSE; - else obj->inScript = PR_TRUE; - } - if (func(obj, PR_TRUE, data) == PARSE_STOP) return CRAWL_PARSE_TERMINATE; - crawl_recycleParseObj(obj); - obj->state = PS_START; - n++; - } else return CRAWL_PARSE_ERROR; /* error */ - break; - case PS_ATTRIBUTE: - /* PS_ATTRIBUTE - expecting an attribute name, or / (RDF only) or > indicating no more attributes */ - /* accept attributes without values, such as <tag attr1 attr2=val2> - or <tag attr2=val2 attr1> - */ - if (obj->inQuote == c) { - obj->inQuote = '\0'; /* close quote */ - } else if (((c == '"') || (c == '\'')) && (obj->inQuote == '\0')) { - /* start a quote if none is already in effect */ - obj->inQuote = c; - } - if (obj->inQuote == '\0') { - if ((((c == '/') && obj->isRDF) || (c == '>')) && (obj->str == NULL)) { - obj->state = PS_CLOSE_BRACKET; - } else if ((c == ' ') || (c == '=') || (c == '\n') || (c == '\r') || ((c == '/') && obj->isRDF) || (c == '>')) { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, '\0') != 0) /* null terminate string */ - return CRAWL_PARSE_OUT_OF_MEMORY; - if (crawl_appendStringList(&obj->tag->attributeNames, &obj->tag->numNames, &obj->tag->sizeNames, obj->str) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - obj->str = NULL; - obj->strLen = obj->strSize = 0; - obj->state = PS_EQUALS; /* if non-null attribute name */ - } else { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, c) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - n++; - } - } else { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, c) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - n++; - } - break; - case PS_EQUALS: - if ((c == ' ') || (c == '\n') || (c == '\r')) { - obj->skipWhitespace = PR_TRUE; - n++; - } else if (c == '=') { - obj->skipWhitespace = PR_TRUE; - obj->state = PS_VALUE; - n++; - } else { /* no value for the attribute - error in RDF? */ - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, '\0') != 0) /* null terminate string */ - return CRAWL_PARSE_OUT_OF_MEMORY; - if (crawl_appendStringList(&obj->tag->attributeValues, &obj->tag->numValues, &obj->tag->sizeValues, obj->str) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - obj->str = NULL; - obj->strLen = obj->strSize = 0; - obj->state = PS_ATTRIBUTE; - } - break; - case PS_VALUE: - /* expecting a value, or space, / (RDF only), or > indicating end of value. */ - { - PRBool include = PR_TRUE; /* whether the current character should be included in value */ - if (obj->inQuote == c) { - obj->inQuote = '\0'; /* close quote */ - include = PR_FALSE; - } else if (((c == '"') || (c == '\'')) && (obj->inQuote == '\0')) { - /* start a quote if none is already in effect */ - obj->inQuote = c; - include = PR_FALSE; - } - if (obj->inQuote == '\0') { - if ((c == '/') && obj->isRDF) { - endOfString = PR_TRUE; - obj->state = PS_CLOSE_BRACKET; - n++; - } else if (c == '>') { - endOfString = PR_TRUE; - obj->state = PS_CLOSE_BRACKET; - } else if ((c == ' ') || (c == '\r') || (c == '\n')) { - endOfString = PR_TRUE; - obj->skipWhitespace = PR_TRUE; - obj->state = PS_ATTRIBUTE; /* if non-null value name */ - n++; - } else if (include) { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, c) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - n++; - } else n++; - } else if (include) { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, c) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - n++; - } else n++; - if (endOfString) { - if (crawl_appendString(&obj->str, &obj->strLen, &obj->strSize, '\0') != 0) /* null terminate string */ - return CRAWL_PARSE_OUT_OF_MEMORY; - if (crawl_appendStringList(&obj->tag->attributeValues, &obj->tag->numValues, &obj->tag->sizeValues, obj->str) != 0) - return CRAWL_PARSE_OUT_OF_MEMORY; - obj->str = NULL; - obj->strLen = obj->strSize = 0; - endOfString = PR_FALSE; - } - break; - } - default: - break; - } - } - } - return CRAWL_PARSE_NO_ERROR; -} - -#if 0 -void printParseObj(CRAWL_ParseObj obj, PRBool isTag, void *data) { - if (isTag) { - CRAWL_Tag tag = CRAWL_GetTagParsed(obj); - if (CRAWL_IsEndTag(tag)) { - printf("</%s>\n", CRAWL_GetTagName(tag)); - } else { - uint16 i; - printf("<%s", CRAWL_GetTagName(tag)); - for (i = 0; i < CRAWL_GetNumberOfAttributes(tag); i++) { - printf(" %s=\"%s\"", CRAWL_GetNthAttributeName(tag, i), CRAWL_GetNthAttributeValue(tag, i)); - } - if (CRAWL_IsEmptyTag(tag)) printf("/>\n"); - else printf(">\n"); - } - } else printf(">>>>>%s<<<<<\n", CRAWL_GetDataParsed(obj)); -} - -void parseLocalFile (char *url) { - PRFileDesc *fp; - int32 len; - char *path; - static char buf[512]; /* xxx alloc */ - CRAWL_ParseObj parse; - - /* XXX need to unescape URL */ - path=&url[8]; - fp = PR_Open(path, PR_RDONLY, 0644); /* WR_ONLY|PR_TRUNCATE */ - if(fp == NULL) - { - /* abortRDFParse(file); */ - return; - } - parse = CRAWL_MakeParseObj(); - while((len=PR_Read(fp, buf, 512))>0) { - int result; - result = CRAWL_ParserPut(parse, buf, len, printParseObj, NULL); - if (result == len) printf("************NO ERRORS************\n"); - else printf("************PARSING ERROR************\n"); - } - PR_Close(fp); - CRAWL_DestroyParseObj(parse); - /* finishRDFParse(file); */ - return; -} -#endif diff --git a/mozilla/network/main/htmparse.h b/mozilla/network/main/htmparse.h deleted file mode 100644 index 394a9ebea8b..00000000000 --- a/mozilla/network/main/htmparse.h +++ /dev/null @@ -1,159 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** htmparse.h ***************************************************/ -/* description: html parser */ - - - /******************************************************************** - - The client calls CRAWL_ParserPut, and gets called back with - a function whose prototype is described by CRAWL_ParseFunc. The - parser calls this function whenever a begin or end tag, or run of - character data has been scanned, and does not build a tree. - - $Revision: 1.2 $ - $Date: 1999-11-06 02:32:28 $ - - *********************************************************************/ - - -#ifndef htmparse_h___ -#define htmparse_h___ -#include "prtypes.h" - -/* return values from CRAWL_ParserPut */ -#define CRAWL_PARSE_NO_ERROR 0 /* no error */ -#define CRAWL_PARSE_ERROR 1 /* syntax error */ -#define CRAWL_PARSE_TERMINATE 2 /* don't continue to parse */ -#define CRAWL_PARSE_OUT_OF_MEMORY 3 /* out of memory */ - -/* return values for CRAWL_ParseFunc callback function */ -#define PARSE_GET_NEXT_TOKEN 0 -#define PARSE_STOP 1 -#define PARSE_OUT_OF_MEMORY 2 - -typedef struct _CRAWL_TagStruc *CRAWL_Tag; - -/* - The client of this API creates a reference to this with CRAWL_MakeParseObj and provides it as - a parameter to CRAWL_ParserPut. It is passed as a parameter to the CRAWL_ParseFunc function and - the parsed data may be extracted from it through the API. It should be considered opaque data. -*/ -typedef struct _CRAWL_ParseObjStruc *CRAWL_ParseObj; - -/* - Typedef for a parse callback. The memory in CRAWL_ParseObj is reused across successive calls. -*/ -typedef int -(PR_CALLBACK *CRAWL_ParseFunc)(CRAWL_ParseObj obj, PRBool isTag, void *data); - -/****************************************************************************************/ -/* public API */ -/****************************************************************************************/ - -NSPR_BEGIN_EXTERN_C - - /* - Returns the tag parsed - */ -PR_EXTERN(CRAWL_Tag) -CRAWL_GetTagParsed(CRAWL_ParseObj obj); - -/* - Returns the character data between tags -*/ -PR_EXTERN(char*) -CRAWL_GetDataParsed(CRAWL_ParseObj obj); - -/* - Returns the tag name -*/ -PR_EXTERN(char*) -CRAWL_GetTagName(CRAWL_Tag tag); - -/* - Returns the libparse tag code as defined in pa_tags.h -*/ -PR_EXTERN(intn) -CRAWL_GetTagToken(CRAWL_Tag tag); - -/* - a tag of the form <tagname /> Empty tags are recognized only if the page has been designated as - containing RDF (the API doesn't support this yet) -*/ -PR_EXTERN(PRBool) -CRAWL_IsEmptyTag(CRAWL_Tag tag); - -/* - A tag of the form </tagname>. -*/ -PR_EXTERN(PRBool) -CRAWL_IsEndTag(CRAWL_Tag tag); - -/* - Returns the tag attribute given a name -*/ -PR_EXTERN(char*) -CRAWL_GetAttributeValue(CRAWL_Tag tag, char *attributeName); - -/* - Returns the number of attributes for the tag. -*/ -PR_EXTERN(uint16) -CRAWL_GetNumberOfAttributes(CRAWL_Tag tag); - -/* - Returns the nth attribute of the tag. -*/ -PR_EXTERN(char*) -CRAWL_GetNthAttributeName(CRAWL_Tag tag, uint16 n); - -/* - Returns the nth attribute value of the tag. -*/ -PR_EXTERN(char*) -CRAWL_GetNthAttributeValue(CRAWL_Tag tag, uint16 n); - -/* - Creates a new CRAWL_ParseObj suitable for passing to CRAWL_ParserPut. - Returns NULL if out of memory. -*/ -PR_EXTERN(CRAWL_ParseObj) -CRAWL_MakeParseObj(); - -/* - Destroys the CRAWL_ParseObj and all associated memory -*/ -PR_EXTERN(void) -CRAWL_DestroyParseObj(CRAWL_ParseObj obj); - -/* - Parse characters in buffer and call func when an element (tag or data) has been - scanned. Returns an error code. The same CRAWL_ParseObj must be provided for successive - puts in the same buffer. It is up to the caller to create and destroy the CRAWL_ParseObj. -*/ -PR_EXTERN(int) -CRAWL_ParserPut(CRAWL_ParseObj obj, char *str, uint32 len, CRAWL_ParseFunc func, void *data); - -NSPR_END_EXTERN_C - -#endif /* htmparse_h___ */ diff --git a/mozilla/network/main/jsautocf.c b/mozilla/network/main/jsautocf.c deleted file mode 100644 index 6a481b85ffa..00000000000 --- a/mozilla/network/main/jsautocf.c +++ /dev/null @@ -1,303 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" /* LF */ - -#include <time.h> - -#include "jsautocf.h" -#include "xp_mem.h" /* PR_NEWZAP() */ -#ifndef XP_MAC -#include <sys/types.h> -#endif -#include "libi18n.h" - -#include "mkgeturl.h" -#include "mkstream.h" -#include "mkformat.h" -#include "net_xp_file.h" -#include "mime.h" -#include "cvactive.h" -#include "gui.h" -#include "msgcom.h" - -#if defined(XP_UNIX) || defined(XP_WIN32) -#include "prnetdb.h" -#else -#define PRHostEnt struct hostent -#endif - -/* - * Private object for the proxy config loader stream. - * - * - */ -typedef struct _JSACF_Object { - MWContext * context; - int flag; -} JSACF_Object; - - -/* - * A struct for holding queued state. - * - * The state is saved when NET_GetURL() is called for the first time, - * and the Javascript autoconfig retrieve has to be started (and finished) - * before the first actual document can be loaded. - * - * A pre-exit function for the Javascript autoconfig URL restarts the - * original URL retrieve by calling NET_GetURL() again with the - * same parameters. - * - */ -typedef struct _JSACF_QueuedState { - URL_Struct * URL_s; - FO_Present_Types output_format; - MWContext * window_id; - Net_GetUrlExitFunc* exit_routine; -} JSACF_QueuedState; - -PRIVATE Bool jsacf_loading = FALSE; -PRIVATE Bool jsacf_ok = FALSE; -PRIVATE char * jsacf_url = NULL; -PRIVATE char * jsacf_src_buf = NULL; -PRIVATE int jsacf_src_len = 0; - - -/* - * Saves out the proxy autoconfig file to disk, in case the server - * is down the next time. - * - * Returns 0 on success, -1 on failure. - * - */ -PRIVATE int jsacf_save_config(void) -{ - XP_File fp; - int32 len = 0; - - // TODO: jonm - if(!(fp = NET_XP_FileOpen("", xpProxyConfig, XP_FILE_WRITE))) - return -1; - - len = NET_XP_FileWrite(jsacf_src_buf, jsacf_src_len, fp); - NET_XP_FileClose(fp); - if (len != jsacf_src_len) - return -1; - - return 0; -} - - -/* - * Reads the proxy autoconfig file from disk. - * This is called if the config server is not responding. - * - * returns 0 on success -1 on failure. - * - */ -PRIVATE int jsacf_read_config(void) -{ - XP_StatStruct st; - XP_File fp; - - if (NET_XP_Stat("", &st, xpProxyConfig) == -1) - return -1; - - if (!(fp = NET_XP_FileOpen("", xpProxyConfig, XP_FILE_READ))) - return -1; - - jsacf_src_len = st.st_size; - jsacf_src_buf = (char *)PR_Malloc(jsacf_src_len + 1); - if (!jsacf_src_buf) { - NET_XP_FileClose(fp); - jsacf_src_len = 0; - return -1; - } - - if ((jsacf_src_len = NET_XP_FileRead(jsacf_src_buf, jsacf_src_len, fp)) > 0) - { - jsacf_src_buf[jsacf_src_len] = '\0'; - } - else - { - PR_Free(jsacf_src_buf); - jsacf_src_buf = NULL; - jsacf_src_len = 0; - } - - NET_XP_FileClose(fp); - - return 0; -} - - - -/* - * Private stream object methods for receiving the proxy autoconfig - * file. - * - * - */ -PRIVATE int jsacf_write(NET_StreamClass *stream, CONST char *buf, int32 len) -{ - JSACF_Object *obj=stream->data_object; - if (len > 0) { - if (!jsacf_src_buf) - jsacf_src_buf = (char*)PR_Malloc(len + 1); - else - jsacf_src_buf = (char*)PR_Realloc(jsacf_src_buf, - jsacf_src_len + len + 1); - - if (!jsacf_src_buf) { /* Out of memory */ - jsacf_src_len = 0; - return MK_DATA_LOADED; - } - - memcpy(jsacf_src_buf + jsacf_src_len, buf, len); - jsacf_src_len += len; - jsacf_src_buf[jsacf_src_len] = '\0'; - } - return MK_DATA_LOADED; -} - - -PRIVATE unsigned int jsacf_write_ready(NET_StreamClass *stream) -{ - return MAX_WRITE_READY; -} - -extern int PREF_EvaluateJSBuffer(char * js_buffer, size_t length); - -PRIVATE void jsacf_complete(NET_StreamClass *stream) -{ - JSACF_Object *obj=stream->data_object; - int err = PREF_EvaluateJSBuffer(jsacf_src_buf,jsacf_src_len); - if (jsacf_src_buf) PR_Free(jsacf_src_buf); -} - - -PRIVATE void jsacf_abort(NET_StreamClass *stream, int status) -{ - JSACF_Object *obj=stream->data_object; - jsacf_loading = FALSE; -// FE_Alert(obj->context, CONFIG_LOAD_ABORTED); - PR_Free(obj); -} - -/* - * A stream constructor function for application/x-ns-proxy-autoconfig. - * - * - * - */ -MODULE_PRIVATE NET_StreamClass * -NET_JavaScriptAutoConfig(int fmt, void *data_obj, URL_Struct *URL_s, MWContext *w) -{ - JSACF_Object *obj; - NET_StreamClass *stream; - -#ifdef LATER - if (!jsacf_loading) { - /* - * The Navigator didn't start this config retrieve - * intentionally. Discarding the config. - */ - alert2(w, CONFIG_BLAST_WARNING, URL_s->address); - return NULL; - } - else { - NET_Progress(w, XP_GetString( XP_RECEIVING_PROXY_AUTOCFG ) ); - } -#endif - - if (jsacf_src_buf) { - PR_Free(jsacf_src_buf); - jsacf_src_buf = NULL; - jsacf_src_len = 0; - } - - if (!(stream = PR_NEWZAP(NET_StreamClass))) - return NULL; - - if (!(obj = PR_NEWZAP(JSACF_Object))) { - PR_Free(stream); - return NULL; - } - - obj->context = w; - - stream->data_object = obj; - stream->name = "JavaScriptAutoConfigLoader"; - stream->complete = (MKStreamCompleteFunc) jsacf_complete; - stream->abort = (MKStreamAbortFunc) jsacf_abort; - stream->put_block = (MKStreamWriteFunc) jsacf_write; - stream->is_write_ready = (MKStreamWriteReadyFunc)jsacf_write_ready; - stream->window_id = w; - - return stream; -} - - -void jsacf_exit_routine(URL_Struct *URL_s, int status, MWContext *window_id) -{} - -PRIVATE void -simple_exit(URL_Struct *URL_s, int status, MWContext *window_id) -{ - if(status != MK_CHANGING_CONTEXT) - NET_FreeURLStruct(URL_s); -} - -/* - * Called by mkgeturl.c to originally retrieve, and re-retrieve - * the javascript autoconfig file. - * - * autoconfig_url is the URL pointing to the autoconfig. - * - */ -MODULE_PRIVATE int NET_LoadJavaScriptConfig(char *autoconf_url,MWContext *window_id) -{ - URL_Struct *my_url_s = NULL; - - if (!autoconf_url) - return -1; - - StrAllocCopy(jsacf_url, autoconf_url); - my_url_s = NET_CreateURLStruct(autoconf_url, NET_SUPER_RELOAD); - - /* Alert the proxy autoconfig module that config is coming */ - jsacf_loading = TRUE; - - return NET_GetURL(my_url_s, FO_CACHE_AND_JAVASCRIPT_CONFIG, window_id, simple_exit); - //return FE_GetURL(window_id, my_url_s); -} - -/* - * Returns a pointer to a NULL-terminted buffer which contains - * the text of the proxy autoconfig file. - * - * - */ -PUBLIC char * NET_GetJavaScriptConfigSource(void) -{ - return jsacf_src_buf; -} diff --git a/mozilla/network/main/jsautocf.h b/mozilla/network/main/jsautocf.h deleted file mode 100644 index a81c1696249..00000000000 --- a/mozilla/network/main/jsautocf.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * jsautocf.h: JavaScript auto-config parser and evaluator - */ - -#ifndef MK_JAVASCRIPT_AUTO_CONFIG -#define MK_JAVASCRIPT_AUTO_CONFIG - - -#include "xp_mcom.h" -#include "xp.h" - -/* - * A stream constructor function for application/x-ns-javascript-autoconfig. - * - * - * - */ -MODULE_PRIVATE NET_StreamClass * -NET_JavaScriptAutoConfig(int fmt, void *data_obj, URL_Struct *URL_s, MWContext *w); - -MODULE_PRIVATE int NET_LoadJavaScriptConfig(char *autoconf_url,MWContext *window_id); - -void jsacf_exit_routine(URL_Struct *URL_s, int status, MWContext *window_id); -PUBLIC char * NET_GetJavaScriptConfigSource(void); -PUBLIC XP_Bool NET_InitPacfContext(void); - - -#endif /* ! MK_JAVASCRIPT_AUTO_CONFIG */ - diff --git a/mozilla/network/main/jscookie.c b/mozilla/network/main/jscookie.c deleted file mode 100644 index 61a43314273..00000000000 --- a/mozilla/network/main/jscookie.c +++ /dev/null @@ -1,622 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - jscookie.c -- javascript reflection of cookies for filters. - Created: Frederick G.M. Roeber <roeber@netscape.com>, 12-Jul-97. - Adopted: Judson Valeski, 1997. - Large chunks of this were stolen from jsmsg.c. - */ - -#include "mkutils.h" -#include "mkutils.h" -#include "mkparse.h" -#include "mkgeturl.h" -#include "cookies.h" -#include "prefapi.h" -#include "jsapi.h" -#include "xp_core.h" -#include "xp_mcom.h" -#include "jscookie.h" -#include "ds.h" -#include "xpgetstr.h" -#include "net_xp_file.h" - -extern int MK_ACCESS_JAVASCRIPT_COOKIE_FILTER; - -static JSObject *filter_obj = NULL; -static JSContext *filter_context = NULL; - -static JSBool error_reporter_installed = JS_FALSE; -static JSErrorReporter previous_error_reporter; - -/* tells us when we should recompile the file. */ -static JSBool need_compile = JS_TRUE; - -/* This is the private instance data associated with a cookie */ -typedef struct JSCookieData { - JSContext *js_context; - JSObject *js_object; - JSCFCookieData *data; - PRPackedBool property_changed, rejected, accepted, ask, decision_made; -} JSCookieData; - -/* The properties of a cookie that we reflect */ -enum cookie_slot { - COOKIE_PATH = -1, - COOKIE_DOMAIN = -2, - COOKIE_NAME = -3, - COOKIE_VALUE = -4, - COOKIE_EXPIRES = -5, - COOKIE_URL = -6, - COOKIE_IS_SECURE = -7, - COOKIE_IS_DOMAIN = -8, - COOKIE_PROMPT_PREF = -9, - COOKIE_PREF = -10 -}; - -/* - * Should more of these be readonly? What does it mean for a cookie - * to de secure? -chouck - */ -static JSPropertySpec cookie_props[] = { - { "path", COOKIE_PATH, JSPROP_ENUMERATE }, - { "domain", COOKIE_DOMAIN, JSPROP_ENUMERATE }, - { "name", COOKIE_NAME, JSPROP_ENUMERATE }, - { "value", COOKIE_VALUE, JSPROP_ENUMERATE }, - { "expires", COOKIE_EXPIRES, JSPROP_ENUMERATE }, - { "url", COOKIE_URL, JSPROP_ENUMERATE|JSPROP_READONLY }, - { "isSecure", COOKIE_IS_SECURE, JSPROP_ENUMERATE }, - { "isDomain", COOKIE_IS_DOMAIN, JSPROP_ENUMERATE }, - { "prompt", COOKIE_PROMPT_PREF, JSPROP_ENUMERATE|JSPROP_READONLY }, - { "preference", COOKIE_PREF, JSPROP_ENUMERATE|JSPROP_READONLY }, - { 0 } -}; - -PR_STATIC_CALLBACK(JSBool) -cookie_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) -{ - JSCookieData *data; - JSString *str; - jsint slot; - - data = (JSCookieData *)JS_GetPrivate(cx, obj); - if (!data) - return JS_TRUE; - - if (!JSVAL_IS_INT(id)) - return JS_TRUE; - - slot = JSVAL_TO_INT(id); - - switch (slot) { - case COOKIE_PATH: - str = JS_NewStringCopyZ(cx, (const char *)data->data->path_from_header); - if( (JSString *)0 == str ) - return JS_FALSE; - *vp = STRING_TO_JSVAL(str); - break; - case COOKIE_DOMAIN: - str = JS_NewStringCopyZ(cx, (const char *)data->data->host_from_header); - if( (JSString *)0 == str ) - return JS_FALSE; - *vp = STRING_TO_JSVAL(str); - break; - case COOKIE_NAME: - str = JS_NewStringCopyZ(cx, (const char *)data->data->name_from_header); - if( (JSString *)0 == str ) - return JS_FALSE; - *vp = STRING_TO_JSVAL(str); - break; - case COOKIE_VALUE: - str = JS_NewStringCopyZ(cx, (const char *)data->data->cookie_from_header); - if( (JSString *)0 == str ) - return JS_FALSE; - *vp = STRING_TO_JSVAL(str); - break; - case COOKIE_EXPIRES: - *vp = INT_TO_JSVAL(data->data->expires); - break; - case COOKIE_URL: - str = JS_NewStringCopyZ(cx, (const char *)data->data->url); - if( (JSString *)0 == str ) - return JS_FALSE; - *vp = STRING_TO_JSVAL(str); - break; - case COOKIE_IS_SECURE: - *vp = BOOLEAN_TO_JSVAL(data->data->secure); - break; - case COOKIE_IS_DOMAIN: - *vp = BOOLEAN_TO_JSVAL(data->data->domain); - break; - case COOKIE_PROMPT_PREF: - *vp = BOOLEAN_TO_JSVAL(data->data->prompt); - break; - case COOKIE_PREF: - *vp = INT_TO_JSVAL(data->data->preference); - break; - } - - return JS_TRUE; -} - -PR_STATIC_CALLBACK(JSBool) -cookie_setProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) -{ - JSCookieData *data; - jsint slot; - PRInt32 i; - JSBool b; - - data = (JSCookieData *)JS_GetPrivate(cx, obj); - if (!data) - return JS_TRUE; - - if (!JSVAL_IS_INT(id)) - return JS_TRUE; - - slot = JSVAL_TO_INT(id); - - if (slot == COOKIE_PATH) { - data->data->path_from_header = JS_GetStringBytes(JSVAL_TO_STRING(*vp)); - } - else if (slot == COOKIE_DOMAIN) { - data->data->host_from_header = JS_GetStringBytes(JSVAL_TO_STRING(*vp)); - } - else if (slot == COOKIE_NAME) { - data->data->name_from_header = JS_GetStringBytes(JSVAL_TO_STRING(*vp)); - } - else if (slot == COOKIE_VALUE) { - data->data->cookie_from_header = JS_GetStringBytes(JSVAL_TO_STRING(*vp)); - } - else if (slot == COOKIE_EXPIRES) { - if( !JS_ValueToInt32(cx, *vp, (long *)&i) ) - return JS_FALSE; - data->data->expires = i; - } - else if (slot == COOKIE_IS_SECURE) { - if( !JS_ValueToBoolean(cx, *vp, &b) ) - return JS_FALSE; - data->data->secure = b; - } - else if (slot == COOKIE_IS_DOMAIN) { - if( !JS_ValueToBoolean(cx, *vp, &b) ) - return JS_FALSE; - data->data->domain = b; - } - - data->property_changed = TRUE; - return JS_TRUE; -} - -PR_STATIC_CALLBACK(void) -cookie_finalize(JSContext *cx, JSObject *obj) -{ - JSCookieData *cookie; - cookie = JS_GetPrivate(cx, obj); - FREEIF(cookie); -} - -/* So we can possibly add functions "global" to filters... */ -static JSClass global_class = { - "CookieFilters", 0 /* no private data */, - JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, - JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub -}; - -static JSClass js_cookie_class = { - "Cookie", JSCLASS_HAS_PRIVATE, - JS_PropertyStub, JS_PropertyStub, cookie_getProperty, cookie_setProperty, - JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, cookie_finalize -}; - -/* cookie.accept() -- mark it okay */ -PR_STATIC_CALLBACK(JSBool) -cookie_accept(JSContext *cx, JSObject *obj, uint argc, jsval *argv, jsval * rval) -{ - JSCookieData *data; - - if (!(data = (JSCookieData*)JS_GetInstancePrivate(cx, obj, &js_cookie_class, argv))) - return JS_FALSE; - - data->accepted = TRUE; - data->rejected = FALSE; - data->ask = FALSE; - data->decision_made = TRUE; - - return JS_TRUE; -} - -/* cookie.reject() -- reject it out of hand */ -PR_STATIC_CALLBACK(JSBool) -cookie_reject(JSContext *cx, JSObject *obj, uint argc, jsval *argv, jsval * rval) -{ - JSCookieData *data; - - if (!(data = (JSCookieData*)JS_GetInstancePrivate(cx, obj, &js_cookie_class, argv))) - return JS_FALSE; - - data->accepted = FALSE; - data->rejected = TRUE; - data->ask = FALSE; - data->decision_made = TRUE; - - return JS_TRUE; -} - -/* cookie.ask() -- ask the luser, even if that pref is off */ -PR_STATIC_CALLBACK(JSBool) -cookie_ask(JSContext *cx, JSObject *obj, uint argc, jsval *argv, jsval * rval) -{ - JSCookieData *data; - - if (!(data = (JSCookieData*)JS_GetInstancePrivate(cx, obj, &js_cookie_class, argv))) - return JS_FALSE; - - data->accepted = FALSE; - data->rejected = FALSE; - data->ask = TRUE; - data->decision_made = TRUE; - - return JS_TRUE; -} - -/* cookie.confirm() -- pop up a confirmation box */ -PR_STATIC_CALLBACK(JSBool) -cookie_confirm(JSContext *cx, JSObject *obj, uint argc, jsval *argv, jsval * rval) -{ - JSCookieData *data; - JSString *str; - char *msg = (char *)0; - Bool result; - MWContext * context = XP_FindSomeContext(); - - if (argc < 1 || !context) - return JS_FALSE; - - if (!(data = (JSCookieData*)JS_GetInstancePrivate(cx, obj, &js_cookie_class, argv))) - return JS_FALSE; - - str = JS_ValueToString(cx, argv[0]); - if (!str) - return JS_FALSE; - - StrAllocCopy(msg, XP_GetString(MK_ACCESS_JAVASCRIPT_COOKIE_FILTER)); - StrAllocCat(msg, JS_GetStringBytes(str)); - if (!msg) - return JS_FALSE; - - result = FE_Confirm(context, msg); - FREEIF(msg); - - *rval = BOOLEAN_TO_JSVAL(result); - - return JS_TRUE; -} - -#if DEBUG -/* trace() -- outputs spew to stderr. Actually, this (or something like it - that perhaps outputs to the same file that the rest of the filter logging code - writes to) would probably be very useful in the normal course of writing filters. */ -PR_STATIC_CALLBACK(JSBool) -cookie_filter_trace(JSContext *cx, JSObject * obj, uint argc, jsval *argv, jsval * rval) -{ - - if (argc > 0) - { - JSString *str; - const char *trace_str; - if (!(str = JS_ValueToString(cx, argv[0]))) - return JS_FALSE; - - trace_str = JS_GetStringBytes(str); - if (*trace_str != '\0') - { - fprintf (stderr, "cookie filter trace: %s\n", trace_str); - } - return JS_TRUE; - } - - return JS_FALSE; -} -#endif - -static JSFunctionSpec cookie_methods[] = { - { "accept", cookie_accept, 0 }, - { "reject", cookie_reject, 0 }, - { "ask", cookie_ask, 0 }, - { "confirm", cookie_confirm, 1 }, - { 0 } -}; - -static JSFunctionSpec filter_methods[] = { -#ifdef DEBUG - { "trace", cookie_filter_trace, 1 }, -#endif - { 0 } -}; - -PRIVATE void -destroyJSCookieFilterStuff(void) -{ - filter_obj = NULL; -} - -/* - * This function used to take an MWContext and store it as the private data - * of the filter object. That is a no-no since the filter_obj is going to - * be around until the end of time but there is no guarentee that the - * context won't get free'd out from under us. The solution is to not - * hold onto any particular context but just call XP_FindSomeContext() or - * some derivative of it when we need to. - */ -PRIVATE JSContext * -initializeJSCookieFilterStuff() -{ - - /* Only bother initializing once */ - if (filter_obj) - return filter_context; - - /* If we can't get the mozilla-thread global context just bail */ - if ( (PREF_OK != PREF_GetConfigContext(&filter_context)) - || !filter_context) - return NULL; - - JS_BeginRequest(filter_context); - /* create our "global" object. We make the message object a child of this */ - filter_obj = JS_NewObject(filter_context, &global_class, NULL, NULL); - - /* MLM - don't do JS_InitStandardClasses() twice */ - if (!filter_obj - || !JS_DefineFunctions(filter_context, filter_obj, filter_methods)) - { - JS_EndRequest(filter_context); - destroyJSCookieFilterStuff(); - return NULL; - } - - JS_EndRequest(filter_context); - return filter_context; -} - -PRIVATE JSObject * -newCookieObject(void) -{ - JSObject *rv; - JSCookieData *cookie_data; - - rv = JS_DefineObject(filter_context, filter_obj, - "cookie", &js_cookie_class, - NULL, JSPROP_ENUMERATE); - - if( (JSObject *)0 == rv ) - return (JSObject *)0; - - cookie_data = PR_NEWZAP(JSCookieData); - - if( (JSCookieData *)0 == cookie_data ) - return (JSObject *)0; - - if( !JS_SetPrivate(filter_context, rv, cookie_data) - || !JS_DefineProperties(filter_context, rv, cookie_props) - || !JS_DefineFunctions(filter_context, rv, cookie_methods)) { - return (JSObject *)0; - } - - return rv; -} - -PR_STATIC_CALLBACK(void) -jscookie_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report) -{ - char *msg = NULL; - MWContext *context; - - context = XP_FindSomeContext(); - if(!context || !report) - return; - - /*XXX: i18n-ise this */ - msg = PR_sprintf_append(NULL, - "JavaScript Cookie Filter Error:\n" - "You will be prompted manually to accept or reject this cookie.\n" - "Filename: %s\n" - "Line #: %u\n" - "%s\n" - "%.*s\n", - report->filename, - report->lineno, - report->linebuf, - (int)(report->tokenptr - report->linebuf) + 1, - "^" - ); - - if (!msg) - return; - - FE_Alert(context, msg); - PR_Free(msg); - - return; -} - -PRIVATE JSBool -compileJSCookieFilters(void) -{ - static time_t m_time = 0; /* the last modification time of filters.js */ - static JSBool ret_val = JS_FALSE; - char *filename; - XP_File fp; - XP_StatStruct stats; - - if (!need_compile) - return ret_val; - - filename = WH_FileName("", xpJSCookieFilters); - - PR_LogPrint("+Filename for script filter is %s\n", filename); - - /* If we can't get to the file, get the hell outa dodge. */ - if(NET_XP_Stat(filename, &stats, xpJSCookieFilters)) - return ret_val; - - if (stats.st_mtime > m_time || need_compile) - { - long fileLength; - char *buffer; - jsval rval; - - m_time = stats.st_mtime; - - fileLength = stats.st_size; - if (fileLength <= 1) - { - ret_val = JS_FALSE; - return ret_val; - } - - if( !(fp = NET_XP_FileOpen(filename, xpJSCookieFilters, "r")) ) { - ret_val = JS_FALSE; - return ret_val; - } - - buffer = (char*)malloc(fileLength); - if (!buffer) { - NET_XP_FileClose(fp); - ret_val = JS_FALSE; - return ret_val; - } - - fileLength = NET_XP_FileRead(buffer, fileLength, fp); - - NET_XP_FileClose(fp); - - PR_LogPrint("+Compiling filters.js...\n"); - - ret_val = JS_EvaluateScript(filter_context, filter_obj, buffer, fileLength, - filename, 1, &rval); - - PR_LogPrint("+Done.\n"); - - PR_Free(buffer); - - need_compile = JS_FALSE; - } - - return ret_val; -} - -PUBLIC JSCFResult -JSCF_Execute( - MWContext *mwcontext, - const char *script_name, - JSCFCookieData *data, - Bool *data_changed - ) -{ - jsval result; - jsval filter_arg; /* we will this in with the message object we create. */ - JSObject *cookie_obj; - JSCookieData *cookie_data; - - if (!script_name) - return JSCF_error; - - /* initialize the filter stuff, and bomb out early if it fails */ - if (!initializeJSCookieFilterStuff()) - return JSCF_error; - - JS_BeginRequest(filter_context); - - /* - * try loading (reloading if necessary) the filter file before bothering - * to create any JS-objects - */ - if (!compileJSCookieFilters()) { - JS_EndRequest(filter_context); - return JSCF_error; - } - - if (!error_reporter_installed) - { - error_reporter_installed = JS_TRUE; - previous_error_reporter = JS_SetErrorReporter(filter_context, - jscookie_ErrorReporter); - } - - - cookie_obj = newCookieObject(); - if( (JSObject *)0 == cookie_obj ) { - JS_EndRequest(filter_context); - return JSCF_error; - } - - cookie_data = (JSCookieData *)JS_GetPrivate(filter_context, cookie_obj); - cookie_data->js_context = filter_context; - cookie_data->js_object = cookie_obj; - cookie_data->data = data; - cookie_data->property_changed = FALSE; - cookie_data->rejected = FALSE; - cookie_data->accepted = FALSE; - cookie_data->decision_made = FALSE; - - filter_arg = OBJECT_TO_JSVAL(cookie_obj); - JS_CallFunctionName(filter_context, filter_obj, script_name, 1, - &filter_arg, &result); - - JS_EndRequest(filter_context); - - *data_changed = cookie_data->property_changed; - if( cookie_data->decision_made ) { - if( cookie_data->rejected ) - return JSCF_reject; - else if( cookie_data->accepted ) - return JSCF_accept; - else if( cookie_data->ask ) - return JSCF_ask; - } - - return JSCF_whatever; -} - -PUBLIC void -JSCF_Cleanup(void) -{ - TRACEMSG(("+Cleaning up JS Cookie Filters")); - - need_compile = JS_TRUE; - - if (filter_context) - { - JS_BeginRequest(filter_context); - if (error_reporter_installed) - { - error_reporter_installed = JS_FALSE; - JS_SetErrorReporter(filter_context, previous_error_reporter); - } - - JS_GC(filter_context); - - destroyJSCookieFilterStuff(); - JS_EndRequest(filter_context); - } -} diff --git a/mozilla/network/main/makefile.win b/mozilla/network/main/makefile.win deleted file mode 100644 index 28b0459de5b..00000000000 --- a/mozilla/network/main/makefile.win +++ /dev/null @@ -1,184 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network LIB -# -#------------------------------------------------------------------------ - -DEPTH=..\.. -include <$(DEPTH)\config\config.mak> - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT -#LCFLAGS = $(LCFLAGS) -DNO_NETWORK_POLLING - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ -!ifdef MOZ_MAIL_NEWS - .\$(OBJDIR)\mkabook.obj \ -!endif - .\$(OBJDIR)\jsautocf.obj \ - .\$(OBJDIR)\jscookie.obj \ - .\$(OBJDIR)\mkautocf.obj \ - .\$(OBJDIR)\mkconect.obj \ - .\$(OBJDIR)\mkfsort.obj \ - .\$(OBJDIR)\mkhelp.obj \ - .\$(OBJDIR)\mkinit.obj \ - .\$(OBJDIR)\mkmessag.obj \ - .\$(OBJDIR)\mkpadpac.obj \ - .\$(OBJDIR)\mkparse.obj \ - .\$(OBJDIR)\mkselect.obj \ - .\$(OBJDIR)\mksockrw.obj \ - .\$(OBJDIR)\mksort.obj \ - .\$(OBJDIR)\mkstream.obj \ - .\$(OBJDIR)\mktrace.obj \ - .\$(OBJDIR)\mkutils.obj \ - .\$(OBJDIR)\prefetch.obj \ - .\$(OBJDIR)\mkgeturl.obj \ - .\$(OBJDIR)\win-dns.obj \ - .\$(OBJDIR)\singsignStub.obj \ - $(NULL) - - -CSRCS = \ - jsautocf.c \ - jscookie.c \ - mkabook.cpp \ - mkalert.c \ - mkautocf.c \ - mkconect.c \ - mkformat.c \ - mkfsort.c \ - mkgeturl.c \ - mkhelp.c \ - mkinit.c \ - mkmessag.c \ - mkpadpac.c \ - mkparse.c \ - mkselect.c \ - mksockrw.c \ - mksort.c \ - mktrace.c \ - mkutils.c \ - prefetch.c \ - $(NULL) - -CPPSRCS = \ - win-dns.cpp \ - singsignStub.cpp \ - $(NULL) - -MODULE=network - -LIBRARY_NAME=network - -EXTRA_LIBS= - -!ifdef NU_CACHE -REQUIRES= foo parse jtools java zlib nspr dbm util network js security mimetype ldap imap4url ldapurl net progress cache -!else -REQUIRES= foo parse jtools java zlib nspr dbm util network js security mimetype ldap imap4url ldapurl net progress -!endif -EXPORTS= mkstream.h \ - net_xp_file.h \ - mkprefs.h \ - mkparse.h \ - mkfsort.h \ - mksort.h \ - mkgeturl.h \ - mkselect.h \ - mktcp.h \ - netutils.h \ - netstream.h \ - mkpadpac.h \ - mkautocf.h \ - mkutils.h \ - mktrace.h \ -#ifdef MOZ_MAIL_NEWS - mkldap.h \ -#endif /* MOZ_MAIL_NEWS */ - mkhelp.h \ - -C_OBJS = \ - $(NULL) - - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS=-I$(PUBLIC)\jtools \ - -I$(PUBLIC)\zlib \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\dbm \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\parse \ - -I$(PUBLIC)\lay \ - -I$(PUBLIC)\style \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\libfont \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\netcnvts \ - -I$(PUBLIC)\httpurl \ - -I$(PUBLIC)\sockstub \ - -I$(PUBLIC)\cnetinit \ - -I$(PUBLIC)\mimetype \ - -I$(PUBLIC)\network \ -!ifdef NU_CACHE - -I$(PUBLIC)\cache \ -!endif - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\net \ - -I$(PUBLIC)\progress \ - -I$(PUBLIC)\ldapurl \ - -I$(PUBLIC)\imap4url \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\nntpurl \ - -I$(PUBLIC)\certurl \ - -I$(PUBLIC)\pop3url \ - -I$(PUBLIC)\mailbxurl \ - -I$(PUBLIC)\wallet \ - -I$(PUBLIC)\raptor \ - -I$(PUBLIC)\netlib \ - -I$(PUBLIC)\xpcom -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/main/mkabook.cpp b/mozilla/network/main/mkabook.cpp deleted file mode 100644 index 5693841bb5e..00000000000 --- a/mozilla/network/main/mkabook.cpp +++ /dev/null @@ -1,882 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -// -// mkabook.cpp -- Handles "addbook:" " URLs for core Navigator, without -// requiring libmsg. mkabook is intended for adding -// to the address-book. -// -// - -#include "mkutils.h" - -#include "xp.h" -#include "xp_str.h" - -#include "mkgeturl.h" -#include "mkabook.h" -#include "addrbook.h" - -#include "abcom.h" -#include "xpgetstr.h" -#include "pw_public.h" - -extern "C" -{ - extern int MK_OUT_OF_MEMORY; - extern int MK_MALFORMED_URL_ERROR; - extern int MK_ADDR_IMPORT_CARDS; - extern int MK_ADDR_IMPORT_MAILINGLISTS; - extern int MK_ADDR_EXPORT_CARDS; - extern int MK_MSG_ADDRESS_BOOK; - extern int MK_ADDR_EXPORT_TITLE; - extern int MK_ADDR_IMPORT_TITLE; -} - -typedef enum { - abImportVCard, - abImport, - abExport, - abCopy /* copying, deleting, moving address book entries */ -} net_abUrlType; - -class NET_AddressBookConnData -{ -public: - NET_AddressBookConnData (ActiveEntry * ce) - { - m_commandData = NULL; - m_addressBook = NULL; - m_urlType = abImportVCard; - m_started = FALSE; - m_ce = ce; - m_container = NULL; - - // Netlib magic so we get a timeslice without waiting for a read-ready socket. - // It would be nice to ditch this, but the LDAP SDK manages the sockets. - if (m_ce) - { - m_ce->socket = NULL; - NET_SetCallNetlibAllTheTime(m_ce->window_id, "mkabook"); - } - } - - virtual ~NET_AddressBookConnData () - { - if (m_container) - { - AB_ReleaseContainer(m_container); - m_container = NULL; - } - - // Netlib magic so we won't get called anymore for this URL - // It would be nice to ditch this, but the LDAP SDK manages the sockets. - NET_ClearCallNetlibAllTheTime(m_ce->window_id, "mkabook"); - m_ce = NULL; - } - -#ifdef MOZ_NEWADDR - virtual int Interrupt() = 0; - virtual int Process() = 0; - virtual int Load() = 0; -#else - virtual int Interrupt() {return 0;} - virtual int Process() { return 0;} - virtual int Load() {return 0;} -#endif - -#ifdef MOZ_NEWADDR - virtual int Initialize(const char * url) {return 0;} -#else - XP_Bool Initialize(const char *url) { return FALSE;} - -#endif - - - void *m_cookie; - char *m_commandData; - ABook *m_addressBook; // only used by old address book APIs....remove when everyone is using the new APIs... - ActiveEntry *m_ce; - AB_ContainerInfo * m_container; - - net_abUrlType m_urlType; - XP_Bool m_started; -}; - -/********************************************************************************************** - The connection data class for importing a vcard URL into an address book. This operation is - actually a synchronous so we shouldn't have to fill in implementations for interrupt... -***********************************************************************************************/ -class net_AddressBookAddVCard : public NET_AddressBookConnData -{ -public: - net_AddressBookAddVCard(ActiveEntry * ce); - virtual ~net_AddressBookAddVCard(); - - virtual int Load(); - virtual int Process(); - virtual int Initialize(const char * url); - virtual int Interrupt(); - -protected: - int LoadContainerToAddTo(); -}; - -net_AddressBookAddVCard::net_AddressBookAddVCard(ActiveEntry *ce) : NET_AddressBookConnData(ce) -{ - m_urlType = abImportVCard; -} - -net_AddressBookAddVCard::~net_AddressBookAddVCard() -{} - -int net_AddressBookAddVCard::LoadContainerToAddTo() -{ - // acquire list of personal address books, then grab the first one... - XP_List * containers = AB_AcquireAddressBookContainers(m_ce->window_id); - if (containers) - { - // extract the first one - int index = 1; - m_container = NULL; - while (!m_container && index <= XP_ListCount(containers)) - m_container = (AB_ContainerInfo *) XP_ListGetObjectNum (containers, index++); - if (m_container) - AB_AcquireContainer(m_container); // acquire our own ref count - - AB_ReleaseContainersList(containers); // release ref count on all the ctrs - } - - return 0; -} - -int net_AddressBookAddVCard::Load() -{ - // load m_container...right now this is just the first address book available... - return LoadContainerToAddTo(); -} - -int net_AddressBookAddVCard::Process() -{ - // since this is a synchronous operation, do the import... - int status = 0; - if (m_container) - status = AB_ImportVCards(m_container, m_commandData); - - return MK_CONNECTED; -} - -int net_AddressBookAddVCard::Interrupt() -{ - XP_ASSERT(FALSE); // this should not happen because vcard happens synch.... - return 0; -} - -int net_AddressBookAddVCard::Initialize(const char * url) -{ - char *search = NET_ParseURL (url, GET_SEARCH_PART); - m_urlType = abImportVCard; - if (search) - { - m_commandData = XP_STRDUP (search + 7); - NET_UnEscape (m_commandData); - } - XP_FREEIF(search); - return 0; -} - -/********************************************************************************************** - All of our asynch operations in the new address book (export and import right now), use - progress windows. We use this class to pull out the progress window commonality between - export and import. net_AddressBookAsynchData handles creation and destruction of the - progress panes. We use virtual methods to determine the appropriate title and description - text for the progress windows -************************************************************************************************/ - -// call back function for canceling asynch operations... -static void CancelAsynch(void *closure) -{ - MWContext *progressContext = (MWContext *)closure; - if (progressContext) - XP_InterruptContext(progressContext); -} - -class net_AddressBookAsynchData : public NET_AddressBookConnData -{ -public: - net_AddressBookAsynchData(ActiveEntry * ce); - virtual ~net_AddressBookAsynchData(); - - // all address book connect data classes support Load, Process, Initialize and Interrupt - // as these 4 methods are called by the NET_ functions in mkabook.h - virtual int Load(); // creates progress windows... - - virtual int Process() = 0; - virtual int Initialize(const char * url) = 0; - virtual int Interrupt() = 0; - - // string functions used to build the progress window - virtual char * GetPWTitle() { return NULL;} - virtual char * GetPWLine1Text() { return NULL;} // caller must free this string... - virtual char * GetPWLine2Text() { return NULL;} // caller must free this string.. - -protected: - // Some asynch urls use progress windows.... - MWContext *m_progressContext; - pw_ptr m_progressWindow; -}; - -net_AddressBookAsynchData::net_AddressBookAsynchData(ActiveEntry * ce) : NET_AddressBookConnData(ce) -{ - m_progressContext = NULL; - m_progressWindow = NULL; -} - -net_AddressBookAsynchData::~net_AddressBookAsynchData() -{ - if (m_progressWindow) - { - PW_Hide(m_progressWindow); - PW_Destroy(m_progressWindow); - } - - if (m_progressContext) - PW_DestroyProgressContext(m_progressContext); -} - -int net_AddressBookAsynchData::Load() -{ - int status = 0; - // get m_container from the url struct... - if (m_ce && m_ce->URL_s) - m_container = (AB_ContainerInfo *)m_ce->URL_s->owner_data; // it was already acquired when it was inserted into the url_struct... - - if (m_container) - { - m_progressContext = PW_CreateProgressContext(); - if (m_progressContext) - { - m_progressWindow = PW_Create(NULL, pwStandard); - if (m_progressWindow) - { - PW_AssociateWindowWithContext(m_progressContext, m_progressWindow); - char * title = GetPWTitle(); - char * line1Text = GetPWLine1Text(); - char * line2Text = GetPWLine2Text(); - - // it is okay to set a NULL title or line... - PW_SetWindowTitle(m_progressWindow, title); // resource string - PW_SetLine1(m_progressWindow, line1Text);// do we want anything here? - PW_SetLine2(m_progressWindow, line2Text); // mscott: again...add a real resource string for this - PW_SetProgressRange(m_progressWindow,0,100); - PW_SetCancelCallback(m_progressWindow, CancelAsynch, m_ce->window_id); - PW_Show(m_progressWindow); - - // free any allocated strings - XP_FREEIF(line1Text); - XP_FREEIF(line2Text); - XP_FREEIF(title); - } - else - PW_DestroyProgressContext(m_progressContext); - } // if context - } // if container - - return status; -} - -/********************************************************************************************** - The connection data class for copying/moving entries between address books. This operation is - asynch. We assume that the AB_AddressCopyInfo struct for the transfer is stored in the owner_data - field of the url_struct. In addition, status information will be shown through the current event's - context. -***********************************************************************************************/ -class net_AddressBookCopy : public net_AddressBookAsynchData -{ -public: - net_AddressBookCopy(ActiveEntry * ce); - virtual ~net_AddressBookCopy(); - - virtual int Load(); - virtual int Process(); - virtual int Initialize(const char * url); - virtual int Interrupt(); - -protected: - // any state we may ned to store... - AB_AddressBookCopyInfo * m_abCopyInfo; -}; - -net_AddressBookCopy::net_AddressBookCopy(ActiveEntry * ce) : net_AddressBookAsynchData(ce) -{ - if (ce && ce->URL_s) - m_abCopyInfo = (AB_AddressBookCopyInfo *) ce->URL_s->owner_data; - else - m_abCopyInfo = NULL; -} - -net_AddressBookCopy::~net_AddressBookCopy() -{ - if (m_abCopyInfo) - XP_ASSERT(FALSE); // struct should have been released by finish or interrupt calls... -} - -int net_AddressBookCopy::Load() // over ride this from base class so we don't create the progress window... -{ - return 0; -} - -int net_AddressBookCopy::Initialize(const char * /* url */) -{ - // we don't have any command data for address book copy urls.... - m_urlType = abCopy; - return 0; -} - -int net_AddressBookCopy::Process() -{ - int status = 0; - XP_Bool copyFinished = FALSE; - if (m_abCopyInfo) - { - if (!m_started) // if we haven't begun the copy...use the begin APIs... - status = AB_BeginEntryCopy (m_abCopyInfo->srcContainer, m_ce->window_id, m_abCopyInfo, &m_cookie, &copyFinished); - else // otherwise do more... - status = AB_MoreEntryCopy (m_abCopyInfo->srcContainer, m_ce->window_id, m_abCopyInfo, &m_cookie, &copyFinished); - - if (status != AB_SUCCESS) // then mark ourselves as finished! - { - XP_ASSERT(FALSE); // what condition failed to cause us to be here?? - copyFinished = TRUE; - } - - // all progress is handled by the src container - - if (copyFinished) // if we are finished, - { - AB_FinishEntryCopy(m_abCopyInfo->srcContainer, m_ce->window_id, m_abCopyInfo, &m_cookie); // clean up everything.. - m_abCopyInfo = NULL; - status = MK_CONNECTED; - } - else - status = MK_WAITING_FOR_CONNECTION; - } - else - status = MK_CONNECTED; // this copy is done...we didn't have a copy info struct!!!! - - return status; -} - -int net_AddressBookCopy::Interrupt() -{ - // we are shutting down... - if (m_abCopyInfo) - AB_InterruptEntryCopy(m_abCopyInfo->srcContainer, m_ce->window_id, m_abCopyInfo, &m_cookie); - - m_abCopyInfo = NULL; - return 0; -} - -/********************************************************************************************** - The connection data class for import. Importing in the new address book is asynch. The - file to import is contained in the URL. However, the particular address book to import into - is stored in the owner_data field of the URL struct which is in the active entry. When the - URL_struct is created, the container was reference counted. So when you are done importing, - or if importing is canceled, we are now responsible for releasing the reference count - on the container. - - m_cookie is actually a struct which represents the import state for the container. When the - import is finished or interrupted, the container will free this cookie struct... -************************************************************************************************/ - - -class net_AddressBookImport : public net_AddressBookAsynchData -{ -public: - net_AddressBookImport(ActiveEntry * ce); - virtual ~net_AddressBookImport(); - - // leave it to the subclass to implement these.. - virtual int Process(); - virtual int Initialize(const char * url); - virtual int Interrupt(); - - int UpdateProgress(); - - // string functions used to build the progress window - virtual char * GetPWTitle(); - virtual char * GetPWLine1Text(); // caller must free this string... - virtual char * GetPWLine2Text(); // caller must free this string.. - -protected: - // import in the new address book is asynch..we need a progress window to show it off.... - uint32 m_passCount; // importing LDIF requires 2 passes....we want to keep track of which pass we are on for progress purposes... -}; - -net_AddressBookImport::net_AddressBookImport(ActiveEntry * ce) : net_AddressBookAsynchData(ce) -{ - m_passCount = 1; // always start with first pass... -} - -net_AddressBookImport::~net_AddressBookImport() -{ - if (m_cookie) - XP_ASSERT(FALSE); // should have been freed and cleared by container import code.... - - // container is released by base class... -} - -int net_AddressBookImport::Initialize(const char * url) -{ - char * search = NET_ParseURL(url, GET_SEARCH_PART); - - m_urlType = abImport; - m_commandData = XP_STRDUP(search+6); - NET_UnEscape(m_commandData); - return 0; -} - -char * net_AddressBookImport::GetPWTitle() -{ - return XP_STRDUP(XP_GetString(MK_ADDR_IMPORT_TITLE)); -} - -char * net_AddressBookImport::GetPWLine1Text() -{ - return NULL; // no line 1 text for import pane -} - -char * net_AddressBookImport::GetPWLine2Text() -{ - AB_ContainerAttribValue * attrib = NULL; - AB_GetContainerAttribute(m_container, attribName, &attrib); - - char * lineText = NULL; - if (m_passCount <= 1) - { - if (attrib->u.string) - lineText = PR_smprintf (XP_GetString(MK_ADDR_IMPORT_CARDS), attrib->u.string); - else - lineText = PR_smprintf (XP_GetString(MK_ADDR_IMPORT_CARDS),XP_GetString(MK_MSG_ADDRESS_BOOK)); - } - else - { - if (attrib->u.string) - lineText = PR_smprintf (XP_GetString(MK_ADDR_IMPORT_MAILINGLISTS), attrib->u.string); - else - lineText = PR_smprintf (XP_GetString(MK_ADDR_IMPORT_MAILINGLISTS), XP_GetString(MK_MSG_ADDRESS_BOOK)); - } - - AB_FreeContainerAttribValue(attrib); - - return lineText; -} - - -int net_AddressBookImport::Process() -{ - int status = 0; - XP_Bool importFinished; - if (!m_started) // if we haven't begun the import...use the begin APIs... - status = AB_ImportBegin (m_container, NULL, m_commandData /* file name */, &m_cookie /* import state */, &importFinished); - else // otherwise do more... - status = AB_ImportMore (m_container, &m_cookie, &importFinished); - - UpdateProgress(); - - // are we done? - if (importFinished) // if we are finished, - { - AB_ImportFinish(m_container, &m_cookie); - status = MK_CONNECTED; - } - else - status = MK_WAITING_FOR_CONNECTION; - - return status; -} - -int net_AddressBookImport::UpdateProgress () -{ - // now update progress bar... - uint32 position = 0; // position in the import file - uint32 fileLength = 0; - uint32 passCount = m_passCount; - int status = AB_ImportProgress(m_container, m_cookie, &position, &fileLength, &passCount); - if (passCount != m_passCount) - { - m_passCount = passCount; - char * text = GetPWLine1Text(); - PW_SetLine1(m_progressWindow, text); // mscott: again...add a real resource string for this - XP_FREEIF(text); - } - - if (fileLength) - { - int32 percent = (position * 100) / fileLength; - PW_SetProgressValue(m_progressWindow, percent); - } - return 0; -} - -int net_AddressBookImport::Interrupt() -{ - // we are shutting down... - AB_ImportInterrupt(m_container, &m_cookie); // destroys the container... - m_cookie = NULL; - // destruction will clean up the progress pane stuff... - return 0; -} - - -/********************************************************************************************** - The connection data class for export. Exporting in the new address book is asynch. The - file to export to is contained in the URL. However, the particular address book to export from - is stored in the owner_data field of the URL struct which is in the active entry. When the - URL_struct is created, the container was reference counted. So when you are done exporting, - or if export is canceled, we are responsible for releasing the reference count - on the container. - - m_cookie is actually a struct which represents the export state for the container. When the - export is finished or interrupted, the container will free this cookie struct... -************************************************************************************************/ - - -class net_AddressBookExport : public net_AddressBookAsynchData -{ -public: - net_AddressBookExport(ActiveEntry * ce); - virtual ~net_AddressBookExport(); - - virtual int Process(); - virtual int Initialize(const char * url); - virtual int Interrupt(); - - int UpdateProgress(); - - // string functions used to build the progress window - virtual char * GetPWTitle(); - virtual char * GetPWLine1Text(); // caller must free this string... - virtual char * GetPWLine2Text(); // caller must free this string.. - -protected: -}; - -net_AddressBookExport::net_AddressBookExport(ActiveEntry * ce) : net_AddressBookAsynchData(ce) -{} - -net_AddressBookExport::~net_AddressBookExport() -{ - if (m_cookie) - XP_ASSERT(FALSE); // should have been freed and cleared by container import code.... - - // container is released by base class... - // progress window is destroyed by base class.. -} - -int net_AddressBookExport::Initialize(const char * url) -{ - char * search = NET_ParseURL(url, GET_SEARCH_PART); - m_urlType = abExport; - m_commandData = XP_STRDUP(search+6); // + 6 to skip over the "?file=" part - NET_UnEscape(m_commandData); - return 0; -} - -char * net_AddressBookExport::GetPWTitle() -{ - return XP_STRDUP(XP_GetString(MK_ADDR_EXPORT_TITLE)); -} - -char * net_AddressBookExport::GetPWLine1Text() -{ - return NULL; // no line 1 text for import pane -} - -char * net_AddressBookExport::GetPWLine2Text() -{ - AB_ContainerAttribValue * attrib = NULL; - AB_GetContainerAttribute(m_container, attribName, &attrib); - - char * lineText = NULL; - if (attrib->u.string) - lineText = PR_smprintf (XP_GetString(MK_ADDR_EXPORT_CARDS), attrib->u.string); - else - lineText = PR_smprintf (XP_GetString(MK_ADDR_EXPORT_CARDS),XP_GetString(MK_MSG_ADDRESS_BOOK)); - AB_FreeContainerAttribValue(attrib); - - return lineText; -} - -int net_AddressBookExport::Process() -{ - int status = 0; - XP_Bool exportFinished; - if (!m_started) // if we haven't begun the import...use the begin APIs... - status = AB_ExportBegin (m_container, NULL, m_commandData /* file name */, &m_cookie /* import state */, &exportFinished); - else // otherwise do more... - status = AB_ExportMore (m_container, &m_cookie, &exportFinished); - - UpdateProgress(); - - // are we done? - if (exportFinished) // if we are finished, - { - AB_ExportFinish(m_container, &m_cookie); - status = MK_CONNECTED; - } - else - status = MK_WAITING_FOR_CONNECTION; - - return status; -} - -int net_AddressBookExport::UpdateProgress () -{ - // now update progress bar... - uint32 numberExported = 0; - uint32 totalEntries = 0; - - int status = AB_ExportProgress(m_container, m_cookie, &numberExported, &totalEntries); - - if (totalEntries) - { - int32 percent = (numberExported * 100) / totalEntries; - PW_SetProgressValue(m_progressWindow, percent); - } - return 0; -} - -int net_AddressBookExport::Interrupt() -{ - // we are shutting down... - AB_ExportInterrupt(m_container, &m_cookie); // destroys the container... - m_cookie = NULL; - // destruction will clean up the progress pane stuff... - return 0; -} - -// -// Callbacks from NET_GetURL -// -#ifdef MOZ_NEWADDR - -extern "C" int32 net_ProcessAddressBook (ActiveEntry *ce) -{ - int status = 0; - NET_AddressBookConnData *cd = (NET_AddressBookConnData*) ce->con_data; - if (cd) - { - status = cd->Process(); // should return MK_WAITING_FOR_CONNECTION - cd->m_started = TRUE; - if (status < 0 || status == MK_CONNECTED) - { - delete cd; - ce->con_data = NULL; - } - } - - if(status == MK_CONNECTED) // i don't understand why mkgeturl won't end the url on MK_CONNECTED, but it doesn't... - status = -1; - - ce->status = status; - return ce->status; -} - -extern "C" int32 net_AddressBookLoad (ActiveEntry *ce) -{ - ce->status = -1; - int status = ce->status; - // examine URL to determine what type of connection data we need to create... - char * url = ce->URL_s->address; - char *path = NET_ParseURL (url, GET_PATH_PART); - char * search = NET_ParseURL(url, GET_SEARCH_PART); - NET_AddressBookConnData *cd = NULL; - switch (path[0]) - { - case 'a': - case 'A': - if (!XP_STRNCASECMP(path,"add",3)) - { - if (!XP_STRNCASECMP (search, "?vcard=", 7)) - cd = new net_AddressBookAddVCard(ce); - if (!cd) - status = MK_OUT_OF_MEMORY; - } - else - XP_ASSERT(FALSE); - break; - case 'i': - case 'I': - if (!XP_STRNCASECMP (path, "import", 6)) - { - if (!XP_STRNCASECMP (search, "?file=", 6)) - { - cd = new net_AddressBookImport(ce); - if (!cd) - status = MK_OUT_OF_MEMORY; - } //if ?file=... - } - break; - case 'e': - case 'E': - if (!XP_STRNCASECMP (path, "export", 6)) - { - if (!XP_STRNCASECMP (search, "?file=", 6)) - { - cd = new net_AddressBookExport(ce); - if (!cd) - status = MK_OUT_OF_MEMORY; - } //if ?file=... - } - break; - case 'c': - case 'C': - if (!XP_STRNCASECMP(path, "copy", 4)) - { - // we have no search part on copy urls.... - cd = new net_AddressBookCopy(ce); - if (!cd) - status = MK_OUT_OF_MEMORY; - } - break; - default: - status = MK_MALFORMED_URL_ERROR; - XP_ASSERT(FALSE); - - } - - ce->status = status; // catch any errors like MK_OUT_OF_MEMORY... - if (cd) - { - cd->Initialize(url); - cd->Load(); - ce->con_data = cd; // store the connection data - ce->status = net_ProcessAddressBook (ce); - } - - XP_FREEIF(path); - XP_FREEIF(search); - return ce->status; -} - -extern "C" int32 net_InterruptAddressBook (ActiveEntry * ce) -{ - ce->status = MK_INTERRUPTED; - NET_AddressBookConnData *cd = (NET_AddressBookConnData*) ce->con_data; - - if (cd) - { - cd->Interrupt(); - delete cd; - } - - return ce->status; -} -extern "C" void net_CleanupAddressBook(void) -{ - // I'm not sure what cleanup stuff I have to do here... - // leaving it empty for now... -} - -#else -extern "C" int32 net_ProcessAddressBook (ActiveEntry *ce) -{ - NET_AddressBookConnData *cd = (NET_AddressBookConnData*) ce->con_data; - switch (cd->m_urlType) - { - case abImportVCard: - AB_ImportFromVcardURL(cd->m_addressBook, ce->window_id, cd->m_commandData); //mscott - ce->status = -1; //phil/mscott should work, but seems not to. MK_CONNECTED; - break; - case abImport: - if (!cd->m_started) - ce->status = MK_CONNECTED; //mscott AB_ImportBegin (cd->m_addressBook, ce->window_id, cd->m_commandData, &cd->m_cookie); - else - ce->status = MK_CONNECTED; //mscott AB_ImportMore (cd->m_addressBook, ce->window_id, cd->m_cookie); - break; - } - - cd->m_started = TRUE; - - // Either an error, or we're already done - if (ce->status != MK_WAITING_FOR_CONNECTION) - delete cd; - - return ce->status; - return -1; -} - -extern "C" int32 net_AddressBookLoad (ActiveEntry *ce) -{ - ce->status = -1; - - NET_AddressBookConnData *cd = new NET_AddressBookConnData(ce); - if (!cd) - return MK_OUT_OF_MEMORY; - - ce->con_data = cd; - - if (cd->Initialize (ce->URL_s->address)) - ce->status = net_ProcessAddressBook(ce); - - return ce->status; -} - -extern "C" void -net_CleanupAddressBook(void) -{} - -extern "C" int32 net_InterruptAddressBook (ActiveEntry * ce) -{ - ce->status = MK_INTERRUPTED; - NET_AddressBookConnData *cd = (NET_AddressBookConnData*) ce->con_data; - - switch (cd->m_urlType) - { - case abImportVCard: - XP_ASSERT(FALSE); // this shouldn't happen because vCard import happens synchronously - break; - case abImport: - //mscott AB_ImportInterrupt (cd->m_addressBook, ce->window_id, cd->m_cookie); - break; - default: - XP_ASSERT(FALSE); - } - - delete cd; - - return ce->status; -} -#endif - -MODULE_PRIVATE void -NET_InitAddressBookProtocol(void) -{ - static NET_ProtoImpl abook_proto_impl; - - abook_proto_impl.init = net_AddressBookLoad; - abook_proto_impl.process = net_ProcessAddressBook; - abook_proto_impl.interrupt = net_InterruptAddressBook; - abook_proto_impl.cleanup = net_CleanupAddressBook; - - NET_RegisterProtocolImplementation(&abook_proto_impl, ADDRESS_BOOK_TYPE_URL); -} diff --git a/mozilla/network/main/mkabook.h b/mozilla/network/main/mkabook.h deleted file mode 100644 index 6e5af66fa8c..00000000000 --- a/mozilla/network/main/mkabook.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKABOOK_H -#define MKABOOK_H - -PR_BEGIN_EXTERN_C - -void NET_InitAddressBookProtocol(void); - -PR_END_EXTERN_C - -#endif diff --git a/mozilla/network/main/mkalert.c b/mozilla/network/main/mkalert.c deleted file mode 100644 index 02c38c7a536..00000000000 --- a/mozilla/network/main/mkalert.c +++ /dev/null @@ -1,297 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" -#include "mkgeturl.h" - -#include <stdio.h> -#include <ctype.h> -#include <stdarg.h> - -PUBLIC Bool -FE_SecurityDialog(MWContext * context, int message) -{ - switch(message) - { - case SD_INSECURE_POST_FROM_SECURE_DOC: - case SD_INSECURE_POST_FROM_INSECURE_DOC: - case SD_ENTERING_SECURE_SPACE: - case SD_LEAVING_SECURE_SPACE: - case SD_INSECURE_DOCS_WITHIN_SECURE_DOCS_NOT_SHOWN: - case SD_REDIRECTION_TO_INSECURE_DOC: - case SD_REDIRECTION_TO_SECURE_SITE: - printf("Security message: %d", message); - } -} - -void -TESTFE_AllConnectionsComplete(MWContext * context) -{ -} - -void -TESTFE_EnableClicking(MWContext * context) -{ -} - -void -XFE_SetProgressBarPercent(MWContext * context, int percent) -{ -} - -PUBLIC const char * -FE_UsersMailAddress(void) -{ - return("montulli@netscape.com"); -} - -PUBLIC const char * -FE_UsersFullName(void) -{ - return(NULL); -} - -extern void sample_exit_routine(URL_Struct *URL_s,int status,MWContext *window_id); - -PUBLIC void -FE_EditMailMessage (MWContext *context, - const char * to_address, - const char * subject, - const char * newsgroups, - const char * references, - const char * news_url) -{ -#if 0 - URL_Struct * URL_s; - char buffer[356]; - - sprintf(buffer, "mailto:%.256s", to_address); - - URL_s = NET_CreateURLStruct(buffer, FALSE); - - StrAllocCopy(URL_s->post_headers,"Subject: This is a test\r\nX-URL: http://bogus\r\n"); - StrAllocCopy(URL_s->post_data,"This is a test, this is only a test\n"); - URL_s->method = URL_POST_METHOD; - - NET_GetURL(URL_s, FO_CACHE_AND_PRESENT, (MWContext *)0 ,sample_exit_routine); - - return; -#endif -} - - -PUBLIC void -FE_ConnectToRemoteHost(MWContext * window_id, int url_type, char * hostname, char * port, char * username) -{ -} - - -extern NET_StreamClass * -IL_NewStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *context) -{ -return(NULL); -} - -fe_MakeViewSourceStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *context) -{ -return(NULL); -} - -fe_MakeMailToStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *context) -{ -return(NULL); -} - - -fe_MakePPMStream (int format_out, - void *data_obj, - URL_Struct *URL_s, - MWContext *context) -{ -return(NULL); -} - -Bool -TESTFE_ShowAllNewsArticles(MWContext * window_id) -{ -return(FALSE); -} - - -intn -LO_Format(void * data_object, PA_Tag *tag, intn status) -{ -return(0); -} - - -void -PR_LogPrint (const char* message, ...) -{ - int actualLen; - static char xp_Buffer[2048]; - va_list stack; - - va_start (stack, message); - actualLen = vsprintf (xp_Buffer, message, stack); - va_end (stack); - - fwrite(xp_Buffer, 1, strlen(xp_Buffer), stderr); - fprintf (stderr, "\n"); -} - - - -PUBLIC int32 FE_GetContextID(MWContext * window_id) -{ - return((int) window_id); -} - -PUBLIC int TESTFE_FileSortMethod(MWContext * window_id) -{ - return(SORT_BY_NAME); -} - -PUBLIC Bool TESTFE_UseFancyNewsgroupListing (MWContext * window_id) -{ - return(TRUE); -} - -PUBLIC Bool TESTFE_UseFancyFTP(MWContext * window_id) -{ - return(1); -} - -PUBLIC int TESTFE_CheckForInterrupt(void * window_id) -{ - /* check check check check and check again */ - return(0); -} - -PUBLIC void TESTFE_Spinner (MWContext * window_id) -{ - /* big wheel keep on rolling. Proud Mary keep on.... */ -} - -PUBLIC void TESTFE_Alert (MWContext * window_id, CONST char * mess) -{ - TRACEMSG(("WWW Alert: %s\n", mess)); -} - -PUBLIC void TESTFE_Progress (MWContext * window_id, CONST char * mess) -{ - TRACEMSG((" %s ...\n", mess)); -} - -PUBLIC void TESTFE_GraphProgressInit (MWContext * window_id, URL_Struct *url, int32 total_length) -{ - TRACEMSG((" GraphInit: %s is %d long...\n", url->address, total_length)); -} - -PUBLIC void TESTFE_GraphProgressDestroy (MWContext * window_id, URL_Struct *url, int32 bytes_transferred, int32 total_length) -{ - TRACEMSG((" GraphDestroy: %s is %d long...\n", url->address, total_length)); -} - -PUBLIC void TESTFE_GraphProgress (MWContext * window_id, URL_Struct *url, int32 cur_length, int32 length_delta, int32 total_length) -{ - TRACEMSG((" GraphProgress: %d of %d ...\n", cur_length, total_length)); -} - -PUBLIC Bool TESTFE_Confirm (MWContext * window_id, CONST char * mess) -{ - char Reply[4]; - char *URep; - - fprintf(stderr, "WWW: %s (y/n) ", mess); - - - fgets(Reply, 4, stdin); /* get reply, max 3 characters */ - URep=Reply; - while (*URep) { - if (*URep == '\n') { - *URep = (char)0; /* Overwrite newline */ - break; - } - *URep=toupper(*URep); - URep++; /* This was previously embedded in the TOUPPER */ - /* call an it became evaluated twice because */ - } - - if ((PL_strcmp(Reply,"YES")==0) || (PL_strcmp(Reply,"Y")==0)) - return(YES); - else - return(NO); -} - -/* Prompt for answer and get text back -*/ -PUBLIC char * TESTFE_Prompt (MWContext * window_id, CONST char * mess, CONST char * deflt) -{ - char temp[512]; - char * t_string = 0; - - fprintf(stderr, "Prompt: %s", mess); - if (deflt) fprintf(stderr, " (RETURN for [%s]) ", deflt); - - fgets(temp, 200, stdin); - temp[PL_strlen(temp)-1] = (char)0; /* Overwrite newline */ - - StrAllocCopy(t_string, *temp ? temp : deflt); - return t_string; -} - - -/* Prompt for password without echoing the reply -*/ -PUBLIC char * TESTFE_PromptPassword (MWContext * window_id, CONST char * mess) -{ - char *result = NULL; - char pw[80]; - - printf("%s",mess ? mess : "Type your password:"); - scanf("%s",pw); - - StrAllocCopy(result, pw); - return result; -} - - -PUBLIC void TESTFE_PromptUsernameAndPassword (MWContext * window_id, - CONST char * mess, - char ** username, - char ** password) -{ - if (mess) - fprintf(stderr, "WWW: %s\n", mess); - *username = TESTFE_Prompt(window_id, "Username: ", *username); - *password = TESTFE_PromptPassword(window_id, "Password: "); -} - diff --git a/mozilla/network/main/mkautocf.c b/mozilla/network/main/mkautocf.c deleted file mode 100644 index 466ce54d2fd..00000000000 --- a/mozilla/network/main/mkautocf.c +++ /dev/null @@ -1,1731 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * mkautocf.c: Proxy auto-config parser and evaluator - * Ari Luotonen - * - * Updated and Documented by Judson Valeski 11/19/1997 - */ -#include "mkutils.h" /* LF */ -#include "mktcp.h" -#include "netutils.h" -#include "prsystem.h" -#include "mkpadpac.h" -#include "net_xp_file.h" -#include <time.h> -#include "mkautocf.h" -#include "xp_mem.h" /* PR_NEWZAP() */ -#ifndef XP_MAC -#include <sys/types.h> -#endif -#include "libi18n.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "mkgeturl.h" -#include "mkformat.h" -#include "mime.h" -#include "cvactive.h" -#include "gui.h" -#include "msgcom.h" -#include "prefapi.h" -#define WANT_ENUM_STRING_IDS -#include "allxpstr.h" -#undef WANT_ENUM_STRING_IDS -#include "xp_regexp.h" - -#include "prnetdb.h" - -#include "net.h" -#include "libmocha.h" -#include "jsapi.h" -#include "jscompat.h" -#include "jspubtd.h" -#include "jsautocf.h" - -/* for XP_GetString() */ -#include "xpgetstr.h" -#ifdef NOT -extern int XP_BAD_KEYWORD_IN_PROXY_AUTOCFG; -extern int XP_RETRY_AGAIN_PROXY; -extern int XP_RETRY_AGAIN_SOCKS; -extern int XP_RETRY_AGAIN_PROXY_OR_SOCKS; -extern int XP_PROXY_UNAVAILABLE_TRY_AGAIN; -extern int XP_ALL_PROXIES_DOWN_TRY_AGAIN; -extern int XP_ALL_SOCKS_DOWN; -extern int XP_ALL_DOWN_MIX; -extern int XP_OVERRIDE_PROXY; -extern int XP_OVERRIDE_SOCKS; -extern int XP_OVERRIDE_MIX; -extern int XP_STILL_OVERRIDE_PROXY; -extern int XP_STILL_OVERRIDE_SOCKS; -extern int XP_STILL_OVERRIDE_MIX; -extern int XP_NO_CONFIG_RECIEVED; -extern int XP_NO_CONFIG_RECEIVED_NO_FAILOVER; -extern int XP_EMPTY_CONFIG_USE_PREV; -extern int XP_BAD_CONFIG_USE_PREV; -extern int XP_BAD_CONFIG_IGNORED; -extern int XP_BAD_TYPE_USE_PREV; -extern int XP_BAD_TYPE_CONFIG_IGNORED; -extern int XP_CONF_LOAD_FAILED_IGNORED; -extern int XP_CONF_LOAD_FAILED_NO_FAILOVER; -extern int XP_CONF_LOAD_FAILED_USE_PREV; -extern int XP_EVEN_SAVED_IS_BAD; -extern int XP_CONFIG_LOAD_ABORTED; -extern int XP_CONFIG_BLAST_WARNING; -extern int XP_RECEIVING_PROXY_AUTOCFG; -extern int XP_AUTOADMIN_MISSING; -#endif - -#define PACF_MIN_RETRY_AFTER 300 -#define PACF_MIN_RETRY_ASK 25 -#define PACF_AUTO_RETRY_AFTER 1800 -#define PACF_DIRECT_INTERVAL 1200 -#define PACF_RETRY_OK_AFTER 30 - -/* Types of retrievals: retrieve directly, thru a proxy, or using socks. */ -typedef enum _PACF_Type { - PACF_TYPE_INVALID = 0, - PACF_TYPE_DIRECT, - PACF_TYPE_PROXY, - PACF_TYPE_SOCKS -} PACF_Type; - -/* Info about the proxy/socks server hostname/IP address and port. - * These nodes are kept in a list so we don't have to parse the pac file - * every time to gather proxy/socks info. */ -typedef struct _PACF_Node { - PACF_Type type; /* direct | proxy | socks */ - char * addr; - u_long socks_addr; - short socks_port; - int retries; - time_t retrying; - time_t last_try; - time_t down_since; -} PACF_Node; - -/* Private object for the proxy config loader stream. */ -typedef struct _PACF_Object { - MWContext * context; - int flag; -} PACF_Object; - -/* A struct for holding queued state. - * - * The state is saved when NET_GetURL() is called for the first time, - * and the proxy autoconfig retrieve has to be started (and finished) - * before the first actual document can be loaded. - * - * A pre-exit function for the proxy autoconfig URL restarts the - * original URL retrieve by calling NET_GetURL() again with the - * same parameters. */ -typedef struct _PACF_QueuedState { - URL_Struct * URL_s; - FO_Present_Types output_format; - MWContext * window_id; - Net_GetUrlExitFunc* exit_routine; -} PACF_QueuedState; - -typedef enum { - PACF_SECONDARY_URL, - PACF_BINDINGS -} pc_slot; - -/* Declared in mkgeturl.c. NET_GetURL uses these variables to determine - * whether or not the pac file has been loaded. */ -extern XP_Bool NET_FindProxyInJSC(void); -extern XP_Bool NET_GlobalAcLoaded; -extern PRBool NET_ProxyAcLoaded; - -/* Private proxy auto-config variables */ -PRIVATE Bool pacf_do_failover = TRUE; -PRIVATE Bool pacf_loading = FALSE; -PRIVATE Bool pacf_ok = FALSE; -PRIVATE char * pacf_url = NULL; -PRIVATE char * pacf_src_buf = NULL; -PRIVATE int pacf_src_len = 0; -PRIVATE XP_List*pacf_all_nodes = NULL; -PRIVATE time_t pacf_direct_until = (time_t)0; -PRIVATE int pacf_direct_cnt = 0; -PRIVATE PACF_QueuedState *queued_state = NULL; -PRIVATE XP_List*pacf_bad_keywords = NULL; - -PRIVATE Bool pacf_find_proxy_undefined = FALSE; - -/* Javascript stuff. A javascript context does the interpretation and - * compilation of the pac file. */ -PRIVATE JSPropertySpec pc_props[] = { - {"secondary", PACF_SECONDARY_URL}, - {"bindings", PACF_BINDINGS}, - {0} -}; - -PRIVATE JSClass pc_class = { - "ProxyConfig", 0, - JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, - JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub -}; - -/* PRIVATE JSPropertySpec no_props[1] = { { NULL } }; */ -PRIVATE JSObject *proxyConfig = NULL; -PRIVATE JSObject *globalConfig = NULL; -PRIVATE JSContext *configContext = NULL; - -/* The javascript methods */ -MODULE_PRIVATE JSBool PR_CALLBACK proxy_weekdayRange(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_dateRange(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_timeRange(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_isPlainHostName(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_dnsDomainLevels(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_dnsDomainIs(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_localHostOrDomainIs(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_isResolvable(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_dnsResolve(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_isInNet(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_myIpAddress(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); -MODULE_PRIVATE JSBool PR_CALLBACK proxy_regExpMatch(JSContext *mc, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval); - -PRIVATE JSFunctionSpec pc_methods[] = { - { "weekdayRange", proxy_weekdayRange, 3}, - { "dateRange", proxy_dateRange, 7}, - { "timeRange", proxy_timeRange, 7}, - { "isPlainHostName", proxy_isPlainHostName, 1}, - { "dnsDomainLevels", proxy_dnsDomainLevels, 1}, - { "dnsDomainIs", proxy_dnsDomainIs, 2}, - { "localHostOrDomainIs", proxy_localHostOrDomainIs, 2}, - { "isResolvable", proxy_isResolvable, 1}, - { "dnsResolve", proxy_dnsResolve, 1}, - { "isInNet", proxy_isInNet, 3}, - { "myIpAddress", proxy_myIpAddress, 0}, - { "regExpMatch", proxy_regExpMatch, 2}, - { "shExpMatch", proxy_regExpMatch, 2}, - { NULL, NULL, 0} -}; - -PRIVATE char *mkMethodString( int method ) { - char *mstr= NULL; - - switch ( method ) { - case URL_GET_METHOD: - mstr = PL_strdup("GET"); - break; - case URL_POST_METHOD: - mstr = PL_strdup("POST"); - break; - case URL_HEAD_METHOD: - mstr = PL_strdup("HEAD"); - break; - case URL_PUT_METHOD: - mstr = PL_strdup("PUT"); - break; - case URL_DELETE_METHOD: - mstr = PL_strdup("DELETE"); - break; - case URL_MKDIR_METHOD : - mstr = PL_strdup("MKDIR"); - break; - case URL_MOVE_METHOD: - mstr = PL_strdup("MOVE"); - break; - case URL_INDEX_METHOD: - mstr = PL_strdup("INDEX"); - break; - case URL_GETPROPERTIES_METHOD: - mstr = PL_strdup("GETPROPERTIES"); - break; - } - return mstr; -} - -PRIVATE char *msg2(char *fmt, char *prm) { - char *msg = (char *)PR_Malloc(PL_strlen(fmt) + 100 + - (prm ? PL_strlen(prm) : 0)); - if (msg) - sprintf(msg, fmt, prm ? prm : "-"); - - return msg; -} - -PRIVATE Bool confirm2(MWContext *context, char *fmt, char *prm) { - Bool rv = TRUE; - char *msg = msg2(fmt, prm); - if (msg) { - rv = FE_Confirm(context, msg); - PR_Free(msg); - } - return rv; -} - -PRIVATE void alert2(MWContext *context, char *fmt, char *prm) { - char *msg = msg2(fmt, prm); - if (msg) { - FE_Alert(context, msg); - PR_Free(msg); - } -} - -/* Returns a node representing a proxy/SOCKS server address or - * direct access, and guarantees to return the same node if one - * was already created for that address. */ -PRIVATE PACF_Node *lookup_create_node(PACF_Type type, char *addr) { - if (!pacf_all_nodes) - pacf_all_nodes = XP_ListNew(); - - /* Truncate at 64 characters -- gethostbyname() is evil */ - if (addr && PL_strlen(addr) > 64) - addr[64] = '\0'; - - if (!type || (!addr && (type == PACF_TYPE_PROXY || - type == PACF_TYPE_SOCKS))) - { - return NULL; - } - else - { - XP_List *cur = pacf_all_nodes; - PACF_Node *node; - - while ((node = (PACF_Node *)XP_ListNextObject(cur)) != NULL) { - if (node->type == type && - ((!node->addr && !addr) || - ( node->addr && addr && !strcmp(node->addr, addr)))) - { - return node; - } - } - - node = PR_NEWZAP(PACF_Node); - if (node) { - node->type = type; - node->addr = PL_strdup(addr); - - XP_ListAddObject(pacf_all_nodes, node); - } - - return node; - } -} - -/* Called by netlib when it notices that a proxy is down. */ -PRIVATE PACF_Node * pacf_proxy_is_down(MWContext *context, - char *proxy_addr, - u_long socks_addr, - short socks_port) { - XP_List *cur = pacf_all_nodes; - PACF_Node *node; - - while ((node = (PACF_Node *)XP_ListNextObject(cur)) != NULL) { - if ((proxy_addr && node->addr && !PL_strcmp(node->addr, proxy_addr)) || - (socks_addr && - node->socks_addr == socks_addr && - node->socks_port == socks_port)) - { - time_t now = time(NULL); - - if (!node->down_since) { - - node->down_since = now; - } - node->last_try = now; - node->retrying = (time_t)0; - return node; - } - } - return NULL; -} - -PRIVATE Bool fill_return_values(PACF_Type type, - PACF_Node * node, - char ** ret_proxy_addr, - u_long * ret_socks_addr, - short * ret_socks_port) { - *ret_proxy_addr = NULL; - *ret_socks_addr = 0; - *ret_socks_port = 0; - - if(!node) - return FALSE; - - if (type == PACF_TYPE_PROXY) { - *ret_proxy_addr = node->addr; - } - else if (!node->socks_addr) { - char *p, *host = NULL; - - StrAllocCopy(host, node->addr); - p = PL_strchr(host, ':'); - if (p) { - *p++ = '\0'; - node->socks_port = (short)atoi(p); - } - else { - node->socks_port = 1080; - } - - if (isdigit(*host)) { - /* - * Some systems return a number instead of a struct - */ - node->socks_addr = inet_addr(host); - } - else { - PRStatus rv; - PRHostEnt *hp; - PRHostEnt hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - - NET_InGetHostByName++; /* global semaphore */ - rv = PR_GetHostByName(host, dbbuf, sizeof(dbbuf), &hpbuf); - hp = (rv == PR_SUCCESS ? &hpbuf : NULL); - NET_InGetHostByName--; /* global semaphore */ - - if (!hp) - return FALSE; /* Fail? */ - - memcpy(&node->socks_addr, hp->h_addr, hp->h_length); - } - } - - *ret_socks_addr = node->socks_addr; - *ret_socks_port = node->socks_port; - return TRUE; -} - -/* NET_SetNoProxyFailover - * Sets a flag that indicates that proxy failover should not - * be done. This is used by the Enterprise Kit code, where - * the customer might configure the client to use specific - * proxies. In these cases, failover can cause different - * proxies, or no proxies to be used. */ -PUBLIC void -NET_SetNoProxyFailover(void) { - pacf_do_failover = FALSE; -} - -PUBLIC PRBool -NET_LoadingPac(void) { - return pacf_loading; -} - -#ifdef MOZILLA_CLIENT -/* - * NET_GetNoProxyFailover - */ -MODULE_PRIVATE Bool -NET_GetNoProxyFailover(void) { - return ( pacf_do_failover == FALSE ); -} -#endif /* MOZILLA_CLIENT */ - -/* Called by netlib to get a single string of "host:port" format, - * given the string of possibilities returned by the Mocha script. - * - * This function will return an address to a proxy that is (to its - * knowledge) up and running. Netlib can later inform this module - * using the function pacf_proxy_is_down() that a proxy is down - * and should not be called for a few minutes. - * - * Returns FALSE if everything has failed, and an error should be - * displayed to the user. - * - * Returns TRUE if there is hope. - * If *ret is NULL, a direct connection should be attempted. - * If *ret is not null, it is the proxy address to use. */ -MODULE_PRIVATE Bool -pacf_get_proxy_addr(MWContext *context, char *list, char **ret_proxy_addr, - u_long *ret_socks_addr, short *ret_socks_port) { - Bool rv = FALSE; - char *my_copy, *cur, *p, *addr; - PACF_Type type = PACF_TYPE_INVALID; - PACF_Node *node; - PACF_Node *sm_ptr = NULL; - PACF_Node *went_down = NULL; - time_t now = time(NULL); - time_t smallest = (time_t)0; - int proxy_cnt = 0; - int socks_cnt = 0; - int retry_now = 0; - - if (!list || !*list || !ret_proxy_addr || !ret_socks_addr || !ret_socks_port) - return FALSE; - - if (*ret_proxy_addr || *ret_socks_addr) { - /* - * We get called here because this proxy/SOCKS server was down. - */ - went_down = pacf_proxy_is_down(context, *ret_proxy_addr, - *ret_socks_addr, *ret_socks_port); - } - - *ret_proxy_addr = NULL; - *ret_socks_addr = 0; - *ret_socks_port = 0; - - cur = my_copy = PL_strdup(list); - - TRACEMSG(("Getting proxy addr from config list: %s", list)); - - do { - p = PL_strchr(cur, ';'); - if (p) { - do { - *p++ = '\0'; - } while (*p && NET_IS_SPACE(*p)); - } - - for (addr=cur; *addr && !NET_IS_SPACE(*addr); addr++) - ; - if (*addr) { - do { - *addr++ = '\0'; - } while (*addr && NET_IS_SPACE(*addr)); - } - - type = ((!PL_strcasecmp(cur, "DIRECT")) ? PACF_TYPE_DIRECT : - (!PL_strcasecmp(cur, "PROXY")) ? PACF_TYPE_PROXY : - (!PL_strcasecmp(cur, "SOCKS")) ? PACF_TYPE_SOCKS : - PACF_TYPE_INVALID ); - - if (type == PACF_TYPE_DIRECT) /* don't use a proxy */ - { - rv = TRUE; - break; /* done */ - } - else if (type == PACF_TYPE_PROXY || /* use a proxy or... */ - type == PACF_TYPE_SOCKS ) /* use SOCKS */ - { - if (type == PACF_TYPE_PROXY) - proxy_cnt++; - else - socks_cnt++; - - node = lookup_create_node(type, addr); - if (*addr && node) { - if (node->down_since && node->retrying && - now - node->retrying > PACF_RETRY_OK_AFTER) - { - node->down_since = node->retrying = (time_t)0; - } - - if (!node->down_since) - { - if (fill_return_values(type, node, - ret_proxy_addr, - ret_socks_addr, - ret_socks_port)) - { - rv = TRUE; - break; - } - } - else if (now - node->last_try > - (node->retries + 1) * PACF_AUTO_RETRY_AFTER) - { - node->retries++; - if (fill_return_values(type, node, - ret_proxy_addr, - ret_socks_addr, - ret_socks_port)) - { - node->retrying = now; - rv = TRUE; - break; - } - } - else if (node != went_down && - (!smallest || smallest > node->last_try)) - { - smallest = node->last_try; - sm_ptr = node; - } - } - } - else /* invalid entry */ - { - char *key = NULL; - - if (!pacf_bad_keywords) - { - pacf_bad_keywords = XP_ListNew(); - } - else - { - XP_List *ptr = pacf_bad_keywords; - - while ((key = (char *)XP_ListNextObject(ptr)) != NULL) { - if (!strcmp(key, cur)) - break; - } - } - - if (!key && XP_ListCount(pacf_bad_keywords) < 3) - { - key = PL_strdup(cur); - XP_ListAddObject(pacf_bad_keywords, key); - alert2(context, XP_GetString(XP_BAD_KEYWORD_IN_PROXY_AUTOCFG), cur); - } - } - - cur = p; - - } while (cur && *cur); - - PR_Free(my_copy); - - if (rv) - return TRUE; - - /* If we didn't return just above here, and we're using a pad pac file, - * something went wrong with it so disable it for this session and return - * true so we go direct. */ - if(NET_UsingPadPac()) { - net_UsePadPac(FALSE); - return TRUE; - } - - if (pacf_do_failover && pacf_direct_until) { - if (now < pacf_direct_until) - { - return TRUE; - } - else if (!FE_Confirm(context, - !socks_cnt ? XP_GetString(XP_RETRY_AGAIN_PROXY) : - !proxy_cnt ? XP_GetString(XP_RETRY_AGAIN_SOCKS) : XP_GetString(XP_RETRY_AGAIN_PROXY_OR_SOCKS))) - { - pacf_direct_until = now + (++pacf_direct_cnt) * PACF_DIRECT_INTERVAL; - return TRUE; - } - else - { - pacf_direct_until = (time_t)0; - retry_now = 1; - } - } - - if (smallest && - (retry_now || - now - smallest > PACF_MIN_RETRY_AFTER || - (sm_ptr && !sm_ptr->retrying && - now - smallest > PACF_MIN_RETRY_ASK && - confirm2(context, - (!socks_cnt && proxy_cnt==1 ? XP_GetString(XP_PROXY_UNAVAILABLE_TRY_AGAIN) : - !socks_cnt && proxy_cnt >1 ? XP_GetString(XP_ALL_PROXIES_DOWN_TRY_AGAIN) : - !proxy_cnt ? XP_GetString(XP_ALL_SOCKS_DOWN) : - XP_GetString(XP_ALL_DOWN_MIX)), - sm_ptr->addr))) && - fill_return_values(type, sm_ptr, - ret_proxy_addr, ret_socks_addr, ret_socks_port)) - { - sm_ptr->retrying = now; - sm_ptr->retries++; - return TRUE; - } - else if (pacf_do_failover && FE_Confirm(context, - !pacf_direct_cnt ? - (!socks_cnt ? XP_GetString(XP_OVERRIDE_PROXY) : - !proxy_cnt ? XP_GetString(XP_OVERRIDE_SOCKS) : XP_GetString(XP_OVERRIDE_MIX)) : - (!socks_cnt ? XP_GetString(XP_STILL_OVERRIDE_PROXY) : - !proxy_cnt ? XP_GetString(XP_STILL_OVERRIDE_SOCKS) : XP_GetString(XP_STILL_OVERRIDE_SOCKS)))) - { - pacf_direct_until = now + (++pacf_direct_cnt) * PACF_DIRECT_INTERVAL; - return TRUE; - } - else - { - return FALSE; - } -} - - - -/* Saves out the proxy autoconfig file to disk, in case the server - * is down the next time. - * - * Returns 0 on success, -1 on failure. */ -PRIVATE int pacf_save_config(void) { - XP_File fp; - int32 len = 0; - - if (!pacf_do_failover || !pacf_src_buf || !*pacf_src_buf || pacf_src_len <= 0) - return -1; - - if(!(fp = NET_XP_FileOpen("", xpProxyConfig, XP_FILE_WRITE))) - return -1; - - len = NET_XP_FileWrite(pacf_src_buf, pacf_src_len, fp); - NET_XP_FileClose(fp); - if (len != pacf_src_len) - return -1; - - return 0; -} - -/* Reads the proxy autoconfig file from disk. - * This is called if the config server is not responding. - * - * returns 0 on success -1 on failure. */ -PRIVATE int pacf_read_config(void) { - XP_StatStruct st; - XP_File fp; - - if (NET_XP_Stat("", &st, xpProxyConfig) == -1) - return -1; - - if (!(fp = NET_XP_FileOpen("", xpProxyConfig, XP_FILE_READ))) - return -1; - - pacf_src_len = st.st_size; - pacf_src_buf = (char *)PR_Malloc(pacf_src_len + 1); - if (!pacf_src_buf) { - NET_XP_FileClose(fp); - pacf_src_len = 0; - return -1; - } - - if ((pacf_src_len = NET_XP_FileRead(pacf_src_buf, pacf_src_len, fp)) > 0) - { - pacf_src_buf[pacf_src_len] = '\0'; - } - else - { - PR_Free(pacf_src_buf); - pacf_src_buf = NULL; - pacf_src_len = 0; - } - - NET_XP_FileClose(fp); - - return 0; -} - -/* Private stream object methods for receiving the proxy autoconfig file. */ -PRIVATE int pacf_write(NET_StreamClass *stream, CONST char *buf, int32 len) { - PACF_Object *obj; - obj=stream->data_object; - if (len > 0) { - if (!pacf_src_buf) - pacf_src_buf = (char*)PR_Malloc(len + 1); - else - pacf_src_buf = (char*)PR_Realloc(pacf_src_buf, - pacf_src_len + len + 1); - - if (!pacf_src_buf) { /* Out of memory */ - pacf_src_len = 0; - return MK_DATA_LOADED; - } - - memcpy(pacf_src_buf + pacf_src_len, buf, len); - pacf_src_len += len; - pacf_src_buf[pacf_src_len] = '\0'; - } - return MK_DATA_LOADED; -} - -PRIVATE unsigned int pacf_write_ready(NET_StreamClass *stream) { - return MAX_WRITE_READY; -} - -PUBLIC XP_Bool -NET_InitPacfContext(void) -{ - XP_Bool first_time = TRUE; - - if ( first_time == FALSE ) return TRUE; - - if ( (PREF_OK != PREF_GetConfigContext(&configContext)) - ||(PREF_OK != PREF_GetGlobalConfigObject(&globalConfig)) ) - return FALSE; - - JS_BeginRequest(configContext); - - proxyConfig = JS_DefineObject(configContext, globalConfig, - "ProxyConfig", - &pc_class, - NULL, - JSPROP_ENUMERATE); - if (proxyConfig) { - if (!JS_DefineProperties(configContext, - proxyConfig, - pc_props)) { - JS_EndRequest(configContext); - return FALSE; - } - - if (!JS_DefineFunctions(configContext, - proxyConfig, - pc_methods)) { - JS_EndRequest(configContext); - return FALSE; - } - - } - - JS_DefineObject(configContext, proxyConfig, - "bindings", - &pc_class, - NULL, - 0); - - JS_EndRequest(configContext); - - first_time = FALSE; - - return TRUE; -} - -PRIVATE void pacf_complete(NET_StreamClass *stream) { - PACF_Object *obj=stream->data_object; - jsval result; - XP_StatStruct st; - JSBool ok; - -retry: - if (!obj->flag || obj->flag == 2) { - pacf_loading = FALSE; - if ( !NET_InitPacfContext() ) return; - } - - if (!pacf_src_buf) { - if ( pacf_do_failover == FALSE && !NET_UsingPadPac() ) { - /* Don't failover to using no proxies */ - FE_Alert(obj->context, XP_GetString(XP_NO_CONFIG_RECEIVED_NO_FAILOVER)); - } - else if (obj->flag != 2 && (NET_XP_Stat("", &st, xpProxyConfig) == -1) && !NET_UsingPadPac()) - { - FE_Alert(obj->context, XP_GetString(XP_NO_CONFIG_RECIEVED)); - } - else - { - if(NET_UsingPadPac()) { - pacf_read_config(); - obj->flag = 1; - goto retry; - } else if (obj->flag == 2 || - confirm2(obj->context, XP_GetString(XP_EMPTY_CONFIG_USE_PREV), pacf_url)) { - pacf_read_config(); - obj->flag = 1; - goto retry; - } - } - pacf_ok = FALSE; - goto out; - } - - JS_BeginRequest(configContext); - ok = JS_EvaluateScript(configContext, proxyConfig, - pacf_src_buf, pacf_src_len, pacf_url, 0, - &result); - JS_EndRequest(configContext); - - if (!ok) { - /* Something went wrong with the js evaluation. If we're using a - * proxy auto-discovery pac file, don't use it again. */ - if(NET_UsingPadPac()) { - net_UsePadPac(FALSE); - goto out; - } - if (obj->flag) { - FE_Alert(obj->context, XP_GetString(XP_EVEN_SAVED_IS_BAD)); - } else if (NET_XP_Stat("", &st, xpProxyConfig) == -1) { - alert2(obj->context, XP_GetString(XP_BAD_CONFIG_IGNORED), pacf_url); - } else if (confirm2(obj->context, XP_GetString(XP_BAD_CONFIG_USE_PREV), pacf_url)) { - PR_Free(pacf_src_buf); - pacf_src_buf = NULL; - pacf_src_len = 0; - pacf_read_config(); - obj->flag = 1; /* Uh (this is a horrid hack) */ - goto retry; - } - pacf_ok = FALSE; - } else { - pacf_ok = TRUE; - if (!obj->flag) { - pacf_save_config(); - } - } - - PR_Free(obj); - -out: - ; -} - -PRIVATE void pacf_abort(NET_StreamClass *stream, int status) { - PACF_Object *obj=stream->data_object; - pacf_loading = FALSE; - FE_Alert(obj->context, XP_GetString(XP_GLOBAL_CONFIG_LOAD_ABORTED)); - PR_Free(obj); -} - - -/* A stream constructor function for application/x-ns-proxy-autoconfig. - * This is used by cvmime.c; it's registered as the stream converter for - * pac files. */ -MODULE_PRIVATE NET_StreamClass * -NET_ProxyAutoConfig(int fmt, void *data_obj, URL_Struct *URL_s, - MWContext *w) { - PACF_Object *obj; - NET_StreamClass *stream; - - if (!pacf_loading) { - /* - * The Navigator didn't start this config retrieve - * intentionally. Discarding the config. - */ - if(!URL_s) - return NULL; - alert2(w, XP_GetString(XP_CONFIG_BLAST_WARNING), URL_s->address); - return NULL; - } - else { - NET_Progress(w, XP_GetString( XP_RECEIVING_PROXY_AUTOCFG ) ); - } - - if (pacf_src_buf) { - PR_Free(pacf_src_buf); - pacf_src_buf = NULL; - pacf_src_len = 0; - } - - if (!(stream = PR_NEWZAP(NET_StreamClass))) - return NULL; - - if (!(obj = PR_NEWZAP(PACF_Object))) { - PR_Free(stream); - return NULL; - } - - obj->context = w; - - stream->data_object = obj; - stream->name = "ProxyAutoConfigLoader"; - stream->complete = (MKStreamCompleteFunc) pacf_complete; - stream->abort = (MKStreamAbortFunc) pacf_abort; - stream->put_block = (MKStreamWriteFunc) pacf_write; - stream->is_write_ready = (MKStreamWriteReadyFunc)pacf_write_ready; - stream->window_id = w; - - return stream; -} - - - -/* calls NET_GetURL() to get the url that had been queued up behind the - * actual pac file url. */ -static void pacf_restart_queued(URL_Struct *URL_s, int status, - MWContext *window_id) { - XP_StatStruct st; - - /* We want to fail silently if we're loading a pad pac and fail, - * so fall through to bottom and load the queued url. */ - if (pacf_loading && !(NET_UsingPadPac() || foundPADPAC) ) { - - if ( pacf_do_failover == FALSE ) { - /* Don't failover to using no proxies */ - FE_Alert(window_id, XP_GetString(XP_CONF_LOAD_FAILED_NO_FAILOVER)); - } - else if (NET_XP_Stat("", &st, xpProxyConfig) == -1) - { - if (status < 0) - FE_Alert(window_id, XP_GetString(XP_CONF_LOAD_FAILED_IGNORED)); - else { - alert2(window_id, XP_GetString(XP_BAD_TYPE_CONFIG_IGNORED), pacf_url); - } - } - else if (status == MK_INTERRUPTED) - { - /* silently fail and retry later */ - NET_ProxyAcLoaded = FALSE; - NET_GlobalAcLoaded = FALSE; - } - else if (status < 0 - ? FE_Confirm(window_id, XP_GetString(XP_CONF_LOAD_FAILED_USE_PREV)) - : confirm2(window_id, XP_GetString(XP_BAD_TYPE_USE_PREV), pacf_url)) - { - PACF_Object *obj = PR_NEWZAP(PACF_Object); - NET_StreamClass stream; - stream.data_object=obj; - - if (obj) { - obj->context = window_id; - obj->flag = 2; - pacf_complete(&stream); - } - } - - pacf_loading = FALSE; - } else { - /* Call this only if everything succeeded -- otherwise - the netlib has already freed the URL_s, and there isn't - a clean fix, so for now we'll just forget the URL load - if proxy config load went foul. - */ - if(queued_state) { - NET_GetURL(queued_state->URL_s, - queued_state->output_format, - queued_state->window_id, - queued_state->exit_routine); - } - } - PR_FREEIF(queued_state); - queued_state = NULL; -} - - - -/* Called by mkgeturl.c to originally retrieve, and re-retrieve - * the proxy autoconfig file. - * - * autoconfig_url is the URL pointing to the autoconfig. - * - * The rest of the parameters are what was passed to NET_GetURL(), - * and when the autoconfig load finishes NET_GetURL() will be called - * with those exact same parameters. - * - * This is because the proxy config is loaded when NET_GetURL() is - * called for the very first time, and the actual request must be put - * on hold when the proxy config is being loaded. - * - * When called from the explicit proxy config RE-load function - * NET_ReloadProxyConfig, the four last parameters are all zero, - * and no request gets restarted. */ -MODULE_PRIVATE int NET_LoadProxyConfig(char *autoconf_url, - URL_Struct *URL_s, - FO_Present_Types output_format, - MWContext *window_id, - Net_GetUrlExitFunc *exit_routine) { - URL_Struct *my_url_s = NULL; - - if (!autoconf_url) - return -1; - - if (!PL_strcmp(autoconf_url,"BAD-NOAUTOADMNLIB")) { - FE_Alert(window_id, XP_GetString( XP_AUTOADMIN_MISSING )); - return -1; - } - - StrAllocCopy(pacf_url, autoconf_url); - my_url_s = NET_CreateURLStruct(autoconf_url, NET_SUPER_RELOAD); - - - if (exit_routine) { - - queued_state = PR_NEWZAP(PACF_QueuedState); - if(!queued_state) - return -1; - queued_state->URL_s = URL_s; - queued_state->output_format = output_format; - queued_state->window_id = window_id; - queued_state->exit_routine = exit_routine; - - if(!my_url_s) - return -1; - - my_url_s->pre_exit_fn = pacf_restart_queued; - } - - /* Alert the proxy autoconfig module that config is coming */ - pacf_loading = TRUE; - pacf_find_proxy_undefined = FALSE; - - return NET_GetURL(my_url_s, FO_PRESENT, window_id, NULL); -} - -/* Returns a pointer to a NULL-terminted buffer which contains - * the text of the proxy autoconfig file. */ -PUBLIC char * NET_GetProxyConfigSource(void) { - - return pacf_src_buf; - -} - - - /* Given a URL, returns the proxy that should be used. - * The proxy is determined by the proxy autoconfig file, - * which is a JavaScript routine. */ -MODULE_PRIVATE char *pacf_find_proxies_for_url(MWContext *context, - URL_Struct *URL_s ) { - jsval rv; - char *buf = NULL; - char *host = NULL; - char *p, *q, *r; - int i, len = 0; - char *safe_url = NULL; - char *orig_url = NULL; - char *method = NULL; - char *bad_url = NULL; - char *result = NULL; - JSBool ok; - - if(!URL_s) - return NULL; - - orig_url=URL_s->address; - method=mkMethodString(URL_s->method); - - /* If proxy failover is not allowed, and we weren't - * able to autoload the proxy, return a string that - * pacf_get_proxy_addr will always fail with. */ - if ( !pacf_do_failover && !pacf_loading && !pacf_ok && !NET_FindProxyInJSC()) { - return ""; - } - - if ( !NET_FindProxyInJSC() && (!orig_url || !pacf_ok || pacf_loading || pacf_find_proxy_undefined)) - return NULL; - - if (!(bad_url = PL_strdup(orig_url))) - goto out; - - len = NET_UnEscapeCnt(bad_url); - - if (!(safe_url = PR_Malloc(2 * len + 1))) /* worst case */ - goto out; - - p = bad_url; - q = safe_url; - for(i=0; i<len; i++, p++) { - switch (*p) { - case '\n': - *q++ = '\\'; - *q++ = 'n'; - break; - case '\r': - *q++ = '\\'; - *q++ = 'r'; - break; - case '\0': - *q++ = '\\'; - *q++ = '0'; - break; - case '"': - *q++ = '\\'; - *q++ = '"'; - break; - case '\\': - *q++ = '\\'; - *q++ = '\\'; - break; - default: - *q++ = *p; - } - } - *q = '\0'; - - len = (int)(q - safe_url); - - if (!(host = PR_Malloc(len + 1))) - goto out; - - if (!(buf = PR_Malloc(len*2 + 50))) - goto out; - - host[0] = '\0'; - - p = PL_strstr(safe_url, "://"); - if (p) { - p += 3; - q = PL_strchr(p, '/'); - if (q) - *q = '\0'; - r = PL_strchr(p, '@'); - if (r) - p = r + 1; - PL_strcpy(host, p); - if (q) - *q = '/'; - p = PL_strchr(host, ':'); - if (p) - *p = '\0'; - } - - if ( NET_FindProxyInJSC() ) { - XP_SPRINTF(buf, "ProxyConfig.FindProxyForURL(\"%s\",\"%s\",\"%s\")", safe_url, host, - method ? method : "" ); - } else { - XP_SPRINTF(buf, "FindProxyForURL(\"%s\",\"%s\",\"%s\")", safe_url, host, - method ? method : "" ); - } - - JS_BeginRequest(configContext); - if (!JS_AddRoot(configContext, &rv)) { - JS_EndRequest(configContext); - goto out; - } - - if ( NET_FindProxyInJSC() ) { - ok = JS_EvaluateScript(configContext, globalConfig, - buf, strlen(buf), 0, 0, &rv); - } else { - ok = JS_EvaluateScript(configContext, proxyConfig, - buf, strlen(buf), 0, 0, &rv); - } - - if (ok) { - if (JSVAL_IS_STRING(rv)) { - const char *name = - JS_GetStringBytes(JSVAL_TO_STRING(rv)); - if (*name) - result = PL_strdup(name); - } - } - - JS_RemoveRoot(configContext, &rv); - JS_EndRequest(configContext); -out: - FREEIF(method); - FREEIF(buf); - FREEIF(host); - FREEIF(safe_url); - FREEIF(bad_url); - return result; - -} - - -/* Utility functions to be called from Javascript (aka Mocha). - * These are the actual implementations of the javascript fucntions that - * are in the javascript pac file. - * - * Get the number of DNS domain levels (number of dots): - * - * dnsDomainLevels(host) - * - * - * Host/URL based conditions: - * - * isPlainHostName(host) - * dnsDomainIs(host, name) - * localHostOrDomainIs(host, name) - * isResolvable(host) - * regExpMatch(host or URL, regexp) - * - * - * Date/time based conditions (limits inclusive): - * - * weekdayRange(wkday) - * weekdayRange(wkday, wkday) - * - * dateRange(day) - * dateRange(day, day) - * dateRange(mon) - * dateRange(mon, mon) - * dateRange(year) - * dateRange(year, year) - * dateRange(day, mon, day, mon) - * dateRange(mon, year, mon, year) - * dateRange(day, mon, year, day, mon, year) - * - * timeRange(hour) - * timeRange(hour, hour) - * timeRange(hour, min, hour, min) - * timeRange(hour, min, sec, hour, min, sec) - * - * - * - */ - -/* Returns true if the hostname doesn't contain a dot - * (is a plain hostname, not an FQDN). - * - * Just a string operation, doesn't consult DNS. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_isPlainHostName(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 1 && JSVAL_IS_STRING(argv[0])) { - const char *h = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - - if (h && !PL_strchr(h, '.')) { - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - - *rval = JSVAL_FALSE; - return JS_TRUE; -} - -/* Returns the number of domain levels in the hostname - * (the number of dots, actually). - * - * Just a string operation, doesn't consult DNS. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_dnsDomainLevels(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - int i = 0; - - if (argc >= 1 && JSVAL_IS_STRING(argv[0])) { - const char *h = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - - if (h) { - while (*h) { - if (*h == '.') - i++; - h++; - } - } - } - - *rval = INT_TO_JSVAL(i); - return JS_TRUE; -} - -/* Checks if the hostname contains the given domain. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_dnsDomainIs(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 2 && JSVAL_IS_STRING(argv[0]) && JSVAL_IS_STRING(argv[1])) { - const char *h = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - const char *p = JS_GetStringBytes(JSVAL_TO_STRING(argv[1])); - int len1, len2; - - if (h && p && (len1 = PL_strlen(h)) >= (len2 = PL_strlen(p)) && - (!PL_strcasecmp(h + len1 - len2, p))) { - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - - *rval = JSVAL_FALSE; - return JS_TRUE; -} - -/* Returns true if the hostname matches exactly the given - * pattern hostname, or if the hostname is just a local hostname - * and it matches the hostname in the pattern FQDN hostname. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_localHostOrDomainIs(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 2 && JSVAL_IS_STRING(argv[0]) && JSVAL_IS_STRING(argv[1])) { - const char *h = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - const char *p = JS_GetStringBytes(JSVAL_TO_STRING(argv[1])); - char *hp, *pp; - - if (h && p) { - hp = PL_strchr(h, '.'); - pp = PL_strchr(p, '.'); - - if (hp || !pp) { - if (!PL_strcasecmp(h,p)) { - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - else if (!PL_strncasecmp(h, p, pp - p)) { - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - } - - *rval = JSVAL_FALSE; - return JS_TRUE; -} - -/* Attempts to resolve the DNS name, and returns TRUE if resolvable. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_isResolvable(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 1 && JSVAL_IS_STRING(argv[0])) { - const char *h = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - PRHostEnt *hp = NULL; - PRStatus rv; - PRHostEnt hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - - if (h) { - char *safe = PL_strdup(h); - if (PL_strlen(safe) > 64) - safe[64] = '\0'; - rv = PR_GetHostByName(safe, dbbuf, sizeof(dbbuf), &hpbuf); - hp = (rv == PR_SUCCESS ? &hpbuf : NULL); - PR_Free(safe); - } - - if (hp) { - TRACEMSG(("~~~~~~~~~~~ isResolvable(%s) returns TRUE\n", h)); - TRACEMSG(("~~~~~~~~~~~ hp = %p, hp->h_name = %s\n", hp, hp->h_name ? hp->h_name : "(null)")); - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - - TRACEMSG(("~~~~~~~~~~~ isResolvable(%s) returns FALSE\n", argv[0])); - *rval = JSVAL_FALSE; - return JS_TRUE; -} - -/* Resolves a DNS name, and returns the IP address string. - * - * Maintains a private cache for the last resolved address (so this - * function can be called multiple times with the same host argument - * without doing actual DNS queries every time). */ -PRIVATE char *proxy_dns_resolve(const char *host) { - static char *cache_host = NULL; - static char *cache_ip = NULL; - PRStatus rv; - PRHostEnt *hp = NULL; - PRHostEnt hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - - if (host) { - const char *p; - char *safe = NULL; - XP_Bool is_numeric_ip = TRUE; - - for(p=host; *p; p++) { - if (!NET_IS_DIGIT(*p) && *p != '.') { - is_numeric_ip = FALSE; - break; - } - } - if (is_numeric_ip) { - return PL_strdup(host); - } - - if (cache_host && cache_ip && !PL_strcmp(cache_host, host)) { - return PL_strdup(cache_ip); - } - safe = PL_strdup(host); - if (safe) { - if (PL_strlen(safe) > 64) - safe[64] = '\0'; - - rv = PR_GetHostByName(safe, dbbuf, sizeof(dbbuf), &hpbuf); - hp = (rv == PR_SUCCESS ? &hpbuf : NULL); - - PR_Free(safe); - } - if (hp) { - char *ip = NULL; - struct in_addr in; - - memcpy(&in.s_addr, hp->h_addr, hp->h_length); - - ip = inet_ntoa(in); - if (ip) { - StrAllocCopy(cache_host, host); - StrAllocCopy(cache_ip, ip); - - return PL_strdup(ip); - } - } - } - - return NULL; -} - -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_dnsResolve(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 1 && JSVAL_IS_STRING(argv[0])) { - const char *host = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - char *ip = proxy_dns_resolve(host); - - if (ip) { - JSString * str = JS_NewString(mc, ip, strlen(ip)); - if (!str) { - PR_Free(ip); - return JS_FALSE; - } - *rval = STRING_TO_JSVAL(str); - return JS_TRUE; - } - } - - *rval = JSVAL_NULL; - return JS_TRUE; -} - -/* Returns the IP address of the host machine as a string. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_myIpAddress(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - static XP_Bool initialized = FALSE; - static char *my_address = NULL; - - if (!initialized) { - char name[100]; - - initialized = TRUE; - if (PR_GetSystemInfo(PR_SI_HOSTNAME, name, sizeof(name)) == PR_SUCCESS) { - my_address = proxy_dns_resolve(name); - } - } - - TRACEMSG(("~~~~~~~~~~~~~~~~~~ myIpAddress() returns %s\n", my_address ? my_address : "(null)")); - - if (my_address) { - JSString *str; - str = JS_NewStringCopyZ(mc, my_address); - if (!str) - return JS_FALSE; - *rval = STRING_TO_JSVAL(str); - return JS_TRUE; - } - - *rval = JSVAL_NULL; - return JS_TRUE; -} - -/* Determines if the host IP address belongs to the given network. - * Uses SOCKS style address pattern and mask: - * - * isInNet(hostname, "111.222.33.0", "255.255.255.0"); */ -PRIVATE unsigned long convert_addr(const char *ip) { - char *p, *q, *buf = NULL; - int i; - unsigned char b[4]; - unsigned long addr = 0L; - - p = buf = PL_strdup(ip); - if (ip && p) { - for(i=0; p && i<4; i++) { - q = PL_strchr(p, '.'); - if (q) { - *q = '\0'; - } - b[i] = XP_ATOI(p) & 0xff; - if (q) { - p = q+1; - } - } - addr = (((unsigned long)b[0] << 24) | - ((unsigned long)b[1] << 16) | - ((unsigned long)b[2] << 8) | - ((unsigned long)b[3])); - - PR_Free(buf); - } - - return htonl(addr); -} - -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_isInNet(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 3 && - JSVAL_IS_STRING(argv[0]) && - JSVAL_IS_STRING(argv[1]) && - JSVAL_IS_STRING(argv[2])) - { - const char *ipstr = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - char *ip = proxy_dns_resolve(ipstr); - const char *patstr = JS_GetStringBytes(JSVAL_TO_STRING(argv[1])); - const char *maskstr = JS_GetStringBytes(JSVAL_TO_STRING(argv[2])); - - if (ip) { - unsigned long host = convert_addr(ip); - unsigned long pat = convert_addr(patstr); - unsigned long mask = convert_addr(maskstr); - - PR_Free(ip); - - if ((mask & host) == (mask & pat)) { - TRACEMSG(("~~~~~~~~~~~~ isInNet(%s(%s), %s, %s) returns TRUE\n", - ipstr, ip, patstr, maskstr)); - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - } - - TRACEMSG(("~~~~~~~~~~~~ isInNet() returns FALSE\n")); - - *rval = JSVAL_FALSE; - return JS_TRUE; -} - -/* Does a regular expression match between the host/URL and the pattern. - * - * Returns true on match. */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_regExpMatch(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - if (argc >= 2 && JSVAL_IS_STRING(argv[0]) && JSVAL_IS_STRING(argv[1])) { - const char *url = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); - const char *pat = JS_GetStringBytes(JSVAL_TO_STRING(argv[1])); - - if (url && pat && XP_RegExpValid((char *) pat) && /* XXX */ - !XP_RegExpMatch((char *) url, (char *) pat, TRUE)) {/* XXX */ - *rval = JSVAL_TRUE; - return JS_TRUE; - } - } - - *rval = JSVAL_FALSE; - return JS_TRUE; -} - -PRIVATE -struct tm * get_struct_tm(JSContext *mc, - unsigned int *argc, jsval *argv) { - time_t now = time(NULL); - - if (*argc > 0 && JSVAL_IS_STRING(argv[*argc-1])) { - const char *laststr = JS_GetStringBytes(JSVAL_TO_STRING(argv[*argc-1])); - if (!PL_strcasecmp(laststr, "GMT")) { - (*argc)--; - return gmtime(&now); - } - } - return localtime(&now); -} - -char *weekdays = "SUNMONTUEWEDTHUFRISAT"; -char *monnames = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; - -PRIVATE int get_no(const char *nam, char *arr) { - char *p = PL_strcasestr(arr, nam); - return p ? (((int)(p - arr)) / 3) : -1; -} - -PRIVATE int get_em(JSContext *mc, int argc, jsval *argv, - int *d, int *m, int *y) { - int i=0; - - *m = *d = *y = -1; - - for (i=0; i<argc; i++) { - if (JSVAL_IS_STRING(argv[i])) { - *m = get_no(JS_GetStringBytes(JSVAL_TO_STRING(argv[i])), monnames); - } - else if (JSVAL_IS_NUMBER(argv[i])) { - if (JSVAL_TO_INT(argv[i]) > 1900) - *y = JSVAL_TO_INT(argv[i]) - 1900; - else - *d = JSVAL_TO_INT(argv[i]); - } - else { - assert(0); - } - } - return ((*d > -1 ? 1 : 0) + - (*m > -1 ? 1 : 0) + - (*y > -1 ? 1 : 0)); -} - -PRIVATE int are_different(JSContext *mc, jsval *argv) { - int d1, d2, m1, m2, y1, y2; - - get_em(mc, 1, argv, &d1, &m1, &y1); - get_em(mc, 1, &argv[1], &d2, &m2, &y2); - - return ((d1 == -1 || d2 == -1) && - (m1 == -1 || m2 == -1) && - (y1 == -1 || y2 == -1)); -} - -PRIVATE long get_rel(int sel_d, int sel_m, int sel_y, int d, int m, int y) { - return ((sel_d > -1 ? d : 0) + - (sel_m > -1 ? m : 0) * 31 + - (sel_y > -1 ? y : 0) * 372); -} - -PRIVATE int cmp_properly(int sel_y, long rel_lo, long rel, long rel_hi) { - if (sel_y || rel_lo < rel_hi) - return rel_lo <= rel && rel <= rel_hi; - else - return rel_lo <= rel || rel <= rel_hi; -} - -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_dateRange(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - int d1, d2, m1, m2, y1, y2; - struct tm *tms = get_struct_tm(mc, &argc, argv); - - d1 = d2 = m1 = m2 = y1 = y2 = -1; - - if (argc == 1 || argc == 3 || (argc==2 && are_different(mc, argv))) - { - *rval = ((get_em(mc, argc, argv, &d1, &m1, &y1) && - (d1 == -1 || d1 == tms->tm_mday) && - (m1 == -1 || m1 == tms->tm_mon) && - (y1 == -1 || y1 == tms->tm_year)) - ? JSVAL_TRUE : JSVAL_FALSE); - } - else - { - *rval = (((get_em(mc, argc/2, argv, &d1, &m1, &y1) == - get_em(mc, argc/2, &argv[argc/2], &d2, &m2, &y2)) && - cmp_properly(y1, - get_rel(d1, m1, y1, d1, m1, y1), - get_rel(d1, m1, y1, tms->tm_mday, tms->tm_mon, tms->tm_year), - get_rel(d1, m1, y1, d2, m2, y2))) - ? JSVAL_TRUE : JSVAL_FALSE); - } - return JS_TRUE; -} - -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_weekdayRange(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - struct tm *tms = get_struct_tm(mc, &argc, argv); - int i=0, j=0; - - if (argc >= 1) - i = get_no(JS_GetStringBytes(JSVAL_TO_STRING(argv[0])), weekdays); - if (argc >= 2) - j = get_no(JS_GetStringBytes(JSVAL_TO_STRING(argv[1])), weekdays); - - *rval = (((argc == 1 && i == tms->tm_wday) || - (argc == 2 && ((i <= j && (i <= tms->tm_wday && j >= tms->tm_wday)) || - (i > j && (i <= tms->tm_wday || j >= tms->tm_wday))))) - ? JSVAL_TRUE : JSVAL_FALSE); - return JS_TRUE; -} - -/* timeRange(<hr>) - * timeRange(<hr>, <hr>) - * timeRange(<hr>, <min>, <hr>, <min>) - * timeRange(<hr>, <min>, <sec>, <hr>, <min>, <sec>) */ -MODULE_PRIVATE JSBool PR_CALLBACK -proxy_timeRange(JSContext *mc, JSObject *obj, unsigned int argc, - jsval *argv, jsval *rval) { - int32 secondsA=0, secondsB=0, secondsC=0; - struct tm *tms = get_struct_tm(mc, &argc, argv); - - if(argc == 1) { - secondsA = JSVAL_TO_INT(argv[0])*60*60; - secondsB = tms->tm_hour*60*60; - *rval = (secondsA == secondsB) ? JSVAL_TRUE : JSVAL_FALSE; - return JS_TRUE; - } - if(argc == 2) { - secondsA = JSVAL_TO_INT(argv[0])*60*60; - secondsB = tms->tm_hour*60*60; - secondsC = JSVAL_TO_INT(argv[1])*60*60; - } - if(argc == 4) { - secondsA = JSVAL_TO_INT(argv[0])*60*60 + JSVAL_TO_INT(argv[1])*60; - secondsB = tms->tm_hour*60*60 + tms->tm_min*60; - secondsC = JSVAL_TO_INT(argv[2])*60*60 + JSVAL_TO_INT(argv[3])*60; - } - if(argc == 6) { - secondsA = JSVAL_TO_INT(argv[0])*60*60 + JSVAL_TO_INT(argv[1])*60 + JSVAL_TO_INT(argv[2]); - secondsB = tms->tm_hour*60*60 + tms->tm_min*60 + tms->tm_sec; - secondsC = JSVAL_TO_INT(argv[3])*60*60 + JSVAL_TO_INT(argv[4])*60 + JSVAL_TO_INT(argv[5]); - } - *rval = (secondsA <= secondsB && secondsB < secondsC) ? JSVAL_TRUE : JSVAL_FALSE; - return JS_TRUE; -} - diff --git a/mozilla/network/main/mkautocf.h b/mozilla/network/main/mkautocf.h deleted file mode 100644 index f0df2f350fa..00000000000 --- a/mozilla/network/main/mkautocf.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* mkautocf.h: Proxy auto-config parser and evaluator - * Ari Luotonen */ - -#ifndef MK_PROXY_AUTO_CONFIG -#define MK_PROXY_AUTO_CONFIG - - -#include "xp_mcom.h" -#include "xp.h" - -/* - * Called by netlib to get a single string of "host:port" format, - * given the XP_List containing opaque proxy config objects. - * - * This function will return an address to a proxy that is (to its - * knowledge) up and running. Netlib can later inform this module - * using the function pacf_proxy_is_down() that a proxy is down - * and should not be called for a few minutes. - * - * Returns FALSE if everything has failed, and an error should be - * displayed to the user. - * - * Returns TRUE if there is hope. - * If *ret is NULL, a direct connection should be attempted. - * If *ret is not null, it is the proxy address to use. - * - */ -MODULE_PRIVATE Bool -pacf_get_proxy_addr(MWContext *context, char *list, - char ** ret_proxy_addr, - unsigned long * ret_socks_addr, - short * ret_socks_port); - - -MODULE_PRIVATE char *pacf_find_proxies_for_url(MWContext *context, - URL_Struct *URL_s); - - -/* - * A stream constructor function for application/x-ns-proxy-autoconfig. - * - * - * - */ -MODULE_PRIVATE NET_StreamClass * -NET_ProxyAutoConfig(int fmt, void *data_obj, URL_Struct *URL_s, MWContext *w); - - -/* - * Called by mkgeturl.c to originally retrieve, and re-retrieve - * the proxy autoconfig file. - * - * autoconfig_url is the URL pointing to the autoconfig. - * - * The rest of the parameters are what was passed to NET_GetURL(), - * and when the autoconfig load finishes NET_GetURL() will be called - * with those exact same parameters. - * - * This is because the proxy config is loaded when NET_GetURL() is - * called for the very first time, and the actual request must be put - * on hold when the proxy config is being loaded. - * - * When called from the explicit proxy config RE-load function - * NET_ReloadProxyConfig, the four last parameters are all zero, - * and no request gets restarted. - * - */ -MODULE_PRIVATE int NET_LoadProxyConfig(char *autoconf_url, - URL_Struct *URL_s, - FO_Present_Types output_format, - MWContext *window_id, - Net_GetUrlExitFunc *exit_routine); - -/* - * NET_GetNoProxyFailover - * Returns TRUE if we're not allowing proxy failover. - */ -MODULE_PRIVATE Bool NET_GetNoProxyFailover(void); - -#endif /* ! MK_PROXY_AUTO_CONFIG */ - diff --git a/mozilla/network/main/mkconect.c b/mozilla/network/main/mkconect.c deleted file mode 100644 index 06a72613e53..00000000000 --- a/mozilla/network/main/mkconect.c +++ /dev/null @@ -1,1622 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * generalized portable TCP routines - * - * Handles calls to async connect and dns routines. - * - * Designed and originally implemented by Lou Montulli '94 - * Modified by Judson Valeski '97 - */ - -#include "rosetta.h" -#include "mkutils.h" -#include "netutils.h" -#include "prerror.h" -#include "prsystem.h" -#include "prefapi.h" -#include "mkpadpac.h" -#include "mkprefs.h" - -#if defined(XP_WIN) -#define ASYNC_DNS -#endif - -#include "mktcp.h" -#include "mkparse.h" -#include "mkgeturl.h" /* for error codes, and some util functions */ -#include "fe_proto.h" /* for externs */ -#ifdef MOZILLA_CLIENT -#include "secnav.h" -#endif /* MOZILLA_CLIENT */ -#include "merrors.h" - -#include "ssl.h" -#include "xp_error.h" - -#if defined(XP_OS2) /*DSR072196 - use os2sock.h*/ -#include "os2sock.h" -#endif /* XP_OS2 */ - -#include "timing.h" - -#if defined(SMOOTH_PROGRESS) -#include "progress.h" -#endif - -#ifdef XP_UNIX -/* #### WARNING, this is duplicated in mksockrw.c - */ -# include <sys/ioctl.h> -/* - * mcom_db.h is only included here to set BYTE_ORDER !!! - * MAXDNAME is pilfered right out of arpa/nameser.h. - */ -# include "mcom_db.h" - -# if defined(__hpux) || defined(_HPUX_SOURCE) -# define BYTE_ORDER BIG_ENDIAN -# define MAXDNAME 256 /* maximum domain name */ -# else -# include <arpa/nameser.h> -# endif - -#include <resolv.h> - -#if defined(HAVE_SYS_FILIO_H) -#include <sys/filio.h> -#endif - -#endif /* XP_UNIX */ - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int MK_CONNECTION_REFUSED; -extern int MK_CONNECTION_TIMED_OUT; -extern int MK_OUT_OF_MEMORY; -extern int MK_UNABLE_TO_CONNECT; -extern int MK_UNABLE_TO_CREATE_SOCKET; -extern int MK_UNABLE_TO_LOCATE_HOST; -extern int MK_UNABLE_TO_LOCATE_SOCKS_HOST; -extern int XP_ERRNO_EALREADY; -extern int XP_ERRNO_ECONNREFUSED; -extern int XP_ERRNO_EINPROGRESS; -extern int XP_ERRNO_EISCONN; -extern int XP_ERRNO_ETIMEDOUT; -extern int XP_ERRNO_EWOULDBLOCK; -extern int XP_PROGRESS_CONTACTHOST; -extern int XP_PROGRESS_LOOKUPHOST; -extern int XP_PROGRESS_NOCONNECTION; -extern int XP_PROGRESS_UNABLELOCATE; -extern int MK_PORT_ACCESS_NOT_ALLOWED; - -/* An awful hack. setupSocks gets set to true after the first call to BeginConnect. - * We don't want to be setting up the socks host/port (a call to gethostbyname) - * until we've gone all the way through the netscape initialization. - */ -static setupSocks=FALSE; - -typedef enum { - NET_TCP_FINISH_DNS_LOOKUP, - NET_TCP_FINISH_CONNECT -} TCPStatesEnum; - -struct _TCP_ConData { - TCPStatesEnum next_state; /* states of the machine */ - PRNetAddr net_addr; - HG93765 - time_t begin_time; -}; - -/* MAX_DNS_LIST_SIZE controls the cache of resolved hosts. - * If it is undefined, the cache will grow without bound. - * If it is defined and >0, then the cache will be limited - * to that many entries. If it is 0, there will be no cache. - * - * also needed for DNS failover... - */ -# define MAX_DNS_LIST_SIZE 10 - -/* Global TCP connect variables - */ -PUBLIC unsigned long NET_SocksHost=0; -PUBLIC short NET_SocksPort=0; -PUBLIC char * NET_SocksHostName=0; - -PUBLIC PRBool socksFailure=FALSE; - -PUBLIC int NET_InGetHostByName = FALSE; /* global semaphore */ - -/* The struct used to define a DNS cache entry */ -typedef struct _DNSEntry { - char *hostname; - PRUint32 *ips; - int32 addressCount; - int h_length; - time_t expirationTime; -} DNSEntry; - -PRIVATE XP_List * dns_list=0; - -PRIVATE int32 dnsCacheExpiration=0; - -#define DEFAULT_TCP_CONNECT_TIMEOUT 35 /* seconds */ -PRIVATE uint32 net_tcp_connect_timeout = DEFAULT_TCP_CONNECT_TIMEOUT;/*seconds*/ - -/* set the number of seconds for the tcp connect timeout - * - * this timeout is used to end connections that do not - * timeout on there own */ -PUBLIC void -NET_SetTCPConnectTimeout(uint32 seconds) { - net_tcp_connect_timeout = seconds; -} - -/* socks support function - * - * if set to NULL socks is off. If set to non null string the string will be - * used as the socks host and socks will be used for all connections. - * - * returns 0 if the numonic hostname given is invalid or gethostbyname - * returns host unknown - * - */ -int NET_SetSocksHost(char * host) -{ - PRBool is_numeric_ip; - char *host_cp; - -#ifdef MOZ_OFFLINE - if (NET_IsOffline() - || !setupSocks) { - /* Either we're offline, or this is the very first call ot setsockshost. */ - socksFailure=FALSE; - return 1; - } -#endif /* MOZ_OFFLINE */ - - if(host && *host) - { - char *cp; - TRACEMSG(("Trying to set Socks host: %s\n", host)); - - /* If there's no port or it's zero, fail out so user gets - * an error and checks his configuration. - */ - if ( ((cp = PL_strrchr(host, ':')) != NULL) - && (*(cp+1) != '\0') - && (*(cp+1) != '0') ) { - *cp = 0; - NET_SocksPort = atoi(cp+1); - } else { - NET_SocksHost = 0; - NET_SocksPort = 0; - PR_FREEIF(NET_SocksHostName); - NET_SocksHostName = 0; - TRACEMSG(("Couldn't find a socks port. :(\n")); - socksFailure=TRUE; - return 0; /* Fail? */ - } - - is_numeric_ip = TRUE; /* init positive */ - for(host_cp = host; *host_cp; host_cp++) - if(!NET_IS_DIGIT(*host_cp) && *host_cp != '.') - { - is_numeric_ip = FALSE; - break; - } - - if (is_numeric_ip) /* Numeric node address */ - { - PRNetAddr netAddr; - PRStatus status; - TRACEMSG(("Socks host is numeric")); - - /* some systems return a number instead of a struct */ - status = PR_StringToNetAddr(host, &netAddr); - if (PR_SUCCESS == status) { - NET_SocksHost = netAddr.inet.ip; - } - if (NET_SocksHostName) PR_Free (NET_SocksHostName); - NET_SocksHostName = PL_strdup(host); - } - else /* name not number */ - { - PRHostEnt *hp; - PRHostEnt hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - PRStatus rv; - - NET_InGetHostByName++; /* global semaphore */ - rv = PR_GetHostByName(host, dbbuf, sizeof(dbbuf), &hpbuf); - hp = (rv == PR_SUCCESS ? &hpbuf : NULL); - NET_InGetHostByName--; /* global semaphore */ - - if (!hp) - { - TRACEMSG(("mktcp.c: Can't find Socks host name `%s'\n", host)); - NET_SocksHost = 0; - if (NET_SocksHostName) PR_Free (NET_SocksHostName); - NET_SocksHostName = 0; - TRACEMSG(("Socks host is bad. :(\n")); - if (cp) { - *cp = ':'; - } - socksFailure=TRUE; - return 0; /* Fail? */ - } - memcpy(&NET_SocksHost, hp->h_addr_list[0], hp->h_length); - } - if (cp) { - *cp = ':'; - } - } - else - { - NET_SocksHost = 0; - if (NET_SocksHostName) PR_Free (NET_SocksHostName); - NET_SocksHostName = NULL; - NET_SocksPort = 0; - TRACEMSG(("Clearing Socks Host\n")); - } - socksFailure=FALSE; - return(1); -} - -/* Used internally as a utility function. */ -PRIVATE void -NET_FreeDNSStruct(DNSEntry * theVictim) -{ - if(theVictim) - { - FREE(theVictim->ips); - FREEIF(theVictim->hostname); - FREE(theVictim); - } -} - -/* Used when user turns the cache off (dnsCacheExpiration is set to 0). */ -PRIVATE void -NET_DeleteDNSList(void) -{ - XP_List * list_obj = dns_list; - DNSEntry * dns_entry; - - if(!list_obj) - return; - while((dns_entry = (DNSEntry *)XP_ListNextObject(list_obj)) != 0) - { - XP_ListRemoveObject(dns_list, dns_entry); - NET_FreeDNSStruct(dns_entry); - } - XP_ListDestroy(dns_list); - return; -} - -PUBLIC void -NET_SetDNSExpirationPref(int32 n) -{ - if((dnsCacheExpiration = n) <= 0) - NET_DeleteDNSList(); -} - -MODULE_PRIVATE int PR_CALLBACK -NET_DNSExpirationPrefChanged(const char * newpref, void * data) -{ - PRInt32 n; - if (PREF_OK != PREF_GetIntPref(pref_dnsExpiration, &n) ) - n = DEF_DNS_EXPIRATION; - NET_SetDNSExpirationPref((int32)n); - return PREF_NOERROR; -} - -/* the dnsCacheExpiration units are seconds */ -PRIVATE int32 -net_GetDNSExpiration(void) -{ - return dnsCacheExpiration; -} - -/* net_CacheDNSEntry - * - * caches the results of a dns lookup for fast - * retrieval - */ -PRIVATE void -net_CacheDNSEntry(char * hostname, - PRHostEnt * host_pointer, - int32 addrCount) -{ -#if defined(MAX_DNS_LIST_SIZE) && (MAX_DNS_LIST_SIZE == 0) - - /* If MAX_DNS_LIST_SIZE is defined, and 0, don't cache anything. */ - return; - -#else /* !defined(MAX_DNS_LIST_SIZE) || (MAX_DNS_LIST_SIZE > 0) */ - - /* Otherwise, MAX_DNS_LIST_SIZE is either the number of entries to - cache, or is undefined, meaning "unlimited." */ - - int32 i; - DNSEntry * new_entry; - - /* Make sure incomming data is valid. */ - if(!hostname || !host_pointer) - return; - - /* Determine whether or not we've got a list going yet. If not, get one */ - if(!dns_list) - dns_list = XP_ListNew(); - if(!dns_list) - return; - - /* Create our DNSEntry object for caching. */ - if(!(new_entry = PR_NEW(DNSEntry))) - return; - - /* Copy the host name. */ - new_entry->hostname = 0; - StrAllocCopy(new_entry->hostname, hostname); - - if(!new_entry->hostname) - { - PR_Free(new_entry); - return; - } - - /* Copy all the ip addresses. */ - if( !(new_entry->ips = (PRUint32 *) PR_Malloc(sizeof(PRUint32) * addrCount)) ) - { - PR_Free(new_entry->hostname); - PR_Free(new_entry); - return; - } - - PR_ASSERT(host_pointer->h_length == 4); - for(i=0; i < addrCount; i++) - { - memcpy(&new_entry->ips[i], host_pointer->h_addr_list[i], 4); - } - - /* Copy all the other data. */ - new_entry->addressCount = addrCount; - new_entry->h_length = host_pointer->h_length; - new_entry->expirationTime = time(NULL) + (net_GetDNSExpiration()); /* Current time plus expiration */ - - XP_ListAddObject(dns_list, new_entry); - -# ifdef MAX_DNS_LIST_SIZE - /* check to make sure the list is not overflowing the maximum size. */ - if(XP_ListCount(dns_list) > MAX_DNS_LIST_SIZE) - { - DNSEntry * first_entry = (DNSEntry *) XP_ListRemoveEndObject(dns_list); - NET_FreeDNSStruct(first_entry); - } -# endif /* defined(MAX_DNS_LIST_SIZE) */ - -#endif /* !defined(MAX_DNS_LIST_SIZE) || (MAX_DNS_LIST_SIZE > 0) */ - return; -} - -/* net_CheckDNSCache - * - * checks the list of cached dns entries and returns - * the dns info in the form of struct hostent if a match is - * found for the passed in hostname - */ -PRIVATE DNSEntry * -net_CheckDNSCache(CONST char * hostname) -{ - XP_List *list_obj = dns_list; - DNSEntry * dns_entry; - - if(!hostname || !dns_list) - return(0); - - while((dns_entry = (DNSEntry *)XP_ListNextObject(list_obj)) != 0) - { - TRACEMSG(("net_CheckDNSCache: comparing %s and %s", hostname, dns_entry->hostname)); - if(dns_entry->hostname && !PL_strcasecmp(hostname, dns_entry->hostname)) - { - /* See if the dns entry has expired, if so, get rid of it */ - if(dns_entry->expirationTime < time(NULL)) - { - XP_ListRemoveObject(dns_list, dns_entry); - NET_FreeDNSStruct(dns_entry); - return 0; - } - return(dns_entry); - } - } - return(0); -} - -/* a list of dis-allowed ports for gopher connections for security reasons */ -PRIVATE int net_bad_ports_table[] = { -1, 7, 9, 11, 13, 15, 17, 19, 20, -21, 23, 25, 37, 42, 43, 53, 77, 79, 87, 95, 101, 102, -103, 104, 109, 110, 111, 113, 115, 117, 119, -135, 143, 389, 512, 513, 514, 515, 526, 530, 531, 532, -540, 556, 601, 6000, 0 }; - -/* Lookup a host name. If ASYNC_DNS is defined a platform specific async - * lookup will occur. - * - * return: 0 on sucess, -1 on failure. MK_WAITING_FOR_LOOKUP is always - * returned after first call when ASYNC_DNS is defined (you have to call - * it again). - * - * On success hostEnt is not null. */ -#if defined(XP_WIN) -extern int NET_AsyncDNSLookup(void* aContext, - const char* aHostPort, - PRHostEnt** aHoststructPtrPtr, - PRFileDesc* aSocket); -#endif - -PRIVATE int -#ifndef ASYNC_DNS -net_dns_lookup(char *host, - PRHostEnt **hostEnt, - char *dbbuf, - PRHostEnt *hpbuf) -#else -net_dns_lookup(MWContext *windowID, - char *host, - PRHostEnt **hostEnt, - PRFileDesc *socket) -#endif /* ASYNC_DNS */ - - -{ - int status; - NET_InGetHostByName++; - PR_ASSERT(host); - PR_ASSERT(hostEnt); -#ifndef ASYNC_DNS - PR_ASSERT(dbbuf); - PR_ASSERT(hpbuf); - - /* Not asyncronus, completes a full lookup before returing. */ - status = PR_GetHostByName(host, dbbuf, PR_NETDB_BUF_SIZE, hpbuf); - - if(status == PR_SUCCESS) { - /* Success, hpbuf points to a valid hostent. */ - NET_InGetHostByName--; - *hostEnt=hpbuf; - return status; - } -#else /* ASYNC_DNS */ - PR_ASSERT(windowID); - PR_ASSERT(socket); - /* FE_StartAsyncDNSLookup should fill in the hoststruct - * or leave zero the pointer if not found - * it can also return MK_WAITING_FOR_LOOKUP - * if it's not done yet. - * - * dbbuf and hpbuf are not needed in ASYNC_DNS case. */ - status = NET_AsyncDNSLookup(windowID, host, hostEnt, socket); - - if(status == MK_WAITING_FOR_LOOKUP) { - /* Always get here after first call to FE_Async.. for a - * particular host name. This ensures execution doesn't - * block. */ - NET_InGetHostByName--; - return status; - } - else if(status == 0) { - /* Success, hostEnt points to a valid hostent. */ - NET_InGetHostByName--; - return status; - } -#endif /* ASYNC_DNS */ - /* FAIL */ - NET_InGetHostByName--; - /* must set this pointer to NULL if we fail. FE_AsyncDNSLookup does - * this but PR_GetHostByName doesn't, so we cover our bases here. */ - *hostEnt = NULL; - return -1; -} - -/* find the ip address of a host and set sin->sin_addr to that address - * return 0 on success */ - -PRIVATE int -net_FindAddress (const char *host_ptr, - PRNetAddr *net_addr, - MWContext *window_id, - PRFileDesc *sock) { - PRHostEnt *hoststruct_pointer; /* Pointer to host - See netdb.h */ - DNSEntry * cache_pointer; - char *port, *host_port=0, *host_cp; - - /* acts as a flag to determine whether or not this is the first failure. If it is, we want to sanityCheckDNS - which determines whether or not we've got a good net connection, sort of */ - static XP_Bool first_dns_failure=TRUE; - static int random_host_number = -1; - static time_t random_host_expiration = 0; - static XP_Bool tryPAD=TRUE; - XP_Bool is_numeric_ip; - - if(!host_ptr || !*host_ptr) - return -1; - - /* Proxy Auto-Discovery (PAD) */ - if(tryPAD && MK_PadEnabled && MK_padPacURL && *MK_padPacURL) { - PRHostEnt *hostEnt=NULL; - static PRFileDesc *socket=NULL; - if(!PL_strncasecmp(MK_padPacURL, "file:", 5)) { - /* Don't allow file urls because they're hard to figure out in an xp way. */ - tryPAD=FALSE; - foundPADPAC=FALSE; - } else { - if(socket == NULL) - socket=PR_NewTCPSocket(); - if(socket != NULL) { - char *padHost=NET_ParseURL(MK_padPacURL, GET_HOST_PART); - if(padHost && *padHost) { - char *colon=PL_strchr(padHost, ':'); - int status; -#ifndef ASYNC_DNS - char dbbuf[PR_NETDB_BUF_SIZE]; - PRHostEnt dpbuf; -#endif - if(colon) - *colon='\0'; -#ifndef ASYNC_DNS - status = net_dns_lookup(padHost, &hostEnt, dbbuf, &dpbuf); -#else - status = net_dns_lookup(window_id, padHost, &hostEnt, socket); -#endif /* ASYNC_DNS */ - if(status != MK_WAITING_FOR_LOOKUP) { - PR_Close(socket); - socket=NULL; - if(hostEnt != NULL) - /* We found the padpac */ - foundPADPAC=TRUE; - tryPAD=FALSE; - } - if(colon) - *colon=':'; - } else { - PR_Close(socket); - socket=NULL; - tryPAD=FALSE; - } - PR_FREEIF(padHost); - } /* End socket not null */ - } - } /* End tryPAD */ - - StrAllocCopy(host_port, host_ptr); /* Make a copy we can mess with */ - if (!host_port) - return -1; - - /* Parse port number if present */ - port = PL_strchr(host_port, ':'); - if (port) { - *port++ = 0; - if (NET_IS_DIGIT(*port)) { - unsigned short port_num = (unsigned short) atol(port); - int i; - - /* check for illegal ports */ - /* if the explicit port number equals - * the default port number let it through - */ - if(port_num != PR_ntohs(net_addr->inet.port)) { - /* disallow well known ports */ - for(i=0; net_bad_ports_table[i]; i++) - if(port_num == net_bad_ports_table[i]) { - char *error_msg = PL_strdup(XP_GetString(MK_PORT_ACCESS_NOT_ALLOWED)); - if(error_msg) { - FE_Alert(window_id, error_msg); - PR_Free(error_msg); - } - - /* return special error code - * that NET_BeginConnect knows - * about. - */ - PR_Free(host_port); - return(MK_UNABLE_TO_CONNECT); - } - - net_addr->inet.port = PR_htons(port_num); - } - - } - } - - /* see if this host entry is already cached */ - if( (cache_pointer = net_CheckDNSCache(host_port)) != NULL ) { - /* call FE_ClearDNSSelect to catch the case of a cache hit before - * a successfull lookup response for this particular socket. - * This happens when a previous socket lookup for the same host - * succeeded and propagated the cache entry before this one - * finished. - */ - - NET_ClearDNSSelect(window_id, sock); - - net_addr->inet.ip = cache_pointer->ips[0]; - - PR_Free(host_port); - return(0); /* FOUND OK */ - } - - /* Determine whether or not we're dealing with an ip address as the host */ - is_numeric_ip = TRUE; /* init positive */ - for(host_cp = host_port; *host_cp; host_cp++) - if(!NET_IS_DIGIT(*host_cp) && *host_cp != '.') { - is_numeric_ip = FALSE; - break; - } - - /* Parse host number if present. */ - if (is_numeric_ip) { - PRUint16 port = net_addr->inet.port; /* save a copy */ - if(PR_SUCCESS != PR_StringToNetAddr(host_port, net_addr)) { - PR_ASSERT(0); - PR_Free(host_port); - return(-1); /* fail */ - } - net_addr->inet.port = port; /* StringToNetAddr overites the port num */ - /* name not number */ - } else { - int32 addressCount=0; - char *remapped_host_port=0; - - /* randomly remap home.netscape.com to home1.netscape.com through - * home32.netscape.com - * cache the original name not the new one. - */ - if((!PL_strncasecmp(host_port, "home.", 5) - || !PL_strncasecmp(host_port, "rl.", 3)) - && (PL_strcasestr(host_port+2, ".netscape.com") - || PL_strcasestr(host_port+2, ".mcom.com"))) { - time_t cur_time = time(NULL); - char temp_string[32]; - XP_Bool is_rl_host; - - *temp_string = '\0'; - - is_rl_host = !PL_strncasecmp(host_port, "rl.", 3); - - if(random_host_number == -1 || random_host_expiration < cur_time) { - /* pick a new random number */ - random_host_expiration = cur_time + (60 * 5); /* five min */ - random_host_number = (XP_RANDOM() & 31); - } - - if(is_rl_host) - PR_snprintf(temp_string, sizeof(temp_string), "rl%d%s", - random_host_number+1, host_port+2); - else - PR_snprintf(temp_string, sizeof(temp_string), "home%d%s", - random_host_number+1, host_port+4); - - StrAllocCopy(remapped_host_port, temp_string); - - TRACEMSG(("Remapping %s to %s", host_port, remapped_host_port)); - } - -#ifdef XP_UNIX - { - /* Implement a terrible hack just for unix. If the environment - * variable SOCKS_NS is defined, stomp on the host that the DNS - * code uses for host lookup to be a specific ip address. */ - static char firstTime = 1; - if (firstTime) { - PRNetAddr netAddr; - PRStatus status; - char *ns = getenv("SOCKS_NS"); - firstTime = 0; - if (ns && ns[0]) { - /* Use a specific host for dns lookups */ - extern int res_init (void); - res_init(); - status = PR_StringToNetAddr(ns, &netAddr); - if (PR_SUCCESS == status) { - _res.nsaddr_list[0].sin_addr.s_addr = netAddr.inet.ip; - } - _res.nscount = 1; - } - } - } -#endif - - { - int status; -#ifndef ASYNC_DNS - char dbbuf[PR_NETDB_BUF_SIZE]; - PRHostEnt dpbuf; -#endif - /* malloc the string to prevent overflow */ - char *msg = PR_smprintf(XP_GetString(XP_PROGRESS_LOOKUPHOST), host_port); - - if(msg) { -#if defined(SMOOTH_PROGRESS) - PM_Status(window_id, NULL, msg); -#else - NET_Progress(window_id, msg); -#endif - PR_Free(msg); - } - - TIMING_STARTCLOCK_NAME("dns:lookup", (remapped_host_port ? remapped_host_port : host_port)); - -#ifndef ASYNC_DNS - status = net_dns_lookup( - (remapped_host_port ? - remapped_host_port : - host_port), - &hoststruct_pointer, - dbbuf, - &dpbuf); -#else - status = net_dns_lookup(window_id, - (remapped_host_port ? - remapped_host_port : - host_port), - &hoststruct_pointer, - sock); -#endif /* ASYNC_DNS */ - /* sucess if hoststruct_pointer is not null */ - if(status == MK_WAITING_FOR_LOOKUP) { - PR_Free(host_port); - return status; - } - } - - TIMING_STOPCLOCK_NAME("dns:lookup", (remapped_host_port ? remapped_host_port : host_port), - window_id, (hoststruct_pointer ? "ok" : "error")); - - if (!hoststruct_pointer) { - if(first_dns_failure) { - first_dns_failure = FALSE; - /* On the proxy causes confusing messages. - * This function is only implemented on for XP_UNIX. */ - NET_SanityCheckDNS(window_id); - } - TRACEMSG(("mktcp.c: Can't find host name `%s'. Errno #%d\n", - host_port, PR_GetError())); - PR_Free(host_port); - TRACEMSG(("gethostbyname failed with error: %d\n", PR_GetError())); - return -1; /* Fail? */ - } - - /* Count the number of addresses returned in the A record. */ - for (addressCount=0; hoststruct_pointer->h_addr_list[addressCount]; addressCount++) {;} - - /* If the addressCount is zero we've got a problem */ - if (addressCount == 0) { - PR_ASSERT(0); - PR_Free(host_port); - return -1; - } - - /* Copy the first address in the list to the sin. char ** h_addr_list */ - PR_ASSERT(hoststruct_pointer->h_length == 4); - memcpy(&net_addr->inet.ip, hoststruct_pointer->h_addr_list[0], 4); - - /* if NET_GetDNSExpiration() returns 0 we are considering the cache disabled */ - if(net_GetDNSExpiration() > 0) - net_CacheDNSEntry(host_port, hoststruct_pointer, addressCount); - } /* end name not number else*/ - -#ifdef DEBUG - { - char str[64]; - PR_NetAddrToString(net_addr, str, sizeof(str)); - TRACEMSG(("TCP.c: Found address %s and port %d", str, (int)PR_ntohs(net_addr->inet.port))); - } -#endif - - PR_Free(host_port); - return(0); /* OK, we found an address */ -} - -/* FREE left over tcp connection data if there is any - */ -MODULE_PRIVATE void -NET_FreeTCPConData(TCP_ConData * data) -{ - TRACEMSG(("Freeing TCPConData...Done with connect (i hope)")); - FREEIF(data) -} - -PRIVATE int -net_start_first_connect(const char *host, - PRFileDesc *sock, - MWContext *window_id, - TCP_ConData *tcp_con_data, - char **error_msg, - PRUint32 localIP) -{ - - /* malloc the string to prevent overflow - */ - int32 len = PL_strlen(XP_GetString(XP_PROGRESS_CONTACTHOST)); - char * buf; - - len += PL_strlen(host); - - buf = (char *)PR_Malloc((len+10)*sizeof(char)); - if(buf) - { - PR_snprintf(buf, (len+10)*sizeof(char), - XP_GetString(XP_PROGRESS_CONTACTHOST), host); -#if defined(SMOOTH_PROGRESS) - PM_Status(window_id, NULL, buf); -#else - NET_Progress(window_id, buf); -#endif - FREE(buf); - } - - HG26300 - /* set the begining time to be the current time. - * the timeout value will be compared to this - * later - */ - tcp_con_data->begin_time = time(NULL); - -#define CONNECT_TIMEOUT 0 - - /* Bind to a user specified local IP address if specified. - * Netlib does not check the validity of this address. - * The user is guaranteing it's existence and usability. */ - if ( localIP > 0 ) { - PRStatus status; - PRErrorCode errorCode; /* see http://www.mozilla.org/docs/refList/refNSPR/prerr.htm#1027954 */ - PRNetAddr *addr = (PRNetAddr *)PR_Malloc(sizeof(PRNetAddr)); - if (!addr) - return MK_UNABLE_TO_CONNECT; - status = PR_InitializeNetAddr(PR_IpAddrNull, 0, addr); - if (status != PR_SUCCESS) { - errorCode = PR_GetError(); - } else { - addr->inet.ip = localIP; - status = PR_Bind(sock, addr); - if (status != PR_SUCCESS) { - errorCode = PR_GetError(); - } - } - PR_Free(addr); - } - - /* if it's not equal to PR_SUCCESS something went wrong - * - * PRNetAddr is binary compatible with struct sockaddr - */ - if(PR_SUCCESS != PR_Connect (sock, - &tcp_con_data->net_addr, - CONNECT_TIMEOUT)) - { - - int rv = PR_GetError(); - -#if !defined(XP_MAC) && !defined(XP_WIN16) - PR_ASSERT(rv != PR_WOULD_BLOCK_ERROR); /* should never happen */ -#endif - if (rv == PR_IN_PROGRESS_ERROR || rv == PR_WOULD_BLOCK_ERROR) - { - tcp_con_data->next_state = NET_TCP_FINISH_CONNECT; - return(MK_WAITING_FOR_CONNECTION); /* not connected yet */ - } - else if (rv == PR_IS_CONNECTED_ERROR) - { - return(MK_CONNECTED); /* already connected */ - } - else - { - PR_Close(sock); - if(rv == PR_CONNECT_REFUSED_ERROR) - { - *error_msg = NET_ExplainErrorDetails(MK_CONNECTION_REFUSED, host); - - TRACEMSG(("connect: refused\n")); - - return(MK_CONNECTION_REFUSED); - } - else if(rv == PR_CONNECT_TIMEOUT_ERROR) - { - *error_msg = NET_ExplainErrorDetails(MK_CONNECTION_TIMED_OUT); - - TRACEMSG(("connect: timed out\n")); - - return(MK_CONNECTION_TIMED_OUT); - } - else - { - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONNECT, rv); - - TRACEMSG(("connect: unable to connect %i\n", rv)); - - return (MK_UNABLE_TO_CONNECT); - } - } - } - - /* else good connect */ - - return(MK_CONNECTED); -} - -/* Finds the DNSEntry with hostname in it, removes it if it only has one address, otherwise - removes the first address and shifts the other(s) forward so they can be tried. */ -PRIVATE XP_Bool -net_connection_failed(CONST char *hostname) -{ - DNSEntry *dns_entry = 0; - char *hostCopy=NULL, *port=NULL; - - if(!hostname) - return FALSE; - - StrAllocCopy(hostCopy, hostname); - if(!hostCopy) - return FALSE; - - /* Look for a port */ - if( (port = PL_strchr(hostCopy, ':')) != NULL ) - *port = '\0'; - - dns_entry = net_CheckDNSCache(hostCopy); - FREE(hostCopy); - /* If we find the cached dns entry pull the address off the top because it is the one - that failed. Then shift the others up to the front of the list. */ - if (dns_entry) - { - /* If there is only one (most common case) ip address associated with this host, - blow the entire entry away */ - if (dns_entry->addressCount == 1) - { - XP_ListRemoveObject(dns_list, dns_entry); - NET_FreeDNSStruct(dns_entry); - return FALSE; - } - else /* Failover case */ - { - dns_entry->addressCount--; - /* Shift addresses up one, overwriting the first one */ - memmove(dns_entry->ips, - &dns_entry->ips[1], - sizeof(PRUint32) * dns_entry->addressCount ); - /* Null terminate the array */ - dns_entry->ips[dns_entry->addressCount] = 0; - return TRUE; - } - } - /* If the host wasn't in the cache then caching is off or an ip address was sent in here - and we don't want to keep trying this address so return false. */ - return FALSE; -} - - -/* - * Non blocking connect begin function. It will most likely - * return negative. If it does, NET_ConnectFinish() will - * need to be called repeatably until a connect is established. - * - * return's negative on error - * return's MK_WAITING_FOR_CONNECTION when continue is neccessary - * return's MK_CONNECTED on true connect - */ - -MODULE_PRIVATE int -NET_BeginConnect (CONST char *url, - char *ip_address_string, - char *prot_name, - int def_port, - PRFileDesc **sock, - HG92743 - TCP_ConData **tcp_con_data, - MWContext *window_id, - char **error_msg, - unsigned long socks_host, - short socks_port, - PRUint32 localIP) -{ - - char * proxy=NULL; - PRInt32 iPort=0; - char text[MAXHOSTNAMELEN + 8]; - CONST char *host; - char *althost=0; - int status; - PRFileDesc *fd; - char *host_string=0; - PRSocketOptionData opt; -#ifdef MOZ_OFFLINE - if (NET_IsOffline()) /* if we're offline, ret error - dmb 11/25/96 */ - return MK_OFFLINE; -#endif /* MOZ_OFFLINE */ - TRACEMSG(("NET_BeginConnect called for url: %s", url)); - - /* One time startup flag. If this is the first time in BeginConnect, - * make sure the socks is setup if it needs to be. - */ - if(!setupSocks) { - setupSocks=TRUE; - if (NET_GetProxyStyle() == PROXY_STYLE_MANUAL) { - if ( (PREF_OK != PREF_CopyCharPref(pref_socksServer,&proxy)) - || !proxy || !*proxy ) { - NET_SetSocksHost(NULL); /* NULL is ok */ - } else { - if ( PREF_OK == PREF_GetIntPref(pref_socksPort,&iPort) ) { - PR_snprintf(text, sizeof(text), "%s:%d", proxy, iPort); - NET_SetSocksHost(text); - } - } - } - } - - /* in case finish connect calls us - */ - if(*tcp_con_data) - NET_FreeTCPConData(*tcp_con_data); - - /* construct state table data - */ - *tcp_con_data = PR_NEW(TCP_ConData); - - if(!*tcp_con_data) - { - *error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - memset(*tcp_con_data, 0, sizeof(TCP_ConData)); - - /* Set up Internet defaults and port*/ - PR_InitializeNetAddr(PR_IpAddrNull, (PRUint16) def_port, &(*tcp_con_data)->net_addr); - - if(NET_URL_Type(url)) - { - host_string = NET_ParseURL(url, GET_HOST_PART); - host = host_string; - } - else - { - /* assume that a hostname was passed directly - * instead of a URL - */ - host = url; - } - - /* build a socket - */ - *sock = PR_NewTCPSocket(); - -HG59609 - - if(*sock == NULL) - { - int error = PR_GetError(); - TRACEMSG(("NETSOCKET call returned INVALID_SOCKET: %d", error)); - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CREATE_SOCKET, error); - FREE_AND_CLEAR(host_string); - return(MK_UNABLE_TO_CREATE_SOCKET); - } - -HG40252 - - /* make the socket non-blocking */ - opt.option = PR_SockOpt_Nonblocking; - opt.value.non_blocking = PR_TRUE; - PR_SetSocketOption(*sock, &opt); - -#if defined(XP_WIN16) || (defined(XP_OS2) && !defined(XP_OS2_DOUGSOCK)) - opt.option = PR_SockOpt_Linger; - opt.value.linger.polarity = PR_TRUE; - opt.value.linger.linger = PR_INTERVAL_NO_WAIT; - PR_SetSocketOption(*sock, &opt); -#endif /* XP_WIN16 */ - - /* copy the sock no - */ - fd = *sock; - -HG28879 - { - /* if the socks host is invalid */ - if ( socksFailure && (NET_GetProxyStyle() == PROXY_STYLE_MANUAL) ) - { - char * prefSocksHost = NULL; - /* Tell the FE about the failure */ - int32 len = PL_strlen(XP_GetString(XP_PROGRESS_UNABLELOCATE)); - char * buf; - if( (PREF_OK == PREF_CopyCharPref(pref_socksServer,&prefSocksHost)) - && prefSocksHost) - { - len += PL_strlen(prefSocksHost); - - buf = (char *)PR_Malloc((len+10)*sizeof(char)); - if(buf) - { - PR_snprintf(buf, (len+10)*sizeof(char), - XP_GetString(XP_PROGRESS_UNABLELOCATE), prefSocksHost); -#if defined(SMOOTH_PROGRESS) - PM_Status(window_id, NULL, buf); -#else - NET_Progress(window_id, buf); -#endif - FREE(buf); - } - - /* Tell the user about the failure */ - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LOCATE_SOCKS_HOST, prefSocksHost); - - /* clean up prior to leaving */ - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - PR_Close(*sock); - *sock = NULL; - FREE_AND_CLEAR(host_string); - PR_FREEIF(prefSocksHost); - } - return MK_UNABLE_TO_LOCATE_HOST; - } - } - -HG71089 - - /* if an IP address string was passed in, then use it instead of the - * hostname to do the DNS lookup. - */ - if ( ip_address_string ) { - char *port; - - StrAllocCopy(althost, ip_address_string); - - port = PL_strchr(host, ':'); - if ( port ) { - StrAllocCat(althost, port); - } - } - - status = net_FindAddress(althost?althost:host, - &((*tcp_con_data)->net_addr), - window_id, - *sock); - - if (althost) { - PR_Free(althost); - } - - if(status == MK_WAITING_FOR_LOOKUP) - { - (*tcp_con_data)->next_state = NET_TCP_FINISH_DNS_LOOKUP; - FREE_AND_CLEAR(host_string); - return(MK_WAITING_FOR_CONNECTION); /* not connected yet */ - } - else if (status < 0) - { - { - /* malloc the string to prevent overflow - */ - int32 len = PL_strlen(XP_GetString(XP_PROGRESS_UNABLELOCATE)); - char * buf; - - len += PL_strlen(host); - - buf = (char *)PR_Malloc((len+10)*sizeof(char)); - if(buf) - { - PR_snprintf(buf, (len+10)*sizeof(char), - XP_GetString(XP_PROGRESS_UNABLELOCATE), host); -#if defined(SMOOTH_PROGRESS) - PM_Status(window_id, NULL, buf); -#else - NET_Progress(window_id, buf); -#endif - FREE(buf); - } - } - - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - PR_Close(*sock); - *sock = NULL; - - /* @@@@@ HACK! If we detect an illegal port in - * net_FindAddress we put up an error message - * and return MK_UNABLE_TO_CONNECT. Don't - * print another message - */ - if(status != MK_UNABLE_TO_CONNECT) - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LOCATE_HOST, - *host ? host : "(no name specified)"); - FREE_AND_CLEAR(host_string); - return MK_UNABLE_TO_LOCATE_HOST; - } - - TIMING_STARTCLOCK_NAME("tcp:connect", url); - - status = net_start_first_connect(host, *sock, window_id, - *tcp_con_data, error_msg, localIP); - - if(status != MK_WAITING_FOR_CONNECTION) - { - TIMING_STOPCLOCK_NAME("tcp:connect", url, window_id, "error"); - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - } - else - { - (*tcp_con_data)->next_state = NET_TCP_FINISH_CONNECT; - /* save in case we need it */ - HG83665 - } - - if(status < 0) - { - net_connection_failed(host); - PR_Close(*sock); - *sock = NULL; - } - - FREE_AND_CLEAR(host_string); - - return(status); -} - - -/* - * Non blocking connect finishing function. This routine polls - * the socket until a connection finally takes place or until - * an error occurs. NET_ConnectFinish() will need to be called - * repeatably until a connect is established. - * - * return's negative on error - * return's MK_WAITING_FOR_CONNECTION when continue is neccessary - * return's MK_CONNECTED on true connect - */ -PUBLIC int -NET_FinishConnect (CONST char *url, - char *prot_name, - int def_port, - PRFileDesc **sock, - TCP_ConData **tcp_con_data, - MWContext *window_id, - char **error_msg, - PRUint32 localIP) -{ - int status; - char *host=NULL; - - TRACEMSG(("NET_FinishConnect called for url: %s", url)); - - if(!*tcp_con_data) /* safty valve */ - { - *error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - switch((*tcp_con_data)->next_state) - { - case NET_TCP_FINISH_DNS_LOOKUP: - { - char * host_string=NULL; - const char * host = NULL; - - if(NET_URL_Type(url)) - { - host_string = NET_ParseURL(url, GET_HOST_PART); - host = host_string; - } - else - { - /* assume that a hostname was passed directly - * instead of a URL - */ - host = url; - } - - status = net_FindAddress(host, - &((*tcp_con_data)->net_addr), - window_id, - *sock); - - if(status == MK_WAITING_FOR_LOOKUP) - { - (*tcp_con_data)->next_state = NET_TCP_FINISH_DNS_LOOKUP; - FREE_AND_CLEAR(host_string); - return(MK_WAITING_FOR_CONNECTION); /* not connected yet */ - } - else if (status < 0) - { - { - /* malloc the string to prevent overflow - */ - int32 len = PL_strlen(XP_GetString(XP_PROGRESS_UNABLELOCATE)); - char * buf; - - len += PL_strlen(host); - - buf = (char *)PR_Malloc((len+10)*sizeof(char)); - if(buf) - { - PR_snprintf(buf, (len+10)*sizeof(char), - XP_GetString(XP_PROGRESS_UNABLELOCATE), host); -#if defined(SMOOTH_PROGRESS) - PM_Status(window_id, NULL, buf); -#else - NET_Progress(window_id, buf); -#endif - FREE(buf); - } - } - - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LOCATE_HOST, host); - FREE_AND_CLEAR(host_string); - return MK_UNABLE_TO_LOCATE_HOST; - } - - TIMING_STARTCLOCK_NAME("tcp:connect", url); - - status = net_start_first_connect(host, *sock, window_id, - *tcp_con_data, error_msg, localIP); - - if(status != MK_WAITING_FOR_CONNECTION) - { - TIMING_STOPCLOCK_NAME("tcp:connect", url, window_id, "error"); - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - } - else - { - (*tcp_con_data)->next_state = NET_TCP_FINISH_CONNECT; - } - - if(status < 0) - { - net_connection_failed(host); - TRACEMSG(("mktcp.c: Error during connect %d\n", PR_GetError())); - PR_Close(*sock); - *sock = NULL; - } - - FREE_AND_CLEAR(host_string); - - return(status); - - } /* end of this part of the case */ - - case NET_TCP_FINISH_CONNECT: - { - PRPollDesc pd; - - pd.fd = *sock; - pd.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; - - /* do another connect here to see if we are actually connected - * - * PRNetAddr is binary compatible with struct sockaddr - */ - if(PR_Poll(&pd, 1, PR_INTERVAL_NO_TIMEOUT) < 1) - { - PR_ASSERT(0); - return MK_WAITING_FOR_CONNECTION; /* perhaps we should error here */ - } - -#if defined(XP_WIN16) - /* Bind to a user specified local IP address if specified. - * Netlib does not check the validity of this address. - * The user is guaranteing it's existence and usability. */ - if ( localIP > 0 ) { - PRStatus status; - PRErrorCode errorCode; /* see http://www.mozilla.org/docs/refList/refNSPR/prerr.htm#1027954 */ - PRNetAddr *addr = (PRNetAddr *)PR_Malloc(sizeof(PRNetAddr)); - if (!addr) - return MK_UNABLE_TO_CONNECT; - status = PR_InitializeNetAddr(PR_IpAddrNull, 0, addr); - if (status != PR_SUCCESS) { - errorCode = PR_GetError(); - } else { - addr->inet.ip = localIP; - status = PR_Bind(sock, addr); - if (status != PR_SUCCESS) { - errorCode = PR_GetError(); - } - } - PR_Free(addr); - } - - if(PR_SUCCESS != PR_Connect (*sock, - &(*tcp_con_data)->net_addr, - CONNECT_TIMEOUT)) -#else - if(PR_SUCCESS != PR_GetConnectStatus(&pd)) -#endif - { - int error; - - error = PR_GetError(); - -#if !defined(XP_MAC) && !defined(XP_WIN16) - PR_ASSERT(error != PR_WOULD_BLOCK_ERROR); /* should never happen */ -#endif - if (error == PR_IN_PROGRESS_ERROR || error == PR_WOULD_BLOCK_ERROR) - { - - /* check the begin time against the current time minus - * the timeout value. Error out if past the timeout - */ - if((time_t)(time(NULL)-net_tcp_connect_timeout) > (*tcp_con_data)->begin_time) - { - error = XP_ERRNO_ETIMEDOUT; - goto error_out; - } - - /* still waiting - */ - return MK_WAITING_FOR_CONNECTION; - } - else if(error != PR_IS_CONNECTED_ERROR) - { -error_out: - - /* if EISCONN then we actually are connected - * otherwise return an error - */ - - /* At this point we know there was a problem with the ip address we tried. */ - TRACEMSG(("mktcp.c: Error during connect: %d\n", error)); - - host = NET_ParseURL(url, GET_HOST_PART); - if(!host) - return -1; - - /* In the case when the url is a host, no protocol, NET_ParseURL returns null byte. - We run up against this case when a proxy was placed into the url instead of - the url itself.*/ - if(*host == '\0') { - FREE(host); - host = NULL; - StrAllocCopy(host, url); - } - - /* If we should try other addresses with this tcpConnection, do it */ - if (net_connection_failed(host)) - { - int status; - - if(*host == '\0') - { - /* the url is a hostname */ - FREE(host); - if( !(host = PL_strdup(url)) ) - return -1; - } - - /* Go get another of the ip addresses */ - status = net_FindAddress(host, - &((*tcp_con_data)->net_addr), - window_id, - *sock); - - FREE(host); - if(status == 0) - return(NET_BeginConnect (url, - NULL, - prot_name, - def_port, - sock, - HG98376 - tcp_con_data, - window_id, - error_msg, - 0, - 0, - localIP)); - /* else fall through to the error */ - } - else - FREE(host); - - TIMING_STOPCLOCK_NAME("tcp:connect", url, window_id, "error"); - - HG92362 - if (error == PR_CONNECT_REFUSED_ERROR) - { - char * host = NET_ParseURL(url, GET_HOST_PART); - *error_msg = NET_ExplainErrorDetails( - MK_CONNECTION_REFUSED, - host); - FREE(host); - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - return MK_CONNECTION_REFUSED; - } - else if (error == PR_CONNECT_TIMEOUT_ERROR) - { - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - *error_msg = NET_ExplainErrorDetails(MK_CONNECTION_TIMED_OUT); - return MK_CONNECTION_TIMED_OUT; - } - else - { - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONNECT, error); - return MK_UNABLE_TO_CONNECT; - } - } - } - - TIMING_STOPCLOCK_NAME("tcp:connect", url, window_id, "ok"); - TRACEMSG(("mktcp.c: Successful connection (message 1)")); - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - return MK_CONNECTED; - } - - default: - NET_FreeTCPConData(*tcp_con_data); - *tcp_con_data = 0; - TRACEMSG(("mktcp.c: bad state during connect")); - - assert(0); /* should never happen */ - - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONNECT, 0); - return(MK_UNABLE_TO_CONNECT); - - } /* end switch on next_state */ - - PR_ASSERT(0); /* should never get here */ - - *error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONNECT, 0); - return(MK_UNABLE_TO_CONNECT); -} - - -/* Free any memory used up - */ -MODULE_PRIVATE void -NET_CleanupTCP(void) -{ - if(dns_list) - { - DNSEntry * tmp_entry; - - while((tmp_entry = (DNSEntry *)XP_ListRemoveTopObject(dns_list)) != NULL) - { - NET_FreeDNSStruct(tmp_entry); - } - - XP_ListDestroy(dns_list); - dns_list = 0; - } - - /* we really should free the socket_buffer but - * that is in the other module as a private :( - */ - return; -} diff --git a/mozilla/network/main/mkfsort.c b/mozilla/network/main/mkfsort.c deleted file mode 100644 index 1f8ef5c0c25..00000000000 --- a/mozilla/network/main/mkfsort.c +++ /dev/null @@ -1,220 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * - * routines to sort an array of file objects - * uses qsort alg - * - * Designed and implemented by Lou Montulli '94 - */ - -#include "mkutils.h" -#include "mkfsort.h" -#include "mkgeturl.h" - -#ifdef PROFILE -#pragma profile on -#endif - -PRIVATE int net_file_sort_method = SORT_BY_NAME; - -/* print a text string in place of the NET_FileEntryInfo special_type int */ -PUBLIC char * -NET_PrintFileType(int special_type) -{ - switch(special_type) - { - case NET_FILE_TYPE: - return("FILE"); - case NET_DIRECTORY: - return("DIRECTORY"); - case NET_SYM_LINK: - return("SYMBOLIC-LINK"); - case NET_SYM_LINK_TO_DIR: - return("SYM-DIRECTORY"); - case NET_SYM_LINK_TO_FILE: - return("SYM-FILE"); - default: - PR_ASSERT(0); - return("FILE"); - } -} - -PRIVATE void -NET_SetFileSortMethod(int method) -{ - net_file_sort_method = method; -} - -MODULE_PRIVATE void NET_FreeEntryInfoStruct(NET_FileEntryInfo *entry_info) -{ - if(entry_info) - { - FREEIF(entry_info->filename); - /* free the struct */ - PR_Free(entry_info); - } -} - -MODULE_PRIVATE NET_FileEntryInfo * NET_CreateFileEntryInfoStruct (void) -{ - NET_FileEntryInfo * new_entry = PR_NEW(NET_FileEntryInfo); - - if(!new_entry) - return(NULL); - - memset(new_entry, 0, sizeof(NET_FileEntryInfo)); - - new_entry->permissions = -1; - - return(new_entry); - -} - -/* This function is used as a comparer function for the Qsort routine. - * It uses a function FE_FileSortMethod() to determine the - * field to sort on. - * - */ -PRIVATE int -NET_CompareFileEntryInfoStructs (const void *ent2, const void *ent1, void *unused) -{ - int status; - const NET_FileEntryInfo *entry1 = *(NET_FileEntryInfo **) ent1; - const NET_FileEntryInfo *entry2 = *(NET_FileEntryInfo **) ent2; - - if(!entry1 || !entry2) - return(-1); - - switch(net_file_sort_method) - { - case SORT_BY_SIZE: - /* both equal or both 0 */ - if(entry1->size == entry2->size) - return(PL_strcmp(entry2->filename, entry1->filename)); - else - if(entry1->size > entry2->size) - return(-1); - else - return(1); - /* break; NOT NEEDED */ - case SORT_BY_TYPE: - if(entry1->cinfo && entry1->cinfo->desc && - entry2->cinfo && entry2->cinfo->desc) - { - status = PL_strcmp(entry1->cinfo->desc, entry2->cinfo->desc); - if(status) - return(status); - /* else fall to filename comparison */ - } - return (PL_strcmp(entry2->filename, entry1->filename)); - /* break; NOT NEEDED */ - case SORT_BY_DATE: - if(entry1->date == entry2->date) - return(PL_strcmp(entry2->filename, entry1->filename)); - else - if(entry1->size > entry2->size) - return(-1); - else - return(1); - /* break; NOT NEEDED */ - case SORT_BY_NAME: - default: - return (PL_strcmp(entry2->filename, entry1->filename)); - } -} - -/* sort the files - */ -MODULE_PRIVATE void -NET_DoFileSort(SortStruct * sort_list) -{ - NET_DoSort(sort_list, NET_CompareFileEntryInfoStructs); -} - -#define PD_PUTS(s) \ -do { \ -if(status > -1) \ - status = (*stream->put_block)(stream, s, PL_strlen(s)); \ -} while(0) - -PUBLIC int -NET_PrintDirectory(SortStruct **sort_base, NET_StreamClass * stream, char * path, URL_Struct *URL_s) -{ - NET_FileEntryInfo * file_entry; - char out_buf[3096]; - char *esc_path = NET_Escape(path, URL_PATH); - int i; - int status=0; - - NET_DoFileSort(*sort_base); - - /* emit 300: URL CRLF */ - PL_strcpy(out_buf, "300: "); - PD_PUTS(out_buf); - PR_snprintf(out_buf, sizeof(out_buf), URL_s->address); - PD_PUTS(out_buf); - - PL_strcpy(out_buf, CRLF); - PD_PUTS(out_buf); - - /* emit 200: Filename Size Content-Type File-type Last-Modified */ - PL_strcpy(out_buf, "200: Filename Content-Length Content-Type File-type Last-Modified"CRLF); - PD_PUTS(out_buf); - - for(i=0; status > -1 && (file_entry = (NET_FileEntryInfo *) - NET_SortRetrieveNumber(*sort_base, i)) != 0; - i++) - { - - - char * esc_time = NET_Escape(ctime(&file_entry->date), URL_XALPHAS); - - strtok(file_entry->filename, "/"); - PR_snprintf(out_buf, sizeof(out_buf), "201: %s %ld %s %s %s"CRLF, - file_entry->filename, - file_entry->size, - file_entry->special_type == NET_DIRECTORY ? "application/http-index-format" : - file_entry->cinfo ? file_entry->cinfo->type : TEXT_PLAIN, - file_entry->special_type == NET_DIRECTORY ? "Directory" : "File", - esc_time); - - PR_Free(esc_time); - - PD_PUTS(out_buf); - - NET_FreeEntryInfoStruct(file_entry); - } - - NET_SortFree(*sort_base); - *sort_base = 0; - - PR_FREEIF(esc_path); - if(status < 0) - return(status); - return(MK_DATA_LOADED); -} - -#ifdef PROFILE -#pragma profile off -#endif - diff --git a/mozilla/network/main/mkfsort.h b/mozilla/network/main/mkfsort.h deleted file mode 100644 index 1086374b860..00000000000 --- a/mozilla/network/main/mkfsort.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKFSORT_H -#define MKFSORT_H - -#include "mksort.h" - -#include <time.h> - -#ifdef XP_UNIX -#include <sys/types.h> -#endif /* XP_UNIX */ - -extern void NET_FreeEntryInfoStruct(NET_FileEntryInfo *entry_info); -extern NET_FileEntryInfo * NET_CreateFileEntryInfoStruct (void); -extern int NET_CompareEntryInfoStructs (void *ent1, void *ent2); -extern void NET_DoFileSort (SortStruct * sort_list); - -extern int -NET_PrintDirectory(SortStruct **sort_base, NET_StreamClass * stream, char * path, URL_Struct *URL_s); - -#endif /* MKFSORT_H */ diff --git a/mozilla/network/main/mkgeturl.c b/mozilla/network/main/mkgeturl.c deleted file mode 100644 index c36b27dfd69..00000000000 --- a/mozilla/network/main/mkgeturl.c +++ /dev/null @@ -1,5251 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* mkgeturl.c - * This file implements the main calling api for netlib. - * Includes NET_InitNetlib, NET_Shutdown, NET_GetURL, and NET_ProcessNet - * - * Designed and originally implemented by Lou Montulli '94 - * Additions/Changes by Judson Valeski, Gagan Saksena 1997. - */ -#if defined(CookieManagement) -/* #define TRUST_LABELS 1 */ -#endif - -#include "rosetta.h" -#include "xp_error.h" -#include "mkutils.h" -#include "mkgeturl.h" -#include "shist.h" -#include "mkparse.h" -#include "mkformat.h" -#include "mkstream.h" -#include "mkpadpac.h" -#include "netcache.h" -#include "mkprefs.h" -#ifdef NU_CACHE -#include "CacheStubs.h" -#endif -#include "nslocks.h" -#include "cookies.h" -#include "httpauth.h" -#include "cnetinit.h" - -#if 0 /* NO PROTOCOLS HERE */ -#include "mkhttp.h" -#include "mkftp.h" -#include "mkgopher.h" -#include "mkremote.h" -#include "mknews.h" -#include "mkpop3.h" -#include "mkdaturl.h" -#include "mkfile.h" -#include "mksmtp.h" -#include "mkcache.h" -#include "mkmemcac.h" -#include "mkmailbx.h" -#include "mkcertld.h" -#include "mkmarimb.h" -#include "libmocha.h" -#include "mkmocha.h" -#endif /* 0 */ - -#ifdef XP_MAC -#ifdef OLD_MOZ_MAIL_NEWS -#ifdef MOZ_SECURITY -#include "mkcertld.h" -#endif /* MOZ_SECURITY */ -#include "mkmailbx.h" -#include "mknews.h" -#include "mknewsgr.h" -#include "mkpop3.h" -#include "mkimap4.h" -#include "mkldap.h" -#endif /* OLD_MOZ_MAIL_NEWS */ -#endif /* XP_MAC */ - -#include "glhist.h" -#include "mkautocf.h" -#include "mkabook.h" -#include "mkhelp.h" -#include "ssl.h" - -#ifdef MOZ_LDAP -#include "mkldap.h" -#endif - -#ifdef OLD_MOZ_MAIL_NEWS -#include "mkimap4.h" -#endif - -#include "mktcp.h" /* for NET_InGetHostByName semaphore */ -#ifdef MOZILLA_CLIENT -#include "secnav.h" -#include "libevent.h" -#include "jscompat.h" -#include "jspubtd.h" -#endif - -#include "libi18n.h" - -#include "np.h" -#include "prefapi.h" -#ifdef XP_MAC -#include "prpriv.h" /* for NewNamedMonitor */ -#else -#include "private/prpriv.h" -#endif - -#include "sslerr.h" -#include "merrors.h" -#include "prefetch.h" - -#ifdef XP_OS2 -#include "os2sock.h" -#endif - -#ifdef EDITOR -#include "edt.h" -#endif - -#ifdef XP_UNIX -#include "prnetdb.h" -#else -#define PRHostEnt struct hostent -#endif - -#include "xplocale.h" - -#ifdef WEBFONTS -#include "nf.h" -#endif /* WEBFONTS */ - -/* plugins: */ -#include "np.h" - -void net_ReleaseContext(MWContext *context); - -#if defined(NETLIB_THREAD) -void net_CallExitRoutineProxy(Net_GetUrlExitFunc* exit_routine, - URL_Struct* URL_s, - int status, - FO_Present_Types format_out, - MWContext* window_id); -#else -#define net_CallExitRoutineProxy net_CallExitRoutine -#endif /* !NETLIB_THREAD */ - -#include "timing.h" - -#ifdef TRUST_LABELS -#include "mkaccess.h" /* change to trust.h for phase 2 */ -#endif - -#if defined(SMOOTH_PROGRESS) -#include "progress.h" -#endif - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int MK_CONNECTION_REFUSED; -extern int MK_CONNECTION_TIMED_OUT; -extern int MK_MALFORMED_URL_ERROR; -extern int MK_OUT_OF_MEMORY; -extern int MK_RELATIVE_TIMEBOMB_MESSAGE; -extern int MK_RELATIVE_TIMEBOMB_WARNING_MESSAGE; -extern int MK_TIMEBOMB_MESSAGE; -extern int MK_TIMEBOMB_URL_PROHIBIT; -extern int MK_TIMEBOMB_WARNING_MESSAGE; -extern int MK_UNABLE_TO_CONNECT; -extern int MK_UNABLE_TO_CREATE_SOCKET; -extern int MK_UNABLE_TO_LOCATE_HOST; -extern int MK_UNABLE_TO_LOCATE_PROXY; -extern int XP_CHECKING_SERVER__FORCE_RELOAD; -extern int XP_OBJECT_HAS_EXPIRED; -extern int XP_CHECKING_SERVER_CACHE_ENTRY; -extern int XP_CHECKING_SERVER__LASTMOD_MISS; -extern int XP_ALERT_CONNECTION_LESSZERO; -extern int XP_ALERT_INTERRUPT_WINDOW; -extern int XP_ALERT_URLS_LESSZERO; -extern int XP_CONFIRM_REPOST_FORMDATA; -extern int XP_CONSULT_SYS_ADMIN; -extern int XP_HTML_MISSING_REPLYDATA; -extern int XP_SOCKS_NS_ENV_VAR; -extern int XP_SOME_HOSTS_UNREACHABLE; -extern int XP_THIS_IS_DNS_VERSION; -extern int XP_THIS_IS_YP_VERSION; -extern int XP_UNKNOWN_HOST; -extern int XP_UNKNOWN_HOSTS; -extern int XP_UNKNOWN_HTTP_PROXY; -extern int XP_UNKNOWN_SOCKS_HOST; -extern int XP_URLS_WAITING_FOR_AN_OPEN_SOCKET; -extern int XP_URLS_WAITING_FOR_FEWER_ACTIVE_URLS; -extern int XP_CONNECTIONS_OPEN; -extern int XP_ACTIVE_URLS; -extern int XP_USING_PREVIOUSLY_CACHED_COPY_INSTEAD; -extern int XP_BAD_AUTOCONFIG_NO_FAILOVER; - -extern int XP_SOCK_CON_SOCK_PROTOCOL; -extern int XP_URL_NOT_FOUND_IN_CACHE; -extern int XP_PARTIAL_CACHE_ENTRY; -extern int XP_MSG_UNKNOWN ; -extern int XP_EDIT_NEW_DOC_URL; -extern int XP_EDIT_NEW_DOC_NAME; -extern int XP_CONFIRM_MAILTO_POST_1; -extern int XP_CONFIRM_MAILTO_POST_2; - -extern int XP_ALERT_OFFLINE_MODE_SELECTED; - -extern void NET_InitMailtoProtocol(void); - -#if defined(JAVA) || defined(NS_MT_SUPPORTED) -#include "nslocks.h" -#include "prlog.h" -#include <stdarg.h> - -PRMonitor* libnet_asyncIO; - -#if defined(SOLARIS) -extern int gethostname(char *, int); -#endif /* SOLARIS */ - -#endif /* JAVA || NS_MT_SUPPORTED */ - -#define LIBNET_UNLOCK_AND_RETURN(value) \ - do { int rv = (value); LIBNET_UNLOCK(); return rv; } while (0) - -/* -** Don't ever forget about this!!! -** -** This is ALL superseeded by the setting in /ns/modules/libpref/src/init/all.js -** lock for timebomb.use_timebomb - -** Define TIMEBOMB_ON for beta builds. -** Undef TIMEBOMB_ON for release builds. -*/ -#define TIMEBOMB_ON -/* #undef TIMEBOMB_ON */ -/* -** After this date all hell breaks loose -*/ -#define TIME_BOMB_TIME 888739203 /* 3/01/98 + 3 secs */ -#ifdef XP_OS2 -#define TIME_BOMB_WARNING_TIME 869976003 /* 7/21/97 + 3 secs */ -#else -#define TIME_BOMB_WARNING_TIME 857203203 /* 3/01/97 + 3 secs */ -#endif - -#ifndef XP_UNIX -#ifdef NADA_VERSION -HG73787 -#else -HG72987 -#endif -#endif - -#ifdef EDITOR -/* - * Strings used for new, empty document creation - * Kluge we use to load a new document is resource with one space. - * These strings are loaded from XP_MSG.I on first GetURL call - * (this allows changing "Untitled" for other languages) -*/ -PUBLIC char *XP_NEW_DOC_URL = NULL; /* "about:editfilenew" */ -/* - * This is the name we want to appear as the URL address - * You can load a new doc using this - it will be changed - * to XP_NEW_DOC_URL. - * When done, XP_NEW_DOC_URL will be changed to XP_NEW_DOC_NAME -*/ -PUBLIC char *XP_NEW_DOC_NAME = NULL; /* "Untitled" */ -#endif - -#ifdef PROFILE -#pragma profile on -#endif - -/* forward decl's */ -PRIVATE void add_slash_to_URL (URL_Struct *URL_s); -PRIVATE Bool override_proxy (CONST char * URL); -HG52422 - -PRIVATE void net_FreeURLAllHeaders(URL_Struct * URL_s); - -PRIVATE NET_TimeBombActive = FALSE; - -typedef struct _WaitingURLStruct { - int type; - URL_Struct *URL_s; - FO_Present_Types format_out; - MWContext *window_id; - Net_GetUrlExitFunc *exit_routine; -} WaitingURLStruct; - -/* Pointers to proxy servers - * They are pointers to a host if - * a proxy environment variable - * was found or they are zero if not. - */ -PRIVATE char * MKftp_proxy=0; -PRIVATE char * MKgopher_proxy=0; -PRIVATE char * MKhttp_proxy=0; -HG62630 -PRIVATE char * MKwais_proxy=0; -PRIVATE char * MKnews_proxy=0; -PRIVATE char * MKno_proxy=0; -PRIVATE char * MKproxy_ac_url=0; -PRIVATE NET_ProxyStyle MKproxy_style = PROXY_STYLE_UNSET; - -PRIVATE char * MKglobal_config_url = 0; - -PRIVATE XP_List * net_EntryList=0; - -#ifdef TRUST_LABELS -/* This list contains all the URL_Struct s that are created */ -PRIVATE XP_List * net_URL_sList=0; -#endif - -MODULE_PRIVATE CacheUseEnum NET_CacheUseMethod=CU_CHECK_PER_SESSION; - -#ifdef XP_WIN16 -#define MAX_NUMBER_OF_PROCESSING_URLS 8 -#else -#define MAX_NUMBER_OF_PROCESSING_URLS 15 -#endif - -#define INITIAL_MAX_ALL_HEADERS 10 -#define MULT_ALL_HEADER_COUNT 2 -#define MAX_ALL_HEADER_COUNT 16000 - -MODULE_PRIVATE time_t NET_StartupTime=0; - -PRIVATE XP_Bool get_url_disabled = FALSE; - -MODULE_PRIVATE PRBool NET_ProxyAcLoaded = PR_FALSE; -MODULE_PRIVATE XP_Bool NET_GlobalAcLoaded = FALSE; -MODULE_PRIVATE int NET_TotalNumberOfOpenConnections=0; -MODULE_PRIVATE int NET_MaxNumberOfOpenConnections=100; -MODULE_PRIVATE int NET_MaxNumberOfOpenConnectionsPerContext=4; -MODULE_PRIVATE int NET_TotalNumberOfProcessingURLs=0; -PRIVATE XP_List * net_waiting_for_actives_url_list=0; -PRIVATE XP_List * net_waiting_for_connection_url_list=0; - -typedef struct NETExitCallbackNode { - struct NETExitCallbackNode *next; - void *arg; - void (* func)(void *arg); -} NETExitCallbackNode; - -PRIVATE NETExitCallbackNode *NETExitCallbackHead = NULL; - -/* forward decl */ -PRIVATE void net_cleanup_reg_protocol_impls(void); -PRIVATE void NET_InitTotallyRandomStuffPeopleAddedProtocols(void); - - -PUBLIC void -NET_DisableGetURL(void) -{ - get_url_disabled = TRUE; -} - -/* fix Mac warning for missing prototype */ -PUBLIC void -NET_AddExitCallback( void (* func)(void *arg), void *arg); - -PUBLIC void -NET_AddExitCallback( void (* func)(void *arg), void *arg) -{ - NETExitCallbackNode *node; - - /* alloc node */ - node = PR_Malloc(sizeof(NETExitCallbackNode)); - if ( node != NULL ) { - /* fill it in */ - node->func = func; - node->arg = arg; - /* link it into the list */ - node->next = NETExitCallbackHead; - NETExitCallbackHead = node; - } - - return; -} - -PRIVATE void -NET_ProcessExitCallbacks(void) -{ - NETExitCallbackNode *node, *freenode; - - node = NETExitCallbackHead; - - while ( node != NULL ) { - (* node->func)(node->arg); - freenode = node; - node = node->next; - PR_Free(freenode); - } - - NETExitCallbackHead = NULL; - - return; -} - -/* Gather manual proxy information from the prefapi. Called from - SetupPrefs and SelectProxyStyle */ -PRIVATE void -NET_UpdateManualProxyInfo(const char * prefChanged) { - - XP_Bool bSetupAll=FALSE; - char * proxy = NULL; - PRInt32 iPort=0; - char text[MAXHOSTNAMELEN + 8]; - - if (!prefChanged) - bSetupAll = TRUE; - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyFtpServer) || - !PL_strcmp(prefChanged, pref_proxyFtpPort)) { - if( (PREF_OK == PREF_CopyCharPref(pref_proxyFtpServer,&proxy)) - && proxy && *proxy) { - if ( (PREF_OK == PREF_GetIntPref(pref_proxyFtpPort,&iPort)) ) { - sprintf(text,"%s:%d", proxy, iPort); - StrAllocCopy(MKftp_proxy, text); - iPort=0; - } else { - FREE_AND_CLEAR(MKftp_proxy); - } - } - else - FREE_AND_CLEAR(MKftp_proxy); - } - if (proxy) FREE_AND_CLEAR(proxy); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyGopherServer) || - !PL_strcmp(prefChanged, pref_proxyGopherPort)) { - if( (PREF_OK == PREF_CopyCharPref(pref_proxyGopherServer,&proxy)) - && proxy && *proxy) { - if ( (PREF_OK == PREF_GetIntPref(pref_proxyGopherPort,&iPort)) ) { - sprintf(text,"%s:%d", proxy, iPort); - StrAllocCopy(MKgopher_proxy, text); - iPort=0; - } else { - FREE_AND_CLEAR(MKgopher_proxy); - } - } - else - FREE_AND_CLEAR(MKgopher_proxy); - } - if (proxy) FREE_AND_CLEAR(proxy); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyHttpServer) || - !PL_strcmp(prefChanged, pref_proxyHttpPort)) { - if( (PREF_OK == PREF_CopyCharPref(pref_proxyHttpServer,&proxy)) - && proxy && *proxy) { - if ( (PREF_OK == PREF_GetIntPref(pref_proxyHttpPort,&iPort)) ) { - sprintf(text,"%s:%d", proxy, iPort); - /* Don't change the proxy info unless necessary. */ - if (PL_strcmp(MKhttp_proxy, text)) - StrAllocCopy(MKhttp_proxy, text); - iPort=0; - } else { - FREE_AND_CLEAR(MKhttp_proxy); - } - } - else - FREE_AND_CLEAR(MKhttp_proxy); - } - if (proxy) FREE_AND_CLEAR(proxy); - - HG24324 - if (proxy) FREE_AND_CLEAR(proxy); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyNewsServer) || - !PL_strcmp(prefChanged, pref_proxyNewsPort)) { - if( (PREF_OK == PREF_CopyCharPref(pref_proxyNewsServer,&proxy)) - && proxy && *proxy) { - if ( (PREF_OK == PREF_GetIntPref(pref_proxyNewsPort,&iPort)) ) { - sprintf(text,"%s:%d", proxy, iPort); - StrAllocCopy(MKnews_proxy, text); - iPort=0; - } else { - FREE_AND_CLEAR(MKnews_proxy); - } - } - else - FREE_AND_CLEAR(MKnews_proxy); - } - if (proxy) FREE_AND_CLEAR(proxy); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyWaisServer) || - !PL_strcmp(prefChanged, pref_proxyWaisPort)) { - if( (PREF_OK == PREF_CopyCharPref(pref_proxyWaisServer,&proxy)) - && proxy && *proxy) { - if ( (PREF_OK == PREF_GetIntPref(pref_proxyWaisPort,&iPort)) ) { - sprintf(text,"%s:%d", proxy, iPort); - StrAllocCopy(MKwais_proxy, text); - iPort=0; - } else { - FREE_AND_CLEAR(MKwais_proxy); - } - } - else - FREE_AND_CLEAR(MKwais_proxy); - } - if (proxy) FREE_AND_CLEAR(proxy); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_socksServer) || - !PL_strcmp(prefChanged, pref_socksPort)) { - if ( (PREF_OK == PREF_CopyCharPref(pref_socksServer,&proxy)) - && proxy && *proxy) { - if ( (PREF_OK == PREF_GetIntPref(pref_socksPort,&iPort)) ) { - PR_snprintf(text, sizeof(text), "%s:%d", proxy, iPort); - NET_SetSocksHost(text); - } else { - NET_SetSocksHost(NULL); /* NULL is ok */ - } - } - else { - NET_SetSocksHost(proxy); /* NULL is ok */ - } - iPort=0; - } - if (proxy) FREE_AND_CLEAR(proxy); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyNoProxiesOn)) { - if( (PREF_OK == PREF_CopyCharPref(pref_proxyNoProxiesOn,&proxy)) - && proxy && *proxy) { - StrAllocCopy(MKno_proxy, proxy); - } else { - FREE_AND_CLEAR(MKno_proxy); - } - } - if (proxy) FREE_AND_CLEAR(proxy); - return; -} - -PUBLIC NET_ProxyStyle -NET_GetProxyStyle(void) -{ - return MKproxy_style; -} - -/* These are used in netlib only for exposing the MKproxy_ac_url - * to proxy autodiscovery stuff in mkpadpac.c */ -MODULE_PRIVATE const char * -net_GetPACUrl(void) { - return MKproxy_ac_url; -} - -MODULE_PRIVATE void -net_SetPACUrl(char *u) { - /* Do a straight assignment, no checking. */ - MKproxy_ac_url=u; -} - -PUBLIC void -NET_SelectProxyStyle(NET_ProxyStyle style) -{ - /* The NET_ProxyStyle enum is defined in net.h. - PROXY_STYLE_UNSET = 0 -- ? - PROXY_STYLE_MANUAL = 1 -- old style proxies - PROXY_STYLE_AUTOMATIC = 2 -- new style proxies - PROXY_STYLE_NONE = 3 -- no proxies, direct connection - */ - char * proxy=0; - - if (MKproxy_style != style) { - NET_ProxyAcLoaded = FALSE; - } - - MKproxy_style = style; - - if (MKproxy_style == PROXY_STYLE_MANUAL) { - /* Get the manual info */ - NET_UpdateManualProxyInfo(NULL); - } - - if (MKproxy_style == PROXY_STYLE_AUTOMATIC) { - /* Get the autoconfig url */ - if ( (PREF_OK == PREF_CopyCharPref(pref_proxyACUrl,&proxy)) - && proxy && *proxy) { - StrAllocCopy(MKproxy_ac_url, proxy); - NET_ProxyAcLoaded = FALSE; - } - if (proxy) FREE_AND_CLEAR(proxy); - } - - /* If we're not in automatic or manual style, clear un-needed internal info */ - if (MKproxy_style != PROXY_STYLE_AUTOMATIC) { - FREE_AND_CLEAR(MKproxy_ac_url); - NET_ProxyAcLoaded = FALSE; - } - - /* If we're not in manual (proxies) clear the un-needed internal info. */ - if (MKproxy_style != PROXY_STYLE_MANUAL) { - FREE_AND_CLEAR(MKftp_proxy); - FREE_AND_CLEAR(MKgopher_proxy); - FREE_AND_CLEAR(MKhttp_proxy); - HG63454 - FREE_AND_CLEAR(MKwais_proxy); - FREE_AND_CLEAR(MKnews_proxy); - FREE_AND_CLEAR(MKno_proxy); - - NET_SetSocksHost(NULL); - } -} - -/* this function loads the proxy values from the various preferences and -sets up the internal cached values...It is called during Init and whenever -a proxy pref is changed...If no specific pref is passed, it sets them all -up */ - -PUBLIC void -NET_SetupPrefs(const char * prefChanged) -{ - XP_Bool bSetupAll=FALSE; - char * proxy = NULL; - - /* if prefChanged is null the following PL_strcmp's are never executed because the - || statement never gets that far because when prefChanged is null bSetupAll is - set to true and is always checked first in the if statement. Don't set prefChanged - to "" if it is null because the UpdateManualProxyInfo below needs null not "" if - prefChanged was originally null. */ - if (!prefChanged) - bSetupAll = TRUE; - - if (bSetupAll || !PL_strcmp(prefChanged, pref_dnsExpiration)) { - PRInt32 n; - if ( (PREF_OK != PREF_GetIntPref(pref_dnsExpiration,&n)) ) { - n = DEF_DNS_EXPIRATION; - } - NET_SetDNSExpirationPref(n); - } - - if (bSetupAll || !PL_strcmp(prefChanged, pref_browserPrefetch)) { - PRInt32 n; - if ( (PREF_OK != PREF_GetIntPref(pref_browserPrefetch,&n)) ) { - n = 0; - } - PRE_Enable((PRUint8)n); - } - - if (bSetupAll || !PL_strcmp(prefChanged,pref_browserCacheMemSize)) { - PRInt32 nMemCache; - if ( (PREF_OK != PREF_GetIntPref(pref_browserCacheMemSize,&nMemCache)) ) { - nMemCache = DEF_MEM_CACHE_SIZE; - } - NET_SetMemoryCacheSize(nMemCache * 1024); - } - - if (bSetupAll || !PL_strcmp(prefChanged,pref_browserCacheDiskSize)) { - PRInt32 nDiskCache; - if ( (PREF_OK != PREF_GetIntPref(pref_browserCacheDiskSize,&nDiskCache)) ) { - nDiskCache = DEF_DISK_CACHE_SIZE; - } - NET_SetDiskCacheSize(nDiskCache * 1024); - } - - if (bSetupAll || !PL_strcmp(prefChanged, pref_browserCacheDocFreq)) { - PRInt32 nDocReqFreq; - if ( (PREF_OK != PREF_GetIntPref(pref_browserCacheDocFreq,&nDocReqFreq)) ) { - nDocReqFreq = DEF_CHECK_DOC_FREQ; - } - NET_SetCacheUseMethod((CacheUseEnum)nDocReqFreq); - } - - HG42422 -#ifdef OLD_MOZ_MAIL_NEWS - if (bSetupAll || !PL_strcmp(prefChanged,pref_mailAllowSignInUName)) { - XP_Bool prefBool; - if ( (PREF_OK != PREF_GetBoolPref(pref_mailAllowSignInUName,&prefBool)) ) { - prefBool = DEF_ALLOW_AT_SIGN_UNAME; - } - NET_SetAllowAtSignInMailUserName (prefBool); - } -#endif /* OLD_MOZ_MAIL_NEWS */ - - if (bSetupAll || !PL_strcmp(prefChanged,pref_proxyACUrl)) { - if ( (PREF_OK == PREF_CopyCharPref(pref_proxyACUrl,&proxy)) - && proxy && *proxy) { - StrAllocCopy(MKproxy_ac_url, proxy); - NET_ProxyAcLoaded = FALSE; - } - else - FREE_AND_CLEAR(MKproxy_ac_url); - } - if (proxy) FREE_AND_CLEAR(proxy); - - NET_UpdateManualProxyInfo(prefChanged); - - if (bSetupAll || !PL_strcmp(prefChanged, pref_proxyType)) { - PRInt32 iType; - if ( (PREF_OK != PREF_GetIntPref(pref_proxyType,&iType)) ) { - iType = DEF_PROXY_TYPE; - } - NET_SelectProxyStyle((NET_ProxyStyle)iType); - } -} - -/* register preference callbacks for netlib prefs -*/ - -MODULE_PRIVATE int PR_CALLBACK NET_PrefChangedFunc(const char *pref, void *data) { - NET_SetupPrefs(pref); - return TRUE; -} - -#ifdef NS_NET_FILE -extern PRBool NET_InitFilesAndDirs(void); -#endif -/* finish the init of 'netlib'. inits cookies, cache, history - * - */ -PUBLIC void -NET_FinishInitNetLib() -{ -#ifdef NS_NET_FILE - /* Initialize all the directories and files that netlib needs. */ - if (!NET_InitFilesAndDirs()) - ; /* do something. */ -#endif - - -#ifdef MOZILLA_CLIENT - NET_CacheInit(); -/* NET_ReadCookies(""); */ -#endif /* MOZILLA_CLIENT */ - - NET_RegisterEnableUrlMatchCallback(); - NET_SetupPrefs(NULL); /* setup initial proxy, socks, dnsExpiration and cache preference info */ - - PREF_RegisterCallback("network.proxy",NET_PrefChangedFunc,NULL); -#ifndef NU_CACHE - PREF_RegisterCallback("browser.cache",NET_PrefChangedFunc,NULL); -#endif - PREF_RegisterCallback("network.hosts.socks_server",NET_PrefChangedFunc,NULL); - PREF_RegisterCallback("network.hosts.socks_serverport",NET_PrefChangedFunc,NULL); - PREF_RegisterCallback("network.dnsCacheExpiration",NET_DNSExpirationPrefChanged,NULL); - NET_RegisterCookiePrefCallbacks(); /* simply inits cookie info in mkaccess.c */ - /* and registers the callbacks */ - /* inits the proxy autodiscovery vars and registers their callbacks. */ - NET_RegisterPadPrefCallbacks(); - PREF_RegisterCallback("mail.allow_at_sign_in_user_name", NET_PrefChangedFunc, NULL); - -#ifdef XP_UNIX - { - char *ac_url = getenv("AUTOCONF_URL"); - if (ac_url) { - NET_SetProxyServer(PROXY_AUTOCONF_URL, ac_url); - NET_SelectProxyStyle(PROXY_STYLE_AUTOMATIC); - } - } -#endif - -} - -/* initialize the netlibrary and set the socket buffer size - */ -PUBLIC int -NET_InitNetLib(int socket_buffer_size, int max_number_of_connections) -{ - int status; - -#if defined(DEBUG) - if (NETLIB==NULL) - NETLIB = PR_NewLogModule("NETLIB"); -#endif - - TRACEMSG(("Initializing Network library")); - - NET_StartupTime = time(NULL); - - /* seed the random generator - */ - XP_SRANDOM((unsigned int) time(NULL)); - - if(max_number_of_connections < 1) - max_number_of_connections = 1; - -#if defined(XP_UNIX) || defined(XP_BEOS) - signal(SIGPIPE, SIG_IGN); -#endif - - - status = NET_ChangeSocketBufferSize(socket_buffer_size); - - NET_ChangeMaxNumberOfConnections(max_number_of_connections); - net_waiting_for_actives_url_list = XP_ListNew(); - net_waiting_for_connection_url_list = XP_ListNew(); - - net_EntryList = XP_ListNew(); -#ifdef TRUST_LABELS - net_URL_sList = XP_ListNew(); -#endif - - NET_TotalNumberOfProcessingURLs=0; /* reset */ - -#if defined(JAVA) || defined(NS_MT_SUPPORTED) - libnet_asyncIO = PR_NewNamedMonitor("libnet"); -#endif - - /* initialize protocol modules - * - * eventually this should be done dynamically, - * but first we need to make URL types be dynamically - * registered, and make URL parsing dynamic as well. - * - * Currently, registering them in the most used order is - * very slightly more efficient - */ - - NET_ClientProtocolInitialize(); - - /* @@@@ these need to move soon */ - NET_InitNFSProtocol(); - NET_InitURNProtocol(); - NET_InitWAISProtocol(); -#ifdef SMART_MAIL - NET_InitPop3Protocol(); -#endif - NET_InitTotallyRandomStuffPeopleAddedProtocols(); - -#if defined(OLD_MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) - NET_InitMailtoProtocol(); /* has a stub for OLD_MOZ_MAIL_NEWS */ -#endif /* OLD_MOZ_MAIL_NEWS || MOZ_MAIL_COMPOSE */ -#ifdef OLD_MOZ_MAIL_NEWS - NET_InitNewsProtocol(); - NET_InitMailboxProtocol(); - NET_InitMsgSearchProtocol(); - - NET_InitLDAPProtocol(); -#ifdef MOZ_SECURITY - NET_InitCertLdapProtocol(); -#endif /* MOZ_SECURITY */ - NET_InitAddressBookProtocol(); - NET_InitIMAP4Protocol(); -#endif /* OLD_MOZ_MAIL_NEWS */ - - return(status); -} - -/* set the maximum allowable number of open connections at any one - * time regardless of the context - */ -PUBLIC void -NET_ChangeMaxNumberOfConnections(int max_number_of_connections) -{ - - /* if already equal return */ - if(NET_MaxNumberOfOpenConnections == max_number_of_connections) - return; - - if(max_number_of_connections < 1) - max_number_of_connections = 1; - - /* make sure that # conns per context is less than or equal - * to this Max - */ - if(NET_MaxNumberOfOpenConnectionsPerContext > max_number_of_connections) - NET_MaxNumberOfOpenConnectionsPerContext = max_number_of_connections; - - NET_MaxNumberOfOpenConnections = max_number_of_connections; - - /* close any open connections to prevent deadlock - */ - net_cleanup_reg_protocol_impls(); -} - -/* set the maximum allowable number of open connections at any one - * time Per context - */ -PUBLIC void -NET_ChangeMaxNumberOfConnectionsPerContext(int max_number_of_connections) -{ - - /* if already equal return */ - if(NET_MaxNumberOfOpenConnectionsPerContext == max_number_of_connections) - return; - - /* gate the number of max connections to be within 1 and 4 - */ - if(max_number_of_connections < 1) - max_number_of_connections = 1; - - if(max_number_of_connections > 6) - max_number_of_connections = 6; - - NET_MaxNumberOfOpenConnectionsPerContext = max_number_of_connections; - - /* close any open connections to prevent deadlock - */ -/* @@@@ NET_CleanupFTP(); */ -#ifdef MOZILLA_CLIENT -#ifdef OLD_MOZ_MAIL_NEWS -/* @@@@ NET_CleanupNews(); */ -#endif /* OLD_MOZ_MAIL_NEWS */ -#endif /* MOZILLA_CLIENT */ - -} - -/* check the date and set off the timebomb if necessary - * - * Calls FE_Alert with a message and then disables - * all network calls to hosts not in our domains, - * except for FTP connects. - */ -PUBLIC Bool -NET_CheckForTimeBomb(MWContext *context) -{ - static Bool done = FALSE; - time_t cur_time; - time_t timebomb_time = 0; - time_t timebomb_warning_time = 0; - - int32 relative_timebomb_days = 0; - int32 relative_timebomb_warning_days = 0; - time_t relative_timebomb_start_date = 0; - char *relative_timebomb_prefs_name; - time_t relative_timebomb_time = 0; - time_t relative_timebomb_warning_time = 0; - Bool have_relative_timebomb = FALSE; - Bool just_started_relative_timebomb = FALSE; - - if(done) - return(NET_TimeBombActive); - - /* - * Check if any timebomb is enabled - */ - PREF_GetConfigInt("timebomb.expiration_time",(PRInt32 *)&timebomb_time); - PREF_GetConfigInt("timebomb.relative_timebomb_days", - (PRInt32 *)&relative_timebomb_days); - - if (relative_timebomb_days >= 1) - have_relative_timebomb = TRUE; - - done = TRUE; - - if ((timebomb_time < 1) && (have_relative_timebomb == FALSE)) - return FALSE; - - cur_time = XP_TIME(); - - /* - * check the absolute timebomb - */ - TRACEMSG(("current time is: %ld %s", cur_time, ctime(&cur_time))); - TRACEMSG(("Timebomb time is: %ld %s", timebomb_time,ctime(&timebomb_time))); - if ((timebomb_time >= 1) && (cur_time > timebomb_time)) - { - char * alert = NET_ExplainErrorDetails(MK_TIMEBOMB_MESSAGE); - - FE_Alert(context, alert); - FREE(alert); - - NET_TimeBombActive = TRUE; - - return(TRUE); - } - - /* - * check the relative timebomb - * (note: we store the start date in prefs using a "secret" name ) - */ - if (have_relative_timebomb) { - TRACEMSG(("Relative timebomb days = %ld", relative_timebomb_days)); - relative_timebomb_prefs_name = NULL; - PREF_CopyConfigString("timebomb.relative_timebomb_secret_name", - &relative_timebomb_prefs_name); - if (relative_timebomb_prefs_name == NULL) - relative_timebomb_prefs_name = - PL_strdup("general.bproxy_cert_digest"); - relative_timebomb_start_date = 0; - PREF_GetIntPref(relative_timebomb_prefs_name, - (PRInt32 *)&relative_timebomb_start_date); - - if (relative_timebomb_start_date < 1) - { - /* if no value must be first time so set start date */ - just_started_relative_timebomb = TRUE; - relative_timebomb_start_date = cur_time; - PREF_SetIntPref(relative_timebomb_prefs_name, - (int32)relative_timebomb_start_date); - } - PR_Free(relative_timebomb_prefs_name); - relative_timebomb_time = relative_timebomb_start_date + - (relative_timebomb_days * 24 * 60 * 60); - if (cur_time > relative_timebomb_time) - { - char *alert = NET_ExplainErrorDetails(MK_RELATIVE_TIMEBOMB_MESSAGE); - - FE_Alert(context, alert); - FREE(alert); - - NET_TimeBombActive = TRUE; - - return(TRUE); - } - } - - /* - * check the absolute timebomb warning - */ - PREF_GetConfigInt("timebomb.warning_time",(PRInt32 *)&timebomb_warning_time); - TRACEMSG(("Timebomb warning time is: %ld %s", timebomb_warning_time, - ctime(&timebomb_warning_time))); - if ((timebomb_warning_time >= 1) && (cur_time > timebomb_warning_time)) - { - char * alert = NET_ExplainErrorDetails( MK_TIMEBOMB_WARNING_MESSAGE, - INTL_ctime(context, &timebomb_time)); - FE_Alert(context, alert); - FREE(alert); - - NET_TimeBombActive = FALSE; - - return(FALSE); - } - - /* - * check the relative timebomb warning - * also: on first use warn user this is timebombed - */ - if (have_relative_timebomb) { - relative_timebomb_warning_days = 0; - PREF_GetConfigInt("timebomb.relative_timebomb_warning_days", - (PRInt32 *)&relative_timebomb_warning_days); - TRACEMSG(("Relative timebomb warning days = %ld", - relative_timebomb_warning_days)); - if (relative_timebomb_warning_days >= 1) - relative_timebomb_warning_time = relative_timebomb_start_date + - (relative_timebomb_warning_days * 24 * 60 * 60); - else - relative_timebomb_warning_time = cur_time; - if (just_started_relative_timebomb || - (cur_time > relative_timebomb_warning_time)) - { - char * alert = NET_ExplainErrorDetails( - MK_RELATIVE_TIMEBOMB_WARNING_MESSAGE, - INTL_ctime(context, &relative_timebomb_time)); - FE_Alert(context, alert); - FREE(alert); - - NET_TimeBombActive = FALSE; - - return(FALSE); - } - } - - return(FALSE); -} - -/* set the way the cache should be used - */ -PUBLIC void -NET_SetCacheUseMethod(CacheUseEnum method) -{ - NET_CacheUseMethod = method; -} - -MODULE_PRIVATE void -net_CallExitRoutine(Net_GetUrlExitFunc *exit_routine, - URL_Struct *URL_s, - int status, - FO_Present_Types format_out, - MWContext *window_id) -{ -#ifdef EDITOR - /* History_entry * his; */ - /* Change all references to "about:editfilenew" into "file:///Untitled" */ - /* Do this for both Browser and Editor windows */ - if( /* EDT_IS_EDITOR(window_id) && */ - URL_s && URL_s->address && - 0 == PL_strcmp(URL_s->address, XP_NEW_DOC_URL) ) - { - PR_Free(URL_s->address); - URL_s->address = PL_strdup(XP_NEW_DOC_NAME); - - /* Not sure if this is the best place to do this, - * but it needs to go someplace! - */ - LO_SetBaseURL(window_id, XP_NEW_DOC_NAME); - - /* Setting context title to NULL will trigger - * Windows front end to use the URL address and set - * doc and window title to "Untitled" - * Do all front ends do this? - * If not, they will have to use EDT_IS_NEW_DOCUMENT - * to test for new doc and update title (in exit_routine) - */ - if ( window_id->title ) { - PR_Free(window_id->title); - window_id->title = NULL; - } - /* Note: We replace "about:editfilenew" with "file:///Untitled" - * in SHIST_AddDocument(), so we don't need to mess with - * History data here. - */ - - /* Set window_id->is_new_document flag appropriately - * This flag allows quicker response for often-called - * status queries at front end - */ - if ( EDT_IS_EDITOR(window_id) ) { - EDT_NEW_DOCUMENT(window_id, TRUE); - } - } -#endif /* EDITOR */ -#if defined(XP_WIN) || defined (XP_MAC) || defined (XP_OS2) - FE_URLEcho(URL_s, status, window_id); -#endif /* XP_WIN/MAC/OS2 */ - - if (!URL_s->load_background) - FE_EnableClicking(window_id); - -#ifdef MOZILLA_CLIENT - if(URL_s->refresh_url && status != MK_INTERRUPTED) - FE_SetRefreshURLTimer(window_id, URL_s); -#endif /* MOZILLA_CLIENT */ - - if (URL_s->pre_exit_fn) - { - Net_GetUrlExitFunc *per = URL_s->pre_exit_fn; - URL_s->pre_exit_fn = 0; - (*per) (URL_s, status, window_id); - } - /* byrd: plugin specific stuff, where we've added our own exit routine: */ - if ((URL_s->owner_data != NULL) && - (URL_s->owner_id == 0x0000BAC0)){ - NPL_URLExit(URL_s,status,window_id); - } - - if ( exit_routine != NULL ) { -#if defined(SingleSignon) - if (status<0 && URL_s->error_msg != NULL) { - SI_RemoveUser(URL_s->address, NULL, TRUE); - } -#endif - (*exit_routine) (URL_s, status, window_id); - } -} - -PRIVATE XP_Bool -net_does_url_require_socket_limit(int urltype) -{ - if( urltype == HTTP_TYPE_URL - HG64398 - || urltype == FTP_TYPE_URL - || urltype == NEWS_TYPE_URL - || urltype == GOPHER_TYPE_URL) - return TRUE; - - return(FALSE); -} - - -PRIVATE XP_Bool -net_is_one_url_allowed_to_run(MWContext *context, int url_type) -{ - /* put a limit on the total number of open connections - */ - if(NET_TotalNumberOfOpenConnections < NET_MaxNumberOfOpenConnectionsPerContext - || !net_does_url_require_socket_limit(url_type)) - { - return(TRUE); - } - else if(NET_TotalNumberOfOpenConnections >= NET_MaxNumberOfOpenConnections) - { - return(FALSE); - } - else - { - XP_List * list_ptr; - ActiveEntry * tmpEntry; - int32 cur_win_id = FE_GetContextID(context); - int real_number_of_connections = 0; - - - /* run through the list of running URLs and check - * for open connections only for this context. - * This will allow for the Total number of open - * connections to only apply to each window not - * to the whole program - */ - list_ptr = net_EntryList; - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(tmpEntry->window_id) - && net_does_url_require_socket_limit(url_type)) - { - real_number_of_connections++; - } - } /* end while */ - - /* pause it if the number of connections per context - * is higher than the per context limit or - */ - if(real_number_of_connections >= NET_MaxNumberOfOpenConnectionsPerContext) - - { - return(FALSE); - } - } - - return(TRUE); -} - -static int -net_push_url_on_wait_queue(int url_type, - URL_Struct *URL_s, - FO_Present_Types format_out, - MWContext *context, - Net_GetUrlExitFunc exit_routine) -{ - - WaitingURLStruct * wus = PR_NEW(WaitingURLStruct); - - TRACEMSG(("Pushing URL on wait queue with %d open connections", - NET_TotalNumberOfOpenConnections )); - if(!wus) - { - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_OUT_OF_MEMORY, - format_out, - context); - net_ReleaseContext(wus->window_id); - return(MK_OUT_OF_MEMORY); - } - - wus->type = url_type; - wus->URL_s = URL_s; - wus->format_out = format_out; - wus->window_id = context; - wus->exit_routine = exit_routine; - - /* add "text/ *" to beginning of list so it gets processed first */ - if (CLEAR_CACHE_BIT(format_out) == FO_INTERNAL_IMAGE) - /* low priority */ - XP_ListAddObjectToEnd(net_waiting_for_connection_url_list, wus); - else - /* higher priority */ - XP_ListAddObject(net_waiting_for_connection_url_list, wus); - - return(0); -} - -/* returns a malloc'd string that has a bunch of netlib - * status info in it. - * - * please free the pointer when done. - */ -PUBLIC char * -NET_PrintNetlibStatus() -{ - char small_buf[128]; - XP_List * list_ptr; - ActiveEntry *tmpEntry; - char *rv=0; - - LIBNET_LOCK(); - list_ptr = net_EntryList; - - sprintf(small_buf, XP_GetString( XP_URLS_WAITING_FOR_AN_OPEN_SOCKET ), - XP_ListCount(net_waiting_for_connection_url_list), - NET_MaxNumberOfOpenConnectionsPerContext); - StrAllocCat(rv, small_buf); - - sprintf(small_buf, XP_GetString( XP_URLS_WAITING_FOR_FEWER_ACTIVE_URLS ), - XP_ListCount(net_waiting_for_actives_url_list)); - StrAllocCat(rv, small_buf); - - sprintf(small_buf, XP_GetString( XP_CONNECTIONS_OPEN ), - NET_TotalNumberOfOpenConnections); - StrAllocCat(rv, small_buf); - - sprintf(small_buf, XP_GetString( XP_ACTIVE_URLS ), - NET_TotalNumberOfProcessingURLs); - StrAllocCat(rv, small_buf); - - while((tmpEntry = (ActiveEntry *)XP_ListNextObject(list_ptr)) != 0) - { - sprintf(small_buf, "------------------------------------\nURL:"); - StrAllocCat(rv, small_buf); - StrAllocCat(rv, tmpEntry->URL_s->address); - StrAllocCat(rv, "\n"); - - sprintf(small_buf, XP_GetString(XP_SOCK_CON_SOCK_PROTOCOL), - tmpEntry->socket, tmpEntry->con_sock, tmpEntry->protocol); - StrAllocCat(rv, small_buf); - } - -#if defined(DEBUG) && defined(JAVA) - { - static int loggingOn = 0; - NETLIB->level = (loggingOn ? PR_LOG_NONE : PR_LOG_DEBUG); - loggingOn = !loggingOn; - } -#endif /* defined(DEBUG) && defined(JAVA) */ - - LIBNET_UNLOCK(); - return(rv); -} - -#define RELEASE_PREFERRED_URLS TRUE -#define RELEASE_PREFERRED_OR_NON_PREFERRED FALSE -#define RELEASE_PREFETCH_URLS TRUE -#define DONT_RELEASE_PREFETCH_URLS FALSE -PRIVATE void -net_release_urls_for_processing(XP_Bool release_prefered, XP_Bool release_prefetch) -{ - XP_List * list_ptr = net_waiting_for_connection_url_list; - WaitingURLStruct * wus; - - while((wus = (WaitingURLStruct *) - XP_ListNextObject(list_ptr)) != NULL) - { - - if(!release_prefered - || ( (wus->format_out != FO_INTERNAL_IMAGE - && wus->format_out != FO_CACHE_AND_INTERNAL_IMAGE) - ) ) - { - /* if the type passed in NOT Prefetch_priority then only - * release URL's that are NOT Prefetch_priority - */ - if(release_prefetch || wus->URL_s->priority != Prefetch_priority) - { - XP_ListRemoveObject(net_waiting_for_connection_url_list, wus); - - /* change prefetch to active prefetch to allow it to load */ - if(wus->URL_s->priority == Prefetch_priority) - wus->URL_s->priority = CurrentlyPrefetching_priority; - - NET_GetURL(wus->URL_s, - wus->format_out, - wus->window_id, - wus->exit_routine); - FREE(wus); - break; - } - } - } -} - -PRIVATE void -net_release_prefetch_urls_for_processing(void) -{ - /* for now release just one url at a time to give the best possibility - * of individual URL's completeing before the user interrupts things - */ - net_release_urls_for_processing(RELEASE_PREFERRED_OR_NON_PREFERRED, - RELEASE_PREFETCH_URLS); - -} - -/* - * Must be called under the cover of the LIBNET_LOCK! - * - * The was_background parameter is used to determine when to call - * FE_AllConnectionsComplete. It should only be called if we've just - * completed processing a URL that's *not* a background loading URL. - * A background URL is one that loads without UI activity e.g. no - * status bar and thermo activity. - * This ensures that looping animations don't call - * FE_AllConnectionsComplete on every loop cycle. -*/ -PRIVATE void -net_CheckForWaitingURL(MWContext * window_id, int protocol, Bool was_background) -{ -#ifdef NSPR - PR_ASSERT(LIBNET_IS_LOCKED()); -#endif - - /* decrement here since this function is called - * after every exit_routine - */ - NET_TotalNumberOfProcessingURLs--; - - if(NET_TotalNumberOfProcessingURLs < 0) - { - FE_Alert(window_id, XP_GetString(XP_ALERT_URLS_LESSZERO)); - NET_TotalNumberOfProcessingURLs = 0; - } - - if(NET_TotalNumberOfOpenConnections < 0) - { - FE_Alert(window_id, XP_GetString(XP_ALERT_CONNECTION_LESSZERO)); - NET_TotalNumberOfOpenConnections = 0; - } - - TRACEMSG(("In: net_CheckForWaitingURL with %d connection waiting URL's, %d active waiting URL's and %d open connections", - XP_ListCount(net_waiting_for_connection_url_list), - XP_ListCount(net_waiting_for_actives_url_list), - NET_TotalNumberOfOpenConnections)); - - /* release preferred streams first */ - net_release_urls_for_processing(RELEASE_PREFERRED_URLS, - DONT_RELEASE_PREFETCH_URLS); - - /* release non-prefered streams */ - net_release_urls_for_processing(RELEASE_PREFERRED_OR_NON_PREFERRED, - DONT_RELEASE_PREFETCH_URLS); - - - if(!NET_AreThereActiveConnectionsForWindow(window_id)) - { - /* if there are prefetch URL's in the queue then we - * arn't quite done yet - */ - net_release_prefetch_urls_for_processing(); - - if(!was_background) - { - ET_SendLoadEvent(window_id, EVENT_XFER_DONE, - NULL, NULL, 0, - FALSE); - FE_AllConnectionsComplete(window_id); - } - } - -} - -PRIVATE int -net_AbortWaitingURL(MWContext * window_id, Bool all, XP_List *list) -{ - XP_List * list_ptr; /* Can't initialize here as list might be null */ - XP_List * prev_list_ptr = list; - XP_List * tmp_list_ptr; - WaitingURLStruct * wus; - int32 cur_win_id=0; - int number_killed = 0; - - /* make sure we actually got a list of things to Abort */ - if (!list) - return(number_killed); - - /* Now initialize the list pointer */ - list_ptr = list->next; - - if(!all && window_id) - cur_win_id = FE_GetContextID(window_id); - - while(list_ptr) - { - wus = (WaitingURLStruct *)list_ptr->object; - - if(all || (window_id && cur_win_id == FE_GetContextID(wus->window_id))) - { - TRACEMSG(("killing waiting URL")); - - /* call exit routine since we are done */ - net_CallExitRoutineProxy(wus->exit_routine, - wus->URL_s, - MK_INTERRUPTED, - wus->format_out, - wus->window_id); - - number_killed += 1; - - tmp_list_ptr = list_ptr; - list_ptr = list_ptr->next; - - /* remove the element from the list - * - * we have to use the function since it does - * funky doubly linked list stuff. - */ - XP_ListRemoveObject(list, wus); - net_ReleaseContext(wus->window_id); - FREE(wus); - } - else - { - prev_list_ptr = list_ptr; - list_ptr = list_ptr->next; - } - } - - return(number_killed); -} - - -/* Helper function for NET_SanityCheckDNS() */ -PRIVATE Bool -net_IsHostResolvable (CONST char *hostname, MWContext *context) -{ -#ifdef XP_UNIX - int rv; - PRHostEnt hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - if (PR_GetHostByName(hostname, dbbuf, sizeof(dbbuf), &hpbuf) == PR_FAILURE) - rv = FALSE; - else - rv = TRUE; - return rv; -#else - return(FALSE); -#endif -} - -/* Accomodate non-dns OS's like SunOS 4.1.3 */ -#if defined(__sun) && !(defined(__svr4__) || defined(__SVR4)) -#define MOZ_MAY_HAVE_DNS -#endif - -#ifdef MOZ_MAY_HAVE_DNS -/* From xfe/dns-stub.o or xfe/nis-stub.o, depending. Gag. */ -extern int fe_HaveDNS; -#endif - - -PUBLIC void -NET_SanityCheckDNS (MWContext *context) -{ -#ifdef XP_UNIX - - char *proxy = MKhttp_proxy; - char *socks = NET_SocksHostName; - char *test_host_1 = "home.netscape.com"; - char *test_host_2 = "home6.netscape.com"; - char *test_host_3 = "internic.net"; - char *message; -#ifdef MOZ_MAY_HAVE_DNS - char temp[1000]; -#endif - - static Bool done; - if (done) return; - done = TRUE; - - message = (char *) PR_Malloc (3000); - if (! message) - return; - *message = 0; - - if (proxy) - proxy = PL_strdup (proxy); - if (socks) - socks = PL_strdup (socks); - - /* Strip off everything after last colon. */ - { - char *s; - if (proxy && (s = PL_strrchr (proxy, ':'))) - *s = 0; - if (socks && (s = PL_strrchr (socks, ':'))) - *s = 0; - } - - if (proxy) - proxy = XP_StripLine (proxy); /* in case it was "hostname: 80" */ - if (socks) - socks = XP_StripLine (socks); - - /* If the hosts are specified as IP numbers, don't try and resolve them. - (Yes, hostnames can't begin with digits.) */ - if (proxy && proxy[0] >= '0' && proxy[0] <= '9') - PR_Free (proxy), proxy = 0; - if (socks && socks[0] >= '0' && socks[0] <= '9') - PR_Free (socks), socks = 0; - - if (proxy && *proxy) - { - /* If there is an HTTP proxy, then we shouldn't try to resolve any - other hosts at all, because they might legitimately be unresolvable. - The HTTP proxy will do all lookups. - */ - if (!net_IsHostResolvable (proxy, context)) - { - sprintf(message, XP_GetString(XP_UNKNOWN_HTTP_PROXY), proxy); - } - } - else - { - /* There is not an HTTP proxy specified. So check the other hosts. - */ - - if (socks && *socks && !net_IsHostResolvable (socks, context)) - { - sprintf(message, XP_GetString(XP_UNKNOWN_SOCKS_HOST), socks); -#ifdef XP_UNIX - PL_strcat (message, XP_GetString(XP_SOCKS_NS_ENV_VAR)); - /* Only Unix has the $SOCKS_NS environment variable. */ -#endif /* XP_UNIX */ - PL_strcat (message, XP_GetString(XP_CONSULT_SYS_ADMIN)); - } - else - { - /* At this point, we're not using a proxy, and either we're not - using a SOCKS host or we're using a resolvable SOCKS host. - So that means that all the usual host names should be resolvable, - and the world is broken if they're not. - */ - char *losers [10]; - int loser_count = 0; - -#ifdef XP_UNIX - char local [255], *local2; - PRHostEnt *hent, hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - - if (gethostname (local, sizeof (local) - 1)) - local [0] = 0; - - /* gethostname() and gethostbyname() often return different data - - on many systems, the former is basename, the latter is FQDN. */ - local2 = 0; - if (local && - (PR_GetHostByName (local, dbbuf, sizeof(dbbuf), &hpbuf) == PR_SUCCESS)) { - hent = &hpbuf; - if (PL_strcmp (local, hent->h_name)) - local2 = PL_strdup (hent->h_name); - } - if (local && *local && !net_IsHostResolvable (local, context)) - losers [loser_count++] = local; - if (local2 && *local2 && !net_IsHostResolvable (local2, context)) - losers [loser_count++] = local2; -#endif /* XP_UNIX */ - - if (!net_IsHostResolvable (test_host_1, context)) - losers [loser_count++] = test_host_1; - if (!net_IsHostResolvable (test_host_2, context)) - losers [loser_count++] = test_host_2; - if (!net_IsHostResolvable (test_host_3, context)) - losers [loser_count++] = test_host_3; - - if (loser_count > 0) - { - if (loser_count > 1) - { - int i; - sprintf(message, XP_GetString(XP_UNKNOWN_HOSTS)); - for (i = 0; i < loser_count; i++) - { - PL_strcat (message, " "); - PL_strcat (message, losers [i]); - PL_strcat (message, "\n"); - } - } - else - { - sprintf(message, XP_GetString(XP_UNKNOWN_HOST), losers[0]); - } - PL_strcat (message, XP_GetString(XP_SOME_HOSTS_UNREACHABLE)); -#ifdef XP_UNIX -# ifdef MOZ_MAY_HAVE_DNS /* compiled on SunOS 4.1.3 */ - if (fe_HaveDNS) - /* Don't talk about $SOCKS_NS in the YP/NIS version. */ -# endif - PL_strcat (message, XP_GetString(XP_SOCKS_NS_ENV_VAR)); - -#ifdef MOZ_MAY_HAVE_DNS /* compiled on SunOS 4.1.3 */ - assert (XP_AppName); - if (fe_HaveDNS) - { - sprintf(temp, XP_GetString(XP_THIS_IS_DNS_VERSION), - XP_AppName); - } - else - { - sprintf(temp, XP_GetString(XP_THIS_IS_YP_VERSION), - XP_AppName); - } - PL_strcat(message, temp); -# endif /* SunOS 4.* */ -#endif /* XP_UNIX */ - PL_strcat (message, XP_GetString(XP_CONSULT_SYS_ADMIN)); - } - -#ifdef XP_UNIX - if (local2) PR_Free (local2); -#endif /* XP_UNIX */ - } - } - - if (proxy) PR_Free (proxy); - if (socks) PR_Free (socks); - - if (*message) - FE_Alert (context, message); - PR_Free (message); -#endif /* XP_UNIX full function wrap */ -} - - -/* shutdown the netlibrary, cancel all - * conections and free all - * memory - */ -PUBLIC void -NET_ShutdownNetLib(void) -{ - ActiveEntry *tmpEntry; - -/* #ifdef XP_WIN */ -#if defined(JAVA) || defined(NS_MT_SUPPORTED) - if (libnet_asyncIO) LIBNET_LOCK(); -#else - LIBNET_LOCK(); -#endif - - if(net_waiting_for_actives_url_list) { - net_AbortWaitingURL(0, TRUE, net_waiting_for_actives_url_list); - XP_ListDestroy(net_waiting_for_actives_url_list); - net_waiting_for_actives_url_list = 0; - } - - if(net_waiting_for_connection_url_list) { - net_AbortWaitingURL(0, TRUE, net_waiting_for_connection_url_list); - XP_ListDestroy(net_waiting_for_connection_url_list); - net_waiting_for_connection_url_list = 0; - } - - /* run through list of - * connections - */ - while((tmpEntry = (ActiveEntry *)XP_ListRemoveTopObject(net_EntryList)) != 0) - { - - if(tmpEntry->proto_impl) - { - (*tmpEntry->proto_impl->interrupt)(tmpEntry); - } - else - { - PR_ASSERT(0); - } - - /* XP_OS2_FIX IBM-MAS: limit length of output to keep from blowing trace buffer! */ - /* TRACEMSG does sprintf upto the length of the buffer, thus passing %s is ok */ - TRACEMSG(("End of transfer, entry (soc=%d, con=%d) being removed from list with %d status: %s", - tmpEntry->socket, tmpEntry->con_sock, tmpEntry->status, - (tmpEntry->URL_s->address ? tmpEntry->URL_s->address : "none"))); - - /* call exit routine since we know we are done */ - net_CallExitRoutineProxy(tmpEntry->exit_routine, - tmpEntry->URL_s, - tmpEntry->status, - tmpEntry->format_out, - tmpEntry->window_id); - net_ReleaseContext(tmpEntry->window_id); - PR_Free(tmpEntry); /* free the no longer active entry */ - } - - XP_ListDestroy(net_EntryList); - net_EntryList = 0; - -#ifdef TRUST_LABELS - /* if there are any URL_s on their list delete them, then delete the list */ - if ( net_URL_sList ) { - URL_Struct *tmpURLs; - XP_List *list_ptr = net_URL_sList; - while((tmpURLs = (URL_Struct *) XP_ListNextObject(list_ptr)) != NULL) { - list_ptr = list_ptr->next; /* get the next object before the current object gets deleted */ - NET_FreeURLStruct( tmpURLs ); /* this will remove it from the list */ - } - XP_ListDestroy( net_URL_sList ); - net_URL_sList = 0; - } -#endif - - /* free any memory in the protocol modules - */ - net_cleanup_reg_protocol_impls(); - -#ifdef MOZILLA_CLIENT - NET_SaveCookies(""); -#if defined(SingleSignon) - SI_SaveSignonData(""); -#endif - GH_SaveGlobalHistory(); -#endif /* MOZILLA_CLIENT */ - - /* purge existing cache files */ - - /* free memory in the tcp routines - */ - NET_CleanupTCP(); - -#ifdef MOZILLA_CLIENT - NET_CleanupCache(); - NET_SetMemoryCacheSize(0); /* free memory cache */ - -#endif /* MOZILLA_CLIENT */ - -#ifdef XP_UNIX - NET_CleanupFileFormat(NULL); -#else - NET_CleanupFileFormat(); -#endif - -/* #ifdef XP_WIN */ -#if defined(JAVA) || defined(NS_MT_SUPPORTED) - if (libnet_asyncIO) LIBNET_UNLOCK(); -#else - LIBNET_UNLOCK(); -#endif -} - -static PRBool warn_on_mailto_post = PR_TRUE; - -extern void -NET_WarnOnMailtoPost(PRBool warn) -{ - warn_on_mailto_post = warn; - return; -} - -/* use a small static array for speed of traversal. - * We rely on the fact that we dont expect ton's of - * protocol implementations to be dynamically added - * so a static size is managable for now. - * - * URL types should really be dynamic so that we dont have - * to define types in net.h - */ -#define MAX_NUMBER_OF_PROTOCOL_IMPLS LAST_URL_TYPE - -typedef struct { - NET_ProtoImpl *impl; - int url_type; -} net_ProtoImplAndTypeAssoc; - -PRIVATE net_ProtoImplAndTypeAssoc net_proto_impls[MAX_NUMBER_OF_PROTOCOL_IMPLS]; -PRIVATE net_number_of_proto_impls = 0; - -/* registers a protocol impelementation for a particular url_type - * see NET_URL_Type() for types - */ -PR_IMPLEMENT(void) - NET_RegisterProtocolImplementation(NET_ProtoImpl *impl, int for_url_type) -{ - - if(!impl || for_url_type < 0 || for_url_type > LAST_URL_TYPE) - { - PR_ASSERT(0); - return; - } - - net_proto_impls[net_number_of_proto_impls].impl = impl; - net_proto_impls[net_number_of_proto_impls].url_type = for_url_type; - - net_number_of_proto_impls++; -} - -/* get a handle to a protocol implemenation - */ -NET_ProtoImpl * -net_get_protocol_impl(int for_url_type) -{ - int count=0; - - /* if we ever get around to doing dynamic protocol loading - * this would be a good place to plug it in. - * just load a DLL with the implementation and - * return the handle. - * The integer URL_TYPE would need to be replaced with - * strings or some other identifier so that it can all be - * handled dynamically - */ - - for(; count < net_number_of_proto_impls; count++) - { - if(net_proto_impls[count].url_type == for_url_type) - return net_proto_impls[count].impl; - } - -/* PR_ASSERT(0); *//* should always find one */ - return NULL; -} - -void -net_cleanup_reg_protocol_impls(void) -{ - int count=0; - - for(; count < net_number_of_proto_impls; count++) - { - (*net_proto_impls[count].impl->cleanup)(); - } - -} - -/* register and begin a transfer. - * - * returns negative if the transfer errored or finished during the call - * otherwise returns 0 or greater. - * - * A URL, an output format, a window context pointer, and a callback routine - * should be passed in. - */ - -PUBLIC int -NET_GetURL (URL_Struct *URL_s, - FO_Present_Types output_format, - MWContext *window_id, - Net_GetUrlExitFunc* exit_routine) -{ - int status=MK_MALFORMED_URL_ERROR; - int pacf_status=TRUE; - int type; - int cache_method=0; - ActiveEntry *this_entry=0; /* a new entry */ - char *new_address; - int processcallbacks = 0; - Bool confirm; - Bool load_background; - char *confirmstring; - - if ( get_url_disabled ) { - /* So that external URL's can't be loaded */ - return -1; - } - - TRACEMSG(("Entering NET_GetURL")); - LIBNET_LOCK(); - - -#ifdef XP_WIN - /* this runs a timer to periodically call the netlib - * so that we still get events even when OnIdle is never - * called - */ - NET_SetNetlibSlowKickTimer(TRUE); -#endif - - PR_ASSERT (URL_s && URL_s->address); -#ifdef MOZILLA_CLIENT - if ( URL_s->mailto_post && warn_on_mailto_post) { - confirmstring = NULL; - confirm = FALSE; - - StrAllocCopy(confirmstring, XP_GetString(XP_CONFIRM_MAILTO_POST_1)); - StrAllocCat(confirmstring, XP_GetString(XP_CONFIRM_MAILTO_POST_2)); - - if ( confirmstring ) { - confirm = FE_Confirm(window_id, confirmstring); - PR_Free(confirmstring); - } - - if ( !confirm ) { - /* abort url - */ - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_INTERRUPTED, - output_format, - window_id); - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_INTERRUPTED); - } - } -#endif /* MOZILLA_CLIENT */ -#ifdef EDITOR - /* First time here - get our strings out of XP_MSG */ - if (XP_NEW_DOC_URL == NULL) { - StrAllocCopy(XP_NEW_DOC_URL, XP_GetString(XP_EDIT_NEW_DOC_URL)); - } - if (XP_NEW_DOC_NAME == NULL) { - StrAllocCopy(XP_NEW_DOC_NAME, XP_GetString(XP_EDIT_NEW_DOC_NAME)); - } - - if( !window_id->is_new_document ) { - /* Test for "Untitled" URL */ - if( 0 == PL_strcmp(URL_s->address, XP_NEW_DOC_NAME) ) { - /* Change request to load "file:///Untitled" into "about:editfilenew" */ - PR_Free(URL_s->address); - URL_s->address = PL_strdup(XP_NEW_DOC_URL); - /* Set flag so FE can quickly detect new doc */ - window_id->is_new_document = TRUE; - } - else if( 0 == PL_strcmp(URL_s->address, XP_NEW_DOC_URL) ) { - window_id->is_new_document = TRUE; - } -#if 0 - /* This is bad! We run through here when loading images, - which shares the context, - so we shouldn't clear the new document flag */ - else { - /* Be sure this is FALSE if not a new document */ - window_id->is_new_document = FALSE; - } -#endif - } - - /* Hack to allow special URL for new Editor doc - * and still allow filtering of non-editable doc types - * All editor GetUrl calls should use FO_EDIT or FO_CACHE_AND_EDIT - * When we know we have a new document, we change it to FO_CACHE_AND_PRESENT - * so it can load the "about:" url without complaining - */ - if( EDT_IS_EDITOR(window_id) && window_id->is_new_document && - (output_format == FO_EDIT || output_format == FO_CACHE_AND_EDIT) ){ - output_format = FO_CACHE_AND_PRESENT; - } -#endif -#ifdef MOZILLA_CLIENT - - /* Hack. Proxy AutoDiscovery. If we want to use proxy autodiscovery - * simply point the MKproxy_ac_url to the MK_padpacURL and use all - * all the same logic. */ - if(!MKproxy_ac_url && NET_UsingPadPac()) { - NET_SetNoProxyFailover(); - MKproxy_ac_url=MK_padPacURL; - } - - /* Initialize global/auto proxy codepath. This gets called for every - * NET_GetURL() call. */ - if ( -#ifdef MOZ_OFFLINE - !NET_IsOffline() && -#endif /* MOZ_OFFLINE */ - /* Do we even have auto config urls set? If not, don't bother - * continuing. See mkautocf.c for more info. */ - (MKglobal_config_url || MKproxy_ac_url) - && (CLEAR_CACHE_BIT(output_format) == FO_PRESENT) - && (!(type = NET_URL_Type(URL_s->address)) - || type == HTTP_TYPE_URL - HG77355 - || type == GOPHER_TYPE_URL - || type == FTP_TYPE_URL - || type == WAIS_TYPE_URL - || type == URN_TYPE_URL - || type == NFS_TYPE_URL - || type == POP3_TYPE_URL - || (type == NEWS_TYPE_URL && !PL_strncasecmp(URL_s->address, "snews:", 6))) - ) { - int status=-1; - /* Figure out which auto config we're dealing (global or pac file - * with and load it. - * If the status is other than -1, the load started and the - * originally requested url will be loaded by the pre_exit_fn() - * that is in the proxy auto config URL_Struct. */ - if(MKglobal_config_url && !NET_GlobalAcLoaded) { - NET_GlobalAcLoaded=TRUE; - status=NET_LoadProxyConfig(MKglobal_config_url, - URL_s, - output_format, - window_id, - exit_routine); - } - /* else we know we're dealing with a proxyACL (the other - * possibility in the above if statement) so see if it's - * loaded or not. Also make sure we want to use it (i.e. style is - * automatic or if we want to use a proxy autodiscovery url). */ - else if(!NET_ProxyAcLoaded - && ( (MKproxy_style == PROXY_STYLE_AUTOMATIC) - || !MKproxy_style - || NET_UsingPadPac() ) ) { - NET_ProxyAcLoaded=TRUE; - status=NET_LoadProxyConfig(MKproxy_ac_url, - URL_s, - output_format, - window_id, - exit_routine); - } - if(status != -1) - LIBNET_UNLOCK_AND_RETURN(status); - } /* End big proxy if */ - -#endif /* MOZILLA_CLIENT */ - - load_background = URL_s->load_background; - - /* kill leading and trailing spaces in the URL address - */ - new_address = XP_StripLine(URL_s->address); - if(new_address != URL_s->address) - { - memmove(URL_s->address, new_address, PL_strlen(new_address)+1); - } - - /* get the protocol type - */ - type = NET_URL_Type(URL_s->address); - - if (URL_s->method == URL_HEAD_METHOD && - type != HTTP_TYPE_URL HG42421 && type != FILE_TYPE_URL) { - /* We can only do HEAD on http connections. */ - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_MALFORMED_URL_ERROR, /* Is this right? ### */ - output_format, - window_id); - /* increment since it will get decremented */ - NET_TotalNumberOfProcessingURLs++; - net_CheckForWaitingURL(window_id, 0, load_background); - - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_MALFORMED_URL_ERROR); - } - - /* XP_OS2_FIX IBM-MAS:limit length of output to keep from blowing trace buffer! */ - TRACEMSG(("Called NET_GetURL with FO: %d URL %-.1900s --", output_format, URL_s->address)); - TRACEMSG(("with method: %d, and post headers: %s", URL_s->method, - URL_s->post_headers ? URL_s->post_headers : "none")); - - /* if this URL is for prefetching, put it on the wait queue until - * everything else is done - */ - if(URL_s->priority == Prefetch_priority) - { - LIBNET_UNLOCK_AND_RETURN(net_push_url_on_wait_queue(type, - URL_s, - output_format, - window_id, - exit_routine)); - } - -#if defined(SMOOTH_PROGRESS) - PM_StartBinding(window_id, URL_s); -#endif - - /* put a limit on the total number of active urls - */ - if((NET_TotalNumberOfProcessingURLs >= MAX_NUMBER_OF_PROCESSING_URLS) && - ((output_format & FO_ONLY_FROM_CACHE) == 0)) - { - LIBNET_UNLOCK_AND_RETURN(net_push_url_on_wait_queue(type, - URL_s, - output_format, - window_id, - exit_routine)); - } - - /* if we get this far then we should add the URL - * to the number of processing URL's - */ - NET_TotalNumberOfProcessingURLs++; - - if(type == VIEW_SOURCE_TYPE_URL) - { - /* this is a view-source: URL - * strip off the front stuff - */ - char *new_address=0; - /* the colon is guarenteed to be there */ - StrAllocCopy(new_address, PL_strchr(URL_s->address, ':')+1); - FREE(URL_s->address); - URL_s->address = new_address; - URL_s->allow_content_change = TRUE; - - type = NET_URL_Type(URL_s->address); - - /* remap the format out for the fo_present type - */ - if(CLEAR_CACHE_BIT(output_format) == FO_PRESENT) - output_format = FO_VIEW_SOURCE; - } - - if(type == MARIMBA_TYPE_URL) - { - /* If this a castanet URL, and Netcaster is not installed, try http:// - * Otherwise, we let the castanet protocol handler do its thing. - */ - if( ! FE_IsNetcasterInstalled() ) - { - char *new_address; - /* Replace castanet:// with http:// */ - /* Allocate space for 'http' + the rest of the string */ - new_address = PR_Malloc(PL_strlen(PL_strchr(URL_s->address, ':'))+5); - - PR_ASSERT(new_address); - *new_address=0; - PL_strcat(new_address,"http"); - PL_strcat(new_address,PL_strchr(URL_s->address, ':')); - - FREE(URL_s->address); - URL_s->address = new_address; - - type = NET_URL_Type(URL_s->address); - } - } - - if(type == NETHELP_TYPE_URL) - { - /* this is a nethelp: URL - * separate into its component parts, the mapping file in URL_s->address, - * and the topic in URL_s->fe_data - */ - - if (NET_ParseNetHelpURL(URL_s) == MK_OUT_OF_MEMORY) { - LIBNET_UNLOCK_AND_RETURN(MK_OUT_OF_MEMORY); - } - - type = NET_URL_Type(URL_s->address); - - output_format = FO_LOAD_HTML_HELP_MAP_FILE; - } - -#ifdef MOZILLA_CLIENT - if( -#if defined(MOZ_LITE) && defined(XP_UNIX) - (type == NEWS_TYPE_URL && FE_AlternateNewsReader(URL_s->address)) || -#endif -#if defined(XP_WIN) || defined(XP_MAC) || defined(XP_OS2) - FE_UseExternalProtocolModule(window_id, output_format, URL_s, exit_routine) || -#endif - NPL_HandleURL(window_id, output_format, URL_s, exit_routine)) - { - /* don't call the exit routine since the - * External protocol module will call it - */ - net_CheckForWaitingURL(window_id, 0, load_background); - - LIBNET_UNLOCK_AND_RETURN(-1); /* all done */ - } - - if(NET_TimeBombActive) - { - /* Timebomb has gone off!! - * - * limit URL's to FTP and anything in our domains - */ - if(type != FTP_TYPE_URL - && type != ABOUT_TYPE_URL - && type != FILE_TYPE_URL - && type != MAILBOX_TYPE_URL - && type != IMAP_TYPE_URL - && type != POP3_TYPE_URL - && type != MOCHA_TYPE_URL - && type != DATA_TYPE_URL - && type != HTML_DIALOG_HANDLER_TYPE_URL - && type != HTML_PANEL_HANDLER_TYPE_URL - HG87237 - - && !PL_strcasestr(URL_s->address, "mcom.com") - && !PL_strcasestr(URL_s->address, "netscape.com")) - { - char * alert = NET_ExplainErrorDetails(MK_TIMEBOMB_URL_PROHIBIT); - - FE_Alert(window_id, alert); - FREE(alert); - - /* we need at least an address - * if we don't have it exit this routine - */ - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_TIMEBOMB_URL_PROHIBIT, - output_format, - window_id); - - net_CheckForWaitingURL(window_id, 0, load_background); - - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_TIMEBOMB_URL_PROHIBIT); - } - } - - /* put up security dialog boxes to tell the user - * about transitions - * - * only do this for FO_PRESENT objects and objects - * not coming out of history - * and also make sure that the object is not being asked - * for twice via the "304 use local copy" method - */ - if(output_format == FO_CACHE_AND_PRESENT - && !URL_s->history_num - && !URL_s->use_local_copy) - { - Bool continue_loading_url = TRUE; - History_entry * h = SHIST_GetCurrent(&window_id->hist); - - /* this is some protection against the "mail document" - * feature popping up a dialog warning about an insecure - * post. - * If the type is MAILTO and the first post header - * begins with "Content-type" then it is a post from - * inside a form, otherwise it is just a normal MAILTO - * - * And, of course, anything not a MAILTO link will fall - * into the if as well. - */ - if(type != MAILTO_TYPE_URL - || !URL_s->post_headers - || !PL_strncmp("Content-type", URL_s->post_headers, 12)) - { - if(h HG52423) - { - /* if this is not a secure transaction */ - if(HG76373 - && !(type == NEWS_TYPE_URL && - toupper(*URL_s->address) == 'S') ) - { - if(URL_s->method == URL_POST_METHOD) - { - continue_loading_url = HG72388 - } - else if(!URL_s->redirecting_url - && type != MAILTO_TYPE_URL - && type != ABOUT_TYPE_URL - && type != MOCHA_TYPE_URL) - { - /* don't put up in case of redirect or mocha - */ - continue_loading_url = HG52223 - } - } - } - else - { - /* put up a dialog for all insecure posts - * except news and mail posts - */ - if(URL_s->method == URL_POST_METHOD - HG53535 - && type != INTERNAL_NEWS_TYPE_URL - && type != NEWS_TYPE_URL - && type != HTML_DIALOG_HANDLER_TYPE_URL - && type != HTML_PANEL_HANDLER_TYPE_URL - && type != MAILTO_TYPE_URL) - { - continue_loading_url = (Bool)SECNAV_SecurityDialog(window_id, SD_INSECURE_POST_FROM_INSECURE_DOC); - } - } - - if(!continue_loading_url) - { - /* abort url - */ - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_INTERRUPTED, - output_format, - window_id); - net_CheckForWaitingURL(window_id, 0, load_background); - - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_INTERRUPTED); - } - } - } -#endif /* MOZILLA_CLIENT */ - - /* - * if the string is not a valid URL we are just going - * to punt, so we may as well try it as http - */ - if(type==0) - { - char *munged; - -#define INT_SEARCH_URL "http://cgi.netscape.com/cgi-bin/url_search.cgi?search=" -#define INT_SEARCH_URL_TYPE HTTP_TYPE_URL - - if(!(munged = (char*) PR_Malloc(PL_strlen(URL_s->address)+20))) - { - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_OUT_OF_MEMORY, - output_format, - window_id); - - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_OUT_OF_MEMORY); - } - -#ifdef EDITOR - /* Some platforms resize a window while creating it. An example is - * Windows in Communicator 4.0. On these platforms, - * the Composer View Document Source window can end up here with a - * bizarre (and potentially localized) URL of "View Document Source". - * If we allow this URL to be resolved, it will cause a search engine - * to be triggered. - * Fortunately, edit_view_source_hack is TRUE iff the context is - * a Composer View Document Source window. - */ - if ( window_id->edit_view_source_hack ){ - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_INTERRUPTED, - output_format, - window_id); - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_INTERRUPTED); - } -#endif - - /* if it starts with a question mark or has a space it's - * a search URL - */ - if(*URL_s->address == '?' || PL_strchr(URL_s->address, ' ')) - { - /* URL contains spaces. Treat it as search text. */ - char *escaped; - - if(*URL_s->address == '?') - escaped = NET_Escape(URL_s->address+1, URL_XPALPHAS); - else - escaped = NET_Escape(URL_s->address, URL_XPALPHAS); - - if(escaped) - { - char *pUrl; - FREE(munged); - if ( (PREF_OK == PREF_CopyCharPref(pref_searchUrl,&pUrl)) - && pUrl) { - munged = PR_smprintf("%s%s", pUrl, escaped); - FREE(escaped); - PR_Free(pUrl); - } - type = INT_SEARCH_URL_TYPE; - } - } - else - { - if(*URL_s->address == '/') - { - PL_strcpy(munged, "file:"); - type = FILE_TYPE_URL; - } - else if(!PL_strncasecmp(URL_s->address, "ftp", 3)) - { - PL_strcpy(munged, "ftp://"); - type = FTP_TYPE_URL; - } - else if(!PL_strncasecmp(URL_s->address, "gopher", 6)) - { - PL_strcpy(munged, "gopher://"); - type = GOPHER_TYPE_URL; - } - else if(!PL_strncasecmp(URL_s->address, "news", 4) - || !PL_strncasecmp(URL_s->address, "nntp", 4)) - { - PL_strcpy(munged, "news://"); - type = NEWS_TYPE_URL; - } - else - { - PL_strcpy(munged, "http://"); - type = HTTP_TYPE_URL; - } - - PL_strcat(munged, URL_s->address); - } - - PR_Free(URL_s->address); - URL_s->address = munged; - -#ifdef MOZILLA_CLIENT - /* Try the external protocol handlers again, since with the - * newly appended protocol, they might work this time. - */ - if( - #if defined(XP_WIN) || defined(XP_MAC) - FE_UseExternalProtocolModule(window_id, output_format, URL_s, exit_routine) || - #endif - NPL_HandleURL(window_id, output_format, URL_s, exit_routine)) - { - /* don't call the exit routine since the - * External protocol module will call it - */ - net_CheckForWaitingURL(window_id, 0, load_background); - - LIBNET_UNLOCK_AND_RETURN(-1); /* all done */ - } -#endif /* MOZILLA_CLIENT */ - } - - if(type == HTTP_TYPE_URL || type == FILE_TYPE_URL || - HG73277 || type == GOPHER_TYPE_URL -#ifdef JAVA -#if 0 -/* DHIREN */ /* Kludge because castanet URLs don't work when there's no Java */ - || type == MARIMBA_TYPE_URL -#endif -#endif - ) - add_slash_to_URL(URL_s); - -#ifdef MOZILLA_CLIENT - /* - * If this is a resize-reload OR a view-source URL, try to use the - * URL's wysiwyg: counterpart. - */ - URL_s->resize_reload = (URL_s->force_reload == NET_RESIZE_RELOAD); - if(URL_s->wysiwyg_url && - (URL_s->resize_reload == TRUE || - CLEAR_CACHE_BIT(output_format) == FO_VIEW_SOURCE)) - { - StrAllocCopy(URL_s->address, URL_s->wysiwyg_url); - type = WYSIWYG_TYPE_URL; - } - - /* the FE's were screwing up the use of force_reload - * to get around a bug in the scroll to named anchor - * code. So I gave them an enum NET_RESIZE_RELOAD - * that they could use instead. NET_RESIZE_RELOAD - * should be treated just like NET_DONT_RELOAD within - * the netlib - */ - if((URL_s->force_reload == NET_RESIZE_RELOAD) || - (URL_s->force_reload == NET_CACHE_ONLY_RELOAD)) - URL_s->force_reload = NET_DONT_RELOAD; - - /* Before looking in the cache, make sure we check the - * special cases to know if - * we're allowed to use modified content. - * Two cases so far: a view-source URL, and - * any non-internal URL. Non-internal URLs are - * the result of link clicks, drag-and-drop, etc. - */ - if ((CLEAR_CACHE_BIT(output_format) == FO_VIEW_SOURCE) || - (!URL_s->internal_url && - (CLEAR_CACHE_BIT(output_format) != FO_MAIL_TO))) - URL_s->allow_content_change = TRUE; - /* check for the url in the cache - */ - if (type != FILE_TYPE_URL) - cache_method = NET_FindURLInCache(URL_s, window_id); - - if (!cache_method) - { - TIMING_MESSAGE(("cache,%.64s,%08x,not found", URL_s->address, window_id)); - - /* cache testing stuff */ - if(NET_IsCacheTraceOn()) - { - char *buf = 0; - StrAllocCopy(buf, XP_GetString(XP_URL_NOT_FOUND_IN_CACHE)); - StrAllocCat(buf, URL_s->address); - FE_Alert(window_id, buf); - FREE(buf); - } - - /* if wysiwyg, there must be a cache entry or we retry the real url */ - if(type == WYSIWYG_TYPE_URL) - { - const char *real_url = LM_SkipWysiwygURLPrefix(URL_s->address); - - /* XXX can't use StrAllocCopy because it frees dest first */ - if (real_url && (new_address = PL_strdup(real_url)) != NULL) - { - /* cache miss: we must clear this flag so scripts rerun */ - URL_s->resize_reload = FALSE; - - PR_Free(URL_s->address); - URL_s->address = new_address; - FREE_AND_CLEAR(URL_s->wysiwyg_url); - /* - * Since the call to NET_GetURL will increment the - * following counter again, we decrement it so as not - * to overcount. - */ - NET_TotalNumberOfProcessingURLs--; - LIBNET_UNLOCK_AND_RETURN( - NET_GetURL(URL_s, output_format, window_id, exit_routine) - ); - } - } - } - - /* if cache_method is non zero then we have this URL cached. Use - * the bogus cache url type - * - * This nasty bit of logic figures out if we really - * need to reload it or if we can use the cached copy - */ - else - { - if(URL_s->use_local_copy || output_format & FO_ONLY_FROM_CACHE) - { - /* the cached file is valid so use it unilaterally - */ - TIMING_MESSAGE(("cache,%.64s,%08x,valid", URL_s->address, window_id)); - type = cache_method; - } - else if(URL_s->real_content_length > URL_s->content_length) - { - /* cache testing stuff */ - if(NET_IsCacheTraceOn()) - { - char *buf = 0; - StrAllocCopy(buf, XP_GetString(XP_PARTIAL_CACHE_ENTRY)); - StrAllocCat(buf, URL_s->address); - FE_Alert(window_id, buf); - FREE(buf); - } - -#ifdef NU_CACHE - URL_s->cache_object = 0; -#else - URL_s->memory_copy = 0; -#endif - cache_method = 0; - TRACEMSG(("Getting the rest of a partial cache file")); - TIMING_MESSAGE(("cache,%.64s,%08x,partial", URL_s->address, window_id)); - } - else if (URL_s->force_reload != NET_DONT_RELOAD) - { - TRACEMSG(("Force reload flag set. Checking server to see if modified")); - TIMING_MESSAGE(("cache,%.64s,%08x,forced reload", - URL_s->address, window_id)); - - /* cache testing stuff */ - if(NET_IsCacheTraceOn()) - { - char *buf = 0; - StrAllocCopy(buf, XP_GetString(XP_CHECKING_SERVER__FORCE_RELOAD)); - StrAllocCat(buf, URL_s->address); - FE_Alert(window_id, buf); - FREE(buf); - } - - /* strip the cache file and - * memory pointer - */ - if (type == WYSIWYG_TYPE_URL) - type = cache_method; - else - { - FREE_AND_CLEAR(URL_s->cache_file); -#ifdef NU_CACHE - URL_s->cache_object = 0; -#else - URL_s->memory_copy = 0; -#endif - cache_method = 0; - } - } - else if(URL_s->expires) - { - time_t cur_time = time(NULL); - - if(cur_time > URL_s->expires) - { - FREE_AND_CLEAR(URL_s->cache_file); -#ifdef NU_CACHE - URL_s->cache_object = 0; -#else - URL_s->memory_copy = 0; -#endif - URL_s->expires = 0; /* remove cache reference */ - cache_method = 0; - - TIMING_MESSAGE(("cache,%.64s,%08x,expired", - URL_s->address, window_id)); - - /* cache testing stuff */ - if(NET_IsCacheTraceOn()) - { - char *buf = 0; - StrAllocCopy(buf, XP_GetString(XP_OBJECT_HAS_EXPIRED)); - StrAllocCat(buf, URL_s->address); - FE_Alert(window_id, buf); - FREE(buf); - } - } - else - { - /* the cached file is valid so use it unilaterally - */ - TIMING_MESSAGE(("cache,%.64s,%08x,valid", - URL_s->address, window_id)); - - type = cache_method; - } - } - else if((NET_CacheUseMethod == CU_NEVER_CHECK || URL_s->history_num) - && !URL_s->expires) - { - TIMING_MESSAGE(("cache,%.64s,%08x,valid", - URL_s->address, window_id)); - - type = cache_method; - } - else if(NET_CacheUseMethod == CU_CHECK_ALL_THE_TIME - && CLEAR_CACHE_BIT(output_format) == FO_PRESENT - && (type == HTTP_TYPE_URL HG73738) - && !URL_s->expires) - { - /* cache testing stuff */ - if(NET_IsCacheTraceOn()) - { - char *buf = 0; - StrAllocCopy(buf, XP_GetString(XP_CHECKING_SERVER_CACHE_ENTRY)); - StrAllocCat(buf, URL_s->address); - FE_Alert(window_id, buf); - FREE(buf); - } - - /* if it's an HTTP URL and its not an Internal image - * and it's not being asked for with ONLY FROM CACHE - * and it's not coming out of the history - * and it doesn't have an expiration date... - * FORCE Reload it - */ - TIMING_MESSAGE(("cache,%.64s,%08x,forced reload:non-history http", - URL_s->address, window_id)); - - TRACEMSG(("Non history http file found. Force reloading it ")); - /* strip the cache file and - * memory pointer - */ - FREE_AND_CLEAR(URL_s->cache_file); -#ifdef NU_CACHE - URL_s->cache_object = 0; -#else - URL_s->memory_copy = 0; -#endif - cache_method = 0; - - } - else if(!URL_s->last_modified - && CLEAR_CACHE_BIT(output_format) == FO_PRESENT - && (type == HTTP_TYPE_URL HG62522) -#ifdef MOZ_OFFLINE - && !NET_IsOffline() -#endif /* MOZ_OFFLINE */ - ) /* *X* check for is offline */ - { - TIMING_MESSAGE(("cache,%.64s,%08x,forced reload:non-history cgi", - URL_s->address, window_id)); - - TRACEMSG(("Non history cgi script found (probably)." - " Force reloading it ")); - /* cache testing stuff */ - if(NET_IsCacheTraceOn()) - { - char *buf = 0; - StrAllocCopy(buf, XP_GetString(XP_CHECKING_SERVER__LASTMOD_MISS)); - StrAllocCat(buf, URL_s->address); - FE_Alert(window_id, buf); - FREE(buf); - } - - /* strip the cache file and - * memory pointer - */ - FREE_AND_CLEAR(URL_s->cache_file); -#ifdef NU_CACHE - URL_s->cache_object = 0; -#else - URL_s->memory_copy = 0; -#endif - URL_s->expires = 0; /* remove cache reference */ - cache_method = 0; - } - else - { - /* the cached file is valid so use it unilaterally - */ - TIMING_MESSAGE(("cache,%.64s,%08x,valid", URL_s->address, window_id)); - - type = cache_method; - } - } -#endif /* MOZILLA_CLIENT */ - - /* - * If the object should only come out of the cache - * we should abort now if there is not a cache object - */ - if(output_format & FO_ONLY_FROM_CACHE) - { - TRACEMSG(("object called with ONLY_FROM_CACHE format out")); - - if(!cache_method) - { - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_OBJECT_NOT_IN_CACHE, - output_format, - window_id); - net_CheckForWaitingURL(window_id, type, load_background); - - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_OBJECT_NOT_IN_CACHE); - } - else - { - /* remove the ONLY_FROM_CACHE designation and replace - * it with CACHE_AND.. so that we go through the cacheing - * module again so that we can memory cache disk objects - * and do the right thing in general - */ - output_format = CLEAR_PRESENT_BIT(output_format,FO_ONLY_FROM_CACHE); - output_format = SET_PRESENT_BIT(output_format,FO_CACHE_ONLY); - } - } - - /* put a limit on the total number of open connections - */ - if(!net_is_one_url_allowed_to_run(window_id, type)) - { - NET_TotalNumberOfProcessingURLs--; /* waiting not processing */ - LIBNET_UNLOCK_AND_RETURN(net_push_url_on_wait_queue(type, - URL_s, - output_format, - window_id, - exit_routine)); - } - - /* start a new entry */ - this_entry = PR_NEW(ActiveEntry); - if(!this_entry) - { - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_OUT_OF_MEMORY, - output_format, - window_id); - - net_ReleaseContext(window_id); - LIBNET_UNLOCK_AND_RETURN(MK_OUT_OF_MEMORY); - } - - /* init new entry */ - memset(this_entry, 0, sizeof(ActiveEntry)); - this_entry->URL_s = URL_s; - this_entry->socket = NULL; - this_entry->con_sock = NULL; - this_entry->exit_routine = exit_routine; - this_entry->window_id = window_id; - this_entry->protocol = type; - - /* set the format out for the entry - */ - this_entry->format_out = output_format; - - /* set it busy */ - this_entry->busy = TRUE; - - /* add it to the processing list now - */ - XP_ListAddObjectToEnd(net_EntryList, this_entry); - - /* Set the timer to call NET_ProcessNet after we - * have submitted a network request. - * BUG #123826 - */ -#if defined(XP_UNIX) - /* temporarily use busy poll to ease transition */ - NET_SetCallNetlibAllTheTime(window_id, "mkgeturl"); -#endif - - - - /* this will protect against multiple posts unknown to the - * user - * - * check if the method is post and it came from the - * history and it isn't coming from the cache - */ - if(URL_s->method == URL_POST_METHOD - && !URL_s->expires - && !cache_method - && URL_s->history_num) - { - if(URL_s->force_reload != NET_DONT_RELOAD) - { - if(!FE_Confirm(window_id, XP_GetString(XP_CONFIRM_REPOST_FORMDATA))) - { - XP_ListRemoveObject(net_EntryList, this_entry); - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_INTERRUPTED, - output_format, - window_id); - /* will get decremented */ - net_CheckForWaitingURL(window_id, this_entry->protocol, - load_background); - - net_ReleaseContext(window_id); - PR_Free(this_entry); /* not needed any more */ - - LIBNET_UNLOCK_AND_RETURN(MK_INTERRUPTED); - } - /* otherwise fall through and repost - */ - } - else - { - NET_StreamClass * stream; - char buffer[1000]; - - StrAllocCopy(URL_s->content_type, TEXT_HTML); - stream = NET_StreamBuilder(CLEAR_CACHE_BIT(output_format), - URL_s, - window_id); - if(stream) - { - PL_strcpy(buffer, XP_GetString(XP_HTML_MISSING_REPLYDATA)); - (*stream->put_block)(stream, - buffer, - PL_strlen(buffer)); - (*stream->complete)(stream); - } - - XP_ListRemoveObject(net_EntryList, this_entry); - - net_CallExitRoutineProxy(exit_routine, - URL_s, - MK_INTERRUPTED, - output_format, - window_id); - net_CheckForWaitingURL(window_id, this_entry->protocol, - load_background); - - net_ReleaseContext(window_id); - PR_Free(this_entry); /* not needed any more */ - - LIBNET_UNLOCK_AND_RETURN(MK_INTERRUPTED); - } - } - -redo_load_switch: /* come here on file/ftp retry */ - - /* This code path handles the case when a pac/global file has been loaded - * and we now want to use it in for a request. If we find a proxy/socks - * server to use, we call NET_HTTPLoad here, skipping the below switch. - * See mkautocf.c for more info. */ - pacf_status = TRUE; - if ((NET_ProxyAcLoaded || NET_GlobalAcLoaded) - && (this_entry->protocol == HTTP_TYPE_URL - HG62363 - || this_entry->protocol == GOPHER_TYPE_URL - || this_entry->protocol == FTP_TYPE_URL - || this_entry->protocol == WAIS_TYPE_URL - || this_entry->protocol == URN_TYPE_URL - || this_entry->protocol == NFS_TYPE_URL - || (this_entry->protocol == NEWS_TYPE_URL - && !PL_strncasecmp(URL_s->address, "snews:", 6) - ) - ) - && ((this_entry->proxy_conf = - pacf_find_proxies_for_url(window_id, URL_s)) != NULL) - && (pacf_status = pacf_get_proxy_addr(window_id, - this_entry->proxy_conf, - &this_entry->proxy_addr, - &this_entry->socks_host, - &this_entry->socks_port)) != 0 - && this_entry->proxy_addr - ) - { - TRACEMSG(("PAC returned \"%s\" for \"%s\".", this_entry->proxy_conf, URL_s->address)); - HG24242 - - /* Everything else except SNEWS gets loaded by HTTP loader, - * including HTTPS. */ - if (this_entry->protocol != NEWS_TYPE_URL) { - this_entry->proto_impl = net_get_protocol_impl(HTTP_TYPE_URL); - } else { - this_entry->proto_impl = net_get_protocol_impl(NEWS_TYPE_URL); - } - - if(this_entry->proto_impl) - status = (*this_entry->proto_impl->init)(this_entry); - } - else if ( pacf_status == FALSE && NET_GetNoProxyFailover() == TRUE ) - { - status = MK_UNABLE_TO_LOCATE_PROXY; - FE_Alert(window_id, XP_GetString(XP_BAD_AUTOCONFIG_NO_FAILOVER)); - } - else - { - char *proxy_address = NULL; - /* If this url struct indicates that it doesn't want to use a proxy, - * skip it. */ - if (!this_entry->URL_s->bypassProxy) { - proxy_address = NET_FindProxyHostForUrl(type, this_entry->URL_s->address); - } - if(proxy_address) - { - this_entry->protocol = HTTP_TYPE_URL; - this_entry->proxy_addr = proxy_address; - } - - this_entry->proto_impl = net_get_protocol_impl(this_entry->protocol); - - if(this_entry->proto_impl) - { - status = (*this_entry->proto_impl->init)(this_entry); - } - else - { - /* bad url */ - URL_s->error_msg = - NET_ExplainErrorDetails(MK_MALFORMED_URL_ERROR, - this_entry->URL_s->address); - status = MK_MALFORMED_URL_ERROR; - this_entry->status = MK_MALFORMED_URL_ERROR; - } - } - - /* the entry is no longer busy - */ - this_entry->busy = FALSE; - -#ifdef MOZILLA_CLIENT - /* OH NASTY A GOTO! - * If we went into load file and what we really wanted to do - * was use FTP, LoadFile will return MK_USE_FTP_INSTEAD so - * we will go back up to the beginning of the switch and - * use ftp instead - */ - if(status == MK_USE_FTP_INSTEAD) - { - type = FTP_TYPE_URL; - this_entry->protocol = type; /* change protocol designator */ - this_entry->status = 0; /* reset */ - goto redo_load_switch; - } - else -#endif /* MOZILLA_CLIENT */ - if(this_entry->status == MK_USE_COPY_FROM_CACHE) - { - TRACEMSG(("304 Not modified recieved using cached entry\n")); - -#ifdef MOZILLA_CLIENT - NET_RefreshCacheFileExpiration(this_entry->URL_s); -#endif /* MOZILLA_CLIENT */ - - /* turn off force reload by telling it to use local copy - */ - this_entry->URL_s->use_local_copy = TRUE; - - /* restart the transfer - */ - XP_ListRemoveObject(net_EntryList, this_entry); - status = NET_GetURL(this_entry->URL_s, - this_entry->format_out, - this_entry->window_id, - this_entry->exit_routine); - - net_CheckForWaitingURL(this_entry->window_id, - this_entry->protocol, - this_entry->URL_s->load_background); - - PR_Free(this_entry); - LIBNET_UNLOCK_AND_RETURN(0); - } - else if(this_entry->status == MK_DO_REDIRECT) - { - /* this redirect should just call GetURL again - */ - int status; - XP_ListRemoveObject(net_EntryList, this_entry); - status =NET_GetURL(this_entry->URL_s, - this_entry->format_out, - this_entry->window_id, - this_entry->exit_routine); - net_CheckForWaitingURL(this_entry->window_id, - this_entry->protocol, - load_background); - PR_Free(this_entry); /* not needed any more */ - LIBNET_UNLOCK_AND_RETURN(0); - } - else if(this_entry->status == MK_TOO_MANY_OPEN_FILES) - { - /* Queue this URL so it gets tried again - */ - XP_ListRemoveObject(net_EntryList, this_entry); - status = net_push_url_on_wait_queue( - NET_URL_Type(this_entry->URL_s->address), - this_entry->URL_s, - this_entry->format_out, - this_entry->window_id, - this_entry->exit_routine); - NET_TotalNumberOfProcessingURLs--; - PR_Free(this_entry); - LIBNET_UNLOCK_AND_RETURN(status); - } - else if(this_entry->status == MK_OFFLINE) - { - /* Stop the stars and put up a nice message - */ - XP_ListRemoveObject(net_EntryList, this_entry); - { - if (window_id->type != MWContextMail && window_id->type != MWContextMailMsg && - (CLEAR_CACHE_BIT(output_format) != FO_INTERNAL_IMAGE) && - (CLEAR_CACHE_BIT(output_format) != FO_EMBED) && - (CLEAR_CACHE_BIT(output_format) != FO_PLUGIN) && - (CLEAR_CACHE_BIT(output_format) != FO_DO_JAVA)) - { - /* We only display the message for top-level items (i.e., not for - inline images, plugins, or java classes */ - - char * alert = PL_strdup(XP_GetString(XP_ALERT_OFFLINE_MODE_SELECTED)); - FE_Alert(window_id, alert); - FREE(alert); - } - } - - net_CallExitRoutineProxy(this_entry->exit_routine, - this_entry->URL_s, - this_entry->status, - this_entry->format_out, - this_entry->window_id); - - - /* Check for WaitingURL decrements TotalNumberofProcessingURLS */ - net_CheckForWaitingURL(this_entry->window_id, - this_entry->protocol, - load_background); - - net_ReleaseContext(this_entry->window_id); - PR_Free(this_entry); - LIBNET_UNLOCK_AND_RETURN(MK_OFFLINE); - } - - if(status < 0) /* check for finished state */ - { - - /* XP_OS2_FIX IBM-MAS: limit length of output string to keep from blowing trace buffer */ - TRACEMSG(("End of transfer, entry (soc=%d, con=%d) being removed from list with %d status: %-.1900s", - this_entry->socket, this_entry->con_sock, this_entry->status, - this_entry->URL_s->address)); - - XP_ListRemoveObject(net_EntryList, this_entry); - - net_CallExitRoutineProxy(this_entry->exit_routine, - this_entry->URL_s, - this_entry->status, - this_entry->format_out, - this_entry->window_id); - net_CheckForWaitingURL(this_entry->window_id, - this_entry->protocol, - load_background); - net_ReleaseContext(this_entry->window_id); - PR_Free(this_entry); /* not needed any more */ - } - - TRACEMSG(("Leaving GetURL with %d items in list", - XP_ListCount(net_EntryList))); - - /* XXX - hack for chromeless windows - jsw 10/27/95 */ - LIBNET_UNLOCK(); - if ( processcallbacks ) { - NET_ProcessExitCallbacks(); - } - - return status; - -#ifdef NOTDEF /* this is the real code here */ - LIBNET_UNLOCK_AND_RETURN(status); -#endif -} - -/* this thing is a hack that will allow http streams - waiting on passwd auth to resume XXX */ -PUBLIC void NET_ResumeWithAuth (void *closure) -{ - XP_List * iter = NULL; - ActiveEntry * tmpEntry = NULL; - NET_AuthClosure *auth_closure = (NET_AuthClosure *) closure; - - /* check to see if our entry is in the list */ - if (XP_ListIsEmpty(net_EntryList)) { - TRACEMSG (("NET_ResumeWithAuth: no list! we're busted ...")); - return; - } - iter = net_EntryList; - - while ((tmpEntry = (ActiveEntry *) XP_ListNextObject(iter))) { - if (tmpEntry == (ActiveEntry *) auth_closure->_private) { - break; - } - } - - if (!tmpEntry) - return; - - if (auth_closure && auth_closure->pass && *auth_closure->pass) { - - TRACEMSG (("NET_ResumeWithAuth: auth succeeded: %s", tmpEntry->URL_s->address)); - - /* now try it again */ - if (tmpEntry->proto_impl->resume) - tmpEntry->proto_impl->resume (tmpEntry, auth_closure, PR_TRUE); - - } else { - TRACEMSG (("NET_ResumeWithAuth(): auth failed: %s", tmpEntry->URL_s->address)); - if (tmpEntry->proto_impl->resume) - tmpEntry->proto_impl->resume (tmpEntry, auth_closure, PR_FALSE); - } - - /* now free the closure struct */ - PR_Free(auth_closure); - return; -} - -/* process_net is called from the client's main event loop and - * causes connections to be read and processed. Multiple - * connections can be processed simultaneously. - */ -PUBLIC int NET_ProcessNet (PRFileDesc *ready_fd, int fd_type) { - ActiveEntry * tmpEntry; - XP_List * list_item; - int rv= -1; - Bool load_background; - -#ifdef XP_OS2_FIX - /* assume no local files in net_EntryList. - * see "Thrash Optomization", below */ - int localfiles = 0; -#endif - - TRACEMSG(("Entering ProcessNet! ready_fd: %d", ready_fd)); - LIBNET_LOCK(); - - if(XP_ListIsEmpty(net_EntryList)) { - TRACEMSG(("Invalid call to NET_ProcessNet with fd: %d - No active entries\n", ready_fd)); - -#ifdef MOZILLA_CLIENT - if (fd_type == NET_EVERYTIME_TYPE) { - MWContext *c = XP_FindContextOfType(0, MWContextBrowser); - if (!c) c = XP_FindContextOfType(0, MWContextMail); - if (!c) c = XP_FindContextOfType(0, MWContextNews); - if (!c) c = XP_FindContextOfType(0, MWContextMessageComposition); - if (!c) c = XP_FindContextOfType(0, MWContextMailMsg); - if (!c) c = XP_FindContextOfType(0, MWContextPane); - - if (c) { - if(NET_IsCallNetlibAllTheTimeSet(c, NULL)) { - NET_ClearCallNetlibAllTheTime(c, "mkgeturl"); - } - NET_SetNetlibSlowKickTimer(FALSE); - } - } -#endif /* MOZILLA_CLIENT */ - - LIBNET_UNLOCK_AND_RETURN(0); /* no entries to process */ - } /* XP_ListIsEmpty(net_EntryList) */ - - if(NET_InGetHostByName) { - TRACEMSG(("call to processnet while doing gethostbyname call")); - PR_ASSERT(0); - LIBNET_UNLOCK_AND_RETURN(1); - } - - /* if NULL is passed into ProcessNet use select to - * figure out if a socket is ready */ - if(ready_fd == NULL) { - /* try and find a socket ready for reading */ -#define MAX_SIMULTANIOUS_SOCKETS 100 - /* should never have more than MAX sockets */ - PRPollDesc poll_desc_array[MAX_SIMULTANIOUS_SOCKETS]; - unsigned int fd_set_size=0; - - /* reorder the list so that we get a round robin effect */ - XP_ListMoveTopToBottom(net_EntryList); - - fd_type = NET_SOCKET_FD; - - /* process one socket ready for reading */ - list_item = net_EntryList; - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_item)) != 0) - { - if(tmpEntry->busy) - continue; - - if(!tmpEntry->local_file && !tmpEntry->memory_file) - { - if (tmpEntry->socket != NULL) { - if(tmpEntry->con_sock) { - poll_desc_array[fd_set_size].fd = tmpEntry->con_sock; - poll_desc_array[fd_set_size].in_flags = PR_POLL_READ | PR_POLL_EXCEPT | PR_POLL_WRITE; - } else { - poll_desc_array[fd_set_size].fd = tmpEntry->socket; - poll_desc_array[fd_set_size].in_flags = PR_POLL_READ | PR_POLL_EXCEPT; - } - - fd_set_size++; - PR_ASSERT(fd_set_size < MAX_SIMULTANIOUS_SOCKETS); - } - } else if(tmpEntry == - (ActiveEntry *) XP_ListGetObjectNum(net_EntryList, 1)) - { - /* if this is the very first object in the list - * and it's a local file or a memory cache copy - * then use this one entry and skip the select call - * we won't deadlock because we reorder the list - * with every call to net process net. */ - fd_type = NET_LOCAL_FILE_FD; - ready_fd = tmpEntry->socket; /* it's actually going to be NULL in this case */ - - /* call yeild to let other thread do something */ - PR_Sleep(PR_INTERVAL_NO_WAIT); - - break; /* exit while() */ - } - } /* end while() */ - - /* in case we set it for the local file type above */ - if(fd_type == NET_SOCKET_FD) { - int count=0; - - PR_Sleep(PR_INTERVAL_NO_WAIT); /* thread yeild */ - - if( PR_Poll(poll_desc_array, fd_set_size, 0) < 1 ) { - TRACEMSG(("Select returned no active sockets! WASTED CALL TO PROCESS NET")); - LIBNET_UNLOCK_AND_RETURN(XP_ListIsEmpty(net_EntryList) ? 0 : 1); - } - - /* process one socket ready for reading, - * find the first one ready */ - list_item = net_EntryList; - while((tmpEntry=(ActiveEntry *) XP_ListNextObject(list_item)) != 0) - { - if(tmpEntry->busy) - continue; - - if(!tmpEntry->local_file && !tmpEntry->memory_file) { - /* count should line up to the appropriate socket since - * it was added in the same order */ - PR_ASSERT(poll_desc_array[count].fd == tmpEntry->socket - || poll_desc_array[count].fd == tmpEntry->con_sock); - if(poll_desc_array[count].out_flags & (PR_POLL_READ | PR_POLL_WRITE | PR_POLL_EXCEPT)) - { - ready_fd = tmpEntry->socket; - break; - } - count++; - } - } /* end while() */ - - if(!ready_fd) { -#ifdef DEBUG - printf("couldn't find the active socket. Shouldn't ever happen"); -#endif - /* PR_ASSERT(0); */ - LIBNET_UNLOCK_AND_RETURN(XP_ListIsEmpty(net_EntryList) ? 0 : 1); - } - } /* end if(fd_type == NET_SOCKET_FD) */ - } /* end if(ready_fd == NULL)*/ - - list_item = net_EntryList; - - /* process one socket ready for reading - * find the ready socket in the active entry list */ - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_item)) != 0) - { - TRACEMSG(("Found item in Active Entry List. sock #%d con_sock #%d", - tmpEntry->socket, tmpEntry->con_sock)); - - /* this will activate local and memory files as well since the ready_fd - * will be zero and will match the NULL socket ID. - * - * We won't have starvation because the list is reordered every time - */ - if(!tmpEntry->busy - && - (ready_fd == tmpEntry->socket - || ready_fd == tmpEntry->con_sock) ) { - - tmpEntry->busy = TRUE; - - TRACEMSG(("Item has data ready for read")); - - rv = (*tmpEntry->proto_impl->process)(tmpEntry); - - tmpEntry->busy = FALSE; - - /* check for done status on transfer and call - * exit routine if done. */ - if (rv < 0) { - - XP_ListRemoveObject(net_EntryList, tmpEntry); - - if(tmpEntry->status == MK_USE_COPY_FROM_CACHE) { - TRACEMSG(("304 Not modified recieved using cached entry\n")); -#ifdef MOZILLA_CLIENT - NET_RefreshCacheFileExpiration(tmpEntry->URL_s); -#endif /* MOZILLA_CLIENT */ - - /* turn off force reload by telling it to use local copy */ - tmpEntry->URL_s->use_local_copy = TRUE; - - /* restart the transfer */ - NET_GetURL(tmpEntry->URL_s, - tmpEntry->format_out, - tmpEntry->window_id, - tmpEntry->exit_routine); - - net_CheckForWaitingURL(tmpEntry->window_id, - tmpEntry->protocol, - tmpEntry->URL_s->load_background); - } else if(tmpEntry->status == MK_DO_REDIRECT) { - TRACEMSG(("Doing redirect part in ProcessNet")); - - /* restart the whole transfer */ - NET_GetURL(tmpEntry->URL_s, - tmpEntry->format_out, - tmpEntry->window_id, - tmpEntry->exit_routine); - - net_CheckForWaitingURL(tmpEntry->window_id, - tmpEntry->protocol, - tmpEntry->URL_s->load_background); - } else if(tmpEntry->status == MK_TOO_MANY_OPEN_FILES) { - /* Queue this URL so it gets tried again */ - LIBNET_UNLOCK_AND_RETURN(net_push_url_on_wait_queue( - NET_URL_Type(tmpEntry->URL_s->address), - tmpEntry->URL_s, - tmpEntry->format_out, - tmpEntry->window_id, - tmpEntry->exit_routine)); - } -#ifdef NU_CACHE - else if(tmpEntry->status < 0 - && !tmpEntry->URL_s->use_local_copy - HG42469 - && (tmpEntry->status == MK_CONNECTION_REFUSED - || tmpEntry->status == MK_CONNECTION_TIMED_OUT - || tmpEntry->status == MK_UNABLE_TO_CREATE_SOCKET - || tmpEntry->status == MK_UNABLE_TO_LOCATE_HOST - || tmpEntry->status == MK_UNABLE_TO_CONNECT) - && NET_IsURLInCache(tmpEntry->URL_s)) -#else - else if(tmpEntry->status < 0 - && !tmpEntry->URL_s->use_local_copy - HG42469 - && (tmpEntry->status == MK_CONNECTION_REFUSED - || tmpEntry->status == MK_CONNECTION_TIMED_OUT - || tmpEntry->status == MK_UNABLE_TO_CREATE_SOCKET - || tmpEntry->status == MK_UNABLE_TO_LOCATE_HOST - || tmpEntry->status == MK_UNABLE_TO_CONNECT) - && (NET_IsURLInDiskCache(tmpEntry->URL_s) - || NET_IsURLInMemCache(tmpEntry->URL_s))) -#endif - { - /* if the status is negative something went wrong - * with the load. If last_modified is set - * then we probably have a cache file, - * but it might be a broken image so - * make sure "use_local_copy" is not - * set. - * - * Only do this when we can't connect to the - * server. */ - - /* if we had a cache file and got a load - * error, go ahead and use it anyways */ - - /* turn off force reload by telling it to use local copy */ - tmpEntry->URL_s->use_local_copy = TRUE; - - if(CLEAR_CACHE_BIT(tmpEntry->format_out) == FO_PRESENT) - { - StrAllocCat(tmpEntry->URL_s->error_msg, - XP_GetString( XP_USING_PREVIOUSLY_CACHED_COPY_INSTEAD ) ); - - FE_Alert(tmpEntry->window_id, - tmpEntry->URL_s->error_msg); - } - - FREE_AND_CLEAR(tmpEntry->URL_s->error_msg); - - /* restart the transfer */ - NET_GetURL(tmpEntry->URL_s, - tmpEntry->format_out, - tmpEntry->window_id, - tmpEntry->exit_routine); - - net_CheckForWaitingURL(tmpEntry->window_id, - tmpEntry->protocol, - tmpEntry->URL_s->load_background); - } else { - /* XP_OS2_FIX IBM-MAS: limit size of URL string to 100 to keep from blowing trace message buffer! */ - TRACEMSG(("End of transfer, entry (soc=%d, con=%d) being removed from list with %d status: %-.1900s", - tmpEntry->socket, tmpEntry->con_sock, tmpEntry->status, - (tmpEntry->URL_s->address ? tmpEntry->URL_s->address : ""))); - - /* catch out of memory errors at the lowest - * level since we don't do it at all the out - * of memory condition spots */ - if(tmpEntry->status == MK_OUT_OF_MEMORY - && !tmpEntry->URL_s->error_msg) { - tmpEntry->URL_s->error_msg = - NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - } - - load_background = tmpEntry->URL_s->load_background; - /* run the exit routine */ - net_CallExitRoutineProxy(tmpEntry->exit_routine, - tmpEntry->URL_s, - tmpEntry->status, - tmpEntry->format_out, - tmpEntry->window_id); - - net_CheckForWaitingURL(tmpEntry->window_id, - tmpEntry->protocol, - load_background); - -#ifdef MILAN - /* if the error was caused by a NETWORK DOWN - * then interrupt the window. This - * could still be a problem since another - * window may be active, but it should get - * the same error */ - if(PR_GetOSError() == XP_ERRNO_ENETDOWN) { - NET_SilentInterruptWindow(tmpEntry->window_id); - } -#endif /* MILAN */ - - net_ReleaseContext(tmpEntry->window_id); - } /* end status variable if statements */ - - PR_Free(tmpEntry); /* free the now non active entry */ - - } /* end if rv < 0 */ - - TRACEMSG(("Leaving process net with %d items in list", - XP_ListCount(net_EntryList))); - - LIBNET_UNLOCK_AND_RETURN(XP_ListIsEmpty(net_EntryList) ? 0 : 1); /* all done */ - - } /* end if !tmpEntry->busy */ - - } /* end while */ - - /* the active socket wasn't found in the list :( */ - TRACEMSG(("Invalid call to NET_ProcessNet: Active item with passed in fd: %d not found\n", ready_fd)); - - LIBNET_UNLOCK_AND_RETURN(XP_ListIsEmpty(net_EntryList) ? 0 : 1); -} - -/* - * net_InterruptActiveStream - * Kills a single stream given its ActiveEntry* - * * FrontEndCancel -> NetInterruptWindow -> net_InterruptActiveStream - * * LayoutNewDoc -> KillOtherLayouts -> net_InterruptActiveStream - * - * Also removes the entry from the active list and frees it. - * Also allows waiting urls into the active list. - */ -PRIVATE int -net_InterruptActiveStream (ActiveEntry *entry, Bool show_warning) -{ - TRACEMSG(("Terminating transfer on port #%d, proto: %d", - entry->socket, entry->protocol)); - - /* remove it from the active list first to prevent - * reentrant problem - */ - XP_ListRemoveObject(net_EntryList, entry); - - if(entry->proto_impl) - { - (*entry->proto_impl->interrupt)(entry); - } - else - { - PR_ASSERT(0); - } - - /* XP_OS2_FIX IBM-MAS: limit length of output string to keep from blowing trace buffer */ - TRACEMSG(("End of transfer, entry (soc=%d, con=%d) being removed from list with %d status: %-.1900s", - entry->socket, entry->con_sock, entry->status, entry->URL_s->address)); - - /* call exit routine since we know we are done */ - net_CallExitRoutineProxy(entry->exit_routine, - entry->URL_s, - entry->status, - entry->format_out, - entry->window_id); - - /* decrement here since we don't call checkForWaitingURL's - */ - NET_TotalNumberOfProcessingURLs--; - - if(!NET_AreThereActiveConnectionsForWindow(entry->window_id)) - FE_AllConnectionsComplete(entry->window_id); - - /* free the no longer active entry */ - net_ReleaseContext(entry->window_id); - PR_Free(entry); - - return 0; -} - -/* use a URL struct to find an active entry - * The netlib lock must be held prior to calling this - * returns NULL if not found - */ -PRIVATE ActiveEntry * -net_find_ac_from_url(URL_Struct *nurl) -{ - XP_List * iter = net_EntryList; - ActiveEntry *tmpEntry = NULL, *rv = NULL; - - while ((tmpEntry = (ActiveEntry *) XP_ListNextObject(iter)) != NULL) - { - if (tmpEntry->URL_s == nurl) - { - rv = tmpEntry; - break; - } - } - - return(rv); -} - -PUBLIC Bool -NET_SetActiveEntryBusyStatus(URL_Struct *nurl, Bool set_busy) -{ - ActiveEntry *entry = NULL; - - entry = net_find_ac_from_url(nurl); - - if(entry) - entry->busy = set_busy; - - return (entry != 0); -} - -/* - * NET_InterruptStream kills just stream associated with an URL. - */ -PUBLIC int -NET_InterruptStream (URL_Struct *nurl) -{ - /* Find the ActiveEntry structure for this URL */ - ActiveEntry *entryToKill = NULL; - int status; - - TRACEMSG(("Entering NET_InterruptStream")); - LIBNET_LOCK(); - - if(NET_InGetHostByName) - { - TRACEMSG(("call to InterrruptStream while doing gethostbyname call")); - LIBNET_UNLOCK_AND_RETURN(1); - } - - entryToKill = net_find_ac_from_url(nurl); - -/* assert (entryToKill);*/ - /* Kill it & free it */ - if (entryToKill) - status = net_InterruptActiveStream (entryToKill, TRUE); - else - status = -1; - - LIBNET_UNLOCK_AND_RETURN(status); -} - - -/* interrupt a LoadURL action by using a socket number as - * an index. NOTE: that this cannot interrupt non-socket - * based operations such as file or memory cache loads - * - * returns -1 on error. - */ -PUBLIC int -NET_InterruptSocket (PRFileDesc *socket) -{ - /* Find the ActiveEntry structure for this URL */ - ActiveEntry *tmpEntry = NULL, *entryToKill = NULL; - XP_List * iter; - int status; - - TRACEMSG(("Entering NET_InterruptSocket")); - LIBNET_LOCK(); - iter = net_EntryList; - - if(NET_InGetHostByName) - { - TRACEMSG(("call to InterrruptStream while doing gethostbyname call")); - LIBNET_UNLOCK_AND_RETURN(1); - } - - while ((tmpEntry = (ActiveEntry *) XP_ListNextObject(iter)) != NULL) { - if (tmpEntry->con_sock == socket || tmpEntry->socket == socket) { - entryToKill = tmpEntry; - break; - } - } - - if (entryToKill) - status = net_InterruptActiveStream (entryToKill, TRUE); - else - status = -1; - - LIBNET_UNLOCK_AND_RETURN(status); -} - -/* - * NET_SetNewContext changes the context associated with a URL Struct. - * can also change the url exit routine, which causes the old one to be - * called with a status of MK_CHANGING_CONTEXT - */ -PUBLIC int -NET_SetNewContext(URL_Struct *URL_s, MWContext * new_context, Net_GetUrlExitFunc *exit_routine) -{ - /* Find the ActiveEntry structure for this URL */ - ActiveEntry *tmpEntry = NULL; - XP_List * iter; - MWContext *old_window_id; - - LIBNET_LOCK(); - iter = net_EntryList; - - while ((tmpEntry = (ActiveEntry *) XP_ListNextObject(iter)) != NULL) - { - if (tmpEntry->URL_s == URL_s) - { -#if defined(SMOOTH_PROGRESS) - /* When the URL load gets redirected to another window, - we need to notify the progress manager from the old - window that the URL need no longer be tracked */ - PM_StopBinding(tmpEntry->window_id, URL_s, -1, NULL); -#endif - /* call the old exit routine now with the old context */ - /* call with MK_CHANGING_CONTEXT, FE shouldn't free URL_s */ - net_CallExitRoutineProxy(tmpEntry->exit_routine, - URL_s, - MK_CHANGING_CONTEXT, - 0, - tmpEntry->window_id); - - /* see if we're changing exit routines */ - if(exit_routine != NULL) { - /* okay to change now. */ - tmpEntry->exit_routine = exit_routine; - } - old_window_id = tmpEntry->window_id; - tmpEntry->window_id = new_context; - -#if defined(SMOOTH_PROGRESS) - /* Inform the progress manager in the new context about - the URL that it just received */ - PM_StartBinding(tmpEntry->window_id, URL_s); -#endif - -#ifdef XP_WIN - /* - * Windows needs a way to know when a URL switches contexts, - * so that it can keep the NCAPI progress messages - * specific to a URL loading and not specific to the - * context attempting to load. - * So sue me. GAB 10-16-95 - */ - FE_UrlChangedContext(URL_s, old_window_id, new_context); -#endif /* XP_WIN */ - - /* if there are no more connections in the old context, we - * need to call AllConnectionsComplete - */ - if(!NET_AreThereActiveConnectionsForWindow(old_window_id)) - FE_AllConnectionsComplete(old_window_id); - - net_ReleaseContext(old_window_id); - LIBNET_UNLOCK(); - return(0); - } - } - - /* couldn't find it :( */ - PR_ASSERT (0); - - LIBNET_UNLOCK(); - return(-1); -} - -/* returns true if the stream is safe for setting up a new - * context and using a separate window. - * - * This will return FALSE in multipart/mixed cases where - * it is impossible to use separate windows for the - * same stream. - */ -PUBLIC Bool -NET_IsSafeForNewContext(URL_Struct *URL_s) -{ - if(!URL_s || URL_s->is_active) - return(FALSE); - - return(TRUE); -} - - -/* NET_InterruptTransfer - * - * Interrupts all transfers in progress that have the same window id as - * the one passed in. - */ -PRIVATE int -net_InternalInterruptWindow(MWContext * window_id, Bool show_warning) -{ - int starting_list_count; - ActiveEntry * tmpEntry; - ActiveEntry * tmpEntry2; - XP_List * list_item; - int32 cur_win_id = FE_GetContextID(window_id); - int number_killed=0; - XP_Bool call_all_connections_complete = TRUE; - - TRACEMSG(("-------Interrupt Transfer called!")); - - LIBNET_LOCK(); - list_item = net_EntryList; - starting_list_count = XP_ListCount(net_EntryList); - -#ifdef DEBUG - if(NET_InGetHostByName) - { - TRACEMSG(("call to InterrruptWindow while doing gethostbyname call")); - LIBNET_UNLOCK_AND_RETURN(1); - } -#endif /* DEBUG */ - - number_killed = net_AbortWaitingURL(window_id, - FALSE, - net_waiting_for_actives_url_list); - number_killed += net_AbortWaitingURL(window_id, - FALSE, - net_waiting_for_connection_url_list); - - /* run through the whole list of connections and - * interrupt any of them that have a matching window - * id. - */ - tmpEntry = (ActiveEntry *) XP_ListNextObject(list_item); - - while(tmpEntry) - { - /* advance to the next item NOW in case we free this one */ - tmpEntry2 = (ActiveEntry *) XP_ListNextObject(list_item); - - if(FE_GetContextID(tmpEntry->window_id) == cur_win_id) - { - if(tmpEntry->busy) - { - if(show_warning) - { - TRACEMSG(("AAAACK, reentrant protection kicking in.!!!")); -#ifdef DEBUG - FE_Alert(tmpEntry->window_id, XP_GetString(XP_ALERT_INTERRUPT_WINDOW)); -#endif /* DEBUG */ - } - } - else - { - FE_EnableClicking(window_id); - net_InterruptActiveStream (tmpEntry, show_warning); - number_killed += 1; - - /* unset call_all_connections_complete here - * since InterruptActiveStream will already - * call all_connections_complete when it detects - * that there are no more active connections - * going on for the window. - */ - call_all_connections_complete = FALSE; - } - } /* end if cur_win_id */ - - tmpEntry = tmpEntry2; - } /* end while */ - - /* If all_connection_complete was called, FE might have destroyed - * the context. So dont call FE_EnableClicking() if - * call_all_connections_complete was already called. - */ - if (call_all_connections_complete) - FE_EnableClicking(window_id); - - /* we are sure that all connections are complete - * but only call it if we killed one. - */ - if(number_killed && call_all_connections_complete) - FE_AllConnectionsComplete(window_id); - - - TRACEMSG(("Leaving Interrupt transfer with %d items in list", - XP_ListCount(net_EntryList))); - - LIBNET_UNLOCK_AND_RETURN(starting_list_count - XP_ListCount(net_EntryList)); - -} - -/* - * Interrupts all transfers in progress that have the same window id as - * the one passed in. - */ -PUBLIC int -NET_InterruptWindow(MWContext * window_id) -{ -/* call interruptwindow twice so that things we interrupt that call NET_GetURL - * will be interrupted as well - */ - - int rv = net_InternalInterruptWindow(window_id, TRUE); - #ifdef XP_MAC - /* pchen - Fix bug #72831. On Mac, continuously call - * net_InternalInterruptWindow while - * NET_AreThereNonBusyActiveConnectionsForWindow returns true - */ - while(NET_AreThereNonBusyActiveConnectionsForWindow(window_id)) - #endif /* XP_MAC */ - rv += net_InternalInterruptWindow(window_id, TRUE); - return(rv); -} - -/* - * Silently Interrupts all transfers in progress that have the same - * window id as the one passed in. - */ -MODULE_PRIVATE int -NET_SilentInterruptWindow(MWContext * window_id) -{ - return(net_InternalInterruptWindow(window_id, FALSE)); -} - -/* check for any active URL transfers in progress for the given - * window Id - * - * It is possible that there exist URL's on the wait queue that - * will not be returned by this function. It is recommended - * that you call NET_InterruptWindow(MWContext * window_id) - * when FALSE is returned to make sure that the wait queue is - * cleared as well. - * - * It is also possible that some URLs will be explicitly marked as - * "background" URLs that are not identified as active, even though - * they are. - */ -PUBLIC Bool -NET_AreThereActiveConnectionsForWindow(MWContext * window_id) -{ - ActiveEntry * tmpEntry; - int32 cur_win_id = FE_GetContextID(window_id); - XP_List * list_ptr; - WaitingURLStruct * wus; - - LIBNET_LOCK(); - - TRACEMSG(("-------NET_AreThereActiveConnectionsForWindow called!")); - - /* check for connections in the wait queue - */ - list_ptr = net_waiting_for_actives_url_list; - while((wus = (WaitingURLStruct*) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(wus->window_id) && - !wus->URL_s->load_background) - { - LIBNET_UNLOCK(); - return(TRUE); - } - } - - /* check for connections in the connections wait queue - */ - list_ptr = net_waiting_for_connection_url_list; - while((wus = (WaitingURLStruct*) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(wus->window_id) && - !wus->URL_s->load_background) - { - LIBNET_UNLOCK(); - return(TRUE); - } - } - - /* run through the whole list of active connections and - * return true if any of them have the passed in window id - */ - list_ptr = net_EntryList; - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(tmpEntry->window_id) && - !tmpEntry->URL_s->load_background) - { - LIBNET_UNLOCK(); - return(TRUE); - } - - } /* end while */ - - LIBNET_UNLOCK(); - return(FALSE); -} - - -PUBLIC Bool -NET_AreThereActiveConnections() -{ - Bool ret_value; - LIBNET_LOCK(); - ret_value = XP_ListIsEmpty(net_waiting_for_actives_url_list) && - XP_ListIsEmpty(net_waiting_for_connection_url_list) && - XP_ListIsEmpty(net_EntryList); - LIBNET_UNLOCK(); - return !ret_value; -} - - -#ifdef XP_MAC -/* pchen - Fix bug #72831. Same as NET_AreThereActiveConnectionsForWindow - * except that it will return false if there is an active connection that - * is busy. - */ -PUBLIC Bool -NET_AreThereNonBusyActiveConnectionsForWindow(MWContext * window_id) -{ - ActiveEntry * tmpEntry; - int32 cur_win_id = FE_GetContextID(window_id); - XP_List * list_ptr; - WaitingURLStruct * wus; - - LIBNET_LOCK(); - - TRACEMSG(("-------NET_AreThereActiveConnectionsForWindow called!")); - - /* check for connections in the wait queue - */ - list_ptr = net_waiting_for_actives_url_list; - while((wus = (WaitingURLStruct*) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(wus->window_id) && - !wus->URL_s->load_background) - { - LIBNET_UNLOCK(); - return(TRUE); - } - } - - /* check for connections in the connections wait queue - */ - list_ptr = net_waiting_for_connection_url_list; - while((wus = (WaitingURLStruct*) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(wus->window_id) && - !wus->URL_s->load_background) - { - LIBNET_UNLOCK(); - return(TRUE); - } - } - - /* run through the whole list of active connections and - * return true if any of them have the passed in window id - */ - list_ptr = net_EntryList; - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_ptr)) != NULL) - { - if(cur_win_id == FE_GetContextID(tmpEntry->window_id) && - !tmpEntry->URL_s->load_background && - !tmpEntry->busy) - { - LIBNET_UNLOCK(); - return(TRUE); - } - - } /* end while */ - - LIBNET_UNLOCK(); - return(FALSE); -} -#endif /* XP_MAC */ - -/* KM - Are there other ActiveEntry structures being processed with the same - context? */ -/* fix Mac warning for missing prototype */ -PUBLIC Bool -NET_AreThereActiveConnectionsForWindowWithOtherActiveEntry(ActiveEntry *thisEntry); - -PUBLIC Bool -NET_AreThereActiveConnectionsForWindowWithOtherActiveEntry(ActiveEntry *thisEntry) -{ - ActiveEntry * tmpEntry; - int32 cur_win_id = FE_GetContextID(thisEntry->window_id); - XP_List * list_ptr; - - LIBNET_LOCK(); - - /* run through the whole list of active connections and - * return true if any of them have the passed in window id - * with a different entry - */ - list_ptr = net_EntryList; - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_ptr)) != NULL) - { - if((cur_win_id == FE_GetContextID(tmpEntry->window_id)) && - (tmpEntry != thisEntry)) - { - LIBNET_UNLOCK(); - return(TRUE); - } - - } /* end while */ - - LIBNET_UNLOCK(); - return(FALSE); -} - - -/* - * GAB 04-23-96 - * We're interested in knowing if there are any operations which - * will cause activity of the said type, in the said context. - * This is in the interests of PE, where they desire a world of - * dial on demand (hanging up the phone when we're not doing anything - * on the network). - * - * Args: - * window_id The said context to check. - * If NULL, check them all (disregard). - * waiting Include waiting queues in check if TRUE. - * Note that waiting queues do not know thier type - * yet (local, cache, or net), thus type can not - * be correctly checked. I can only assume that - * we have the technology to mostly decide this - * before the fact, but I see no facility available. - * background Include background activity in the check if TRUE. - * Returns: - * Bool TRUE, there is chance of activity of said type. - * FALSE, that particular type of activity is not present. - * - */ -PUBLIC Bool -NET_HasNetworkActivity(MWContext * window_id, Bool waiting, Bool background) -{ - ActiveEntry * tmpEntry; - XP_List * list_ptr; - WaitingURLStruct * wus; - - LIBNET_LOCK(); - - TRACEMSG(("-------NET_HasNetworkActivity called!")); - - /* check for connections in the wait queue - */ - if(waiting) - { - list_ptr = net_waiting_for_actives_url_list; - while((wus = (WaitingURLStruct*) XP_ListNextObject(list_ptr)) != NULL) - { - if((window_id == NULL || - FE_GetContextID(window_id) == - FE_GetContextID(wus->window_id)) && - (background || !wus->URL_s->load_background)) - { - LIBNET_UNLOCK(); - return(TRUE); - } - } - - /* check for connections in the connections wait queue - */ - list_ptr = net_waiting_for_connection_url_list; - while((wus = (WaitingURLStruct*) XP_ListNextObject(list_ptr)) != NULL) - { - if((window_id == NULL || - FE_GetContextID(window_id) == - FE_GetContextID(wus->window_id)) && - (background || !wus->URL_s->load_background)) - { - LIBNET_UNLOCK(); - return(TRUE); - } - } - } - - /* run through the whole list of active connections - */ - list_ptr = net_EntryList; - while((tmpEntry = (ActiveEntry *) XP_ListNextObject(list_ptr)) != NULL) - { - if((window_id == NULL || - FE_GetContextID(window_id) == - FE_GetContextID(tmpEntry->window_id)) && - (background || !tmpEntry->URL_s->load_background) && - !tmpEntry->memory_file && - !tmpEntry->local_file) - { - LIBNET_UNLOCK(); - return(TRUE); - } - - } /* end while */ - - LIBNET_UNLOCK(); - return(FALSE); -} - - -/* malloc, init, and set the URL structure used - * for the network library - */ -PUBLIC URL_Struct * -NET_CreateURLStruct (CONST char *url, NET_ReloadMethod force_reload) -{ - uint32 all_headers_size; - URL_Struct * URL_s = PR_NEW(URL_Struct); - - if(!URL_s) - { - return NULL; - } - - /* zap the whole structure */ - memset (URL_s, 0, sizeof (URL_Struct)); - - URL_s->SARCache = NULL; - - /* we haven't modified the address at all (since we are just creating it)*/ - URL_s->address_modified=NO; - - URL_s->method = URL_GET_METHOD; - - URL_s->force_reload = force_reload; - - URL_s->load_background = FALSE; - - URL_s->ref_count = 1; - - /* Allocate space for pointers to hold message (http, news etc) headers */ - all_headers_size = - INITIAL_MAX_ALL_HEADERS * sizeof (URL_s->all_headers.key[0]); - URL_s->all_headers.key = (char **) PR_Malloc(all_headers_size); - if(!URL_s->all_headers.key) - { - NET_FreeURLStruct(URL_s); - return NULL; - } - memset (URL_s->all_headers.key, 0, all_headers_size); - - all_headers_size = - INITIAL_MAX_ALL_HEADERS * sizeof (URL_s->all_headers.value[0]); - URL_s->all_headers.value = (char **) PR_Malloc(all_headers_size); - if(!URL_s->all_headers.value) - { - NET_FreeURLStruct(URL_s); - return NULL; - } - memset (URL_s->all_headers.value, 0, all_headers_size); - - URL_s->all_headers.max_index = INITIAL_MAX_ALL_HEADERS; - - URL_s->owner_data = NULL; - URL_s->owner_id = 0; - - /* set the passed in value */ - StrAllocCopy(URL_s->address, url); - if (!URL_s->address) { - /* out of memory, clean up previously allocated objects */ - NET_FreeURLStruct(URL_s); - URL_s = NULL; - } - -#ifdef TRUST_LABELS - /* add the newly minted URL_s struct to the list of the same so - * that when cookie to trust label matching occurs I can find the - * associated trust list */ - if ( URL_s && net_URL_sList ) { - LIBNET_LOCK(); - XP_ListAddObjectToEnd( net_URL_sList, URL_s ); - LIBNET_UNLOCK(); - } -#endif - - return(URL_s); -} - -/* Increase the size of AllHeaders in URL_struct - */ -PRIVATE Bool -net_EnlargeURLAllHeaders (URL_Struct * URL_s) -{ - uint32 number_of_entries = - URL_s->all_headers.empty_index * MULT_ALL_HEADER_COUNT; - uint32 realloc_size = - number_of_entries * sizeof (URL_s->all_headers.key[0]); - char **temp; - - if (number_of_entries < MAX_ALL_HEADER_COUNT) { - - temp = (char **) PR_Realloc(URL_s->all_headers.key, realloc_size); - if (temp) { - URL_s->all_headers.key = temp; - - temp = (char **) PR_Realloc(URL_s->all_headers.value, realloc_size); - if (temp) { - URL_s->all_headers.value = temp; - - URL_s->all_headers.max_index = number_of_entries; - return(TRUE); - } - } - } - net_FreeURLAllHeaders(URL_s); - return(FALSE); -} - - -/* Append Key, Value pair into AllHeaders list of URL_struct - */ -PUBLIC Bool -NET_AddToAllHeaders(URL_Struct * URL_s, char *name, char *value) -{ - char *key_ptr; - char *value_ptr; - - PR_ASSERT(URL_s); - PR_ASSERT(name); - PR_ASSERT(value); - - if ((URL_s->all_headers.empty_index >= URL_s->all_headers.max_index) && - (!net_EnlargeURLAllHeaders(URL_s))) { - return(FALSE); - } - - key_ptr = URL_s->all_headers.key[URL_s->all_headers.empty_index] = - PL_strdup(name); - if (!key_ptr) { - net_FreeURLAllHeaders(URL_s); - return(FALSE); - } - - value_ptr = URL_s->all_headers.value[URL_s->all_headers.empty_index] = - PL_strdup(value); - if (!value_ptr) { - PR_Free(key_ptr); - URL_s->all_headers.key[URL_s->all_headers.empty_index] = NULL; - net_FreeURLAllHeaders(URL_s); - return(FALSE); - } - URL_s->all_headers.empty_index++; - return(TRUE); -} - -/* Set the option IPAddressString field - * This field overrides the hostname when doing the connect, - * and allows Java to specify a spelling of an IP number. - * Out of memory condition will cause the URL_struct to be destroyed. - */ -PUBLIC int -NET_SetURLIPAddressString (URL_Struct * URL_s, CONST char *ip_string) -{ - PR_ASSERT(URL_s); - - FREEIF(URL_s->IPAddressString); - URL_s->IPAddressString = NULL; - - /* set the passed in value */ - StrAllocCopy(URL_s->IPAddressString, ip_string); - return NULL == URL_s->IPAddressString; -} - -PUBLIC URL_Struct * -NET_HoldURLStruct (URL_Struct * URL_s) -{ - if(URL_s) { - PR_ASSERT(URL_s->ref_count > 0); - URL_s->ref_count++; - } - return URL_s; -} - - -/* free the contents and the URL structure when finished - */ -PUBLIC void -NET_FreeURLStruct (URL_Struct * URL_s) -{ - if(!URL_s) - return; - - /* if someone is holding onto a pointer to us don't die */ - PR_ASSERT(URL_s->ref_count > 0); - URL_s->ref_count--; - if(URL_s->ref_count > 0) - return; - -#ifdef TRUST_LABELS - /* remove URL_s struct from the list of the same */ - if ( URL_s && net_URL_sList ) { - LIBNET_LOCK(); - XP_ListRemoveObject( net_URL_sList, URL_s ); - LIBNET_UNLOCK(); - } -#endif - - FREEIF(URL_s->address); - FREEIF(URL_s->username); - FREEIF(URL_s->password); - FREEIF(URL_s->IPAddressString); - FREEIF(URL_s->referer); - FREEIF(URL_s->post_data); - FREEIF(URL_s->post_headers); - FREEIF(URL_s->content_type); - FREEIF(URL_s->content_encoding); - FREEIF(URL_s->x_mac_type); - FREEIF(URL_s->x_mac_creator); - FREEIF(URL_s->charset); - FREEIF(URL_s->boundary); - FREEIF(URL_s->redirecting_url); - FREEIF(URL_s->authenticate); - FREEIF(URL_s->protection_template); - FREEIF(URL_s->http_headers); - FREEIF(URL_s->cache_file); - FREEIF(URL_s->window_target); - FREEIF(URL_s->window_chrome); - FREEIF(URL_s->refresh_url); - FREEIF(URL_s->wysiwyg_url); - FREEIF(URL_s->etag); - FREEIF(URL_s->origin_url); - FREEIF(URL_s->error_msg); - - HG87376 - - /* Free all memory associated with header information */ - net_FreeURLAllHeaders(URL_s); - - if(URL_s->files_to_post) - { - /* free a null terminated array of filenames - */ - int i=0; - for(i=0; URL_s->files_to_post[i] != NULL; i++) - { - FREE(URL_s->files_to_post[i]); /* free the filenames */ - } - FREE(URL_s->files_to_post); /* free the array */ - } - - /* Like files_to_post. */ - if(URL_s->post_to) - { - /* free a null terminated array of filenames - */ - int i=0; - for(i=0; URL_s->post_to[i] != NULL; i++) - { - FREE(URL_s->post_to[i]); /* free the URLs */ - } - FREE(URL_s->post_to); /* free the array */ - } - - - /* free the array */ - PR_FREEIF(URL_s->add_crlf); - - PR_FREEIF(URL_s->page_services_url); - - if (URL_s->privacy_policy_url != (char*)(-1)) { - PR_FREEIF(URL_s->privacy_policy_url); - } else { - URL_s->privacy_policy_url = NULL; - } - -#ifdef TRUST_LABELS - /* delete the entries and the trust list, if the list was created then there - * are entries on it. */ - if ( URL_s->TrustList != NULL ) { - /* delete each trust list entry then delete the list */ - TrustLabel *ALabel; - XP_List *tempList = URL_s->TrustList; - while ( (ALabel = XP_ListRemoveEndObject( tempList )) != NULL ) { - TL_Destruct( ALabel ); - } - XP_ListDestroy( URL_s->TrustList ); - URL_s->TrustList = NULL; - } -#endif - - PR_Free(URL_s); -} - -/* free the contents of AllHeader structure that is part of URL_Struct - */ -PRIVATE void -net_FreeURLAllHeaders (URL_Struct * URL_s) -{ - uint32 i=0; - - /* Free all memory associated with header information */ - for (i = 0; i < URL_s->all_headers.empty_index; i++) { - if (URL_s->all_headers.key) { - FREEIF(URL_s->all_headers.key[i]); - } - if (URL_s->all_headers.value) { - FREEIF(URL_s->all_headers.value[i]); - } - } - URL_s->all_headers.empty_index = URL_s->all_headers.max_index = 0; - - FREEIF(URL_s->all_headers.key); - FREEIF(URL_s->all_headers.value); - URL_s->all_headers.key = URL_s->all_headers.value = NULL; -} - - -/* if there is no slash in a URL besides the two that specify a host - * then add one to the end. - * - * this fails with file:// URLs of the form file:///Hard_disk - * because there are 3 leading slashes already. Fixed for Mac, to fix bug 113706 - * - */ -PRIVATE void add_slash_to_URL (URL_Struct *URL_s) -{ - char *colon=PL_strchr(URL_s->address,':'); /* must find colon */ - char *slash; - - /* make sure there is a hostname - */ -#if defined(XP_MAC) /* || defined(XP_WIN) || defined(XP_UNIX) - add when comfortable.*/ - /* should probably be XP at some stage */ - if (PL_strncmp("file://", URL_s->address, 7) == 0) - { - slash = PL_strchr(colon + 4,'/'); - } - else -#endif - if(*(colon+1) == '/' && *(colon+2) == '/') - slash = PL_strchr(colon+3,'/'); - else - return; - - if(slash==NULL) - { - TRACEMSG(("GetURL: URL %-.1900s changed to ",URL_s->address)); - -#ifdef MOZILLA_CLIENT - /* add it now to the Global history since we can't get this - * name back :( this is a bug because we are not sure - * that the link will actually work. - */ - GH_UpdateGlobalHistory(URL_s); -#endif /* MOZILLA_CLIENT */ - - StrAllocCat(URL_s->address, "/"); - URL_s->address_modified = YES; - - TRACEMSG(("%-.1900s",URL_s->address)); - } -} - -#ifdef MOZILLA_CLIENT -HG83667 - -PRIVATE int32 -net_HTMLPanelLoad(ActiveEntry *ce) -{ - if(ce->URL_s) - StrAllocCopy(ce->URL_s->charset, INTL_ResourceCharSet()); -#if 0 /* Used to be MODULAR_NETLIB */ - XP_HandleHTMLPanel(ce->URL_s); -#endif - return -1; -} - -PRIVATE int32 -net_HTMLDialogLoad(ActiveEntry *ce) -{ - if(ce->URL_s) - StrAllocCopy(ce->URL_s->charset, INTL_ResourceCharSet()); -#if 0 /* Used to be MODULAR_NETLIB */ - XP_HandleHTMLDialog(ce->URL_s); -#endif - return -1; -} - -PRIVATE int32 -net_WysiwygLoad(ActiveEntry *ce) -{ - const char *real_url = LM_SkipWysiwygURLPrefix(ce->URL_s->address); - char *new_address; - - /* XXX can't use StrAllocCopy because it frees dest first */ - if (real_url && (new_address = PL_strdup(real_url)) != NULL) - { - PR_Free(ce->URL_s->address); - ce->URL_s->address = new_address; - FREE_AND_CLEAR(ce->URL_s->wysiwyg_url); - } - - /* no need to free real_url */ - - ce->status = MK_DO_REDIRECT; - return MK_DO_REDIRECT; -} - -PRIVATE int32 -net_ProtoMainStub(ActiveEntry *ce) -{ -#ifdef DO_ANNOYING_ASSERTS_IN_STUBS - PR_ASSERT(0); -#endif - return -1; -} - -PRIVATE void -net_ProtoCleanupStub(void) -{ -} - -PRIVATE void -net_reg_random_protocol(NET_ProtoInitFunc *LoadRoutine, int type) -{ - NET_ProtoImpl *random_proto_impl; - - random_proto_impl = PR_NEW(NET_ProtoImpl); - - if(!random_proto_impl) - return; - - random_proto_impl->init = LoadRoutine; - random_proto_impl->process = net_ProtoMainStub; - random_proto_impl->interrupt = net_ProtoMainStub; - random_proto_impl->resume = NULL; /* not usually need */ - random_proto_impl->cleanup = net_ProtoCleanupStub; - - NET_RegisterProtocolImplementation(random_proto_impl, type); -} - -/* don't you just hate it when people come along and hack this - * kind of stuff into your code. - * - * @@@ clean this up some time - */ -PRIVATE void -NET_InitTotallyRandomStuffPeopleAddedProtocols(void) -{ - HG00484 - net_reg_random_protocol(net_HTMLPanelLoad, HTML_PANEL_HANDLER_TYPE_URL); - net_reg_random_protocol(net_HTMLDialogLoad, HTML_DIALOG_HANDLER_TYPE_URL); - net_reg_random_protocol(net_WysiwygLoad, WYSIWYG_TYPE_URL); -} - -#endif /* MOZILLA_CLIENT */ - -/* - * Check the no_proxy environment variable to get the list - * of hosts for which proxy server is not consulted. - * - * no_proxy is a comma- or space-separated list of machine - * or domain names, with optional :port part. If no :port - * part is present, it applies to all ports on that domain. - * - * Example: "netscape.com,some.domain:8001" - * - */ -PRIVATE Bool override_proxy (CONST char * URL) -{ - char * p = NULL; - char * host = NULL; - int port = 0; - int h_len = 0; - char *no_proxy = MKno_proxy; - - if(no_proxy==NULL) - return(FALSE); - - if (!(host = NET_ParseURL(URL, GET_HOST_PART))) - return NO; - - if (!*host) - { - PR_Free(host); - return NO; - } - - p = PL_strchr(host, ':'); - if (p) /* Port specified */ - { - *p++ = 0; /* Chop off port */ - port = atoi(p); - } - else - { /* Use default port */ - char * access = NET_ParseURL(URL, GET_PROTOCOL_PART); - if (access) { - if (!PL_strcmp(access,"http")) port = 80; - else if (!PL_strcmp(access,"gopher")) port = 70; - else if (!PL_strcmp(access,"ftp")) port = 21; - PR_Free(access); - } - } - if (!port) port = 80; /* Default */ - h_len = PL_strlen(host); - - while (*no_proxy) { - char * end; - char * colon = NULL; - int templ_port = 0; - int t_len; - - while (*no_proxy && (isspace(*no_proxy) || *no_proxy==',')) - no_proxy++; /* Skip whitespace and separators */ - - end = no_proxy; - while (*end && !isspace(*end) && *end != ',') /* Find separator */ - { - if (*end==':') colon = end; /* Port number given */ - end++; - } - - if (colon) - { - templ_port = atoi(colon+1); - t_len = colon - no_proxy; - } - else - { - t_len = end - no_proxy; - } - - /* don't worry about case when comparing the requested host to the proxies in the - no proxy list, i.e. use PL_strncasecmp */ - if ((!templ_port || templ_port == port) && (t_len > 0 && t_len <= h_len && - !PL_strncasecmp(host + h_len - t_len, no_proxy, t_len))) - { - PR_Free(host); - return YES; - } - if (*end) - no_proxy = end+1; - else - break; - } - - PR_Free(host); - return NO; -} - -PUBLIC void -NET_SetProxyServer(NET_ProxyType type, const char * org_host_port) -{ - char *host_port = 0; - - if(org_host_port && *org_host_port) { - host_port = PL_strdup(org_host_port); - - if(!host_port) - return; - - /* limit the size of host_port to within MAXHOSTNAMELEN */ - if(PL_strlen(host_port) > MAXHOSTNAMELEN) - host_port[MAXHOSTNAMELEN] = '\0'; - } - - TRACEMSG(("NET_SetProxyServer called with host: %-.1900s", - host_port ? host_port : "(null)")); - - switch(type) - { - case PROXY_AUTOCONF_URL: - if (host_port) { - if (!MKproxy_ac_url || PL_strcmp(MKproxy_ac_url, org_host_port)) { - StrAllocCopy(MKproxy_ac_url, org_host_port); - NET_ProxyAcLoaded = FALSE; - } - } - else { - if (MKproxy_ac_url) { - FREE_AND_CLEAR(MKproxy_ac_url); - NET_ProxyAcLoaded = FALSE; - } - } - break; - - case FTP_PROXY: - if(host_port) - StrAllocCopy(MKftp_proxy, host_port); - else - FREE_AND_CLEAR(MKftp_proxy); - break; - case GOPHER_PROXY: - if(host_port) - StrAllocCopy(MKgopher_proxy, host_port); - else - FREE_AND_CLEAR(MKgopher_proxy); - break; - case HTTP_PROXY: - if(host_port) - StrAllocCopy(MKhttp_proxy, host_port); - else - FREE_AND_CLEAR(MKhttp_proxy); - break; - HG88000 - case NEWS_PROXY: - if(host_port) - StrAllocCopy(MKnews_proxy, host_port); - else - FREE_AND_CLEAR(MKnews_proxy); - break; - case WAIS_PROXY: - if(host_port) - StrAllocCopy(MKwais_proxy, host_port); - else - FREE_AND_CLEAR(MKno_proxy); - break; - - case NO_PROXY: - if(host_port) - StrAllocCopy(MKno_proxy, org_host_port); - break; - - default: - /* ignore */ - break; - } - - FREEIF(host_port); -} - -/* return a proxy server host and port to the caller or NULL - * - * all this proxy bussiness should be rewritten to be generalized - * and not switch() based [LJM] - */ -MODULE_PRIVATE char * -NET_FindProxyHostForUrl(int url_type, char *url_address) -{ - - if(override_proxy(url_address)) - return NULL; - - switch(url_type) - { - case FTP_TYPE_URL: - return MKftp_proxy; - break; - - case GOPHER_TYPE_URL: - return(MKgopher_proxy); - break; - - case HTTP_TYPE_URL: - case URN_TYPE_URL: - case NFS_TYPE_URL: - return(MKhttp_proxy); - break; - - HG50027 - - case NEWS_TYPE_URL: - case INTERNAL_NEWS_TYPE_URL: - return(MKnews_proxy); - break; - - case WAIS_TYPE_URL: - return(MKwais_proxy); - break; - - default: - /* ignore */ - break; - } - - return NULL; -} - -/* Force it to reload automatic proxy config. - * This function simply sets a flag so the config will be - * reloaded during the next geturl. It doesn't actually - * do the reloading here. */ -#ifdef MOZILLA_CLIENT -PUBLIC void -NET_ReloadProxyConfig(MWContext *window_id) -{ - /* if we have a global config load it */ - if (MKglobal_config_url) - NET_GlobalAcLoaded = FALSE; - /* else if we have an old style proxy config and we are set on automatic...load it - * , or if we're using the old style proxy config that is actually a proxy autodiscovery - * url, reload it also */ - else if( (MKproxy_ac_url && (!MKproxy_style || MKproxy_style == PROXY_STYLE_AUTOMATIC)) - || (NET_UsingPadPac()) ) - NET_ProxyAcLoaded = FALSE; -} -#endif /* MOZILLA_CLIENT */ - - -/* Debugging routine prints an URL (and string "header") - */ -#ifdef DEBUG -void TraceURL (URL_Struct *url, char *header) -{ - TRACEMSG(("URL %-.1900s", header)); - if (url->address) TRACEMSG((" address %s", url->address)); - if (url->content_length) TRACEMSG((" content_length %i", url->content_length)); - if (url->content_type) TRACEMSG((" content_type %s", url->content_type)); - if (url->content_encoding) TRACEMSG((" content_encoding %s", url->content_encoding)); -} -#endif - -/* This function's existance was prompted by the front end desiring the ability to put the - client in kiosk mode. The function removes any potentially sensitive information from the - background: passwords, caches, histories, cookies. */ -/* fix Mac warning of missing prototype */ -PUBLIC void -NET_DestroyEvidence(); - -PUBLIC void -NET_DestroyEvidence() -{ - int32 oldSize = 0; - - /* Handle authorizations */ - NET_RemoveAllAuthorizations(); - - /* Handle global history */ - GH_ClearGlobalHistory(); - - /* Handle Session History */ - - /* Handle cookies */ - NET_RemoveAllCookies(); - -#if defined(SingleSingon) - /* Handle single signons */ - SI_RemoveAllSignonData(); -#endif - - /* Handle disk cache */ - oldSize = NET_GetDiskCacheSize(); - NET_SetDiskCacheSize(0); /* zero it out */ - NET_SetDiskCacheSize(oldSize); /* set it back up */ - - /* Handle memory cache */ - oldSize = NET_GetMemoryCacheSize(); - NET_SetMemoryCacheSize(0); /* zero it out */ - NET_SetMemoryCacheSize(oldSize); /* set it back up */ -} - -#if !defined(OLD_MOZ_MAIL_NEWS) && !defined(MOZ_MAIL_COMPOSE) - -/* this whole mess should get moved to the mksmtp.c file - * where it can share the InitMailtoProtocol function - * since that is what it is trying to replace - * - * for now InitMailto will be duplicated inside the ifdef. - */ - -#define CE_URL_S cur_entry->URL_s -#define CE_STATUS cur_entry->status - -extern void FE_AlternateCompose( - char * from, char * reply_to, char * to, char * cc, char * bcc, - char * fcc, char * newsgroups, char * followup_to, - char * organization, char * subject, char * references, - char * other_random_headers, char * priority, - char * attachment, char * newspost_url, char * body); - -MODULE_PRIVATE -int32 net_MailtoLoad (ActiveEntry * cur_entry) -{ - char *parms = NET_ParseURL (CE_URL_S->address, GET_SEARCH_PART); - char *rest = parms; - char *from = 0; /* internal only */ - char *reply_to = 0; /* internal only */ - char *to = 0; - char *cc = 0; - char *bcc = 0; - char *fcc = 0; /* internal only */ - char *newsgroups = 0; - char *followup_to = 0; - char *html_part = 0; /* internal only */ - char *organization = 0; /* internal only */ - char *subject = 0; - char *references = 0; - char *attachment = 0; /* internal only */ - char *body = 0; - char *other_random_headers = 0; /* unused (for now) */ - char *priority = 0; - char *newshost = 0; /* internal only */ - HG72762 - char *newspost_url = 0; - XP_Bool force_plain_text = FALSE; - to = NET_ParseURL (CE_URL_S->address, GET_PATH_PART); - if (rest && *rest == '?') - { - /* start past the '?' */ - rest++; - rest = strtok (rest, "&"); - while (rest && *rest) - { - char *token = rest; - char *value = 0; - char *eq = PL_strchr (token, '='); - if (eq) - { - value = eq+1; - *eq = 0; - } - switch (*token) - { - case 'A': case 'a': - if (!PL_strcasecmp (token, "attachment") && - CE_URL_S->internal_url) - StrAllocCopy (attachment, value); - break; - case 'B': case 'b': - if (!PL_strcasecmp (token, "bcc")) - { - if (bcc && *bcc) - { - StrAllocCat (bcc, ", "); - StrAllocCat (bcc, value); - } - else - { - StrAllocCopy (bcc, value); - } - } - else if (!PL_strcasecmp (token, "body")) - { - if (body && *body) - { - StrAllocCat (body, "\n"); - StrAllocCat (body, value); - } - else - { - StrAllocCopy (body, value); - } - } - break; - case 'C': case 'c': - if (!PL_strcasecmp (token, "cc")) - { - if (cc && *cc) - { - StrAllocCat (cc, ", "); - StrAllocCat (cc, value); - } - else - { - StrAllocCopy (cc, value); - } - } - break; - HG16262 - case 'F': case 'f': - if (!PL_strcasecmp (token, "followup-to")) - StrAllocCopy (followup_to, value); - else if (!PL_strcasecmp (token, "from") && - CE_URL_S->internal_url) - StrAllocCopy (from, value); - else if (!PL_strcasecmp (token, "force-plain-text") && - CE_URL_S->internal_url) - force_plain_text = TRUE; - break; - case 'H': case 'h': - if (!PL_strcasecmp(token, "html-part") && - CE_URL_S->internal_url) { - StrAllocCopy(html_part, value); - } - case 'N': case 'n': - if (!PL_strcasecmp (token, "newsgroups")) - StrAllocCopy (newsgroups, value); - else if (!PL_strcasecmp (token, "newshost") && - CE_URL_S->internal_url) - StrAllocCopy (newshost, value); - break; - case 'O': case 'o': - if (!PL_strcasecmp (token, "organization") && - CE_URL_S->internal_url) - StrAllocCopy (organization, value); - break; - case 'R': case 'r': - if (!PL_strcasecmp (token, "references")) - StrAllocCopy (references, value); - else if (!PL_strcasecmp (token, "reply-to") && - CE_URL_S->internal_url) - StrAllocCopy (reply_to, value); - break; - case 'S': case 's': - if(!PL_strcasecmp (token, "subject")) - StrAllocCopy (subject, value); - HG72661 - break; - case 'P': case 'p': - if (!PL_strcasecmp (token, "priority")) - StrAllocCopy (priority, value); - break; - case 'T': case 't': - if (!PL_strcasecmp (token, "to")) - { - if (to && *to) - { - StrAllocCat (to, ", "); - StrAllocCat (to, value); - } - else - { - StrAllocCopy (to, value); - } - } - break; - } - if (eq) - *eq = '='; /* put it back */ - rest = strtok (0, "&"); - } - } - - FREEIF (parms); - if (to) - NET_UnEscape (to); - if (cc) - NET_UnEscape (cc); - if (subject) - NET_UnEscape (subject); - if (newsgroups) - NET_UnEscape (newsgroups); - if (references) - NET_UnEscape (references); - if (attachment) - NET_UnEscape (attachment); - if (body) - NET_UnEscape (body); - if (newshost) - NET_UnEscape (newshost); - - if(newshost) - { - char *prefix = "news://"; - /* char *slash = PL_strrchr (newshost, '/'); -- unused */ - HG32828 - newspost_url = (char *) PR_Malloc (PL_strlen (prefix) + - PL_strlen (newshost) + 10); - if (newspost_url) - { - PL_strcpy (newspost_url, prefix); - PL_strcat (newspost_url, newshost); - PL_strcat (newspost_url, "/"); - } - } - else - { - HG13227 - newspost_url = PL_strdup ("news:"); - } - -#if defined(XP_WIN) || defined(XP_UNIX) /* other FE's add here when Front end code added */ - FE_AlternateCompose( - from, reply_to, to, cc, bcc, fcc, - newsgroups, followup_to, organization, - subject, references, other_random_headers, - priority, attachment, newspost_url, body ); -#endif /* XP_WIN */ - - FREEIF(from); - FREEIF(reply_to); - FREEIF(to); - FREEIF(cc); - FREEIF(bcc); - FREEIF(fcc); - FREEIF(newsgroups); - FREEIF(followup_to); - FREEIF(html_part); - FREEIF(organization); - FREEIF(subject); - FREEIF(references); - FREEIF(attachment); - FREEIF(body); - FREEIF(other_random_headers); - FREEIF(newshost); - FREEIF(priority); - FREEIF(newspost_url); - - CE_STATUS = MK_NO_DATA; - return(-1); -} - -PRIVATE int32 -net_MailtoStub(ActiveEntry *ce) -{ -#ifdef DO_ANNOYING_ASSERTS_IN_STUBS - PR_ASSERT(0); -#endif - return(0); /* Well the function definition says it returns SOMETHING! */ -} -PRIVATE void -net_CleanupMailtoStub(void) -{ -#ifdef DO_ANNOYING_ASSERTS_IN_STUBS - PR_ASSERT(0); -#endif -} - -MODULE_PRIVATE void -NET_InitMailtoProtocol(void) -{ - static NET_ProtoImpl mailto_proto_impl; - - mailto_proto_impl.init = net_MailtoLoad; - mailto_proto_impl.process = net_MailtoStub; - mailto_proto_impl.interrupt = net_MailtoStub; - mailto_proto_impl.resume = NULL; - mailto_proto_impl.cleanup = net_CleanupMailtoStub; - - NET_RegisterProtocolImplementation(&mailto_proto_impl, MAILTO_TYPE_URL); -} - -#endif /* OLD_MOZ_MAIL_NEWS */ - -#ifdef TRUST_LABELS -/* given a URL search the list of URL_s structures for one that has - * a non-empty trust list. - * Return a pointer to the non empty trust last */ -XP_List * NET_GetTrustList( char *TargetURL ) -{ - XP_List *RetList = NULL; - XP_List * list_ptr; - URL_Struct * tmpURLs; - char *FromURLs = NULL; - char *FromTarget = NULL; - - if ( TargetURL && PL_strlen( TargetURL ) ) { - LIBNET_LOCK(); - list_ptr = net_URL_sList; - while((tmpURLs = (URL_Struct *) XP_ListNextObject(list_ptr)) != NULL) { - /* first check if this URL_Struct has a trust list. If it does then do - * the name parsing on both URLs. Check for an empty list because due to - * thread switching the list could have been created but no entries added - * to it. */ - if ( tmpURLs->TrustList != NULL && !XP_ListIsEmpty( tmpURLs->TrustList ) ) { - /* This entry has a trustList, see if the URS match. To be safe strip both - * URLs down to host/domain/file. If there is a match - * return the pointer to the trust list */ - char *FromURLs = NET_ParseURL (tmpURLs->address, GET_PATH_PART); - char *FromTarget = NET_ParseURL (TargetURL, GET_PATH_PART); - if( PL_strcmp( FromURLs, FromTarget) == 0 ) { - /* we have a match */ - RetList = tmpURLs->TrustList; - break; - } - } - } - FREEIF( FromURLs ); - FREEIF( FromTarget ); - LIBNET_UNLOCK(); - } - return RetList; -} - -#endif - - -#ifdef PROFILE -#pragma profile off -#endif diff --git a/mozilla/network/main/mkgeturl.h b/mozilla/network/main/mkgeturl.h deleted file mode 100644 index bb44fd6d040..00000000000 --- a/mozilla/network/main/mkgeturl.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKGETURL_H -#define MKGETURL_H - -#include "xp.h" - -/* default values */ -#define DEF_DNS_EXPIRATION 900 -#define DEF_MEM_CACHE_SIZE 8192 -#define DEF_DISK_CACHE_SIZE 7680 -#define DEF_CHECK_DOC_FREQ 0 -#define DEF_ALLOW_AT_SIGN_UNAME FALSE -#define DEF_PROXY_TYPE 3 -#define DEF_COOKIE_BEHAVIOR 0 - -/* fix Mac warnings about missing prototypes */ -MODULE_PRIVATE int PR_CALLBACK -NET_PrefChangedFunc(const char *pref, void *data); - -PUBLIC void NET_DisableGetURL(void); -MODULE_PRIVATE void -net_CallExitRoutine(Net_GetUrlExitFunc *exit_routine, - URL_Struct *URL_s, - int status, - FO_Present_Types format_out, - MWContext *window_id); - -/* Debugging routine prints an URL (and string "header") - */ -PR_BEGIN_EXTERN_C -#ifdef DEBUG -extern void TraceURL (URL_Struct *url, char *header); -#else -#define TraceURL(U,M) -#endif /* DEBUG */ -PR_END_EXTERN_C - -/* forward declared; see below */ -typedef struct _NET_ProtoImpl NET_ProtoImpl; - -/* structure for maintaining multiple active data transfers - */ -typedef struct _ActiveEntry { - URL_Struct *URL_s; /* the URL data */ - int status; /* current status */ - int32 bytes_received; /* number of bytes received so far */ - PRFileDesc *socket; /* data sock */ - PRFileDesc *con_sock; /* socket waiting for connection */ - Bool local_file; /* are we reading a local file */ - Bool memory_file; /* are we reading from memory? */ - int protocol; /* protocol used for transfer */ - NET_ProtoImpl *proto_impl; /* handle to protocol implemenation */ - void *con_data; /* data about the transfer connection and status */ - /* routine to call when finished */ - Net_GetUrlExitFunc *exit_routine; - MWContext * window_id; /* a unique window id */ - FO_Present_Types format_out; /* the output format */ - - NET_StreamClass * save_stream; /* used for cacheing of partial docs - * The file code opens this stream - * and writes part of the file down it. - * Then the stream is saved - * and the rest is loaded from the - * network - */ - Bool busy; - - char * proxy_conf; /* Proxy autoconfig string */ - char * proxy_addr; /* Proxy address in host:port format */ - unsigned long socks_host; /* SOCKS host IP address */ - short socks_port; /* SOCKS port number */ - -} ActiveEntry; - -/* typedefs of protocol implementation functions - * - * All these currently take an ActiveEntry Struct but - * should probably be abstracted out considerably more - */ -typedef int32 NET_ProtoInitFunc(ActiveEntry *ce); -typedef int32 NET_ProtoProcessFunc(ActiveEntry *ce); -typedef int32 NET_ProtoInterruptFunc(ActiveEntry *ce); -typedef int32 NET_ProtoCleanupFunc(void); - -/* a structure to hold the registered implementation of - * a protocol converter - */ -struct _NET_ProtoImpl { - int32 (*init) (ActiveEntry *ce); - int32 (*process) (ActiveEntry *ce); - int32 (*interrupt) (ActiveEntry *ce); - void (*resume) (ActiveEntry *ce, NET_AuthClosure *, PRBool); - /* callback to resume paused streams */ - void (*cleanup) (void); /* note that cleanup can be called more - * than once, when we need to shut down - * connections or free up memory - */ - char * scheme; /* What scheme does this protocol implementation handle */ -}; - -PR_BEGIN_EXTERN_C -extern int NET_TotalNumberOfOpenConnections; -extern int NET_MaxNumberOfOpenConnections; -extern CacheUseEnum NET_CacheUseMethod; -extern time_t NET_StartupTime; /* time we began the program */ -extern PRBool NET_ProxyAcLoaded; -/* - * Silently Interrupts all transfers in progress that have the same - * window id as the one passed in. - */ -extern int NET_SilentInterruptWindow(MWContext * window_id); -/* cause prefs to be read or updated */ -extern void NET_SetupPrefs(const char * prefChanged); - -extern NET_ProxyStyle NET_GetProxyStyle(void); -extern const char * net_GetPACUrl(void); -extern void net_SetPACUrl(char *u); - -/* return a proxy server host and port to the caller or NULL - */ -extern char * NET_FindProxyHostForUrl(int urltype, char *urladdress); - -/* registers a protocol impelementation for a particular url_type - * see NET_URL_Type() for types - */ -PR_EXTERN(void) -NET_RegisterProtocolImplementation(NET_ProtoImpl *impl, int for_url_type); - - -#ifdef TRUST_LABELS -/* given a URL search the list of URL_s structures for one that matches - * and has a non-empty trust list */ -extern XP_List * NET_GetTrustList( char *TargetURL ); -#endif - -NET_ProtoImpl * net_get_protocol_impl(int for_url_type); -MODULE_PRIVATE int32 net_MailtoLoad (ActiveEntry * cur_entry); - -PR_END_EXTERN_C -#endif /* not MKGetURL_H */ diff --git a/mozilla/network/main/mkhelp.c b/mozilla/network/main/mkhelp.c deleted file mode 100644 index db2829be400..00000000000 --- a/mozilla/network/main/mkhelp.c +++ /dev/null @@ -1,1030 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*************************************************** - * - * Routines to parse HTML help mapping file - */ - -#include "mkutils.h" -#include "netutils.h" -#include "xp.h" -#include "mkparse.h" -#include "mkhelp.h" -#include "xp_help.h" -#include "xpgetstr.h" -#include "libmocha.h" /* For the onHelp handler */ -#include "prefapi.h" /* For the onHelp handler */ -#include "fe_proto.h" -#include "mkprefs.h" - -extern char * INTL_ResourceCharSet(void); - -extern int MK_OUT_OF_MEMORY; -extern int MK_CANT_LOAD_HELP_TOPIC; - -#define DEFAULT_HELP_ID "*" -#define DEFAULT_HELP_PROJECT "/help.hpf" /* Note the inclusion of the initial slash */ -#define DEFAULT_HELP_WINDOW_NAME "_HelpWindow" -#define DEFAULT_HELP_WINDOW_HEIGHT 500 -#define DEFAULT_HELP_WINDOW_WIDTH 400 - -#define PREF_NSCP_HELP_URL "http://help.netscape.com/nethelp/" /* This must include the trailing slash */ - -/* Tokens within the .hpf file to parse for */ - -#define ID_MAP_TOKEN "ID_MAP" -#define END_ID_MAP_TOKEN "/ID_MAP" -#define FRAME_GROUP_TOKEN "FRAME_GROUP" -#define SRC_TOKEN "SRC" -#define WINDOW_TOKEN "DEFAULT_WINDOW" -#define END_FRAME_GROUP_TOKEN "/FRAME_GROUP" -#define WINDOW_SIZE_TOKEN "WINDOW-SIZE" -#define WINDOW_NAME_TOKEN "WINDOW-NAME" -#define HELP_VERSION_TOKEN "NETHELP-VERSION" -#define TARGET_TOKEN "TARGET" - - -/* @@@ Global hack. See below */ -PRIVATE URL_Struct * frame_content_for_pre_exit_routine=NULL; - -typedef struct _HTMLHelpParseObj { - XP_Bool in_id_mapping; - int32 window_width; - int32 window_height; - int helpVersion; - char *window_name; - char *id_value; - char *default_id_value; - char *url_to_map_file; - char *id; - char *line_buffer; - int32 line_buffer_size; - char *content_target; - XP_List *frame_group_stack; -} HTMLHelpParseObj; - -typedef struct { - char *address; - char *target; -} frame_set_struct; - - -PRIVATE void -simple_exit(URL_Struct *URL_s, int status, MWContext *window_id) -{ - if(status != MK_CHANGING_CONTEXT) - NET_FreeURLStruct(URL_s); -} - - -PUBLIC void -XP_NetHelp(MWContext *pContext, const char *topic) -{ - MWContext *pActiveContext = NULL; - char *pHelpURLString = NULL; - - /* Prepend the vendor name "netscape/" to all of our own topics */ - - if (topic == NULL) { - pHelpURLString = PL_strdup("netscape/home"); - } else { - pHelpURLString = (char *) PR_Malloc(strlen(topic) + strlen("netscape/")+1); - if (!pHelpURLString) { - return; - } - PL_strcpy(pHelpURLString, "netscape/"); - PL_strcpy(&(pHelpURLString[9]), topic); - } - - /* Now get the right context to load it from */ - - if (pContext != NULL) { - pActiveContext = pContext; - } else { - pActiveContext = FE_GetNetHelpContext(); - } - - NET_LoadNetHelpTopic(pActiveContext, pHelpURLString); - - PR_FREEIF(pHelpURLString); -} - - -PUBLIC void -NET_LoadNetHelpTopic(MWContext *pContext, const char *topic) -{ - char *pNetHelpURLString; - URL_Struct *pHelpURL; - - if (topic == NULL) { - return; - } - - /* Convert the fully-specified topic into a nethelp URL: */ - - pNetHelpURLString = (char *) PR_Malloc(strlen(topic) + strlen(NETHELP_URL_PREFIX)+1); - if (!pNetHelpURLString) { - return; - } - - PL_strcpy(pNetHelpURLString, NETHELP_URL_PREFIX); - PL_strcpy(&(pNetHelpURLString[strlen(NETHELP_URL_PREFIX)]), topic); - - pHelpURL = NET_CreateURLStruct(pNetHelpURLString, NET_NORMAL_RELOAD); - - if (!pHelpURL) { - return; - } - - NET_GetURL(pHelpURL, FO_PRESENT, pContext, simple_exit); - - PR_FREEIF(pNetHelpURLString); - -} - -PRIVATE void -net_help_free_frame_group_struct(frame_set_struct *obj) -{ - PR_ASSERT(obj); - if(!obj) - return; - FREEIF(obj->address); - FREEIF(obj->target); - FREE(obj); -} - -/* load the HTML help mapping file and search for - * the id or text to load a specific document - */ -PUBLIC void -NET_GetHTMLHelpFileFromMapFile(MWContext *context, - char *map_file_url, - char *id, - char *search_text) -{ - URL_Struct *URL_s; - - PR_ASSERT(map_file_url && id); - - if(!map_file_url || !id) - return; - - URL_s = NET_CreateURLStruct(map_file_url, NET_DONT_RELOAD); - - if(!URL_s) - return; - - URL_s->fe_data = PL_strdup(id); - - NET_GetURL(URL_s, FO_CACHE_AND_LOAD_HTML_HELP_MAP_FILE, context, simple_exit); -} - -PRIVATE void -net_get_default_help_URL(char **pHelpBase) -{ - int success; - int32 helpType; - - if ((success = PREF_GetIntPref(pref_generalHelpSource, &helpType)) - == PREF_NOERROR) { - - switch (helpType) { - - case 0: /* Netscape's help site: */ - StrAllocCopy(*pHelpBase, PREF_NSCP_HELP_URL); - break; - case 1: /* Internal installed location. */ - *pHelpBase = FE_GetNetHelpDir(); - break; - case 2: - success = PREF_CopyCharPref(pref_generalHelpSourceUrl, pHelpBase); - break; - default: - success = PREF_ERROR; - } - /* ...any of the above might accidentally _not_ end with a '/'*/ - if ((*pHelpBase) && ((*pHelpBase)[PL_strlen(*pHelpBase)-1]) != '/') { - StrAllocCat(*pHelpBase, "/"); - } - } - - /* Fall back on the Netscape help site */ - - if (success != PREF_NOERROR) { - StrAllocCopy(*pHelpBase, PREF_NSCP_HELP_URL); - } - - return; -} - -/* EA: NETHELP Begin */ - /* Takes a nethelp: URL of the form - nethelp:vendor/component:topic[@location/[projectfile.hpf]] - - and separates into the mapping file, with which it replaces URL_s->address, - and a topic, which it places into URL_s->fe_data. - - If a fully specified location (one which includes a projectfile) is given, - the mapping file is set to that. If the given location ends in a slash, - then it is taken to be a directory, and the vendor and component are - appended as directories before the default projectfile name, helpidx.hpf. - If no location is given, the default help location is prepended to the - vendor and component and "helpidx.hpf". - - Examples: - - nethelp:netscape/navigator:url@http://help.netscape.com/navigator/navhelp.hpf - - mapping file: http://help.netscape.com/navigator/navhelp.hpf - - nethelp:netscape/navigator:url@http://help.netscape.com/ - - mapping file: http://help.netscape.com/netscape/navigator/help.hpf - - nethelp:netscape/navigator:url@http://help.netscape.com - - mapping file: http://help.netscape.com (this will result in an error) - - nethelp:netscape/navigator:url - - assuming the default help location were: C:\navigator\help - - mapping file: file:///C|/navigator/help/netscape/navigator/helpidx.hpf - - In all cases, the topic would be "url" - - */ - - -PUBLIC int -NET_ParseNetHelpURL(URL_Struct *URL_s) -{ - /* this is a nethelp: URL - * first, see if it's local or remote by checking for the @ - */ - char *remote_addr_ptr = 0; - char *remote_addr=0; - char *topic_ptr = 0; - char *topic = 0; - char *scheme_specific = 0; - char *pCharacter; - - XP_Bool appendProjFile = FALSE; - - remote_addr_ptr = PL_strchr(URL_s->address, '@'); - - if (!remote_addr_ptr) { - char *default_URL = 0; - - /* it's local, so we need to get the default, then append the project file */ - net_get_default_help_URL(&default_URL); - - if (default_URL) { - StrAllocCopy(remote_addr, default_URL); - PR_Free(default_URL); - } - - appendProjFile = TRUE; - - } else { - *remote_addr_ptr = '\0'; - - StrAllocCopy(remote_addr, remote_addr_ptr+1); - - if (remote_addr && (remote_addr[PL_strlen(remote_addr)] == '/')) { - /* Check to see if the remote_addr ends in a slash. If so, we - have some appending to do */ - - appendProjFile = TRUE; - } - } - - if (!remote_addr) { - /* We've obviously run into some kind of a memory problem here. */ - /* Time to bail */ - return MK_OUT_OF_MEMORY; - } - - /* By now, the URL_s->address has been stripped of any location information */ - /* First, remove the scheme, which is guaranteed to be there. */ - - scheme_specific = PL_strchr(URL_s->address, ':') + 1; - - topic_ptr = PL_strchr(scheme_specific, ':'); - - if (!topic_ptr) { - /* This is an error case, but we'll handle it anyway by defaulting to - the generic topic */ - - StrAllocCopy(topic, DEFAULT_HELP_ID); - } else { - *topic_ptr = '\0'; - StrAllocCopy(topic, topic_ptr+1); - - } - - if (appendProjFile) { - /* Now the URL_s->address will contain only the vendor/component information */ - - /* In an act of incredible lameness, we want to lowercase the - vendor/component, since we say that these will default to - lower case in the spec. - - FIXME!: Note that this may not be correct for double-byte encoded - characters, but the Intl team was unable to come up with a good - solution here; in general, we probably won't have any issue, since - URLs themselves should be in an ASCII-encoding (?). - */ - - pCharacter = scheme_specific; - - while (*pCharacter) - { - *pCharacter = (char) NET_TO_LOWER((unsigned int) *pCharacter); - pCharacter++; - } - - - StrAllocCat(remote_addr, scheme_specific); - StrAllocCat(remote_addr, DEFAULT_HELP_PROJECT); - } - - FREE(URL_s->address); - URL_s->address = remote_addr; - - /* If there is no topic, then we'll still attempt to load the project file and - its window. The other code below should detect the non-existence of a topic and - either revert to a default or do some other elegant solution. */ - - if (topic) { - NET_UnEscape(topic); - URL_s->fe_data = PL_strdup(topic); - } else { - URL_s->fe_data = NULL; - } - - FREEIF(topic); - - return MK_DATA_LOADED; -} - - -/* EA: NETHELP End */ - - -PRIVATE HTMLHelpParseObj * -net_ParseHTMLHelpInit(char *url_to_map_file, char *id) -{ - HTMLHelpParseObj *rv = PR_NEW(HTMLHelpParseObj); - - if(!rv) - return(NULL); - - PR_ASSERT(url_to_map_file && id); - - if(!url_to_map_file || !id) - return(NULL); - - memset(rv, 0, sizeof(HTMLHelpParseObj)); - - rv->url_to_map_file = PL_strdup(url_to_map_file); - rv->id = PL_strdup(id); - rv->helpVersion = 1; - - rv->window_height = DEFAULT_HELP_WINDOW_HEIGHT; - rv->window_width = DEFAULT_HELP_WINDOW_WIDTH; - - rv->frame_group_stack = XP_ListNew(); - - return(rv); -} - -PRIVATE void -net_ParseHTMLHelpFree(HTMLHelpParseObj * obj) -{ - PR_ASSERT(obj); - - if(!obj) - return; - - FREEIF(obj->window_name); - FREEIF(obj->id_value); - FREEIF(obj->default_id_value); - FREEIF(obj->url_to_map_file); - FREEIF(obj->line_buffer); - FREEIF(obj->id); - - if(obj->frame_group_stack) - { - frame_set_struct * frame_group_ptr; - - while((frame_group_ptr = XP_ListRemoveTopObject(obj->frame_group_stack)) != NULL) - net_help_free_frame_group_struct(frame_group_ptr); - - FREE(obj->frame_group_stack); - } - - FREE(obj); -} - -/* parse a line that looks like - * [whitespace]=[whitespace]"token" other stuff... - * - * return token or NULL. - */ -PRIVATE char * -net_get_html_help_token(char *line_data, char**next_word) -{ - char * line = line_data; - char * cp; - - if(next_word) - *next_word = NULL; - - while(NET_IS_SPACE(*line)) line++; - - if(*line != '=') - return(NULL); - - line++; /* go past '=' */ - - while(NET_IS_SPACE(*line)) line++; - - if(*line != '"') - return(NULL); - - line++; /* go past '"' */ - - for(cp=line; *cp; cp++) - if(*cp == '"' && *(cp-1) != '\\') - { - *cp = '\0'; - if(next_word) - { - *next_word = cp+1; - while(NET_IS_SPACE(*(*next_word))) (*next_word)++; - } - break; - } - - return(line); -} - -/* parse lines in an HTML help mapping file. - * get window_size and name, etc... - * - * when the id is found function returns HTML_HELP_ID_FOUND - * on error function returns negative error code. - */ -PRIVATE int -net_ParseHTMLHelpLine(HTMLHelpParseObj *obj, char *line_data) -{ - char *line = XP_StripLine(line_data); - char *token; - char *next_word; - - if(*line == '<') - { - /* find and terminate the end '>' */ - strtok(line, ">"); - - token = XP_StripLine(line+1); - - if(!PL_strncasecmp(token, - ID_MAP_TOKEN, - sizeof(ID_MAP_TOKEN)-1)) - { - obj->in_id_mapping = TRUE; - } - else if(!PL_strncasecmp(token, - END_ID_MAP_TOKEN, - sizeof(END_ID_MAP_TOKEN)-1)) - { - obj->in_id_mapping = FALSE; - } - else if(!PL_strncasecmp(token, - FRAME_GROUP_TOKEN, - sizeof(FRAME_GROUP_TOKEN)-1)) - { - char *cp = token + sizeof(FRAME_GROUP_TOKEN)-1; - frame_set_struct * fgs = PR_NEW(frame_set_struct); - - while(isspace(*cp)) cp++; - - if(fgs) - { - memset(fgs, 0, sizeof(frame_set_struct)); - - next_word=NULL; /* init */ - - do { - if(!PL_strncasecmp(cp, SRC_TOKEN, sizeof(SRC_TOKEN)-1)) - { - char *address = net_get_html_help_token( - cp+sizeof(SRC_TOKEN)-1, - &next_word); - cp = next_word; - fgs->address = PL_strdup(address); - } - else if(!PL_strncasecmp(cp, - WINDOW_TOKEN, - sizeof(WINDOW_TOKEN)-1)) - { - char *window = net_get_html_help_token( - cp+sizeof(WINDOW_TOKEN)-1, - &next_word); - cp = next_word; - fgs->target = PL_strdup(window); - } - else - { - /* unknown attribute. Skip to next whitespace - */ - while(*cp && !isspace(*cp)) - cp++; - - - if(*cp) - { - while(isspace(*cp)) cp++; - next_word = cp; - } - else - { - next_word = NULL; - } - } - - } while(next_word); - - XP_ListAddObject(obj->frame_group_stack, fgs); - } - } - else if(!PL_strncasecmp(token, - END_FRAME_GROUP_TOKEN, - sizeof(END_FRAME_GROUP_TOKEN)-1)) - { - frame_set_struct *fgs; - - fgs = XP_ListRemoveTopObject(obj->frame_group_stack); - - if(fgs) - net_help_free_frame_group_struct(fgs); - } - } - else if(!obj->in_id_mapping) - { - if(!PL_strncasecmp(line, - WINDOW_SIZE_TOKEN, - sizeof(WINDOW_SIZE_TOKEN)-1)) - { - /* get window size */ - char *comma=0; - char *window_size = net_get_html_help_token(line+ - sizeof(WINDOW_SIZE_TOKEN)-1, - NULL); - - if(window_size) - comma = PL_strchr(window_size, ','); - - if(comma) - { - *comma = '\0'; - obj->window_width = XP_ATOI(window_size); - obj->window_height = XP_ATOI(comma+1); - } - } - else if(!PL_strncasecmp(line, - WINDOW_NAME_TOKEN, - sizeof(WINDOW_NAME_TOKEN)-1)) - { - char *window_name = net_get_html_help_token(line+ - sizeof(WINDOW_NAME_TOKEN)-1, - NULL); - - if(window_name) - { - FREEIF(obj->window_name); - obj->window_name = PL_strdup(window_name); - } - } - else if(!PL_strncasecmp(line, - HELP_VERSION_TOKEN, - sizeof(HELP_VERSION_TOKEN)-1)) - { - /* get window size */ - char *help_version = net_get_html_help_token(line+ - sizeof(HELP_VERSION_TOKEN)-1, - NULL); - - if(help_version) - { - obj->helpVersion = XP_ATOI(help_version); - } - } - } - else - { - /* id mapping pair */ - if(!PL_strncasecmp(line, obj->id, PL_strlen(obj->id))) - { - char *id_value = net_get_html_help_token(line+PL_strlen(obj->id), - &next_word); - - if(id_value) - { - obj->id_value = PL_strdup(id_value); - - while(next_word) - { - char *cp = next_word; - - if(!PL_strncasecmp(cp, - TARGET_TOKEN, - sizeof(TARGET_TOKEN)-1)) - { - char *target = net_get_html_help_token( - cp+sizeof(TARGET_TOKEN)-1, - &next_word); - cp = next_word; - obj->content_target = PL_strdup(target); - } - else - { - /* unknown attribute. Skip to next whitespace - */ - while(*cp && !isspace(*cp)) - cp++; - - if(*cp) - { - while(isspace(*cp)) cp++; - next_word = cp; - } - else - { - next_word = NULL; - } - } - } - } - - return(HTML_HELP_ID_FOUND); - } - if(!PL_strncasecmp(line, DEFAULT_HELP_ID, sizeof(DEFAULT_HELP_ID)-1)) - { - char *default_id_value = net_get_html_help_token( - line+sizeof(DEFAULT_HELP_ID)-1, - NULL); - - if(default_id_value) - obj->default_id_value = PL_strdup(default_id_value); - } - - } - - return(0); -} - -PRIVATE -int -NET_ParseHTMLHelpPut(HTMLHelpParseObj *obj, char *str, int32 len) -{ - int32 string_len; - char *new_line; - int32 status; - - if(!obj) - return(MK_OUT_OF_MEMORY); - - /* buffer until we have a line */ - BlockAllocCat(obj->line_buffer, obj->line_buffer_size, str, len); - obj->line_buffer_size += len; - - /* see if we have a line */ - while((new_line = strchr_in_buf(obj->line_buffer, - obj->line_buffer_size, - LF)) != NULL - || ((new_line = strchr_in_buf(obj->line_buffer, - obj->line_buffer_size, - CR)) != NULL) ) - { - /* terminate the line */ - *new_line = '\0'; - - status = net_ParseHTMLHelpLine(obj, obj->line_buffer); - - /* remove the parsed line from obj->line_buffer */ - string_len = (new_line - obj->line_buffer) + 1; - memcpy(obj->line_buffer, - new_line+1, - obj->line_buffer_size-string_len); - obj->line_buffer_size -= string_len; - - if(status == HTML_HELP_ID_FOUND) - return(HTML_HELP_ID_FOUND); - } - - return(0); -} - -PRIVATE void -net_HelpPreExitRoutine(URL_Struct *URL_s, int status, MWContext *context) -{ - - /* @@@@. I wanted to use the fe_data to pass the URL struct - * of the frame content URL. But the fe_data gets cleared - * by the front ends. Therefore I'm using a private global - * store the information. This will work fine as long - * as two help requests don't come in simulatainiously. - */ - - /* compatibility for previous versions of NetHelp */ - if(frame_content_for_pre_exit_routine) { - - NET_GetURL(frame_content_for_pre_exit_routine, - FO_CACHE_AND_PRESENT, - context, - simple_exit); - frame_content_for_pre_exit_routine=NULL; - } else { - LM_SendOnHelp(context); - } - - -} - -PRIVATE void -net_help_init_chrome(Chrome *window_chrome, int32 w, int32 h) -{ - window_chrome->type = MWContextHTMLHelp; - #if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_BEOS) - window_chrome->topmost = FALSE; - #else - window_chrome->topmost = TRUE; - #endif - window_chrome->w_hint = w; - window_chrome->h_hint = h; - window_chrome->allow_resize = TRUE; - window_chrome->show_scrollbar = TRUE; - window_chrome->allow_close = TRUE; - window_chrome->disable_commands = TRUE; - window_chrome->restricted_target = TRUE; -} - -PRIVATE void -net_ParseHTMLHelpLoadHelpDoc(HTMLHelpParseObj *obj, MWContext *context) -{ - URL_Struct *URL_s; - char *frame_address = NULL; - char *content_address = NULL; - MWContext *new_context; - frame_set_struct *fgs; - - if(obj->id_value || obj->default_id_value) - content_address = NET_MakeAbsoluteURL(obj->url_to_map_file, - obj->id_value ? - obj->id_value : - obj->default_id_value); - - if(!content_address) - { - FE_Alert(context, XP_GetString(MK_CANT_LOAD_HELP_TOPIC)); - return; - } - - fgs = XP_ListPeekTopObject(obj->frame_group_stack); - - if(fgs) - { - if(fgs->address) - { - frame_address = NET_MakeAbsoluteURL(obj->url_to_map_file, - fgs->address); - } - } - - if(frame_address) - URL_s = NET_CreateURLStruct(frame_address, NET_DONT_RELOAD); - else - URL_s = NET_CreateURLStruct(content_address, NET_DONT_RELOAD); - - if(!URL_s) - goto cleanup; - - URL_s->window_chrome = PR_NEW(Chrome); - - if(!URL_s->window_chrome) - goto cleanup; - - memset(URL_s->window_chrome, 0, sizeof(Chrome)); - - if(obj->window_name) - URL_s->window_target = PL_strdup(obj->window_name); - else - URL_s->window_target = PL_strdup(DEFAULT_HELP_WINDOW_NAME); - - net_help_init_chrome(URL_s->window_chrome, - obj->window_width, - obj->window_height); - - /* We want to revert the character set of the help frame from the standard - character set, not whatever happened to be the last viewed source */ - - StrAllocCopy(URL_s->charset, INTL_ResourceCharSet()); - - new_context = XP_FindNamedContextInList(NULL, URL_s->window_target); - - if(frame_address) - { - URL_Struct *content_URL_s; - - /* if there is a frame_address then we load the - * frame first and then load the contents - * in the frame exit function. - */ - content_URL_s = NET_CreateURLStruct(content_address, NET_DONT_RELOAD); - - if(obj->content_target) - content_URL_s->window_target = PL_strdup(obj->content_target); - else if(fgs->target) - content_URL_s->window_target = PL_strdup(fgs->target); - - /* doesn't work: URL_s->fe_data = (void *) content_URL_s; */ - - /* hack for older versions, see pre_exit_routine_above */ - if (obj->helpVersion < 2) { - frame_content_for_pre_exit_routine = content_URL_s; - } else { - frame_content_for_pre_exit_routine = NULL; - NET_FreeURLStruct(content_URL_s); - } - - URL_s->pre_exit_fn = net_HelpPreExitRoutine; - } - - if(!new_context) - { - - /* this will cause the load too */ - new_context = FE_MakeNewWindow(context, - URL_s, - (obj->window_name) ? obj->window_name : DEFAULT_HELP_WINDOW_NAME, - URL_s->window_chrome); - - if (HELP_INFO_PTR(*new_context) == NULL) { - new_context->pHelpInfo = PR_NEWZAP(HelpInfoStruct); - } - - if (HELP_INFO_PTR(*new_context)->topicURL != NULL) { - PR_Free(HELP_INFO_PTR(*new_context)->topicURL); - HELP_INFO_PTR(*new_context)->topicURL = NULL; - } - - StrAllocCopy(HELP_INFO_PTR(*new_context)->topicURL, content_address); - - } - else - { - - if (HELP_INFO_PTR(*new_context) == NULL) { - new_context->pHelpInfo = PR_NEWZAP(HelpInfoStruct); - } - - if (HELP_INFO_PTR(*new_context)->topicURL != NULL) { - PR_Free(HELP_INFO_PTR(*new_context)->topicURL); - HELP_INFO_PTR(*new_context)->topicURL = NULL; - } - - StrAllocCopy(HELP_INFO_PTR(*new_context)->topicURL, content_address); - - FE_RaiseWindow(new_context); - - /* Compatibility with earlier versions of NetHelp */ - if (obj->helpVersion < 2) { - FE_GetURL(new_context, URL_s); - } else { - LM_SendOnHelp(new_context); - } - } - -cleanup: - FREEIF(frame_address); - FREE(content_address); - - return; -} - -typedef struct { - HTMLHelpParseObj *parse_obj; - MWContext *context; - XP_Bool file_is_local; -} html_help_map_stream; - -PRIVATE int -net_HMFConvPut(NET_StreamClass *stream, char *s, int32 l) -{ - html_help_map_stream *obj=stream->data_object; - int status = NET_ParseHTMLHelpPut(obj->parse_obj, s, l); - - if(obj->file_is_local && status == HTML_HELP_ID_FOUND) - { - /* abort since we don't need any more of the file */ - return(MK_UNABLE_TO_CONVERT); - } - - return(status); -} - -PRIVATE int -net_HMFConvWriteReady(NET_StreamClass *stream) -{ - return(MAX_WRITE_READY); -} - -PRIVATE void -net_HMFConvComplete(NET_StreamClass *stream) -{ - html_help_map_stream *obj=stream->data_object; - net_ParseHTMLHelpLoadHelpDoc(obj->parse_obj, obj->context); - net_ParseHTMLHelpFree(obj->parse_obj); -} - -PRIVATE void -net_HMFConvAbort(NET_StreamClass *stream, int status) -{ - html_help_map_stream*obj=stream->data_object; - if(status == MK_UNABLE_TO_CONVERT) - net_ParseHTMLHelpLoadHelpDoc(obj->parse_obj, obj->context); - - net_ParseHTMLHelpFree(obj->parse_obj); -} - -PUBLIC NET_StreamClass * -NET_HTMLHelpMapToURL(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id) -{ - html_help_map_stream* obj; - NET_StreamClass* stream; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEW(html_help_map_stream); - if (obj == NULL) - { - FREE(stream); - return(NULL); - } - - memset(obj, 0, sizeof(html_help_map_stream)); -#ifdef NU_CACHE - if (URL_s->cache_file || URL_s->cache_object) - obj->file_is_local = TRUE; -#else - if(URL_s->cache_file || URL_s->memory_copy) - obj->file_is_local = TRUE; -#endif - else - obj->file_is_local = NET_IsLocalFileURL(URL_s->address); - - obj->parse_obj = net_ParseHTMLHelpInit(URL_s->address, URL_s->fe_data); - - if(!obj->parse_obj) - { - FREE(stream); - FREE(obj); - } - - obj->context = window_id; - stream->name = "HTML Help Map File converter"; - stream->complete = (MKStreamCompleteFunc) net_HMFConvComplete; - stream->abort = (MKStreamAbortFunc) net_HMFConvAbort; - stream->put_block = (MKStreamWriteFunc) net_HMFConvPut; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_HMFConvWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - return(stream); -} - - diff --git a/mozilla/network/main/mkhelp.h b/mozilla/network/main/mkhelp.h deleted file mode 100644 index abf513aaf95..00000000000 --- a/mozilla/network/main/mkhelp.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKHELP_H -#define MKHELP_H - -/* EA: Help Begin */ - -/* The following structure stores the URL of the current help topic and project - file of a help window. Because this information is accessed by a javascript - context sometime after the URL is delivered to the window, we needed a persistent - way in which the data would remain associated with a given window, and, - despite a great desire to not muck around with the MWContext, that was the - only thing that was in scope at the time. Lou Montoulli suggested using - fields that are part of the URL_struct, such as the fe_data and Chrome - fields, but these were not in scope at the time that the Javascript calls - were being evaluated. */ - -typedef struct HelpInfoStruct_ { - char *topicURL; - char *projectURL; -} HelpInfoStruct; - -#define HELP_INFO_PTR(MW_CTX) ((HelpInfoStruct *) (MW_CTX).pHelpInfo) - -/* Called by netlib to parse a nethelp URL. ParseNetHelpURL alters the - URL struct passed in to point to the location of the help project file - specified by the nethelp URL. */ - -extern int -NET_ParseNetHelpURL(URL_Struct *URL_s); - -/* stream converter to parse an HTML help mapping file - * and load the url associated with the id - */ -extern NET_StreamClass * -NET_HTMLHelpMapToURL(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id); - -#endif /* MKHELP_H */ - diff --git a/mozilla/network/main/mkinit.c b/mozilla/network/main/mkinit.c deleted file mode 100644 index f0ce99b34be..00000000000 --- a/mozilla/network/main/mkinit.c +++ /dev/null @@ -1,792 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * register all neccessary - * stream converters - */ - -/* Please leave outside of ifdef for window's precompiled headers. */ -#include "mkutils.h" - -#ifdef MOZILLA_CLIENT -#ifdef XP_UNIX /* this whole module is ifdef'd UNIX */ - -#include "netutils.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "mkformat.h" -#include "net.h" - -#include "cvview.h" -#include "cvdisk.h" -#include "cvproxy.h" -#include "cvextcon.h" -#include "txview.h" - -#include "xlate.h" - -#include "libi18n.h" /* For character code set conversion stream */ - -#include "cvactive.h" - -#include "pa_parse.h" - -#include "np.h" - -#include "il_strm.h" /* Image Library stream converters. */ - -/* The master database of mail cap info (link list) */ - -PRIVATE XP_List *NET_mcMasterList = 0; /* May want to save out this info */ - -PUBLIC void -NET_mdataFree(NET_mdataStruct *md) -{ - FREEIF(md->contenttype); - FREEIF(md->command); - FREEIF(md->testcommand); - FREEIF(md->label); - FREEIF(md->printcommand); - FREEIF(md->src_string); - FREEIF(md->xmode); - FREE(md); - md = NULL; -} - -/* File is a directory ?*/ -PRIVATE Bool -net_isDir(char *name) -{ - XP_StatStruct st; - if (!name || !*name) return (FALSE); - if (!stat (name, &st) && S_ISDIR(st.st_mode)) - return (TRUE); - else - return (FALSE); -} - -PUBLIC void -NET_CleanupMailCapList(char* filename) -{ - NET_mdataStruct *mdata; - FILE *fp = NULL; - XP_List *modifiedList = NULL; - - if ( !NET_mcMasterList ) return; - - if ( filename && *filename ) - { - /* Invalid filename, then don't write */ - if ( net_isDir(filename) ) - return; - fp = fopen(filename, "w"); - if ( !fp ) return; - modifiedList = XP_ListNew(); - - while ((mdata=(NET_mdataStruct *)XP_ListRemoveEndObject(NET_mcMasterList))) - { - if (mdata->is_local ) - { - if ( mdata->src_string && *mdata->src_string) - { - fputs(mdata->src_string, fp); - if ( mdata->src_string[strlen(mdata->src_string)-1] != '\n' ) - fputs("\n", fp); - } - else mdata->src_string = 0; - - NET_mdataFree(mdata); - } - else if (mdata->is_modified) - XP_ListAddObject(modifiedList, mdata); - else - { - NET_mdataFree(mdata); - } - } - while ((mdata=(NET_mdataStruct *)XP_ListRemoveEndObject(modifiedList))) - { - if ( mdata->src_string && *mdata->src_string) - { - fputs(mdata->src_string, fp); - if ( mdata->src_string[strlen(mdata->src_string)-1] != '\n' ) - fputs("\n", fp); - } - else mdata->src_string = 0; - NET_mdataFree(mdata); - } - - fclose(fp); - } - else - { - while ((mdata = (NET_mdataStruct *)XP_ListRemoveEndObject(NET_mcMasterList))) - { - NET_mdataFree(mdata); - } - } - XP_ListDestroy(NET_mcMasterList); - NET_mcMasterList = 0; -} - -/* register all your converters - * - * YOU MUST register a "*" converter for - * EVERY format out type, this acts as a default - * and prevents a "Could not convert error" - */ -PUBLIC void -NET_RegisterConverters (char * personal_file, char * global_file) -{ - - - NET_CleanupMailCapList(NULL); - NET_mcMasterList = XP_ListNew(); - - NET_RegisterMIMEDecoders (); - - NET_RegisterExternalViewerCommand (IMAGE_WILDCARD, "xv %s", 0); - - NET_RegisterExternalViewerCommand ("audio/ulaw", "playulaw", 2000); - -#ifdef NOT /* NO default audio */ -#ifdef __sun - NET_RegisterExternalViewerCommand (AUDIO_BASIC, "cat > /dev/audio", 2000); -#else - NET_RegisterExternalViewerCommand (AUDIO_BASIC, "playulaw", 2000); -#endif /* __sgi */ -#endif /* NOT */ - - NET_RegisterExternalViewerCommand (VIDEO_MPEG, - /* throw away stderr and stdout, since - mpeg_play is so darn noisy. */ - "mpeg_play %s >/dev/null 2>&1", 0); - - NET_RegisterExternalViewerCommand ("image/x-xwd", "xwud", 2000); - - /* global file must come first!!!!!!!!!!!!!! - */ - if (global_file) - NET_ProcessMailcapFile (global_file, FALSE); - - if (personal_file) - NET_ProcessMailcapFile (personal_file, TRUE); -} - -/* - * before you modify this, - * make darn sure you want to deviuate from the standard bellcore mailcap - * handling!! *this means you Garrett!!*" - * - * Code borrowed from: - * - * Copyright (c) 1991 Bell Communications Research, Inc. (Bellcore) - * - * Permission to use, copy, modify, and distribute this material - * for any purpose and without fee is hereby granted, provided - * that the above copyright notice and this permission notice - * appear in all copies, and that the name of Bellcore not be - * used in advertising or publicity pertaining to this - * material without the specific, prior written permission - * of an authorized representative of Bellcore. BELLCORE - * MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY - * OF THIS MATERIAL FOR ANY PURPOSE. IT IS PROVIDED "AS IS", - * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. - */ - -/* - * Metamail -- A tool to help diverse mail readers - * cope with diverse multimedia mail formats. - * - * Author: Nathaniel S. Borenstein, Bellcore - * - */ - -struct MailcapEntry { - char *contenttype; - char *command; - char *testcommand; - int needsterminal; - int copiousoutput; - int needtofree; - char *label; - char *printcommand; - int32 stream_buffer_size; - char *xmode; -}; - -#define LINE_BUF_SIZE 2048 -#define TMPFILE_NAME_SIZE 127 - -PRIVATE char *GetCommand (char *s, char **t) -{ - char *s2; - int quoted = 0; - - s2 = (char *) PR_Malloc(PL_strlen(s)*2 + 3); /* absolute max, if all % signs */ - if(!s2) - return(NULL); - *s2 = 0; - *t = s2; - - - while (s && *s) - { - if (quoted) - { - if (*s == '%') - *s2++ = '%'; - - *s2++ = *s++; - quoted = 0; - } - else - { - if (*s == ';') - { - break; /* finish the string below */ - } - if (*s == '\\') - { - quoted = 1; - ++s; - } - else - { - *s2++ = *s++; - } - } - } - - /* look at the last character of the command and make sure it doesn't have - * a '&' - */ - if( s2 > *t && *(s2-1) == '&') - s2--; /* kill the ampersand */ - - *s2 = 0; /* terminate string */ - - if(*s) - return(s+1); - else - return(s); -} - -/* Trims leading and trailing space in the input string while converting - * it to all lower case. - * - * WARNING: Modified input string. - */ -PRIVATE char *Cleanse (char *s) -{ - char *tmp, *news, *tmpnews; - - news = s; - /* strip leading white space */ - while (*s && NET_IS_SPACE(*s)) ++s; - /* put in lower case */ - for (tmpnews=news, tmp=s; *tmp; tmpnews++, ++tmp) { - *tmpnews = tolower ((unsigned char)*tmp); - } - *tmpnews = '\0'; - /* strip trailing white space */ - while (*--tmpnews && NET_IS_SPACE(*tmpnews)) *tmpnews = 0; - return(news); -} - -PRIVATE void BuildCommand (char *Buf, char *controlstring, char *TmpFileName) -{ - char *from, *to; - int prefixed = 0; - - for (from=controlstring, to=Buf; *from != '\0'; from++) - { - if (prefixed) - { - prefixed = 0; - switch(*from) - { - case '%': - *to++ = '%'; - break; - case 'n': - case 'F': - fprintf(stderr, "metamail: Bad mailcap \"test\" clause: %s\n", controlstring); - case 's': - if (TmpFileName) - { - PL_strcpy(to, TmpFileName); - to += PL_strlen(TmpFileName); - } - break; - default: - fprintf(stderr, - "%s: Ignoring unsupported format code in mailcap file: %%%c\n", - XP_AppName, *from); - break; - } - } - else if (*from == '%') - { - prefixed = 1; - } - else - { - *to++ = *from; - } - } - *to = 0; -} - -static void -net_register_new_converter(char *contenttype, char *command, char *xmode, - int buffer_size) -{ - /* xmode takes priority over command */ - if (xmode && !PL_strcasecmp(xmode, NET_COMMAND_NETSCAPE)) - { - if ( !PL_strcasecmp(contenttype, TEXT_HTML) ) - NET_RegisterContentTypeConverter (TEXT_HTML, FO_PRESENT, - NULL, INTL_ConvCharCode); - else if (!PL_strcasecmp(contenttype, TEXT_MDL)) - NET_RegisterContentTypeConverter (TEXT_MDL, FO_PRESENT, - NULL, INTL_ConvCharCode); - - else if (!PL_strcasecmp(contenttype, TEXT_PLAIN)) - NET_RegisterContentTypeConverter (TEXT_PLAIN, FO_PRESENT, - NULL, NET_PlainTextConverter); - else if (!PL_strcasecmp(contenttype, IMAGE_GIF)) - NET_RegisterContentTypeConverter (IMAGE_GIF, - FO_PRESENT,NULL, IL_ViewStream); - - else if (!PL_strcasecmp(contenttype, IMAGE_ART)|| - !PL_strcasecmp(contenttype, IMAGE_ART2)) - NET_RegisterContentTypeConverter (IMAGE_ART, FO_PRESENT - ,NULL, IL_ViewStream); - - else if (!PL_strcasecmp(contenttype, IMAGE_XBM) || - !PL_strcasecmp(contenttype, IMAGE_XBM2) || - !PL_strcasecmp(contenttype, IMAGE_XBM3)) - NET_RegisterContentTypeConverter (IMAGE_XBM, - FO_PRESENT,NULL, IL_ViewStream); - - else if (!PL_strcasecmp(contenttype, IMAGE_JPG) || - !PL_strcasecmp(contenttype, IMAGE_PJPG)) - NET_RegisterContentTypeConverter (IMAGE_JPG, - FO_PRESENT,NULL, IL_ViewStream); - - else if (!PL_strcasecmp(contenttype, IMAGE_PNG)) - NET_RegisterContentTypeConverter (IMAGE_PNG, - FO_PRESENT,NULL, IL_ViewStream); - else if (!PL_strcasecmp(contenttype, - APPLICATION_NS_PROXY_AUTOCONFIG)) - NET_RegisterContentTypeConverter( - APPLICATION_NS_PROXY_AUTOCONFIG, - FO_PRESENT, - (void *)0, NET_ProxyAutoConfig); - else if (!PL_strcasecmp(contenttype, - APPLICATION_NS_JAVASCRIPT_AUTOCONFIG)) - NET_RegisterContentTypeConverter( - APPLICATION_NS_JAVASCRIPT_AUTOCONFIG, - FO_PRESENT, - (void *)0, NET_ProxyAutoConfig); - else - { - fprintf(stderr, - "%s: Ignoring unsupported netscape contenttype in user mailcap file.\n", XP_AppName); - } - } - else if (xmode && !strncasecmp(xmode, NET_COMMAND_PLUGIN, - strlen(NET_COMMAND_PLUGIN))) - { - char *pluginName = xmode + strlen(NET_COMMAND_PLUGIN); - /* For plugins enable the plugin for this mimetype */ - NPL_EnablePlugin(contenttype, pluginName, TRUE); - } - else if (xmode && - (!PL_strcasecmp(xmode, NET_COMMAND_SAVE_TO_DISK) || - !PL_strcasecmp(xmode, NET_COMMAND_SAVE_BY_NETSCAPE))) - NET_RegisterContentTypeConverter(contenttype, - FO_PRESENT, - NULL, fe_MakeSaveAsStream ); - - else if (xmode && !PL_strcasecmp(xmode, NET_COMMAND_UNKNOWN)) - NET_RegisterContentTypeConverter(contenttype, - FO_PRESENT, - NULL, fe_MakeSaveAsStream ); - - else if (xmode && !PL_strcasecmp(xmode,NET_COMMAND_DELETED)) - { - /* Do nothing */ - } - else if (command && *command )/* It's an external application then */ - { - - /* register the command - * - * but only if it isn't text/html - */ - if(PL_strcasecmp(contenttype, TEXT_HTML) && - PL_strcasecmp(contenttype, MESSAGE_RFC822) && - PL_strcasecmp(contenttype, MESSAGE_NEWS)) - NET_RegisterExternalViewerCommand(contenttype, command, buffer_size); - } -} - - -PRIVATE int PassesTest (struct MailcapEntry *mc) -{ - int result; - char *cmd, TmpFileName[TMPFILE_NAME_SIZE]; - - if (!mc->testcommand) return(1); - tmpnam(TmpFileName); - cmd = (char *)PR_Malloc(1024); - if (!cmd) - return(0); - BuildCommand(cmd, mc->testcommand, TmpFileName); - TRACEMSG(("Executing test command: %s\n", cmd)); - result = system(cmd); - free(cmd); - - remove(TmpFileName); - - if(result) - TRACEMSG(("[HTInit] Test failed!\n")); - else - TRACEMSG(("[HTInit] Test passed!\n")); - - return(result==0); -} - -PRIVATE int ProcessMailcapEntry (FILE *fp, struct MailcapEntry *mc, - char** src_string, Bool is_local) -{ - NET_cdataStruct *tmp_cd = NULL; - NET_cdataStruct *cd = NULL; - NET_mdataStruct *md = NULL; - int unprocessed_entryalloc = 1023, len; - char *unprocessed_entry, *s, *t, *buffer; - char *arg, *eq; - char *command=0; - - buffer = (char *) PR_Malloc(LINE_BUF_SIZE); - if (!buffer) - return 0; - unprocessed_entry = (char *) PR_Malloc(1 + unprocessed_entryalloc); - if (!unprocessed_entry) - { - free(buffer); - return 0; - } - *unprocessed_entry = '\0'; - while (fgets(buffer, LINE_BUF_SIZE, fp)) - { - if ( !*src_string ) - StrAllocCopy(*src_string, buffer ); - else - *src_string = XP_AppendStr(*src_string, buffer); - - if (buffer[0] == '#') - continue; - len = PL_strlen(buffer); - if (len == 0) - continue; - if (buffer[len-1] == '\n') - buffer[--len] = 0; - if ((len + PL_strlen(unprocessed_entry)) > unprocessed_entryalloc) - { - unprocessed_entryalloc += 1024; - unprocessed_entry = (char *) PR_Realloc(unprocessed_entry, unprocessed_entryalloc+1); - TRACEMSG(("Growing input line in mkinit")); - if (!unprocessed_entry) - { - TRACEMSG(("ERROR! Growing input line in mkinit")); - return 0; - } - } - if (len > 0 && buffer[len-1] == '\\') - { - buffer[len-1] = 0; - PL_strcat(unprocessed_entry, buffer); - } - else - { - PL_strcat(unprocessed_entry, buffer); - break; - } - } - - for (s=unprocessed_entry; *s && NET_IS_SPACE(*s); ++s) - ; /* NULL BODY */ - if (!*s) - { - /* totally blank entry -- quietly ignore */ - free(unprocessed_entry); - free(buffer); - return(0); - } - s = PL_strchr(unprocessed_entry, ';'); - if (s == NULL) - { - fprintf(stderr, "%s: Ignoring invalid mailcap entry: %s\n", - XP_AppName, unprocessed_entry); - free(unprocessed_entry); - free(buffer); - PR_Free(*src_string); - *src_string = 0; - return(0); - } - *s++ = 0; - mc->needsterminal = 0; - mc->copiousoutput = 0; - mc->needtofree = 1; - mc->testcommand = 0; - mc->label = NULL; - mc->printcommand = NULL; - mc->contenttype = 0; /* init */ - mc->xmode = 0; - mc->stream_buffer_size = 0; - StrAllocCopy(mc->contenttype, unprocessed_entry); /* copy */ - if (!mc->contenttype) - { - free(buffer); - TRACEMSG(("mailcap: no content-type")); - return 0; - } - s = GetCommand(s, &mc->command); - - while (s && *s != '\0') - { - arg = s; - eq = PL_strchr(arg, '='); - if (eq) - *eq++ = 0; - else - eq = arg; - - t = GetCommand(eq, &command); - - if (arg && *arg) - { - arg = Cleanse(arg); - if ( eq && !PL_strcmp(arg, NET_MOZILLA_FLAGS)) - { - /* xmode is case sensitive. That is why we dont Cleanse it. */ - mc->xmode = command; - command = 0; - } - else { - command = Cleanse(command); - if (eq && !PL_strcmp(arg, "test")) - { - mc->testcommand = command; - command = 0; - TRACEMSG(("mailcap: found testcommand:%s\n",mc->testcommand)); - } - else if (eq && !PL_strcmp(arg, "description")) - { - mc->label = command; - command = 0; - } - else if (eq && !PL_strcmp(arg, "label")) - { - mc->label = command; /* bogus old name for description */ - command = 0; - } - else if (eq && !PL_strcmp(arg, "stream-buffer-size")) - { - mc->stream_buffer_size = atol(command); - TRACEMSG(("mailcap: found stream-buffer-size:%d\n",mc->stream_buffer_size)); - FREEIF(command); - command = 0; - } - else - FREEIF(command); - } - } - else if (command && *command) FREEIF(command); - s = t; - } - - free(unprocessed_entry); - - /* Copy over the mail cap entry so that it can saved into data base */ - - if (mc) - { - md = NET_mdataCreate(); - - if ( !md ) return (-1); - StrAllocCopy(md->contenttype, mc->contenttype); - StrAllocCopy(md->command, mc->command); - StrAllocCopy(md->testcommand, mc->testcommand); - StrAllocCopy(md->label, mc->label); - StrAllocCopy(md->printcommand, mc->printcommand); - md->stream_buffer_size = mc->stream_buffer_size; - if (is_local && *src_string && **src_string) - StrAllocCopy(md->src_string, *src_string); /* copy buffer */ - StrAllocCopy(md->xmode, mc->xmode); - md->is_local = is_local; - PR_Free(*src_string); - *src_string = 0; - } - - - if (PassesTest(mc)) - { - TRACEMSG(("mailcap: Setting up conversion %s : %s\n", mc->contenttype, - mc->command)); - - net_register_new_converter(XP_StripLine(mc->contenttype), - mc->command, mc->xmode, - mc->stream_buffer_size); - if (md) - md->test_succeed = TRUE; - } - - /* Add to the database */ - if (md) - { - NET_mdataStruct *old_md = NULL; - - if ( !(old_md = NET_mdataExist(md))) - NET_mdataAdd(md); - else - { - NET_mdataRemove(old_md); - NET_mdataAdd(md); - } - - cd = NET_cdataCreate(); - cd->ci.type = 0; - cd->is_external = 1; - cd->is_local = 0; /* This is internal; only for user to view */ - StrAllocCopy(cd->ci.type, md->contenttype ); - - /* Does not exist add this contenttype to mime content list */ - if ( !(tmp_cd = NET_cdataExist(cd) ) ) - NET_cdataAdd(cd); - else /* Already Exist, so we don't need to add it again. Then, free it now */ - NET_cdataRemove(cd); - } - - free(buffer); - FREEIF(mc->contenttype); - FREEIF(mc->command); - FREEIF(mc->testcommand); - FREEIF(mc->label); - FREEIF(mc->xmode); - return(1); -} - -/* reads a mailcap file and adds entries to the - * external viewers converter list - */ -PUBLIC int -NET_ProcessMailcapFile (char *file, Bool is_local) -{ - struct MailcapEntry mc; - FILE *fp; - char *src_string = 0; - - TRACEMSG(("Loading types config file '%s'\n", file)); - - if ( !net_isDir(file) ) - { - fp = fopen(file, "r"); - - while (fp && !feof(fp)) - { - ProcessMailcapEntry(fp, &mc, &src_string, is_local); - } - if (fp) fclose(fp); - } - return(-1); -} - - -PUBLIC XP_List * -mailcap_MasterListPointer(void) -{ - return (NET_mcMasterList); -} - -PUBLIC NET_mdataStruct * -NET_mdataCreate(void) -{ - NET_mdataStruct *md = PR_NEW(NET_mdataStruct); - - if(!md) - return(NULL); - - memset(md, 0, sizeof(NET_mdataStruct)); - - return md; -} - -PUBLIC void -NET_mdataAdd(NET_mdataStruct *md) -{ - XP_ListAddObject(NET_mcMasterList, md); -} - - -PUBLIC void -NET_mdataRemove(NET_mdataStruct *md) -{ - XP_ListRemoveObject(NET_mcMasterList, md); - - NET_mdataFree(md); - -} - -PUBLIC NET_mdataStruct* -NET_mdataExist(NET_mdataStruct *old_md ) -{ - NET_mdataStruct *found_md = NULL; - NET_mdataStruct *md = NULL; - XP_List *infoList; - - infoList = mailcap_MasterListPointer(); - - if ( !infoList ) - return found_md; - - while ((md= (NET_mdataStruct *)XP_ListNextObject(infoList))) - { - if ( old_md->contenttype && - md->contenttype && - !PL_strcasecmp(old_md->contenttype, md->contenttype)) - { - /* found matching type */ - found_md = md; - break; - } - } - return found_md; -} - - - -#endif /* XP_UNIX */ -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/main/mkldap.h b/mozilla/network/main/mkldap.h deleted file mode 100644 index e2aa24086e0..00000000000 --- a/mozilla/network/main/mkldap.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKLDAP_H -#define MKLDAP_H - -PR_BEGIN_EXTERN_C - -void NET_InitLDAPProtocol(void); - -PR_END_EXTERN_C - -#endif diff --git a/mozilla/network/main/mkmessag.c b/mozilla/network/main/mkmessag.c deleted file mode 100644 index 8832e9dcf82..00000000000 --- a/mozilla/network/main/mkmessag.c +++ /dev/null @@ -1,209 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "rosetta.h" -#include "mkutils.h" -#include "mktcp.h" -#include "gui.h" -#include "merrors.h" -#include "xpgetstr.h" -/* - * hack alert: this file contains a switch statement with a gazillion cases, - * so I'd prefer to use enums instead of extern ints in this case -- erik - */ -#define WANT_ENUM_STRING_IDS -#include "allxpstr.h" - -#ifndef XP_UNIX -#include <stdarg.h> -#endif /* !XP_UNIX */ - - -/* - * This function takes an error code and associated error data - * and creates a string containing a textual description of - * what the error is and why it happened. - * - * The returned string is allocated and thus should be freed - * once it has been used. - */ -PUBLIC char * -NET_ExplainErrorDetails (int code, ...) -{ - va_list args; - char *msg = 0; - int sub_error; - - va_start (args, code); - - if (IS_SSL_ERROR(code) || IS_SEC_ERROR(code)) { - const char *s = XP_GetString(code); - msg = (s ? XP_STRDUP(s) : 0); - } - - if (!msg) - switch(code) { - case MK_INTERRUPTED: - case MK_USE_FTP_INSTEAD: - case MK_USE_COPY_FROM_CACHE: - case MK_MAILTO_NOT_READY: - case MK_UNABLE_TO_LOGIN: - case MK_UNABLE_TO_CONVERT: - case MK_IMAGE_LOSSAGE: /* image library generic error */ - case MK_ERROR_SENDING_DATA_COMMAND: - case MK_OFFLINE: - msg = NULL; - break; - - case MK_REDIRECT_ATTEMPT_NOT_ALLOWED: - case MK_SERVER_TIMEOUT: - case MK_CONNECTION_TIMED_OUT: - case MK_OUT_OF_MEMORY: - case MK_TIMEBOMB_URL_PROHIBIT: - case MK_TIMEBOMB_MESSAGE: - case MK_RELATIVE_TIMEBOMB_MESSAGE: - case MK_NO_WAIS_PROXY: - case MK_CREATING_NEWSRC_FILE: - case MK_NNTP_SERVER_NOT_CONFIGURED: - case MK_NNTP_NEWSGROUP_SCAN_ERROR: - case MK_ZERO_LENGTH_FILE: - case MK_BAD_CONNECT: - case MK_UNABLE_TO_USE_PASV_FTP: - case MK_UNABLE_TO_CHANGE_FTP_MODE: - case MK_UNABLE_TO_FTP_CWD: - case MK_UNABLE_TO_SEND_PORT_COMMAND: - case MK_UNABLE_TO_ACCEPT_SOCKET: - case MK_UNABLE_TO_CONNECT2: - case MK_BAD_NNTP_CONNECTION: - case MK_NNTP_SERVER_ERROR: - case MK_SERVER_DISCONNECTED: - case MK_NEWS_ITEM_UNAVAILABLE: - case MK_UNABLE_TO_OPEN_NEWSRC: - case MK_COULD_NOT_LOGIN_TO_SMTP_SERVER: - case MK_MSG_NO_SMTP_HOST: - case MK_COULD_NOT_GET_USERS_MAIL_ADDRESS: - case MK_UNABLE_TO_CONNECT_TO_PROXY: - case MK_UNABLE_TO_LOCATE_PROXY: - case MK_DISK_FULL: - case MK_PRINT_LOSSAGE: - case MK_SECURE_NEWS_PROXY_ERROR: - case MK_SIGNATURE_TOO_LONG: - case MK_SIGNATURE_TOO_WIDE: - case MK_POP3_SERVER_ERROR: - case MK_POP3_USERNAME_UNDEFINED: - case MK_POP3_PASSWORD_UNDEFINED: - case MK_POP3_USERNAME_FAILURE: - case MK_POP3_PASSWORD_FAILURE: - case MK_POP3_NO_MESSAGES: - case MK_POP3_LIST_FAILURE: - case MK_POP3_LAST_FAILURE: - case MK_POP3_RETR_FAILURE: - case MK_POP3_DELE_FAILURE: - case MK_POP3_OUT_OF_DISK_SPACE: - case MK_POP3_MESSAGE_WRITE_ERROR: - case MK_MIME_NO_SENDER: - case MK_MIME_NO_RECIPIENTS: - case MK_MIME_NO_SUBJECT: - case MK_MIME_ERROR_WRITING_FILE: - case MK_MIME_MULTIPART_BLURB: - case MK_MSG_CANT_COPY_TO_SAME_FOLDER: - case MK_MSG_CANT_COPY_TO_QUEUE_FOLDER: - case MK_MSG_CANT_COPY_TO_QUEUE_FOLDER_OLD: - case MK_MSG_CANT_COPY_TO_DRAFTS_FOLDER: - case MK_MSG_CANT_CREATE_FOLDER: - case MK_MSG_FOLDER_ALREADY_EXISTS: - case MK_MSG_FOLDER_NOT_EMPTY: - case MK_MSG_CANT_DELETE_FOLDER: - case MK_MSG_CANT_CREATE_INBOX: - case MK_MSG_CANT_CREATE_MAIL_DIR: - case MK_MSG_NO_POP_HOST: - case MK_MSG_MESSAGE_CANCELLED: - case MK_MSG_FOLDER_UNREADABLE: - case MK_MSG_FOLDER_SUMMARY_UNREADABLE: - case MK_MSG_TMP_FOLDER_UNWRITABLE: - case MK_MSG_ID_NOT_IN_FOLDER: - case MK_MSG_NEWSRC_UNPARSABLE: - case MK_MSG_NO_RETURN_ADDRESS: - case MK_MSG_ERROR_WRITING_NEWSRC: - case MK_MSG_ERROR_WRITING_MAIL_FOLDER: - case MK_MSG_SEARCH_FAILED: - case MK_MSG_FOLDER_BUSY: - msg = XP_STRDUP(XP_GetString(code)); - break; - - case MK_TCP_READ_ERROR: - case MK_TCP_WRITE_ERROR: - case MK_UNABLE_TO_CREATE_SOCKET: - case MK_UNABLE_TO_CONNECT: - case MK_HTTP_TYPE_CONFLICT: - case MK_TCP_ERROR: - sub_error = va_arg(args, int); - if (IS_SSL_ERROR(sub_error) || IS_SEC_ERROR(sub_error)) { - /* - * For SSL/SEC errors, use the message without a wrapper. - */ - msg = XP_STRDUP(XP_GetString(sub_error)); - } else if (code == MK_UNABLE_TO_CONNECT && - (sub_error == XP_ERRNO_EINVAL - || sub_error == XP_ERRNO_EADDRINUSE)) { - /* - * With unable-to-connect errors, some errno values/strings - * are not more helpful, so just use a plain message for these. - */ - msg = XP_STRDUP(XP_GetString(MK_UNABLE_TO_CONNECT2)); - } else { - msg = PR_smprintf(XP_GetString(code), XP_GetString(sub_error)); - } - break; - - case MK_MALFORMED_URL_ERROR: - case MK_COULD_NOT_PUT_FILE: - case MK_UNABLE_TO_LOCATE_FILE: - case MK_NNTP_AUTH_FAILED: - case MK_UNABLE_TO_LOCATE_HOST: - case MK_UNABLE_TO_LOCATE_SOCKS_HOST: - case MK_UNABLE_TO_OPEN_FILE: - case MK_UNABLE_TO_OPEN_TMP_FILE: - case MK_CONNECTION_REFUSED: - case MK_NNTP_ERROR_MESSAGE: - case MK_MSG_COULDNT_OPEN_FCC_FILE: - case MK_TIMEBOMB_WARNING_MESSAGE: - case MK_RELATIVE_TIMEBOMB_WARNING_MESSAGE: - case MK_ERROR_SENDING_FROM_COMMAND: - case MK_ERROR_SENDING_RCPT_COMMAND: - case MK_ERROR_SENDING_MESSAGE: - case MK_SMTP_SERVER_ERROR: - msg = PR_vsmprintf(XP_GetString(code), args); - break; - - case -1: - default: - msg = PR_smprintf(XP_GetString(MK_COMMUNICATIONS_ERROR), code); - break; - } - - va_end (args); - - TRACEMSG(("NET_ExplainErrorDetails generated: %s", msg ? msg : "(none)")); - - return(msg); -} diff --git a/mozilla/network/main/mkpadpac.c b/mozilla/network/main/mkpadpac.c deleted file mode 100644 index 445c2728ba1..00000000000 --- a/mozilla/network/main/mkpadpac.c +++ /dev/null @@ -1,120 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* mkpadpac.c -- Proxy auto-discovery utility function implementation. - Created: Judson Valeski, 01.15.1997 - */ - -#include "prmem.h" -#include "mkpadpac.h" -#include "netutils.h" -#include "mkgeturl.h" /* for NET_GetProxyStyle() */ -#include "prefapi.h" /* for js prefs stuff */ - -/* Global pad variables */ -PUBLIC PRBool foundPADPAC=PR_FALSE; -PUBLIC char *MK_padPacURL=NULL; -PUBLIC PRBool MK_PadEnabled=PR_TRUE; - -MODULE_PRIVATE void net_UsePadPac(PRBool useIt) { - if(useIt) { - net_PadPacURLPrefChanged(NULL, NULL); - } else { - MK_PadEnabled=FALSE; - NET_ProxyAcLoaded=FALSE; - PR_FREEIF(MK_padPacURL); - MK_padPacURL=NULL; - net_SetPACUrl(NULL); - } -} - -/* Return whether we're currently using a pac file via proxy autodiscovery. */ -PUBLIC PRBool NET_UsingPadPac(void) { - return (MK_PadEnabled && foundPADPAC && (NET_GetProxyStyle() == PROXY_STYLE_NONE) ); -} - -/* Set the MK_padPacURL varialbe to point to the string passed in. */ -PUBLIC PRBool NET_SetPadPacURL(char * u) { - char *url=NULL; - if(!u || *u == '\0') - return FALSE; - StrAllocCopy(url, u); - if(url && *url) { - char *host=NET_ParseURL(url, GET_HOST_PART); - if(host && *host && (sizeof(host) <= MAXHOSTNAMELEN) ) { - if(MK_padPacURL) - PR_Free(MK_padPacURL); - MK_padPacURL=url; - return TRUE; - } else { - PR_Free(url); - PR_FREEIF(host); - } - } else { - PR_FREEIF(url); - } - return FALSE; -} - -/* Pref for proxy autodiscovery url */ -MODULE_PRIVATE int PR_CALLBACK -net_PadPacURLPrefChanged(const char *pref, void *data) { - char s[128]; - int len = sizeof(s); - memset(s, 0, len); - - if ( (PREF_OK == PREF_GetCharPref(pref_padPacURL, s, &len)) ) { - NET_SetPadPacURL(s); - } - return PREF_NOERROR; -} - -/* Pref for allowing (or not) proxy autodiscovery. */ -MODULE_PRIVATE int PR_CALLBACK -net_EnablePadPrefChanged(const char *pref, void *data) { - PRBool x = FALSE; - if ( (PREF_OK == PREF_GetBoolPref(pref_enablePad, &x)) ) { - MK_PadEnabled=x; - } - return PREF_NOERROR; -} - -/* called from mkgeturl.c, NET_InitNetLib(). - * Initializes the pad variables and registers pad callbacks */ -PUBLIC void -NET_RegisterPadPrefCallbacks(void) { - PRBool x = FALSE; - char s[128]; - int len=sizeof(s); - memset(s, 0, len); - - if ( (PREF_OK == PREF_GetBoolPref(pref_enablePad, &x)) ) { - MK_PadEnabled=x; - } else { - MK_PadEnabled=x; - } - PREF_RegisterCallback(pref_enablePad, net_EnablePadPrefChanged, NULL); - - if ( (PREF_OK == PREF_GetCharPref(pref_padPacURL, s, &len)) ) { - NET_SetPadPacURL(s); - } - PREF_RegisterCallback(pref_padPacURL, net_PadPacURLPrefChanged, NULL); -} diff --git a/mozilla/network/main/mkpadpac.h b/mozilla/network/main/mkpadpac.h deleted file mode 100644 index 5fae6441101..00000000000 --- a/mozilla/network/main/mkpadpac.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* mkpadpac.h -- Proxy auto-discovery documentation. - Created: Judson Valeski, 01.15.1998 - - Proxy auto-discovery (pad) allows the client to search for and use a - pre-determined proxy auto-configuration (pac) file. The file it looks up - and parses is named in the users prefs file (network.padPacURL). The feature - can be completely disabled by setting the network.enablePad preference to - false. - - Holding to tradition, I've piggy-backed pad onto the current pac file - implementation. If pad is enabled, the MKproxy_ac_url variable (as defined in - mkautocf.c/h) is set to point at the MK_padPacURL. This means that all the - current pac file logic is used once a pac file is located by pad. A pad pac - file is located by asyncronously searching for the host in the pad pac url - in mkconect.c>NET_findAddress(). If the host is found then MKproxy_ac_url is - set to MK_padPacURL (this happens in mkgeturl.c>NET_getURL()) and we treat the - pad pac file just like a pac file. The only difference is that when there's - a problem with the pad pac file, we failover silently to a direct connection, - no error messages get to the user. All the silent failover happens in - mkautocf.c, except for one case in mkhttp.c which handles the case when there - is a problem actually loading the pac file itself. - */ - -#ifndef MKPADPAC_H -#define MKPADPAC_H - -#include "xp.h" -#include "mkprefs.h" - -/* Global pad variables */ -extern PRBool foundPADPAC; -extern char *MK_padPacURL; -extern PRBool MK_PadEnabled; - -/* ***** FUNCTION PROTOTYPES */ - -/* Setup internal variables to use or not use the proxy - * autodiscovery feature. Actually not that simple. */ -MODULE_PRIVATE void net_UsePadPac(PRBool useIt); - -/* Return whether we're currently using a pac file via proxy autodiscovery. - * This function takes three items into consideration: - * 1. Is padpac enabled. - * 2. Was the padpac host found. - * 3. Is the user's proxy style pref set to NONE (i.e. the user is set to go - * direct connection, not proxy, or auto proxy. - * - * If all these are true, then we're using a padpac file. - */ -PUBLIC PRBool NET_UsingPadPac(void); - -/* Return whether or not we are currently in the process of loading - * a proxy autoconfig url. */ -PUBLIC PRBool NET_LoadingPac(void); - -/* Set the MK_padPacURL varialbe to point to the url passed in, - * after checking the url for size limits. - * Returns TRUE if successful, FALSE otherwise. */ -PUBLIC PRBool NET_SetPadPacURL(char * url); - -/* Called by js prefs when the padpac url changes. */ -MODULE_PRIVATE int PR_CALLBACK net_PadPacURLPrefChanged(const char *pref, void *data); - -/* Called by js prefs when the enable padpac pref changes. */ -MODULE_PRIVATE int PR_CALLBACK net_EnablePadPrefChanged(const char *pref, void *data); - -/* Registers the above callbacks with js prefs. */ -PUBLIC void NET_RegisterPadPrefCallbacks(void); - -/* ***** END FUNCTION PROTOTYPES */ - -#endif /* MKPADPAC_H */ diff --git a/mozilla/network/main/mkparse.c b/mozilla/network/main/mkparse.c deleted file mode 100644 index 0f5e3a9fc59..00000000000 --- a/mozilla/network/main/mkparse.c +++ /dev/null @@ -1,1924 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* URL/NET parsing routines - * Additions/Changes by Judson Valeski 1997 - */ - -#include "mkutils.h" -#include "netutils.h" -#include "xp.h" -#include "mkparse.h" -#include "xp_time.h" -#include "mkfsort.h" -#include "prlong.h" -#include "prtime.h" - -extern int MK_OUT_OF_MEMORY; - -#ifdef PROFILE -#pragma profile on -#endif - -/* global */ -XP_List * ExternalURLTypeList=0; - -#define EXTERNAL_TYPE_URL 999 /* a special external URL type */ - -#define HEX_ESCAPE '%' - -/* add an external URL type prefix - * - * this prefix will be used to see if a URL is an absolute - * or a relative URL. - * - * you should just pass in the prefix of the URL - * - * for instance "http" or "ftp" or "foobar". - * - * do not pass in a colon or double slashes. - */ -PUBLIC void -NET_AddExternalURLType(char * type) -{ - XP_List * list_ptr = ExternalURLTypeList; - char * new_type=0; - char * reg_type; - - while((reg_type = (char *)XP_ListNextObject(list_ptr)) != NULL) - { - if(!PL_strcasecmp(reg_type, type)) - return; /* ignore duplicates */ - } - - StrAllocCopy(new_type, type); - - if(!ExternalURLTypeList) - ExternalURLTypeList = XP_ListNew(); - - XP_ListAddObject(ExternalURLTypeList, new_type); - -} - -/* remove an external URL type prefix - */ -PUBLIC void -NET_DelExternalURLType(char * type) -{ - XP_List * list_ptr = ExternalURLTypeList; - char * reg_type; - - while((reg_type = (char *)XP_ListNextObject(list_ptr)) != NULL) - { - if(!PL_strcasecmp(reg_type, type)) - { - /* found it */ - XP_ListRemoveObject(ExternalURLTypeList, reg_type); - return; /* done */ - } - } -} - -/* check the passed in url to see if it is an - * external type url - */ -PRIVATE int -net_CheckForExternalURLType(char * url) -{ - XP_List * list_ptr = ExternalURLTypeList; - char * reg_type; - int len; - - while((reg_type = (char *)XP_ListNextObject(list_ptr)) != NULL) - { - len = PL_strlen(reg_type); - if(!PL_strncasecmp(reg_type, url, len) && url[len] == ':') - { - /* found it */ - return EXTERNAL_TYPE_URL; /* done */ - } - } - - return(0); -} - -/* modifies a url of the form /foo/../foo1 -> /foo1 - * - * it only operates on "file" "ftp" and "http" url's all others are returned - * unmodified - * - * returns the modified passed in URL string - */ -PRIVATE char * -net_ReduceURL (char *url) -{ - int url_type = NET_URL_Type(url); - char * fwd_ptr; - char * url_ptr; - char * path_ptr; - - if(!url) - return(url); - - if(url_type == HTTP_TYPE_URL || url_type == FILE_TYPE_URL || - url_type == FTP_TYPE_URL || - url_type == SECURE_HTTP_TYPE_URL || - url_type == MARIMBA_TYPE_URL) - { - - /* find the path so we only change that and not the host - */ - path_ptr = PL_strchr(url, '/'); - - if(!path_ptr) - return(url); - - if(*(path_ptr+1) == '/') - path_ptr = PL_strchr(path_ptr+2, '/'); - - if(!path_ptr) - return(url); - - fwd_ptr = path_ptr; - url_ptr = path_ptr; - - for(; *fwd_ptr != '\0'; fwd_ptr++) - { - - if(*fwd_ptr == '/' && *(fwd_ptr+1) == '.' && *(fwd_ptr+2) == '/') - { - /* remove ./ - */ - fwd_ptr += 1; - } - else if(*fwd_ptr == '/' && *(fwd_ptr+1) == '.' && *(fwd_ptr+2) == '.' && - (*(fwd_ptr+3) == '/' || *(fwd_ptr+3) == '\0')) - { - /* remove foo/.. - */ - /* reverse the url_ptr to the previous slash - */ - if(url_ptr != path_ptr) - url_ptr--; /* we must be going back at least one */ - for(;*url_ptr != '/' && url_ptr != path_ptr; url_ptr--) - ; /* null body */ - - /* forward the fwd_prt past the ../ - */ - fwd_ptr += 2; - } - else - { - /* copy the url incrementaly - */ - *url_ptr++ = *fwd_ptr; - } - } - *url_ptr = '\0'; /* terminate the url */ - } - - return(url); -} - -/* Makes a relative URL into an absolute one. - * - * If an absolute url is passed in it will be copied and returned. - * - * Always returns a malloc'd string or NULL on out of memory error - */ -PUBLIC char * -NET_MakeAbsoluteURL(char * absolute_url, char * relative_url) -{ - char * ret_url=0; - int new_length; - char * cat_point=0; - char cat_point_char; - int url_type=0; - int base_type; - - /* if either is NULL - */ - if(!absolute_url || !relative_url) - { - StrAllocCopy(ret_url, relative_url); - return(ret_url); - } - - /* use the URL_Type function to figure - * out if it's a recognized URL method - */ - url_type = NET_URL_Type(relative_url); - - /* there are some extra cases we need to catch - */ - if(!url_type) - { - switch(*relative_url) - { - case 'i': - if(!PL_strncmp(relative_url,"internal-icon-", 14) - || !PL_strncmp(relative_url,"internal-external-reconnect:", 28) - || !PL_strcmp(relative_url,"internal-external-plugin")) - url_type = INTERNAL_IMAGE_TYPE_URL; - break; - case '/': - if(!PL_strncasecmp(relative_url, "/mc-icons/", 10) || - !PL_strncasecmp(relative_url, "/ns-icons/", 10)) - { - if(!PL_strcmp(relative_url+10, "menu.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - else if(!PL_strcmp(relative_url+10, "unknown.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - else if(!PL_strcmp(relative_url+10, "text.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - else if(!PL_strcmp(relative_url+10, "image.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - else if(!PL_strcmp(relative_url+10, "sound.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - else if(!PL_strcmp(relative_url+10, "binary.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - else if(!PL_strcmp(relative_url+10, "movie.gif")) - url_type = INTERNAL_IMAGE_TYPE_URL; - } - break; - } - } - else if(url_type == ABOUT_TYPE_URL) - { - /* don't allow about:cache in a document */ - if(!PL_strncasecmp(relative_url, "about:cache", 11) - || !PL_strncasecmp(relative_url, "about:global", 12) - || !PL_strncasecmp(relative_url, "about:image-cache", 17) - || !PL_strncasecmp(relative_url, "about:memory-cache", 18)) - { - return PL_strdup(""); - } - } - - if(!url_type) - url_type = net_CheckForExternalURLType(relative_url); - - if(url_type) - { - /* it's either an absolute url - * or a messed up one of the type proto:/path - * but notice the missing host. - */ - char * colon = PL_strchr(relative_url, ':'); /* must be there */ - - if( (colon && *(colon+1) == '/' && *(colon+2) == '/') || - (url_type != GOPHER_TYPE_URL - && url_type != FTP_TYPE_URL - && url_type != HTTP_TYPE_URL - && url_type != SECURE_HTTP_TYPE_URL - && url_type != RLOGIN_TYPE_URL - && url_type != TELNET_TYPE_URL - && url_type != TN3270_TYPE_URL - && url_type != WAIS_TYPE_URL) ) - { - /* it appears to have all it's parts. Assume it's completely - * absolute - */ - StrAllocCopy(ret_url, relative_url); - return(ret_url); - } - else - { - /* it's a screwed up relative url of the form http:[relative url] - * remove the stuff before and at the colon and treat it as a normal - * relative url - */ - char * colon = PL_strchr(relative_url, ':'); - - relative_url = colon+1; - } - } - - - /* At this point, we know that `relative_url' is not absolute. - If the base URL, `absolute_url', is a "mailbox:" URL, then - we should not allow relative expansion: that is, - NET_MakeAbsoluteURL("mailbox:/A/B/C", "YYY") should not - return "mailbox:/A/B/YYY". - - However, expansion of "#" and "?" parameters should work: - NET_MakeAbsoluteURL("mailbox:/A/B/C?id=XXX", "#part2") - should be allowed to expand to "mailbox:/A/B/C?id=XXX#part2". - - If you allow random HREFs in attached HTML to mail messages to - expand to mailbox URLs, then bad things happen -- among other - things, an entry will be automatically created in the folders - list for each of these bogus non-files. - - It's an open question as to whether relative expansion should - be allowed for news: and snews: URLs. - - Reasons to allow it: - - = ClariNet has been using it - - = (Their reason:) it's the only way for an HTML news message - to refer to another HTML news message in a way which - doesn't make assumptions about the name of the news host, - and which also doesn't assume that the message is on the - default news host. - - Reasons to disallow it: - - = Consistency with "mailbox:" - - = If there is a news message which has type text/html, and - which has a relative URL like <IMG SRC="foo.gif"> in it, - but which has no <BASE> tag, then we would expand that - image to "news:foo.gif". Which would fail, of course, - but which might annoy news admins by generating bogus - references. - - So for now, let's allow - NET_MakeAbsoluteURL("news:123@4", "456@7") => "news:456@7"; and - NET_MakeAbsoluteURL("news://h/123@4", "456@7") => "news://h/456@7". - */ - base_type = NET_URL_Type(absolute_url); - if ((base_type == MAILBOX_TYPE_URL || base_type == IMAP_TYPE_URL || base_type == NEWS_TYPE_URL) && - *relative_url != '#' && - *relative_url != '?') - { - return PL_strdup(""); - } - - if(relative_url[0] == '/' && relative_url[1] == '/') - { - /* a host absolute URL - */ - - /* find the colon after the protocol - */ - cat_point = PL_strchr(absolute_url, ':'); - if (cat_point && base_type == WYSIWYG_TYPE_URL) - cat_point = PL_strchr(cat_point + 1, ':'); - - /* append after the colon - */ - if(cat_point) - cat_point++; - - } - else if(relative_url[0] == '/') - { - /* a path absolute URL - * append at the slash after the host part - */ - - /* find the colon after the protocol - */ - char *colon = PL_strchr(absolute_url, ':'); - if (colon && base_type == WYSIWYG_TYPE_URL) - colon = PL_strchr(colon + 1, ':'); - - if(colon) - { - if(colon[1] == '/' && colon[2] == '/') - { - /* find the next slash - */ - cat_point = PL_strchr(colon+3, '/'); - - if(!cat_point) - { - /* if there isn't another slash then the cat point is the very end - */ - cat_point = &absolute_url[PL_strlen(absolute_url)]; - } - } - else - { - /* no host was given so the cat_point is right after the colon - */ - cat_point = colon+1; - } - -#if defined(XP_WIN) || defined(XP_OS2) - /* this will allow drive letters to work right on windows - */ - if(NET_IS_ALPHA(*cat_point) && *(cat_point+1) == ':') - cat_point += 2; -#endif /* XP_WIN */ - - } - } - else if(relative_url[0] == '#') - { - /* a positioning within the same document relative url - * - * add teh relative url to the full text of the absolute url minus - * any # punctuation the url might have - * - */ - char * hash = PL_strchr(absolute_url, '#'); - - if(hash) - { - char * ques_mark = PL_strchr(absolute_url, '?'); - - if(ques_mark) - { - /* this is a hack. - * copy things to try and make them more correct - */ - *hash = '\0'; - - StrAllocCopy(ret_url, absolute_url); - StrAllocCat(ret_url, relative_url); - StrAllocCat(ret_url, ques_mark); - - *hash = '#'; - - return(net_ReduceURL(ret_url)); - } - - cat_point = hash; - } - else - { - cat_point = &absolute_url[PL_strlen(absolute_url)]; /* the end of the URL */ - } - } - else - { - /* a completely relative URL - * - * append after the last slash - */ - char * ques = PL_strchr(absolute_url, '?'); - char * hash = PL_strchr(absolute_url, '#'); - - if(ques) - *ques = '\0'; - - if(hash) - *hash = '\0'; - - cat_point = PL_strrchr(absolute_url, '/'); - - /* if there are no slashes then append right after the colon after the protocol - */ - if(!cat_point) - cat_point = PL_strchr(absolute_url, ':'); - - /* set the value back - */ - if(ques) - *ques = '?'; - - if(hash) - *hash = '#'; - - if(cat_point) - cat_point++; /* append right after the slash or colon not on it */ - } - - if(cat_point) - { - cat_point_char = *cat_point; /* save the value */ - *cat_point = '\0'; - new_length = PL_strlen(absolute_url) + PL_strlen(relative_url) + 1; - ret_url = (char *) PR_Malloc(new_length); - if(!ret_url) - return(NULL); /* out of memory */ - - PL_strcpy(ret_url, absolute_url); - PL_strcat(ret_url, relative_url); - *cat_point = cat_point_char; /* set the absolute url back to its original state */ - } - else - { - /* something went wrong. just return a copy of the relative url - */ - StrAllocCopy(ret_url, relative_url); - } - - return(net_ReduceURL(ret_url)); -} - -/* - * Returns the number of the month given or -1 on error. - */ -MODULE_PRIVATE int NET_MonthNo (char * month) -{ - int ret; - if (!PL_strncasecmp(month, "JAN", 3)) - ret = 0; - else if (!PL_strncasecmp(month, "FEB", 3)) - ret = 1; - else if (!PL_strncasecmp(month, "MAR", 3)) - ret = 2; - else if (!PL_strncasecmp(month, "APR", 3)) - ret = 3; - else if (!PL_strncasecmp(month, "MAY", 3)) - ret = 4; - else if (!PL_strncasecmp(month, "JUN", 3)) - ret = 5; - else if (!PL_strncasecmp(month, "JUL", 3)) - ret = 6; - else if (!PL_strncasecmp(month, "AUG", 3)) - ret = 7; - else if (!PL_strncasecmp(month, "SEP", 3)) - ret = 8; - else if (!PL_strncasecmp(month, "OCT", 3)) - ret = 9; - else if (!PL_strncasecmp(month, "NOV", 3)) - ret = 10; - else if (!PL_strncasecmp(month, "DEC", 3)) - ret = 11; - else - { - ret = -1; - TRACEMSG(("net_convert_month. Couldn't resolve date.\n")); - } - return ret; -} - - -/* accepts an RFC 850 or RFC 822 date string and returns a - * time_t - */ -MODULE_PRIVATE time_t -NET_ParseDate(char *date_string) -{ -#ifndef USE_OLD_TIME_FUNC - PRTime prdate; - time_t date = 0; - - TRACEMSG(("Parsing date string: %s\n",date_string)); - - /* try using PR_ParseTimeString instead - */ - - if(PR_ParseTimeString(date_string, TRUE, &prdate) == PR_SUCCESS) - { - PRInt64 r, u; - LL_I2L(u, PR_USEC_PER_SEC); - LL_DIV(r, prdate, u); - LL_L2I(date, r); - if (date < 0) { - date = 0; - } - TRACEMSG(("Parsed date as GMT: %s\n", asctime(gmtime(&date)))); - TRACEMSG(("Parsed date as local: %s\n", ctime(&date))); - } - else - { - TRACEMSG(("Could not parse date")); - } - - return (date); - -#else - struct tm time_info; /* Points to static tm structure */ - char *ip; - char mname[256]; - time_t rv; - - TRACEMSG(("Parsing date string: %s\n",date_string)); - - memset(&time_info, 0, sizeof(struct tm)); - - /* Whatever format we're looking at, it will start with weekday. */ - /* Skip to first space. */ - if(!(ip = PL_strchr(date_string,' '))) - return 0; - else - while(NET_IS_SPACE(*ip)) - ++ip; - - /* make sure that the date is less than 256 - * That will keep mname from ever overflowing - */ - if(255 < PL_strlen(ip)) - return(0); - - if(isalpha(*ip)) - { - /* ctime */ - sscanf(ip, (strstr(ip, "DST") ? "%s %d %d:%d:%d %*s %d" - : "%s %d %d:%d:%d %d"), - mname, - &time_info.tm_mday, - &time_info.tm_hour, - &time_info.tm_min, - &time_info.tm_sec, - &time_info.tm_year); - time_info.tm_year -= 1900; - } - else if(ip[2] == '-') - { - /* RFC 850 (normal HTTP) */ - char t[256]; - sscanf(ip,"%s %d:%d:%d", t, - &time_info.tm_hour, - &time_info.tm_min, - &time_info.tm_sec); - t[2] = '\0'; - time_info.tm_mday = atoi(t); - t[6] = '\0'; - PL_strcpy(mname,&t[3]); - time_info.tm_year = atoi(&t[7]); - /* Prevent wraparound from ambiguity */ - if(time_info.tm_year < 70) - time_info.tm_year += 100; - else if(time_info.tm_year > 1900) - time_info.tm_year -= 1900; - } - else - { - /* RFC 822 */ - sscanf(ip,"%d %s %d %d:%d:%d",&time_info.tm_mday, - mname, - &time_info.tm_year, - &time_info.tm_hour, - &time_info.tm_min, - &time_info.tm_sec); - /* since tm_year is years since 1900 and the year we parsed - * is absolute, we need to subtract 1900 years from it - */ - time_info.tm_year -= 1900; - } - time_info.tm_mon = NET_MonthNo(mname); - - if(time_info.tm_mon == -1) /* check for error */ - return(0); - - - TRACEMSG(("Parsed date as: %s\n", asctime(&time_info))); - - rv = mktime(&time_info); - - if(time_info.tm_isdst) - rv -= 3600; - - if(rv == -1) - { - TRACEMSG(("mktime was unable to resolve date/time: %s\n", asctime(&time_info))); - return(0); - } - else - { - TRACEMSG(("Parsed date %s\n", asctime(&time_info))); - TRACEMSG(("\tas %s\n", ctime(&rv))); - return(rv); - } -#endif -} - -/* Also skip '>' as part of host name */ - -MODULE_PRIVATE char * -NET_ParseURL (const char *url, int parts_requested) -{ - char *rv=0,*colon, *slash, *ques_mark, *hash_mark; - char *atSign, *host, *passwordColon, *gtThan; - - assert(url); - - if(!url) - return(StrAllocCat(rv, "")); - colon = PL_strchr(url, ':'); /* returns a const char */ - - /* Get the protocol part, not including anything beyond the colon */ - if (parts_requested & GET_PROTOCOL_PART) { - if(colon) { - char val = *(colon+1); - *(colon+1) = '\0'; - StrAllocCopy(rv, url); - *(colon+1) = val; - - /* If the user wants more url info, tack on extra slashes. */ - if( (parts_requested & GET_HOST_PART) - || (parts_requested & GET_USERNAME_PART) - || (parts_requested & GET_PASSWORD_PART) - ) - { - if( *(colon+1) == '/' && *(colon+2) == '/') - StrAllocCat(rv, "//"); - /* If there's a third slash consider it file:/// and tack on the last slash. */ - if( *(colon+3) == '/' ) - StrAllocCat(rv, "/"); - } - } - } - - - /* Get the username if one exists */ - if (parts_requested & GET_USERNAME_PART) { - if (colon - && (*(colon+1) == '/') - && (*(colon+2) == '/') - && (*(colon+3) != '\0')) { - - if ( (slash = PL_strchr(colon+3, '/')) != NULL) - *slash = '\0'; - if ( (atSign = PL_strchr(colon+3, '@')) != NULL) { - *atSign = '\0'; - if ( (passwordColon = PL_strchr(colon+3, ':')) != NULL) - *passwordColon = '\0'; - StrAllocCat(rv, colon+3); - - /* Get the password if one exists */ - if (parts_requested & GET_PASSWORD_PART) { - if (passwordColon) { - StrAllocCat(rv, ":"); - StrAllocCat(rv, passwordColon+1); - } - } - if (parts_requested & GET_HOST_PART) - StrAllocCat(rv, "@"); - if (passwordColon) - *passwordColon = ':'; - *atSign = '@'; - } - if (slash) - *slash = '/'; - } - } - - /* Get the host part */ - if (parts_requested & GET_HOST_PART) { - if(colon) { - if(*(colon+1) == '/' && *(colon+2) == '/') - { - slash = PL_strchr(colon+3, '/'); - - if(slash) - *slash = '\0'; - - if( (atSign = PL_strchr(colon+3, '@')) != NULL) - host = atSign+1; - else - host = colon+3; - - ques_mark = PL_strchr(host, '?'); - - if(ques_mark) - *ques_mark = '\0'; - - gtThan = PL_strchr(host, '>'); - - if (gtThan) - *gtThan = '\0'; - -/* - * Protect systems whose header files forgot to let the client know when - * gethostbyname would trash their stack. - */ -#ifndef MAXHOSTNAMELEN -#ifdef XP_OS2 -#error Managed to get into NET_ParseURL without defining MAXHOSTNAMELEN !!! -#endif -#endif - /* limit hostnames to within MAXHOSTNAMELEN characters to keep - * from crashing - */ - if(PL_strlen(host) > MAXHOSTNAMELEN) - { - char * cp; - char old_char; - - cp = host+MAXHOSTNAMELEN; - old_char = *cp; - - *cp = '\0'; - - StrAllocCat(rv, host); - - *cp = old_char; - } - else - { - StrAllocCat(rv, host); - } - - if(slash) - *slash = '/'; - - if(ques_mark) - *ques_mark = '?'; - - if (gtThan) - *gtThan = '>'; - } - } - } - - /* Get the path part */ - if (parts_requested & GET_PATH_PART) { - if(colon) { - if(*(colon+1) == '/' && *(colon+2) == '/') - { - /* skip host part */ - slash = PL_strchr(colon+3, '/'); - } - else - { - /* path is right after the colon - */ - slash = colon+1; - } - - if(slash) - { - ques_mark = PL_strchr(slash, '?'); - hash_mark = PL_strchr(slash, '#'); - - if(ques_mark) - *ques_mark = '\0'; - - if(hash_mark) - *hash_mark = '\0'; - - StrAllocCat(rv, slash); - - if(ques_mark) - *ques_mark = '?'; - - if(hash_mark) - *hash_mark = '#'; - } - } - } - - if(parts_requested & GET_HASH_PART) { - hash_mark = PL_strchr(url, '#'); /* returns a const char * */ - - if(hash_mark) - { - ques_mark = PL_strchr(hash_mark, '?'); - - if(ques_mark) - *ques_mark = '\0'; - - StrAllocCat(rv, hash_mark); - - if(ques_mark) - *ques_mark = '?'; - } - } - - if(parts_requested & GET_SEARCH_PART) { - ques_mark = PL_strchr(url, '?'); /* returns a const char * */ - - if(ques_mark) - { - hash_mark = PL_strchr(ques_mark, '#'); - - if(hash_mark) - *hash_mark = '\0'; - - StrAllocCat(rv, ques_mark); - - if(hash_mark) - *hash_mark = '#'; - } - } - - /* copy in a null string if nothing was copied in - */ - if(!rv) - StrAllocCopy(rv, ""); - - /* XP_OS2_FIX IBM-MAS: long URLS blowout tracemsg buffer, - set max to 1900 chars */ - TRACEMSG(("mkparse: ParseURL: parsed - %-.1900s",rv)); - - return rv; -} - -/* DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER - DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER - DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER - - TOXIC! - - Do not even think of changing IS_OK or anything anywhere near it. - - There is much spooky voodoo involving signed and unsigned chars - when using gcc on SunOS 4.1.3. - - If you think you understand it, the smart money says you're wrong. - - TOXIC! - - DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER - DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER - DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER DANGER - */ - -/* encode illegal characters into % escaped hex codes. - * - * mallocs and returns a string that must be freed - */ -PRIVATE CONST -int netCharType[256] = -/* Bit 0 xalpha -- the alphas -** Bit 1 xpalpha -- as xalpha but -** converts spaces to plus and plus to %20 -** Bit 3 ... path -- as xalphas but doesn't escape '/' -*/ - /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ - { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 1x */ - 0,0,0,0,0,0,0,0,0,0,7,4,0,7,7,4, /* 2x !"#$%&'()*+,-./ */ - 7,7,7,7,7,7,7,7,7,7,0,0,0,0,0,0, /* 3x 0123456789:;<=>? */ - 0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* 4x @ABCDEFGHIJKLMNO */ - /* bits for '@' changed from 7 to 0 so '@' can be escaped */ - /* in usernames and passwords in publishing. */ - 7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,7, /* 5X PQRSTUVWXYZ[\]^_ */ - 0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /* 6x `abcdefghijklmno */ - 7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,0, /* 7X pqrstuvwxyz{\}~ DEL */ - 0, }; - -#define IS_OK(C) (netCharType[((unsigned int) (C))] & (mask)) - -PUBLIC char * -NET_Escape (const char * str, int mask) -{ - if(!str) - return NULL; - return NET_EscapeBytes (str, (int32)PL_strlen(str), mask, NULL); -} - -PUBLIC char * -NET_EscapeBytes (const char * str, int32 len, int mask, int32 * out_len) -{ - register CONST unsigned char *src; - register unsigned char *dst; - char *result; - int32 i, extra = 0; - char *hexChars = "0123456789ABCDEF"; - - if(!str) - return(0); - - src = (unsigned char *) str; - for(i = 0; i < len; i++) - { - if (!IS_OK(src[i])) - extra+=2; /* the escape, plus an extra byte for each nibble */ - } - - if(!(result = (char *) PR_Malloc(len + extra + 1))) - return(0); - - dst = (unsigned char *) result; - for(i = 0; i < len; i++) - { - unsigned char c = src[i]; - if (IS_OK(c)) - { - *dst++ = c; - } - else if(mask == URL_XPALPHAS && c == ' ') - { - *dst++ = '+'; /* convert spaces to pluses */ - } - else - { - *dst++ = HEX_ESCAPE; - *dst++ = hexChars[c >> 4]; /* high nibble */ - *dst++ = hexChars[c & 0x0f]; /* low nibble */ - } - } - - *dst = '\0'; /* tack on eos */ - if(out_len) - *out_len = dst - (unsigned char *) result; - return result; -} - -/* return the size of a string if it were to be escaped. - */ -MODULE_PRIVATE int32 -NET_EscapedSize (const char * str, int mask) -{ - int32 extra = 0; - register CONST unsigned char * src; - - if(!str) - return(0); - - for(src=((unsigned char *)str); *src; src++) - if (!IS_OK(*src)) - extra+=2; /* the escape, plus an extra byte for each nibble */ - - return((int32)(src - ((unsigned char *)str)) + extra + 1); -} - - -/* decode % escaped hex codes into character values - */ -#define UNHEX(C) \ - ((C >= '0' && C <= '9') ? C - '0' : \ - ((C >= 'A' && C <= 'F') ? C - 'A' + 10 : \ - ((C >= 'a' && C <= 'f') ? C - 'a' + 10 : 0))) - -/* In-place rewrite of str, code copied from NET_UnEscapeCnt to avoid imposing - * an PL_strlen and making that function call this one. - */ -PUBLIC int32 -NET_UnEscapeBytes (char * str, int32 len) -{ - int32 i = 0; - register char *dst = str; - char c, d; - - while (i < len) - { - c = str[i++]; - if (c == HEX_ESCAPE && i < len) - { - d = str[i++]; - c = UNHEX(d); - if (i < len) - { - d = str[i++]; - c = (c << 4) | UNHEX(d); - } - } - *dst++ = c; - } - *dst = '\0'; - - return (int32)(dst - str); -} - -PUBLIC int -NET_UnEscapeCnt (char * str) -{ - register char *src = str; - register char *dst = str; - - while(*src) - if (*src != HEX_ESCAPE) - { - *dst++ = *src++; - } - else - { - src++; /* walk over escape */ - if (*src) - { - *dst = UNHEX(*src) << 4; - src++; - } - if (*src) - { - *dst = (*dst + UNHEX(*src)); - src++; - } - dst++; - } - - *dst = 0; - - return (int)(dst - str); - -} /* NET_UnEscapeCnt */ - -/* Returns TRUE if URL type is HTTP_TYPE_URL or SECURE_HTTP_TYPE_URL */ -PUBLIC XP_Bool -NET_IsHTTP_URL(const char *URL) -{ - int type = NET_URL_Type (URL); - return ( type == HTTP_TYPE_URL || type == SECURE_HTTP_TYPE_URL ); -} - -/* Note: Should I move XP_ConvertUrlToLocalFile and XP_BackupFileName, - * (currently in winfe\fegui.cpp) to new file of EDT/XP stuff??? -*/ - -/* Converts absolute URL into an URL relative to the base URL - * BasePath must be an HTTP: or FILE: URL type - * input_url should be absolute url of the same type, - * but we pass it through NET_MakeAbsoluteURL so we can use - * relative input - ASSUMES SAME TYPE! - * Return values defined in \include\net.h - * Caller must PR_Free the string -*/ -int NET_MakeRelativeURL( char *base_url, - char *input_url, - char **relative_url ) -{ - int Result = NET_URL_FAIL; - char *base_host = NULL; - char *url_host = NULL; - char *base_path = NULL; - char *url_path = NULL; - char *base_ptr = NULL; - char *url_ptr = NULL; - int base_type, url_type; - char *relative = NULL; - char *absolute_url; - int new_length; - int subdir_count = 0; - int i; - char *colon; - char *slash; - - if( base_url == NULL || input_url == NULL || - PL_strlen(base_url) == 0 || - PL_strlen(input_url) == 0 ){ - return NET_URL_FAIL; - } - - /* Convert to absolute URL */ - absolute_url = NET_MakeAbsoluteURL(base_url, input_url); - - if(absolute_url == NULL){ - return NET_URL_FAIL; - } - - /* We can only hande HTTP and FILE types, - */ - /* Extended to handle FTP urls, for remote editing of ftp documents */ - base_type = NET_URL_Type (base_url); - url_type = NET_URL_Type (absolute_url); - if ( url_type == 0 || - ! ( base_type == FILE_TYPE_URL || - base_type == HTTP_TYPE_URL || - base_type == SECURE_HTTP_TYPE_URL || - base_type == FTP_TYPE_URL) || - ! ( url_type == FILE_TYPE_URL || - url_type == HTTP_TYPE_URL || - url_type == SECURE_HTTP_TYPE_URL || - url_type == FTP_TYPE_URL ) ) { - goto CLEAN_UP; - } - - - /* If not both of same type, - * we return as if different device - */ - if ( url_type != base_type ) { - Result = NET_URL_NOT_ON_SAME_DEVICE; - goto CLEAN_UP; - } - - -#ifdef XP_WIN - /* Check for UNC filenames. E.g. file:////wongfoo/vol1/test.html - * (\\wongfoo\vol1\test.html). - * This is the cheap and dirty hack so things don't completely break. - * We just leave the url absolute if either base or absolute URL is a - * UNC filename. - * - * We should really do the following: - * 1. If both URLs are UNC file URLs *AND* the machine name is the same, - * make the URL relative, else NET_URL_NOT_ON_SAME_DEVICE. - * - * 2. If only one is a UNC filename, NET_URL_NOT_ON_SAME_DEVICE - */ - if (url_type == FILE_TYPE_URL) { /* already checked that types are the same. */ - /* Looking for "file:////" */ - if (PL_strlen(base_url) >= 9 && - !PL_strncmp(base_url + 5,"////",4)) { - Result = NET_URL_NOT_ON_SAME_DEVICE; - goto CLEAN_UP; - } - if (PL_strlen(absolute_url) >= 9 && - !PL_strncmp(absolute_url + 5,"////",4)) { - Result = NET_URL_NOT_ON_SAME_DEVICE; - goto CLEAN_UP; - } - } -#endif - - - /* Different hosts are also = different devices */ - base_host = NET_ParseURL(base_url, GET_HOST_PART); - url_host = NET_ParseURL(absolute_url, GET_HOST_PART); - if (PL_strcmp(base_host,url_host)){ - Result = NET_URL_NOT_ON_SAME_DEVICE; - goto CLEAN_UP; - } - - /* Similar to NET_ParseURL(GET_PATH_PART), - * but we don't strip named anchors and search strings - */ - colon = (char*) PL_strchr(base_url, ':'); /* returns a const char * */ - - if(colon) { - if(*(colon+1) == '/' && *(colon+2) == '/') { - /* skip host part */ - slash = PL_strchr(colon+3, '/'); - } else { - /* path is right after the colon */ - slash = colon+1; - } - if ( slash ) { - base_path = PL_strdup(slash); - } - } - if ( base_path == NULL ){ - goto CLEAN_UP; - } - - colon = (char*) PL_strchr(absolute_url, ':'); - - /* For url_path, find beginning of path in our - * already-allocated "absolute_url" string - * Don't free url_path! - */ - if(colon) { - if(*(colon+1) == '/' && *(colon+2) == '/') { - url_path = PL_strchr(colon+3, '/'); - } else { - url_path = colon+1; - } - } - if ( url_path == NULL ){ - goto CLEAN_UP; - } - - /* TODO: MODIFY FOR NETWORK FILENAMES: //netname//blah */ - - /* Find location of drive separator */ - base_ptr = (char*) PL_strchr(base_path, '|'); - url_ptr = (char*) PL_strchr(url_path, '|'); - - /* Test if drive is different */ - if ( base_ptr && url_ptr && -#if defined(XP_UNIX) || defined(XP_BEOS) - /* Case-sensitive for UNIX */ - *(url_ptr-1) != *(base_ptr-1) ) -#else - NET_TO_LOWER(*(url_ptr-1)) != NET_TO_LOWER(*(base_ptr-1)) ) -#endif - { - Result = NET_URL_NOT_ON_SAME_DEVICE; - goto CLEAN_UP; - } - - if (base_ptr){ - base_ptr++; /* Move to first "/" after drive separator */ - } else { - /* No '|', so start at begining of path */ - base_ptr = base_path; - } - - if(url_ptr){ - url_ptr++; - }else{ - /* We'll just work with copied string here */ - url_ptr = url_path; - } - - /*Find first mismatched character */ - while ( -#if defined(XP_UNIX) || defined(XP_BEOS) - /* Case-sensitive for UNIX */ - *base_ptr == *url_ptr && -#else - NET_TO_LOWER(*base_ptr) == NET_TO_LOWER(*url_ptr) && -#endif - *base_ptr != '\0' && *url_ptr != '\0' ){ - base_ptr++; - url_ptr++; - } - - /* If we next char is "#" and no base is empty, - * then we have a target in the same document - * We are done. - */ - if( *url_ptr == '#' && *base_ptr == '\0' ){ - Result = NET_URL_SAME_DIRECTORY; - } else { - /* Backup to just after previous slash */ - while ( *(url_ptr-1) != '/' && url_ptr != url_path){ url_ptr--; } - - /* If we have more left on the base: - * either the base filename or more subdirectories, - * so count slashes to get number of subdirectories - */ - while ( *base_ptr != '\0' ){ - if (*base_ptr == '/' ){ - subdir_count++; - } - base_ptr++; - } - - /* We are in the same directory if there are no slashes - * in the final relative path - */ - if ( subdir_count == 0 && NULL == PL_strchr(url_ptr, '/') ){ - Result = NET_URL_SAME_DIRECTORY; - } else { - Result = NET_URL_SAME_DEVICE; - } - } - - /* Don't supply relative URL string - just compare result */ - if ( ! relative_url ){ - goto CLEAN_UP; - } - - /* We can now figure out length of relative URL */ - new_length = PL_strlen(url_ptr) + (subdir_count*3) + 1; - relative = (char *) PR_Malloc(new_length); - if ( !relative ){ - /* out of memory */ - Result = NET_URL_FAIL; - goto CLEAN_UP; - } - - *relative = '\0'; - - /* Add "../" for each subdir left in the base */ - for ( i = 0; i < subdir_count; i++ ){ - PL_strcat(relative, "../"); - } - - /* Append the relative path that doesn't match */ - PL_strcat(relative, url_ptr); - -CLEAN_UP: - if ( relative_url ){ - if ( relative ){ - /* We allocced a relative URL - return it */ - *relative_url = relative; - } else { - /* For all other cases, return absolute URL */ - *relative_url = PL_strdup(absolute_url); - } - } - PR_Free(absolute_url); - - if( base_path ){ - PR_Free(base_path); - } - if( base_host ){ - PR_Free(base_host); - } - if( url_host ){ - PR_Free(url_host); - } - return Result; -} - -/* Extract the filename from a source URL - * and construct add it the same path as - * a base URL (replacing file in base) - * BasePath should be an HTTP: or FILE: URL type, - * but we don't check it. - * src_url may be a relative URL - * If a pointer to a string is supplied, - * the new relative URL is returned - * (just the "file" portion of src_url) - * Note: relative_url can be &src_url, - * thus replacing the source - * Caller must PR_Free the string(s) -*/ -char * NET_MakeTargetURL( char *base_url, - char *src_url, - char **relative_url ) -{ - char *target = NULL; - char *targ_ptr; - char *src_ptr; - char *relative_start; - char *base_end; - char *src_start; - char *src_end = NULL; - char *question; - int base_length; - int src_length; - int i; - - if( base_url == NULL || src_url == NULL || - PL_strlen(base_url) == 0 || - PL_strlen(src_url) == 0 ){ - return NULL; - } - - /* Find where to concatenate the source - * we must have a slash or our base isn't valid! - */ - base_end = PL_strrchr(base_url, '/'); - if ( !base_end ){ - return NULL; - } - base_end++; - - - /* Find start of source (usually filename) right after the last slash */ - src_start = PL_strrchr(src_url, '/'); - if (src_start){ - src_start++; - } else { - /* No slash, start at beginning */ - src_start = src_url; - } - - /* Find end at neareast '#' or '?' */ - src_end = PL_strchr(src_start, '#'); - question = PL_strchr(src_start, '?'); - - if ( question && - ( !src_end || question < src_end ) ){ - src_end = question; - } - - /* Calculate length of segments we will copy */ - if ( src_end ){ - src_length = src_end - src_start; - } else { - src_length = PL_strlen(src_start); - } - base_length = base_end - base_url; - - target = (char *) PR_Malloc(base_length + src_length + 1); - if ( target ){ - targ_ptr = target; - src_ptr = base_url; - - /* Copy the base until we reach file part */ - for ( i = 0; i < base_length; i++ ){ - *targ_ptr++ = *src_ptr++; - } - - /* Save the start of the new relative URL */ - relative_start = targ_ptr; - - /* Concatenate the source file */ - for ( i = 0; i < src_length; i++ ){ - *targ_ptr++ = *src_start++; - } - *targ_ptr = '\0'; - - /* Supply the new relative URL if requested */ - if ( relative_url ) { - /* Free existing string */ - if ( *relative_url ){ - PR_Free(*relative_url); - } - *relative_url = PL_strdup(relative_start); - } - } - - return target; -} - - -PUBLIC char * -NET_UnEscape(char * str) -{ - (void)NET_UnEscapeCnt(str); - - return str; -} - -/******************************************************* - * Routines to parse the application/http-index-format - */ -#define MAX_200_FIELDS 50 -#define ARRAY_GROWTH_RATE 50 - -#define UNKNOWN_TOKEN 0 -#define FILENAME_TOKEN 1 -#define CONTENT_LENGTH_TOKEN 2 -#define LAST_MODIFIED_TOKEN 3 -#define CONTENT_TYPE_TOKEN 4 -#define FILE_TYPE_TOKEN 5 -#define PERMISSIONS_TOKEN 6 - -struct _HTTPIndexParserData { - NET_FileEntryInfo ** data_list; - int32 data_list_length; - int32 number_of_files; - char * line_buffer; - int32 line_buffer_size; - char * text_user_message; - char * html_user_message; - char * base_url; - int mapping_array[MAX_200_FIELDS]; -}; - -PUBLIC HTTPIndexParserData * -NET_HTTPIndexParserInit() -{ - /* create and init parser data */ - HTTPIndexParserData * rv = PR_NEW(HTTPIndexParserData); - - if(!rv) - return(NULL); - - memset(rv, 0, sizeof(HTTPIndexParserData)); - - return(rv); -} - -PUBLIC char * -strchr_in_buf(char *string, int32 string_len, char find_char) -{ - char *cp; - char *end = string+string_len; - - for(cp = string; cp < end; cp++) - if(*cp == find_char) - return(cp); - - return(NULL); -} - -/* return the next space or quote separated token */ -PRIVATE char * -net_get_next_http_index_token(char * line) -{ - static char *next_token_start=NULL; - char *start, *end; - - if(line == NULL) - start = next_token_start; - else - start = line; - - if(start == NULL) - return(NULL); - - while(NET_IS_SPACE(*start)) start++; - - if(*start == '"') - { - /* end of token is next quote */ - start++; - - end = start; - - while(*end != '\0' && *end != '"') end++; - } - else - { - /* end of token is next space */ - end = start; - - while(*end != '\0' && *end != ' ') end++; - } - - if(*end == '\0') - next_token_start = end; - else - next_token_start = end+1; - *end = '\0'; - - if(*start == '\0') - return(NULL); - else - return(start); -} - -PRIVATE int -net_parse_http_index_200_line(HTTPIndexParserData *obj, char *data_line) -{ - int32 position=0; - char *token = net_get_next_http_index_token(data_line); - - while(token) - { - if(!PL_strcasecmp("FILENAME", token)) - { - obj->mapping_array[position] = FILENAME_TOKEN; - } - else if(!PL_strcasecmp("CONTENT-LENGTH", token)) - { - obj->mapping_array[position] = CONTENT_LENGTH_TOKEN; - } - else if(!PL_strcasecmp("LAST-MODIFIED", token)) - { - obj->mapping_array[position] = LAST_MODIFIED_TOKEN; - } - else if(!PL_strcasecmp("CONTENT-TYPE", token)) - { - obj->mapping_array[position] = CONTENT_TYPE_TOKEN; - } - else if(!PL_strcasecmp("FILE-TYPE", token)) - { - obj->mapping_array[position] = FILE_TYPE_TOKEN; - } - else if(!PL_strcasecmp("PERMISSIONS", token)) - { - obj->mapping_array[position] = PERMISSIONS_TOKEN; - } - else - { - obj->mapping_array[position] = UNKNOWN_TOKEN; - } - - token = net_get_next_http_index_token(NULL); - position++; - if(position > MAX_200_FIELDS) - break; - } - - return(0); -} - -PRIVATE int -net_parse_http_index_201_line(HTTPIndexParserData *obj, char *data_line) -{ - int32 position=0; - char *token = net_get_next_http_index_token(data_line); - NET_FileEntryInfo *file_struct; - - /* make sure there is enough space for the file - * entry in the array - */ - if(obj->data_list_length < obj->number_of_files+1) - { - /* malloc some more space for the array - */ - if(obj->data_list) - obj->data_list = (NET_FileEntryInfo **) PR_Realloc(obj->data_list, - (obj->data_list_length - + ARRAY_GROWTH_RATE) - * sizeof(NET_FileEntryInfo*)); - else - obj->data_list = (NET_FileEntryInfo **) PR_Malloc(ARRAY_GROWTH_RATE - * sizeof(NET_FileEntryInfo*)); - obj->data_list_length += ARRAY_GROWTH_RATE; - } - - if(!obj->data_list) - return(MK_OUT_OF_MEMORY); - - file_struct = NET_CreateFileEntryInfoStruct(); - if(!file_struct) - return(MK_OUT_OF_MEMORY); - - while(token) - { - NET_UnEscape(token); - switch(obj->mapping_array[position]) - { - case UNKNOWN_TOKEN: - /* ignore unknown token types */ - break; - - case FILENAME_TOKEN: - file_struct->filename = PL_strdup(token); - break; - - case CONTENT_LENGTH_TOKEN: - file_struct->size = atoi(token); - break; - - case LAST_MODIFIED_TOKEN: - { - PRTime prtime; - PRInt64 r, u; - LL_I2L(u, PR_USEC_PER_SEC); - PR_ParseTimeString(token, TRUE, &prtime); - LL_DIV(r, prtime, u); - LL_L2I(file_struct->date, r); - } - break; - - case CONTENT_TYPE_TOKEN: - file_struct->content_type = PL_strdup(token); - break; - - case FILE_TYPE_TOKEN: - if(!PL_strcasecmp(token, "FILE")) - { - file_struct->special_type = NET_FILE_TYPE; - } - else if(!PL_strcasecmp(token, "DIRECTORY")) - { - file_struct->special_type = NET_DIRECTORY; - } - else if(!PL_strcasecmp(token, "SYMBOLIC-LINK")) - { - file_struct->special_type = NET_SYM_LINK; - } - else if(!PL_strcasecmp(token, "SYM-FILE")) - { - file_struct->special_type = NET_SYM_LINK_TO_FILE; - } - else if(!PL_strcasecmp(token, "SYM-DIRECTORY")) - { - file_struct->special_type = NET_SYM_LINK_TO_DIR; - } - break; - - case PERMISSIONS_TOKEN: - if(PL_strlen(token) == 3) - { - file_struct->permissions = 0; - if(token[0] == 'R') - file_struct->permissions |= NET_READ_PERMISSION; - if(token[1] == 'W') - file_struct->permissions |= NET_WRITE_PERMISSION; - if(token[2] == 'E') - file_struct->permissions |= NET_EXECUTE_PERMISSION; - } - break; - - default: - PR_ASSERT(0); - break; - } - - - token = net_get_next_http_index_token(NULL); - position++; - if(position > MAX_200_FIELDS) - break; - } - - /* every struct must have a filename. If it doesn't - * destroy it - */ - if(!file_struct->filename || !*file_struct->filename) - NET_FreeEntryInfoStruct(file_struct); - else - obj->data_list[obj->number_of_files++] = file_struct; - - return(0); -} - - -PUBLIC int -NET_HTTPIndexParserPut(HTTPIndexParserData *obj, char *data, int32 len) -{ - char *data_line, *new_line, *colon; - int32 string_len; - int32 line_code, status; - - if(!obj) - return(MK_OUT_OF_MEMORY); - - /* buffer until we have a line */ - BlockAllocCat(obj->line_buffer, obj->line_buffer_size, data, len); - obj->line_buffer_size += len; - - /* see if we have a line */ - while(((new_line = strchr_in_buf(obj->line_buffer, - obj->line_buffer_size, - CR)) != NULL) - || ((new_line = strchr_in_buf(obj->line_buffer, - obj->line_buffer_size, - LF)) != NULL) ) - { - if(new_line[0] == CR && new_line[1] == LF) - { - *new_line = '\0'; /* get rid of the LF too */ - new_line++; - } - - /* terminate the line */ - *new_line = '\0'; - - data_line = XP_StripLine(obj->line_buffer); - - /* get the line code */ - colon = PL_strchr(data_line, ':'); - - if(!colon) - goto end_of_line; - - *colon = '\0'; - - line_code = atoi(XP_StripLine(data_line)); - - /* reset data_line to the start of data after the colon */ - data_line = colon+1; - - status = 0; - - switch(line_code) - { - case 100: - /* comment line, ignore */ - break; - - case 101: - StrAllocCat(obj->text_user_message, data_line); - StrAllocCat(obj->text_user_message, "\n"); - break; - - case 102: - StrAllocCat(obj->html_user_message, data_line); - StrAllocCat(obj->html_user_message, "\n"); - break; - - case 200: - status = net_parse_http_index_200_line(obj, data_line); - break; - - case 201: - status = net_parse_http_index_201_line(obj, data_line); - break; - - case 300: - StrAllocCat(obj->base_url, data_line); - break; - - default: - /* fall through and ignore the line */ - break; - } - - if(status < 0) - return(status); - -end_of_line: - /* remove the parsed line from obj->line_buffer */ - string_len = (new_line - obj->line_buffer) + 1; - memcpy(obj->line_buffer, - new_line+1, - obj->line_buffer_size-string_len); - obj->line_buffer_size -= string_len; - - } - - return(0); -} - -PUBLIC int -NET_HTTPIndexParserSort(HTTPIndexParserData *data_obj, int sort_method) -{ -/* @@@@@@ soon */ - return(0); -} - -PUBLIC char * -NET_HTTPIndexParserGetTextMessage(HTTPIndexParserData *data_obj) -{ - return(data_obj->text_user_message); -} - -PUBLIC char * -NET_HTTPIndexParserGetHTMLMessage(HTTPIndexParserData *data_obj) -{ - return(data_obj->html_user_message); -} - -PUBLIC char * -NET_HTTPIndexParserGetBaseURL(HTTPIndexParserData *data_obj) -{ - return(data_obj->base_url); -} - -PUBLIC NET_FileEntryInfo * -NET_HTTPIndexParserGetFileNum(HTTPIndexParserData *data_obj, int32 num) -{ - if(num >= data_obj->number_of_files || num < 0) - return(NULL); - - return(data_obj->data_list[num]); -} - -PUBLIC int32 -NET_HTTPIndexParserGetTotalFiles(HTTPIndexParserData *data_obj) -{ - return(data_obj->number_of_files); -} - -PUBLIC void -NET_HTTPIndexParserFree(HTTPIndexParserData *obj) -{ - int32 i; - - if(!obj) - return; - - /* FREE file data structures and array */ - for(i=0; i<obj->number_of_files; i++) - NET_FreeEntryInfoStruct(obj->data_list[i]); - - FREEIF(obj->data_list); /* array */ - FREEIF(obj->line_buffer); - FREEIF(obj->text_user_message); - FREEIF(obj->html_user_message); - FREE(obj); -} - - -#ifdef PROFILE -#pragma profile off -#endif diff --git a/mozilla/network/main/mkparse.h b/mozilla/network/main/mkparse.h deleted file mode 100644 index a29b06d9523..00000000000 --- a/mozilla/network/main/mkparse.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKPARSE_H -#define MKPARSE_H - -/* - * Returns the number of the month given or -1 on error. - */ -extern int NET_MonthNo (char * month); - -/* accepts an RFC 850 or RFC 822 date string and returns a - * time_t - */ -extern time_t NET_ParseDate(char *date_string); - -/* remove front and back white space - * modifies the original string - */ -extern char * NET_Strip (char * s); - -/* find a character in a fixed length buffer */ -extern char * strchr_in_buf(char *string, int32 string_len, char find_char); - -#endif /* MKPARSE_H */ diff --git a/mozilla/network/main/mkprefs.h b/mozilla/network/main/mkprefs.h deleted file mode 100644 index 49d51a71552..00000000000 --- a/mozilla/network/main/mkprefs.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef __mkprefs_h_ -#define __mkprefs_h_ - -#define pref_browserPrefetch "browser.prefetch" -#define pref_browserCacheMemSize "browser.cache.memory_cache_size" -#define pref_browserCacheDiskSize "browser.cache.disk_cache_size" -#define pref_browserCacheDocFreq "browser.cache.check_doc_frequency" -#define pref_mailAllowSignInUName "mail.allow_at_sign_in_user_name" -#define pref_dnsExpiration "network.dnsCacheExpiration" -#define pref_socksPort "network.hosts.socks_serverport" -#define pref_socksServer "network.hosts.socks_server" -#define pref_proxyACUrl "network.proxy.autoconfig_url" -#define pref_proxyType "network.proxy.type" -#define pref_proxyFtpPort "network.proxy.ftp_port" -#define pref_proxyFtpServer "network.proxy.ftp" -#define pref_proxyGopherPort "network.proxy.gopher_port" -#define pref_proxyGopherServer "network.proxy.gopher" -#define pref_proxyHttpPort "network.proxy.http_port" -#define pref_proxyHttpServer "network.proxy.http" -#define pref_proxyNewsPort "network.proxy.news_port" -#define pref_proxyNewsServer "network.proxy.news" -#define pref_proxyWaisPort "network.proxy.wais_port" -#define pref_proxyWaisServer "network.proxy.wais" -#define pref_proxyNoProxiesOn "network.proxy.no_proxies_on" -#define pref_generalHelpSource "general.help_source.site" -#define pref_generalHelpSourceUrl "general.help_source.url" -#define pref_padPacURL "network.padPacURL" -#define pref_enablePad "network.enablePad" -#define pref_mailQuotedStyle "mail.quoted_style" -#define pref_cookieBehavior "network.cookie.cookieBehavior" -#define pref_warnAboutCookies "network.cookie.warnAboutCookies" -#define pref_strictCookieDomains "network.cookie.strictDomains" -#define pref_scriptName "network.cookie.filterName" -#define pref_goBrowsingEnabled "browser.goBrowsing.enabled" -#define pref_sendRefererHeader "network.sendRefererHeader" -#define pref_searchUrl "network.search.url" - -#endif /* __mkprefs_h_ */ diff --git a/mozilla/network/main/mkselect.c b/mozilla/network/main/mkselect.c deleted file mode 100644 index 042b2348c0e..00000000000 --- a/mozilla/network/main/mkselect.c +++ /dev/null @@ -1,468 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * - * This file implements the socket polling functions that - * allow us to quickly determine if there is anything for - * netlib to do at any instance in time. These functions - * previously resided in the FE's but now have been consolidated - * in the backend as part of the NSPR20 transition, since we - * are no longer using winsock async socket notification. - * - * Designed and implemented by Lou Montulli '98 - */ -#include "mkutils.h" -#include "mkselect.h" -#include "nslocks.h" - -typedef enum { - ConnectSelect, - ReadSelect -} SelectType; - -/* define this to use FE timers for the call_netlib_all_the_time - * function. Otherwise we will use NET_PollSockets to perform the - * same functionality - */ -#ifdef XP_WIN -#undef USE_TIMERS_FOR_CALL_ALL_THE_TIME -#else -#define USE_TIMERS_FOR_CALL_ALL_THE_TIME -#endif - -#define MAX_SIMULTANIOUS_SOCKETS 100 -/* should never have more than MAX sockets */ -PRPollDesc poll_desc_array[MAX_SIMULTANIOUS_SOCKETS]; -unsigned int fd_set_size = 0; -PRIVATE int net_calling_all_the_time_count=0; -PRIVATE XP_Bool net_slow_timer_on=FALSE; - -#if defined(NO_NETWORK_POLLING) -#include "private/primpl.h" - -#if defined(XP_PC) -#include "md/_win95.h" - -extern HWND gDNSWindow; -extern UINT gMSGAsyncSelect; - -/* - * Helper routine which extracts the OS specific socket from the PRFileDesc - * structure... - */ -PRInt32 -net_GetOSFDFromFileDesc(PRFileDesc* fd) -{ - PRInt32 osfd = 0; - PRFileDesc *bottom; - bottom = PR_GetIdentitiesLayer(fd, PR_NSPR_IO_LAYER); - - PR_ASSERT(NULL != bottom); /* what to do about that? */ - if ((NULL != bottom) && - (_PR_FILEDESC_OPEN == bottom->secret->state)) { - osfd = bottom->secret->md.osfd; - } - return osfd; -} - -#else /* ! XP_PC */ - -PRInt32 -net_GetOSFDFromFileDesc(PRFileDesc* fd) -{ - PR_ASSERT(0); /* write me */ - return 0; -} - -#endif /* ! XP_PC */ - -/* - * Helper routine which maps the OS specific socket back to its associated - * PRFileDesc structure... - */ -PRFileDesc* -net_GetFileDescFromOSFD(PRInt32 osfd) -{ - int i; - PRFileDesc* fd = NULL; - - /* - * Make sure this function is called inside of the LIBNET lock since - * it modifies global data structures... - */ - PR_ASSERT(LIBNET_IS_LOCKED()); - - for (i=0; i<fd_set_size; i++) { - fd = poll_desc_array[i].fd; - if (net_GetOSFDFromFileDesc(fd) == osfd) { - break; - } - } - return fd; -} - -/* - * Request an asynchronous notification when data is available on the - * given PRFileDesc... - */ -void -net_AsyncSelect(PRFileDesc* fd, long netMask) -{ - SOCKET osfd; - - osfd = (SOCKET)net_GetOSFDFromFileDesc(fd); - - if (0 != osfd) { -#if defined(XP_PC) - WSAAsyncSelect(osfd, gDNSWindow, gMSGAsyncSelect, netMask); -#else /* ! XP_PC */ - PR_ASSERT(0); /* write me */ -#endif /* ! XP_PC */ - } -} - - -/* - * Force the Netlib thread to drop out of its wait state... - */ -void -net_ForceSelect(void) -{ -#if defined(XP_PC) - PostMessage(gDNSWindow, gMSGAsyncSelect, 0, 0L); -#else /* ! XP_PC */ - PR_ASSERT(0); /* write me */ -#endif /* ! XP_PC */ -} - -#endif /* NO_NETWORK_POLLING */ - - -/* Add a select entry, no duplicates. */ -PRIVATE void -net_add_select(SelectType stType, PRFileDesc *prFD) -{ - unsigned int index = fd_set_size; - unsigned int count; - -#define CONNECT_FLAGS (PR_POLL_READ | PR_POLL_EXCEPT | PR_POLL_WRITE) -#define READ_FLAGS (PR_POLL_READ | PR_POLL_EXCEPT) - - /* - * Make sure this function is called inside of the LIBNET lock since - * it modifies global data structures... - */ - PR_ASSERT(LIBNET_IS_LOCKED()); - - /* Go through the list, make sure that there is not already an entry for fd. */ - for(count=0; count < fd_set_size; count++) - { - if(poll_desc_array[count].fd == prFD) - { - /* found it */ - /* verify that it has the same flags that we wan't, - * otherwise add it again with different flags - */ - if((stType == ConnectSelect && poll_desc_array[count].in_flags == CONNECT_FLAGS) - || (stType == ReadSelect && poll_desc_array[count].in_flags == READ_FLAGS)) - { - index = count; - break; - } - } - } - - /* need to add a new one if we didnt' find the index */ - if(index == fd_set_size) - { - poll_desc_array[fd_set_size].fd = prFD; - fd_set_size++; - } - - if(stType == ConnectSelect) - poll_desc_array[index].in_flags = CONNECT_FLAGS; - else if(stType == ReadSelect) - poll_desc_array[index].in_flags = READ_FLAGS; - else - PR_ASSERT(0); - -#if defined(NO_NETWORK_POLLING) - /* Request a notification when data is available on the socket... */ - net_AsyncSelect(prFD, - FD_READ | FD_WRITE | FD_ACCEPT | FD_CONNECT | FD_CLOSE | FD_OOB); -#endif /* NO_NETWORK_POLLING */ -} - -/* Remove a select if it exists. */ -PRIVATE void -net_remove_select(SelectType stType, PRFileDesc *prFD) -{ - unsigned int count; - - /* - * Make sure this function is called inside of the LIBNET lock since - * it modifies global data structures... - */ - PR_ASSERT(LIBNET_IS_LOCKED()); - - /* Go through the list */ - for(count=0; count < fd_set_size; count++) - { - if(poll_desc_array[count].fd == prFD) - { - - if((stType == ConnectSelect && poll_desc_array[count].in_flags == CONNECT_FLAGS) - || (stType == ReadSelect && poll_desc_array[count].in_flags == READ_FLAGS)) - { - /* found it collapse the list */ - fd_set_size--; - if(count < fd_set_size) { - memmove(&poll_desc_array[count], &poll_desc_array[count+1], (fd_set_size - count) * sizeof(PRPollDesc)); - } - -#if defined(NO_NETWORK_POLLING) - /* Cancel any outstanding notification requests for the socket... */ - net_AsyncSelect(prFD, 0); -#endif /* NO_NETWORK_POLLING */ - return; - } - } - } - - /* didn't find it. opps */ -} - -MODULE_PRIVATE void -NET_SetReadPoll(PRFileDesc *fd) -{ - net_add_select(ReadSelect, fd); -} - -MODULE_PRIVATE void -NET_ClearReadPoll(PRFileDesc *fd) -{ - net_remove_select(ReadSelect, fd); -} - -MODULE_PRIVATE void -NET_SetConnectPoll(PRFileDesc *fd) -{ - net_add_select(ConnectSelect, fd); -} - -MODULE_PRIVATE void -NET_ClearConnectPoll(PRFileDesc *fd) -{ - net_remove_select(ConnectSelect, fd); -} - -/* call PR_Poll and call Netlib if necessary - * - * return FALSE if nothing to do. - */ -PUBLIC XP_Bool -NET_PollSockets(void) -{ - static PRIntervalTime interval = 0; - register unsigned int itmp; - -#if defined(NO_NETWORK_POLLING) - /* - * This routine should only be called if network polling is enabled... - */ - PR_ASSERT(0); -#endif /* NO_NETWORK_POLLING */ - - /* - * Enter the LIBNET lock to protect the poll_desc_array and other global - * data structures used by NET_PollSockets(...) - */ - LIBNET_LOCK(); - - if(net_calling_all_the_time_count) - NET_ProcessNet(NULL, NET_EVERYTIME_TYPE); - - if(!interval) - interval = PR_MillisecondsToInterval(1); - - if(1 > fd_set_size) { - LIBNET_UNLOCK(); - return FALSE; - } - - itmp = PR_Poll(poll_desc_array, fd_set_size, interval); - - if(itmp < 1) { - LIBNET_UNLOCK(); - return TRUE; /* potential for doing stuff in the future. */ - } - - /* for now call on all active sockets. */ - /* if this is too much call only one, but reorder the list each time. */ - for(itmp=0; itmp < fd_set_size; itmp++) - { - if(poll_desc_array[itmp].out_flags) - NET_ProcessNet(poll_desc_array[itmp].fd, NET_SOCKET_FD); - } - - LIBNET_UNLOCK(); - return TRUE; -} - -void -net_process_net_timer_callback(void *closure) -{ - PR_ASSERT(net_calling_all_the_time_count >= 0); - if (net_calling_all_the_time_count == 0) - return; - - if (NET_ProcessNet(NULL, NET_EVERYTIME_TYPE) == 0) - net_calling_all_the_time_count = 0; - else - FE_SetTimeout(net_process_net_timer_callback, NULL, 1); -} - -MODULE_PRIVATE void -NET_SetCallNetlibAllTheTime(MWContext *context, char *caller) -{ - PR_ASSERT(net_calling_all_the_time_count >= 0); - -#ifdef USE_TIMERS_FOR_CALL_ALL_THE_TIME - if (net_calling_all_the_time_count == 0) - FE_SetTimeout(net_process_net_timer_callback, NULL, 1); -#endif /* USE_TIMERS_FOR_CALL_ALL_THE_TIME */ - - net_calling_all_the_time_count++; - -#if defined(NO_NETWORK_POLLING) - /* - * Force the netlib thread to drop out of its wait state (ie. select). - * This is necessary, since this function can be called on multiple - * threads... - */ - net_ForceSelect(); -#endif /* NO_NETWORK_POLLING */ -} - -#define SLOW_NETLIB_TIMER_INTERVAL_MILLISECONDS 10 -void -net_process_slow_net_timer_callback(void *closure) -{ - if(!NET_ProcessNet(NULL, NET_EVERYTIME_TYPE)) - net_slow_timer_on = FALSE; /* dont reset the timer */ - else if (net_slow_timer_on) - FE_SetTimeout(net_process_slow_net_timer_callback, - NULL, - SLOW_NETLIB_TIMER_INTERVAL_MILLISECONDS); -} - -/* this function turns on and off a reasonably slow timer that will - * push the netlib along even when it doesn't get any onIdle time. - * this is unfortunately necessary on windows because when a modal - * dialog is up it won't call the OnIdle loop which is currently the - * source of our events. - */ -MODULE_PRIVATE void -NET_SetNetlibSlowKickTimer(PRBool set) -{ - if(net_slow_timer_on == set) - return; /* do nothing */ - - net_slow_timer_on = set; - - /* call immediately */ - if(net_slow_timer_on) - FE_SetTimeout(net_process_slow_net_timer_callback, - NULL, - SLOW_NETLIB_TIMER_INTERVAL_MILLISECONDS); -} - -MODULE_PRIVATE void -NET_ClearCallNetlibAllTheTime(MWContext *context, char *caller) -{ - PR_ASSERT(net_calling_all_the_time_count > 0); - net_calling_all_the_time_count--; -} - -MODULE_PRIVATE PRBool -NET_IsCallNetlibAllTheTimeSet(MWContext *context, char *caller) -{ - if(caller == NULL) - { - if(net_calling_all_the_time_count > 0) - return PR_TRUE; - } - else - { - /* not implemented */ - PR_ASSERT(0); - } - - return PR_FALSE; -} - -MODULE_PRIVATE void -NET_ClearDNSSelect(MWContext *context, PRFileDesc *file_desc) -{ -#if defined(XP_WIN) || (defined(XP_UNIX) && defined(UNIX_ASYNC_DNS)) || (defined(XP_OS2) && !defined(XP_OS2_DOUGSOCK)) - /* FE_AbortDNSLookup(file_desc); */ -#endif /* XP_WIN || (XP_UNIX && UNIX_ASYNC_DNS) || (defined(XP_OS2) && !defined(XP_OS2_DOUGSOCK) */ - -} - -MODULE_PRIVATE void -NET_SetFileReadSelect(MWContext *context, int file_desc) -{ - /* need to conver this over to NSPR PRFileDesc's before it will work */ -/* FE_SetFileReadSelect(context, file_desc); */ -} - -MODULE_PRIVATE void -NET_ClearFileReadSelect(MWContext *context, int file_desc) -{ - /* need to conver this over to NSPR PRFileDesc's before it will work */ -/* FE_ClearReadSelect(context, file_desc); */ -} - -MODULE_PRIVATE void -NET_SetReadSelect(MWContext *context, PRFileDesc *file_desc) -{ - NET_SetReadPoll(file_desc); -} - -MODULE_PRIVATE void -NET_ClearReadSelect(MWContext *context, PRFileDesc *file_desc) -{ - NET_ClearReadPoll(file_desc); -} - -MODULE_PRIVATE void -NET_SetConnectSelect(MWContext *context, PRFileDesc *file_desc) -{ - NET_SetConnectPoll(file_desc); -} - -MODULE_PRIVATE void -NET_ClearConnectSelect(MWContext *context, PRFileDesc *file_desc) -{ - NET_ClearConnectPoll(file_desc); -} diff --git a/mozilla/network/main/mkselect.h b/mozilla/network/main/mkselect.h deleted file mode 100644 index 72143db79a3..00000000000 --- a/mozilla/network/main/mkselect.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKSELECT_H -#define MKSELECT_H - -PR_BEGIN_EXTERN_C - -extern void NET_SetReadPoll(PRFileDesc *fd); - -extern void NET_ClearReadPoll(PRFileDesc *fd); - -extern void NET_SetConnectPoll(PRFileDesc *fd); - -extern void NET_ClearConnectPoll(PRFileDesc *fd); - -/* this function turns on and off a reasonably slow timer that will - * push the netlib along even when it doesn't get any onIdle time. - * this is unfortunately necessary on windows because when a modal - * dialog is up it won't call the OnIdle loop which is currently the - * source of our events. - */ -extern void NET_SetNetlibSlowKickTimer(PRBool set); - -/* set and clear the callnetliballthetime busy poller. - * all reference counting is done internally - * - * the caller string is used in debug builds to detect callers that - * don't set and clear correctly - */ -extern void NET_SetCallNetlibAllTheTime(MWContext *context, char *caller); -extern void NET_ClearCallNetlibAllTheTime(MWContext *context, char *caller); -extern PRBool NET_IsCallNetlibAllTheTimeSet(MWContext *context, char *caller); - -extern void NET_SetReadSelect(MWContext *context, PRFileDesc *file_desc); -extern void NET_ClearReadSelect(MWContext *context, PRFileDesc *file_desc); -extern void NET_SetFileReadSelect(MWContext *context, int file_desc); -extern void NET_ClearFileReadSelect(MWContext *context, int file_desc); -extern void NET_SetConnectSelect(MWContext *context, PRFileDesc *file_desc); -extern void NET_ClearConnectSelect(MWContext *context, PRFileDesc *file_desc); -extern void NET_ClearDNSSelect(MWContext *context, PRFileDesc *file_desc); - -void net_process_net_timer_callback(void *closure); -void net_process_slow_net_timer_callback(void *closure); - -PR_END_EXTERN_C - -#endif /* MKSELECT_H */ diff --git a/mozilla/network/main/mksockrw.c b/mozilla/network/main/mksockrw.c deleted file mode 100644 index 06c9efcdeae..00000000000 --- a/mozilla/network/main/mksockrw.c +++ /dev/null @@ -1,481 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "mkutils.h" -#include "mktcp.h" -#include "mkparse.h" -#include "prerror.h" -#include "mkgeturl.h" /* for error codes */ -#include "fe_proto.h" /* for externs */ -#include "merrors.h" -#include "ssl.h" - -extern int MK_HTTP_TYPE_CONFLICT; -extern int XP_ERRNO_EWOULDBLOCK; - -#ifdef XP_UNIX -/* #### WARNING, this is duplicated in mkconect.c - */ -# include <sys/ioctl.h> -/* - * mcom_db.h is only included here to set BYTE_ORDER !!! - * MAXDNAME is pilfered right out of arpa/nameser.h. - */ -# include "mcom_db.h" - -# if defined(__hpux) || defined(_HPUX_SOURCE) -# define BYTE_ORDER BIG_ENDIAN -# define MAXDNAME 256 /* maximum domain name */ -# else -# include <arpa/nameser.h> -# endif - -#include <resolv.h> - -#if defined(HAVE_SYS_FILIO_H) -#include <sys/filio.h> -#endif - -#endif /* XP_UNIX */ - -#ifdef PROFILE -#pragma profile on -#endif - -/* Global TCP Read/Write variables - */ -PUBLIC char * NET_Socket_Buffer=0; -PUBLIC int NET_Socket_Buffer_Size=0; - -#if defined(XP_UNIX) && defined(XP_BSD_UNIX) - -PRIVATE char * net_real_socket_buffer_ptr=0; - -#include <unistd.h> -#include <malloc.h> - -typedef unsigned int intptr_t; - -char *GetPageAlignedBuffer(int size) -{ - char *rv; - static int pageSize = 0; - - if (pageSize == 0) - { - /* Cache this value to avoid syscall next time */ - pageSize = getpagesize(); - } - - net_real_socket_buffer_ptr = 0; - - /* Allocate too much memory */ - rv = (char *) PR_Malloc(size + pageSize - 1); - if (rv) - { - intptr_t r = (intptr_t) rv; - intptr_t offset = r & (pageSize - 1); - - net_real_socket_buffer_ptr = rv; - - if (offset) - { - /* Have to round up address */ - r = r + pageSize - offset; - } - else - { - /* - ** Could be generous here and realloc to shrink since we - ** don't need the extra space... - */ - } - rv = (char*) r; - } - return rv; -} -#endif /* XP_UNIX */ - -/* allocate memory for the TCP socket - * buffer - */ -PUBLIC int -NET_ChangeSocketBufferSize (int size) -{ - NET_Socket_Buffer_Size = 0; - -#if !defined(XP_MAC) - if(size < 1) - size = 10*1024; /* default */ - - if(size > 31*1024) - size = 31*1024; -#else - /* On the Mac we want a biiiig buffer */ - if (size < 1 || size > 64*1024) - size = 64*1024; -#endif /* XP_MAC */ - - -#if defined(XP_UNIX) && defined(XP_BSD_UNIX) - FREEIF(net_real_socket_buffer_ptr); - NET_Socket_Buffer = GetPageAlignedBuffer(size); -#else - FREEIF(NET_Socket_Buffer); - NET_Socket_Buffer = (char *) PR_Malloc(size); -#endif /* XP_UNIX */ - - if(!NET_Socket_Buffer) - return(0); - - /* else */ - NET_Socket_Buffer_Size = size; - return(1); -} - -/* this is a very standard network write routine. - * - * the only thing special about it is that - * it returns MK_HTTP_TYPE_CONFLICT on special error codes - * - */ -PUBLIC int NET_HTTPNetWrite (PRFileDesc *fildes, CONST void * buf, unsigned int nbyte) -{ - static int status; - - status = (int) NET_BlockingWrite(fildes, buf, nbyte); - -#ifdef XP_UNIX - /* these status codes only work on UNIX - */ - if ((status < 0) - && (status == PR_NOT_CONNECTED_ERROR || status == PR_CONNECT_RESET_ERROR || status == PR_PIPE_ERROR)) - return MK_HTTP_TYPE_CONFLICT; -#endif /* XP_UNIX */ - - /* else */ - return(status); -} - -PUBLIC int32 NET_BlockingWrite (PRFileDesc *filedes, CONST void * buf, unsigned int nbyte) -{ - int32 length_written = 1; - unsigned int tot_len_written = 0; - - while(nbyte > 0 && length_written > -1) - { - length_written = PR_Write(filedes, (const char*) buf+tot_len_written, nbyte); - - if(length_written > -1) - { - nbyte -= (unsigned int) length_written; - tot_len_written += (unsigned int) length_written; - } - else - { - int rv = PR_GetError(); - if(rv == PR_WOULD_BLOCK_ERROR) - { -#if defined(XP_WIN) && defined(MOZILLA_CLIENT) - FEU_StayingAlive(); -#endif - length_written = 1; /* this will let it continue looping */ - } - else - { - return (rv < 0) ? rv : (-rv); - } - } - } - - return(length_written); /* postive or negative */ -} - -#ifdef DEBUG -/* only a debugging routine! - * Prints the output to stderr as well as the socket - */ -MODULE_PRIVATE int -NET_DebugNetWrite (PRFileDesc *fildes, CONST void *buf, unsigned nbyte) -{ - if(MKLib_trace_flag && nbyte > 0) - { -#ifdef XP_UNIX - write(2, "Tx: ", 4); - write(2, buf, nbyte); - write(2, "\n", 1); -#endif - } - - return(PR_Write(fildes, buf, nbyte)); -} - -/* This is a pretty standard read routine for debugging - * - * It prints whatever it reads to stderr for debugging purposes - */ -MODULE_PRIVATE int -NET_DebugNetRead (PRFileDesc *fildes, void * buf, unsigned nbyte) -{ - static int status; /* read return code */ - - status = PR_Read (fildes, buf, nbyte); - - if(MKLib_trace_flag && status != PR_SUCCESS) - { -#ifdef XP_UNIX - write(2,"Rx: ", 4); - write(2, (const char *)buf, status); - write(2, "\n", 1); -#endif - } - - return(status); -} -#endif /* DEBUG */ - - -/* This is a pretty standard read routine - * - * The only special thing that is does is - * that it checks for the special errors encountered - * in a HTTP 1/.9 conflict and returns MK_HTTP_TYPE_CONFLICT - * when encountered - */ -/* fix Mac warning of missing prototype */ -MODULE_PRIVATE int -NET_HTTPNetRead (PRFileDesc *fildes, void *buf, unsigned nbyte); - -MODULE_PRIVATE int -NET_HTTPNetRead (PRFileDesc *fildes, void *buf, unsigned nbyte) -{ - static int status; /* read return code */ - - status = PR_Read (fildes, buf, nbyte); - -#ifdef XP_UNIX - /* check for HTTP server type conflict - */ - if (status == ENOTCONN || status == ECONNRESET || status == EPIPE) - return MK_HTTP_TYPE_CONFLICT; -#endif /* XP_UNIX */ - - /* else */ - return(status); -} - -/* net_BufferedReadLine - * - * will do a single read on the passed in socket - * and try and grok a single line from it. - * - * a '\n' is the demarkation of the end of a line - * - * if a '\n' exists the line will be returned into 'line' as - * a separately malloc'd line. Any extra data - * will be malloc'd into the passed in 'buffer' pointer. - * - * if a '\n' is not found the data read from the - * socket will be appended (realloc'd) to the end of - * the passed in buffer. - * - * the status of the socket read will be passed back - * as a return value - * - * if 'line' is non-zero then a line was available and - * was malloc'd - */ -#define LINE_BUFFER_SIZE 1024 - -MODULE_PRIVATE int -NET_BufferedReadLine (PRFileDesc * sock, - char ** line, - char ** buffer, - int32 * buffer_size, - Bool * pause_for_next_read) -{ - char *strptr, *linefeed=0; - int status=1; - static char line_buffer[LINE_BUFFER_SIZE]; /* maybe this should be static? */ - int line_length; - char *far_end; - - *line = 0; /* init */ - - *pause_for_next_read = TRUE; /* This is the default it may change */ - - - /* scan for line in existing buffer */ - if(*buffer_size > 0) - { - for(strptr = *buffer; strptr < *buffer+*buffer_size; strptr++) - if(*strptr == LF) - { - linefeed = strptr; - break; - } - } - - if(!linefeed) - { - /* get some more data from the socket */ - int32 read_size = MIN(LINE_BUFFER_SIZE, NET_Socket_Buffer_Size); - status = PR_Read(sock, NET_Socket_Buffer, read_size); - - TRACEMSG(("Read %d bytes from socket %d", status, sock)); - - if(status < 0) - { - int rv = PR_GetError(); - if (rv == PR_WOULD_BLOCK_ERROR) - { - /* defaults to *pause_for_next_read = TRUE; */ - return(1); - } - *pause_for_next_read = FALSE; - return (rv < 0) ? rv : (-rv); - } - - TRACEMSG(("Read %d bytes from socket\n",status)); - - if(status > 0) - { - BlockAllocCat(*buffer, *buffer_size, NET_Socket_Buffer, status); - *buffer_size += status; - } - - if(*buffer_size > 0) - { - for(strptr = *buffer; strptr < *buffer+*buffer_size; strptr++) - if(*strptr == LF) - { - linefeed = strptr; - break; - } - } - } - - if(linefeed) - { - int32 tot_buf_size; - - *linefeed = '\0'; - - /* kill the '\r' if it exits */ - if(linefeed > *buffer && *(linefeed-1) == '\r') - *(linefeed-1) = '\0'; - - - /* the number of bytes that the line tekes up */ - line_length = (linefeed+1) - *buffer; - - /* the farthest end of the memory buffer */ - far_end = *buffer+*buffer_size; - - if(line_length == *buffer_size) - { - /* the line is the whole buffer - * no copying is required and we know that - * there can't be any new \n's in the buffer - * so lets return now - */ - *buffer_size = 0; - *line = *buffer; - return(status); - } - - /* set the line pointer now since we know where it - * will end up - */ - *line = far_end-line_length; - - /* I'm doing some optimization here to try and reduce malloc's - * I want to copy the line that the calling function needs - * to the end of the buffer and move the part of the buffer - * that needs saveing to the beginning of the buffer - * that way no mallocs are required. Space will be compacted - * or enlarged by the AllocCat above. - * - * If the line_buffer isn't large enough to hold the whole - * line then we need to do the copy in segments and shift - * the contents of the remaining line segment and buffer - * to the left each time. This is very inefficient - * but the line_buffer is large enough to handle every - * expected line size (since lines should always be less - * than 512). The segmenting should only come into - * play in degenerate cases. - */ - tot_buf_size = *buffer_size; - - while(line_length) - { - - if(line_length > LINE_BUFFER_SIZE) - { - memmove(line_buffer, *buffer, LINE_BUFFER_SIZE); - *buffer_size -= LINE_BUFFER_SIZE; - line_length -= LINE_BUFFER_SIZE; - /* move everything over includeing the parts - * of the buffer already moved - */ - memmove(*buffer, - (*buffer)+LINE_BUFFER_SIZE, - tot_buf_size-LINE_BUFFER_SIZE); - memmove(far_end-LINE_BUFFER_SIZE, line_buffer, LINE_BUFFER_SIZE); - } - else - { - memmove(line_buffer, *buffer, line_length); - *buffer_size -= line_length; - /* move everything over includeing the parts - * of the buffer already moved - */ - memmove(*buffer, - (*buffer)+line_length, - tot_buf_size-line_length); - memmove(far_end-line_length, line_buffer, line_length); - line_length = 0; - } - } - - /* check for another linefeed in the buffered data - * if there is one then we don't want to pause for - * read yet. - */ - linefeed = 0; - for(strptr = *buffer; strptr <= *buffer+*buffer_size; strptr++) - if(*strptr == LF) - { - linefeed = strptr; - break; - } - - if(linefeed) - *pause_for_next_read = FALSE; - } - - return(status); -} - -#ifdef PROFILE -#pragma profile off -#endif diff --git a/mozilla/network/main/mksort.c b/mozilla/network/main/mksort.c deleted file mode 100644 index e92b01abc28..00000000000 --- a/mozilla/network/main/mksort.c +++ /dev/null @@ -1,170 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" -#include "mksort.h" -#include "nsQuickSort.h" - -#define CHUNK_SIZE 400 - -#ifdef PROFILE -#pragma profile on -#endif - - -MODULE_PRIVATE SortStruct * -NET_SortInit (void) -{ - - SortStruct * sort_struct = PR_NEW(SortStruct); - - if(!sort_struct) - return(0); - - sort_struct->list = (void **) PR_Malloc((sizeof(void *) * CHUNK_SIZE)); - - if(!sort_struct->list) - return(0); - - sort_struct->cur_size = CHUNK_SIZE; - sort_struct->num_entries = 0; - - return(sort_struct); -} - -MODULE_PRIVATE Bool -NET_SortAdd (SortStruct * sort_struct, void * add_object) -{ - if(!sort_struct) - { - TRACEMSG(("Trying to add to NULL sort_struct")); - return(0); - } - - if(sort_struct->cur_size == sort_struct->num_entries) - { /* whoops the list was too small, expand it */ - - sort_struct->cur_size += CHUNK_SIZE; - sort_struct->list = (void **) PR_Realloc(sort_struct->list, - (sizeof(void *) * sort_struct->cur_size)); - - if(!sort_struct->list) - return(0); /* very bad! */ - } - - sort_struct->list[sort_struct->num_entries++] = add_object; - - return(1); - -} - -MODULE_PRIVATE Bool -NET_SortInsert(SortStruct * sort_struct, void * insert_before, void * new_object) -{ - int i; - - if(sort_struct->cur_size == sort_struct->num_entries) - { /* whoops the list was too small, expand it */ - - sort_struct->cur_size += CHUNK_SIZE; - sort_struct->list = (void **) PR_Realloc(sort_struct->list, - (sizeof(void *) * sort_struct->cur_size)); - - if(!sort_struct->list) - return(0); /* very bad! */ - } - - /* find the insert_before object in the list - */ - for(i=0; i < sort_struct->num_entries; i++) - { - if(sort_struct->list[i] == insert_before) - break; - } - - if(sort_struct->list[i] == insert_before) - { - void * tmp_ptr1; - void * tmp_ptr2; - - tmp_ptr2 = new_object; - - for(; i < sort_struct->num_entries; i++) - { - tmp_ptr1 = sort_struct->list[i]; - sort_struct->list[i] = tmp_ptr2; - tmp_ptr2 = tmp_ptr1; - } - - sort_struct->list[i] = tmp_ptr2; - sort_struct->num_entries++; - } - else - { - return(0); - } - - return(1); -} - -MODULE_PRIVATE void -NET_DoSort(SortStruct * sort_struct, int (*compar) (const void *, const void *, void *)) -{ - NS_QuickSort(sort_struct->list, (unsigned int) (sort_struct->num_entries), sizeof(void *), compar, NULL); -} - -/* unloads backwards :( - */ -MODULE_PRIVATE void * -NET_SortUnloadNext(SortStruct * sort_struct) -{ - if(sort_struct->num_entries < 1) - return(0); - - return(sort_struct->list[--sort_struct->num_entries]); -} - -MODULE_PRIVATE void * -NET_SortRetrieveNumber(SortStruct * sort_struct, int number) -{ - if(number >= sort_struct->num_entries) - return(0); - - return(sort_struct->list[number]); -} - -MODULE_PRIVATE int -NET_SortCount(SortStruct * sort_struct) -{ - return(sort_struct->num_entries); -} - -MODULE_PRIVATE void -NET_SortFree(SortStruct * sort_struct) -{ - PR_Free(sort_struct->list); - PR_Free(sort_struct); -} - -#ifdef PROFILE -#pragma profile off -#endif - diff --git a/mozilla/network/main/mksort.h b/mozilla/network/main/mksort.h deleted file mode 100644 index 86a685022c7..00000000000 --- a/mozilla/network/main/mksort.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKSORT_H -#define MKSORT_H - -typedef struct _SortStruct { - int cur_size; - int num_entries; - void ** list; -} SortStruct; - - -extern SortStruct * NET_SortInit (void); -extern Bool NET_SortAdd (SortStruct * sort_struct, void * add_object); -extern void NET_DoSort(SortStruct * sort_struct, int (*compar) (const void *, const void *, void *)); -extern void * NET_SortUnloadNext(SortStruct * sort_struct); -extern void * NET_SortRetrieveNumber(SortStruct * sort_struct, int number); -extern int NET_SortCount(SortStruct * sort_struct); -extern Bool NET_SortInsert(SortStruct * sort_struct, void * insert_before, void * new_object); - - - -extern void NET_SortFree(SortStruct * sort_struct); - -#endif /* MKSORT_H */ diff --git a/mozilla/network/main/mkstream.c b/mozilla/network/main/mkstream.c deleted file mode 100644 index d2380f56a21..00000000000 --- a/mozilla/network/main/mkstream.c +++ /dev/null @@ -1,1249 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * Do stream related stuff like push data down the - * stream and determine which converter to use to - * set up the stream. - * Additions/Changes by Judson Valeski 1998 - */ -#include "mkutils.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "mktcp.h" - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_ALERT_CANTFIND_CONVERTER; - - -#ifdef PROFILE -#pragma profile on -#endif - -typedef struct _net_ConverterStruct { - XP_List * converter_stack; /* the ordered list of converters; - * elements are net_ConverterElement's - */ - char * format_in; /* the input (mime) type that the - * function accepts - */ - char * encoding_in; /* the input content-encoding that the - * function accepts, or 0 for `any'. - */ - FO_Present_Types format_out; /* the output type of the function */ - Bool bAutomated; /* this flag currently only used by Window on the - client side. */ -} net_ConverterStruct; - -typedef struct _net_ConverterElement { - NET_Converter * converter; /* the converter function */ - void * data_obj; /* a converter specific data object - * passed in at the - * time of registration - */ -} net_ConverterElement; - -/* MWH - this is an ugly implement to get get around the following: I need to pass - a flag to NET_RegisterContentTypeConverter(), but I don't want to change the API. - If we changed this API please fixed this problem. -*/ - -static Bool autoFlag = 0; - -static Bool needInit = TRUE; /* this is the flag to tell us that we need to initialize - net_converter_list, and net_decoder_list. */ - -PRIVATE XP_List * net_converter_list[MAX_FORMATS_OUT]; /* a list of converters */ -PRIVATE XP_List * net_decoder_list[MAX_FORMATS_OUT]; /* a list of decoders */ - -#define NET_MIME_EXACT_MATCH 1 -#define NET_MIME_PARTIAL_MATCH 2 -#define NET_WILDCARD_MATCH 3 - -/* will compare two mime times and return - * NET_MIME_EXACT_MATCH if they match exactly - * or NET_MIME_PARTIAL_MATCH if they match due - * to a wildcard entry (image.*, or movie.*). - * - * if 'partial' equals '*' then - * NET_WILDCARD_MATCH is returned - * - * If there is no match then 0(zero) is returned - */ -PRIVATE int -net_compare_mime_types(char * absolute, char * partial) -{ - char *star; - - TRACEMSG(("StreamBuilder: Comparing %s and %s\n",absolute, partial)); - - if(!PL_strcasecmp(absolute, partial)) - return(NET_MIME_EXACT_MATCH); - - if(!PL_strcmp(partial, "*")) - return(NET_WILDCARD_MATCH); - - if((star = PL_strchr(partial, '*')) == 0) - return(0); /* not a wildcard mime type */ - - /* compare just the part before the slash star - * - */ - if(!PL_strncasecmp(absolute, partial, (star-1)-partial)) - return(NET_MIME_PARTIAL_MATCH); - - return(0); /* no match */ -} - -PUBLIC XP_Bool -NET_HaveConverterForMimeType(char *content_type) -{ - net_ConverterStruct * cs_ptr; - XP_List * ct_list_ptr = net_converter_list[FO_PRESENT]; - - while ((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ct_list_ptr)) - != 0) - { - if (FO_PRESENT == cs_ptr->format_out) - { - int compare_val = net_compare_mime_types (content_type, cs_ptr->format_in); - if (compare_val == NET_MIME_PARTIAL_MATCH || compare_val == NET_MIME_EXACT_MATCH) - return TRUE; - } - } - - return FALSE; -} - -/* Find a converter routine to create a stream and return the stream struct -*/ -PR_IMPLEMENT(NET_StreamClass *) -NET_StreamBuilder (FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *context) -{ - net_ConverterStruct * cs_ptr; - XP_List * ct_list_ptr = net_converter_list[format_out]; - - - - XP_List * ce_list_ptr = net_decoder_list[format_out]; - - assert (URL_s->content_type); - - TRACEMSG(("Entering StreamBuilder:\n\ - F-in: %s\n\ - F-out: %d\n\ - Enc: %s\n",URL_s->content_type,format_out, - (URL_s->content_encoding ? URL_s->content_encoding : "None Specified"))); - -#if 0 - /* First, determine whether there is a content-type converter for this - document; if there isn't one, then the only way to handle it is to - send it straight to disk, so try that. - */ - if (format_out != FO_SAVE_TO_DISK) - { - while ((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ct_list_ptr)) - != 0) - { - if (format_out == cs_ptr->format_out && - net_compare_mime_types (URL_s->content_type, - cs_ptr->format_in)) - break; - } - - if (! cs_ptr) /* There is no content-type converter; save it. */ - format_out = FO_SAVE_TO_DISK; - ct_list_ptr = net_converter_list; /* Reset for next traversal. */ - } -#endif - - - /* if there are content encodings then - * execute decoders first - */ - /* go through list of converters and choose - * the first exact or partial match we - * find. The order of the list - * is guarenteed by the registration - * routines - * - * the format-out is compared as well. - * - * if there are transfer_encodings use them even before - * content_encodings - */ - if ((URL_s->transfer_encoding && *URL_s->transfer_encoding) - || (URL_s->content_encoding && *URL_s->content_encoding)) - { - char *encoding; - - if(URL_s->transfer_encoding && *URL_s->transfer_encoding) - encoding = URL_s->transfer_encoding; - else - encoding = URL_s->content_encoding; - - - while ((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ce_list_ptr)) - != 0) - { - if (format_out == cs_ptr->format_out && - net_compare_mime_types (URL_s->content_type, - cs_ptr->format_in) && - net_compare_mime_types (encoding, - cs_ptr->encoding_in)) - { - net_ConverterElement *elem = XP_ListPeekTopObject(cs_ptr->converter_stack); - PR_ASSERT(elem != (net_ConverterElement *)0); - return ((NET_StreamClass *) - ((*elem->converter) - (format_out, elem->data_obj, URL_s, context))); - } - } - } - - /* now search for content-type converters - */ - /* go through list of converters and choose - * the first exact or partial match we - * find. The order of the list - * is guarenteed by the registration - * routines - */ - while((cs_ptr=(net_ConverterStruct *) XP_ListNextObject(ct_list_ptr)) != 0) - { - if(format_out == cs_ptr->format_out) - if(net_compare_mime_types(URL_s->content_type, cs_ptr->format_in)) - { - NET_StreamClass *ret_str; - net_ConverterElement *elem = XP_ListPeekTopObject(cs_ptr->converter_stack); - PR_ASSERT(elem != (net_ConverterElement *)0); - ret_str = (NET_StreamClass *) (*elem->converter) (format_out, - elem->data_obj, URL_s, context); - if (ret_str != NULL) - { - return(ret_str); - } - } - } - -#if DEBUG_pnunn - TRACEMSG(("Alert! did not find a converter or decoder\n")); - FE_Alert(context, XP_GetString(XP_ALERT_CANTFIND_CONVERTER)); -#endif - - return(0); /* Uh-oh. didn't find a converter. VERY VERY BAD! */ -} - -/* prints out all presentation mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -MODULE_PRIVATE char * -XP_ListNextPresentationType(PRBool first) -{ - static XP_List * converter_list_ptr; - net_ConverterStruct * converter; - - /* reset list pointers - */ - if(first) - converter_list_ptr = net_converter_list[FO_PRESENT]; - - /* print out next converter if there are any more - */ - converter = (net_ConverterStruct *) XP_ListNextObject(converter_list_ptr); - - if(converter && converter->format_out == FO_PRESENT) - return(converter->format_in); - - /* else */ - return(NULL); -} - -/* prints out all encoding mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -MODULE_PRIVATE char * -XP_ListNextEncodingType(PRBool first) -{ - static XP_List * decoder_list_ptr; - net_ConverterStruct * converter; - static int count; - static index = 0; - static int curArrayIndex = 0; - - - while ((index < count) && (curArrayIndex < MAX_FORMATS_OUT)) { - decoder_list_ptr = net_decoder_list[curArrayIndex]; - count = XP_ListCount(decoder_list_ptr); - if (count > 0) { - index = 0; - break; - } - else count++; - } -#if 0 - /* reset list pointers - */ - if(first) - { - decoder_list_ptr = net_decoder_list; - } -#endif - converter = (net_ConverterStruct *) XP_ListNextObject(decoder_list_ptr); - if(converter) { - index++; - return(converter->format_in); - } - - /* else */ - return(NULL); -} - -PRIVATE void -net_RegisterGenericConverterOrDecoder(XP_List ** conv_list, - char * format_in, - char * encoding_in, - FO_Present_Types format_out, - void * data_obj, - NET_Converter * converter_func) -{ - XP_List * list_ptr = *conv_list; - net_ConverterStruct * converter_struct_ptr; - net_ConverterStruct * new_converter_struct; - net_ConverterElement *elem; - int f_in_type; - XP_List *pList; - int i; - - if (needInit) { /* MWH - this will only happen once. It is pretty ugly, - but I don't know how to get around it. */ - needInit = FALSE; - - for (i = 0; i <MAX_FORMATS_OUT;i++) { - net_converter_list[i] = net_decoder_list[i] = 0; - } - - } - - pList = list_ptr = conv_list[format_out]; - /* check for an existing converter with the same format_in and format_out - * and add this to the list if found. - * - * if the list is NULL XP_ListNextObject will return 0 - */ - while((converter_struct_ptr = (net_ConverterStruct *) XP_ListNextObject(list_ptr)) != 0){ - if(format_out == converter_struct_ptr->format_out) - /* Rewritten to logic equivalent but should-be-faster version:*/ - if (((!encoding_in && !converter_struct_ptr->encoding_in) || - (encoding_in && converter_struct_ptr->encoding_in && - !PL_strcmp (encoding_in, - converter_struct_ptr->encoding_in))) - && !PL_strcasecmp(format_in, converter_struct_ptr->format_in) -#ifdef XP_WIN - && (converter_struct_ptr->bAutomated == autoFlag) -#endif - ) - { - /* Add a new converter element to the list */ - net_ConverterElement *elem = PR_NEWZAP(net_ConverterElement); - if( elem == (net_ConverterElement *)0 ) return; - elem->converter = converter_func; - elem->data_obj = data_obj; - XP_ListAddObject(converter_struct_ptr->converter_stack, elem); - return; - } - } - /* find out the type of entry format_in is - */ - f_in_type = NET_MIME_EXACT_MATCH; - if(PL_strchr(format_in, '*')) - { - if(!PL_strcmp(format_in, "*")) - f_in_type = NET_WILDCARD_MATCH; - else - f_in_type = NET_MIME_PARTIAL_MATCH; - } - - /* if existing converter not found/replaced - * add this converter to the list in - * its order of importance so that we can - * take the first exact or partial fit - */ - new_converter_struct = PR_NEW(net_ConverterStruct); - if(!new_converter_struct) { - return; - } - - new_converter_struct->converter_stack = XP_ListNew(); - if( new_converter_struct->converter_stack == (XP_List *)0 ) - { - PR_Free(new_converter_struct); - return; - } - - elem = PR_NEWZAP(net_ConverterElement); - if( elem == (net_ConverterElement *)0 ) - { - XP_ListDestroy(new_converter_struct->converter_stack); - PR_Free(new_converter_struct); - return; - } - - elem->converter = converter_func; - elem->data_obj = data_obj; - new_converter_struct->format_in = 0; - StrAllocCopy(new_converter_struct->format_in, format_in); - new_converter_struct->encoding_in = (encoding_in - ? PL_strdup (encoding_in) : 0); - new_converter_struct->format_out = format_out; - XP_ListAddObject(new_converter_struct->converter_stack, elem); - new_converter_struct->bAutomated = autoFlag; - - - if(!pList) { -/* if(!*conv_list) */ - /* create the list and add this object - * don't worry about order since there - * can't be any - */ - pList = XP_ListNew(); - if(!pList) - return; /* big error */ - conv_list[format_out] = pList; - XP_ListAddObject(pList, new_converter_struct); - return; - } - if(f_in_type == NET_MIME_EXACT_MATCH) - { -#if defined(XP_WIN) && defined (MOZILLA_CLIENT) - net_ConverterStruct *pRegistered; - XP_List *tempList = pList; - int count = XP_ListCount(tempList); - for (i = 0; i < count; i++) { - pRegistered = (net_ConverterStruct *) XP_ListNextObject(tempList); - - if(new_converter_struct->bAutomated == TRUE) { - if(pRegistered->bAutomated == FALSE) { - XP_ListInsertObject (pList, pRegistered, new_converter_struct); - return; - } - } - - /* if it is an exact match type - * then we can just add it to the beginning - * of the list - */ - if (!PL_strcasecmp(pRegistered->format_in, new_converter_struct->format_in) - && ((!pRegistered->encoding_in && !new_converter_struct->format_in) - || !PL_strcasecmp(pRegistered->encoding_in, new_converter_struct->encoding_in))) { - if(new_converter_struct->bAutomated == TRUE) { - PR_Free( new_converter_struct); - return; - } - - // Overwrite - memcpy(pRegistered, new_converter_struct, sizeof(net_ConverterStruct)); - PR_Free( new_converter_struct); - return; - } - } - - - - - - - - XP_ListInsertObject (pList, pRegistered, new_converter_struct); -#else - XP_ListAddObject(pList, new_converter_struct); - TRACEMSG(("Adding Converter to Beginning of list")); -#endif - } - else if(f_in_type == NET_MIME_PARTIAL_MATCH) - { - /* this is a partial wildcard of the form (image/(star)) - * store it at the end of all the exact match pairs - */ - list_ptr = pList; - while((converter_struct_ptr = (net_ConverterStruct *) XP_ListNextObject(list_ptr)) != 0) - { - if(PL_strchr(converter_struct_ptr->format_in, '*')) - { - XP_ListInsertObject (pList, - converter_struct_ptr, - new_converter_struct); - return; - } - } - /* else no * objects in list */ - XP_ListAddObjectToEnd(pList, new_converter_struct); - TRACEMSG(("Adding Converter to Middle of list")); - } - else - { - /* this is a very wild wildcard match of the form "*" only. - * It has the least precedence so store it at the end - * of the list. (There must always be at least one - * item in the list (see above)) - */ - XP_ListAddObjectToEnd(pList, new_converter_struct); - TRACEMSG(("Adding Converter to end of list")); - } -} - -struct net_encoding_converter -{ - char *encoding_in; - void *data_obj; - NET_Converter * converter_func; -}; - -static struct net_encoding_converter *net_all_encoding_converters; -static int net_encoding_converter_size = 0; -static int net_encoding_converter_fp = 0; - -PUBLIC void* NET_GETDataObject(XP_List* list, char* mineType, void** obj) -{ - net_ConverterStruct* converter_struct_ptr; - - *obj = (void*)0; - - while((converter_struct_ptr = (net_ConverterStruct *)XP_ListNextObject(list)) != NULL) { - if(converter_struct_ptr->bAutomated) { - if(!PL_strcmp(converter_struct_ptr->format_in, mineType)) { - net_ConverterElement *elem = XP_ListPeekTopObject(converter_struct_ptr->converter_stack); - *obj = (void*)converter_struct_ptr; - return elem->data_obj; - } - } - } - - return (void*)0; -} - -PUBLIC XP_List* NET_GetRegConverterList(FO_Present_Types iFormatOut) -{ - return net_converter_list[iFormatOut]; - -} -/* register a routine to decode a stream - */ - -PUBLIC void -NET_RegisterEncodingConverter(char *encoding_in, - void * data_obj, - NET_Converter * converter_func) -{ - - /* Don't register anything right now, but remember that we have a - decoder for this so that we can register it hither and yon at - a later date. - */ - if (net_encoding_converter_size <= net_encoding_converter_fp) - { - net_encoding_converter_size += 10; - if (net_all_encoding_converters) - net_all_encoding_converters = (struct net_encoding_converter *) - PR_Realloc (net_all_encoding_converters, - net_encoding_converter_size - * sizeof (*net_all_encoding_converters)); - else - net_all_encoding_converters = (struct net_encoding_converter *) - PR_Calloc (net_encoding_converter_size, - sizeof (*net_all_encoding_converters)); - } - - { /* Don't register the same decoder twice; having too many - decoders is multiplicatively expensive with respect to the number of - calls to net_RegisterGenericConverterOrDecoder() from the loop inside - NET_RegisterAllEncodingConverters(). */ - int i; - for (i=0; i < net_encoding_converter_fp; i++) - if ((net_all_encoding_converters[i].data_obj == data_obj) - && (net_all_encoding_converters[i].converter_func == converter_func) - && (strcmp(net_all_encoding_converters[i].encoding_in,encoding_in) - == 0)) - return; - } - - net_all_encoding_converters [net_encoding_converter_fp].encoding_in - = PL_strdup (encoding_in); - net_all_encoding_converters [net_encoding_converter_fp].data_obj - = data_obj; - net_all_encoding_converters [net_encoding_converter_fp].converter_func - = converter_func; - net_encoding_converter_fp++; - -} - - -#ifdef MOZILLA_CLIENT - -void -NET_DumpDecoders() -{ -#ifdef DEBUG - net_ConverterStruct * cs_ptr; - XP_List *list_ptr = net_decoder_list[FO_PRESENT]; - - while((cs_ptr = XP_ListNextObject(list_ptr)) != 0) - { - char *msg = PR_smprintf("in: %s out: %d\n",cs_ptr->encoding_in, cs_ptr->format_out); - - TRACEMSG(("%s", msg)); - FREE(msg); - } -#endif /* DEBUG */ -} - -/* register an encoding converter that is used for everything, - * no exeptions - * this is necessary for chunked encoding - */ -MODULE_PRIVATE void -NET_RegisterUniversalEncodingConverter(char *encoding_in, - void * data_obj, - NET_Converter * converter_func) -{ - int i; - - /* for each list in the net_decoder_list array */ - for (i = 0; i < MAX_FORMATS_OUT; i++) - { - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - "*", - encoding_in, - i, /* format out */ - data_obj, - converter_func); - } - -} - -void -NET_RegisterAllEncodingConverters (char *format_in, - FO_Present_Types format_out) -{ - int i; - -#ifdef XP_UNIX - /* On Unix at least, there should be *some* registered... */ - assert (net_encoding_converter_fp > 0); -#endif - - for (i = 0; i < net_encoding_converter_fp; i++) - { - char *encoding_in = net_all_encoding_converters [i].encoding_in; - void *data_obj = net_all_encoding_converters [i].data_obj; - NET_Converter *func = net_all_encoding_converters [i].converter_func; - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - format_in, - encoding_in, - format_out, - data_obj, - func); - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - format_in, - encoding_in, - format_out | FO_CACHE_ONLY, - data_obj, - func); - - net_RegisterGenericConverterOrDecoder (net_decoder_list, - format_in, - encoding_in, - format_out | FO_ONLY_FROM_CACHE, - data_obj, - func); - } -} - -#endif /* MOZILLA_CLIENT */ - - - - -/* Register a routine to convert between format_in and format_out - * - */ -#if (defined(XP_WIN) || defined(XP_OS2)) && defined(MOZILLA_CLIENT) -/* Reroute XP handling of streams for windows. - * MWH -This routine should not be called recursively. - It rely on the static global variable to set the - * automatedflag. The reason for this is I don't to - change the API on NET_RegisterContentTypeConverter - because some other group still depend on this API. - * If we decided to change API, please fix this. - */ -PUBLIC void -NET_RegContentTypeConverter (char * format_in, - FO_Present_Types format_out, - void * data_obj, - NET_Converter * converter_func, - Bool bAutomated) -{ - autoFlag = bAutomated; - NET_RegisterContentTypeConverter (format_in, format_out, - data_obj, - converter_func); - autoFlag = FALSE; - -} - -#endif - -PUBLIC void -NET_RegisterContentTypeConverter (char * format_in, - FO_Present_Types format_out, - void * data_obj, - NET_Converter * converter_func) -{ - net_RegisterGenericConverterOrDecoder(net_converter_list, - format_in, - 0, - format_out, - data_obj, - converter_func); - -} - -#ifdef MOZILLA_CLIENT -#ifdef XP_UNIX - -#include "cvview.h" -#include "cvextcon.h" - -/* register a mime type and a command to be executed - * - * if stream_block_size is zero then the data will be completely - * pooled and the external viewer called with the filename. - * if stream_block_size is greater than zero the viewer will be - * called with a popen and the stream_block_size will be used as - * the maximum size of each buffer to pass to the viewer - */ -MODULE_PRIVATE void -NET_RegisterExternalViewerCommand(char * format_in, - char * system_command, - unsigned int stream_block_size) -{ - CV_ExtViewStruct * new_obj = PR_NEW(CV_ExtViewStruct); - - if(!new_obj) - return; - - memset(new_obj, 0, sizeof(CV_ExtViewStruct)); - - /* make a new copy of the command so it can be passed - * as the data object - */ - StrAllocCopy(new_obj->system_command, system_command); - new_obj->stream_block_size = stream_block_size; - - /* register the routine - */ - NET_RegisterContentTypeConverter(format_in, FO_PRESENT, new_obj, NET_ExtViewerConverter); - - /* Also register the content-encoding converters on this type. - Those get registered only on types we know how to display, - either internally or externally - and don't get registered - on types we know nothing about. - */ - NET_RegisterAllEncodingConverters (format_in, FO_PRESENT); -} - -/* removes all external viewer commands - */ -PUBLIC void -NET_ClearExternalViewerConverters(void) -{ - XP_List * list_ptr; - XP_List *temp_list; - net_ConverterStruct * converter_struct_ptr; - int i; - - for (i = 0; i <MAX_FORMATS_OUT; i++) { - list_ptr = temp_list = net_converter_list[i]; - while((converter_struct_ptr = - (net_ConverterStruct *) XP_ListNextObject(list_ptr))) - { - XP_List *new; - net_ConverterElement *elem; - - new = XP_ListNew(); - if( new == (XP_List *)0 ) return; - - while( (elem = XP_ListRemoveTopObject(converter_struct_ptr->converter_stack)) != (net_ConverterElement *)0 ) - { - if( elem->converter == NET_ExtViewerConverter ) - { - PR_FREEIF(elem->data_obj); - PR_Free(elem); - continue; - } - else - { - XP_ListAddObjectToEnd(new, elem); - } - } - - XP_ListDestroy(converter_struct_ptr->converter_stack); - - if( XP_ListCount(new) > 0 ) - { - converter_struct_ptr->converter_stack = new; - } - else - { - XP_ListDestroy(new); - XP_ListRemoveObject(temp_list, converter_struct_ptr); - PR_Free(converter_struct_ptr->format_in); - PR_Free(converter_struct_ptr->encoding_in); - PR_Free(converter_struct_ptr); - } - } - } -} - -/* removes all registered converters of any kind - */ -PUBLIC void -NET_ClearAllConverters(void) -{ - net_ConverterStruct * aConverter; - net_ConverterElement * aConverterStackElement; - XP_List * theList; - int i; - - /* for each list in the net_converter_list array */ - for (i = 0; i < MAX_FORMATS_OUT; i++) { - theList = net_converter_list[i]; - /* Traverse it, removing each converter, and freeing its data */ - while( aConverter = (net_ConverterStruct *) XP_ListRemoveTopObject(theList) ) - { - FREEIF(aConverter->format_in); - FREEIF(aConverter->encoding_in); - while( aConverterStackElement = XP_ListRemoveTopObject(aConverter->converter_stack) ) - { -#ifdef XP_UNIX - if(aConverterStackElement->converter == NET_ExtViewerConverter) - PR_FREEIF(aConverterStackElement->data_obj); -#endif /* XP_UNIX */ - PR_Free(aConverterStackElement); - } - XP_ListDestroy(aConverter->converter_stack); - FREE(aConverter); - } - XP_ListDestroy(theList); - net_converter_list[i] = NULL; - } - - /* for each list in the net_decoder_list array */ - for (i = 0; i < MAX_FORMATS_OUT; i++) { - theList = net_decoder_list[i]; - /* Traverse it, removing each converter, and freeing its data */ - while( aConverter = (net_ConverterStruct *) XP_ListRemoveTopObject(theList) ) - { - FREEIF(aConverter->format_in); - FREEIF(aConverter->encoding_in); - while( aConverterStackElement = XP_ListRemoveTopObject(aConverter->converter_stack) ) - { -#ifdef XP_UNIX - if(aConverterStackElement->converter == NET_ExtViewerConverter) - PR_FREEIF(aConverterStackElement->data_obj); -#endif /* XP_UNIX */ - PR_Free(aConverterStackElement); - } - XP_ListDestroy(aConverter->converter_stack); - FREE(aConverter); - } - XP_ListDestroy(theList); - net_decoder_list[i] = NULL; - } -} - -/* register an external program to act as a content-type - * converter - */ -MODULE_PRIVATE void -NET_RegisterExternalConverterCommand(char * format_in, - int format_out, - char * system_command, - char * new_format) -{ - CV_ExtConverterStruct * new_obj = PR_NEW(CV_ExtConverterStruct); - - if(!new_obj) - return; - - memset(new_obj, 0, sizeof(CV_ExtConverterStruct)); - - /* make a new copy of the command so it can be passed - * as the data object - */ - StrAllocCopy(new_obj->command, system_command); - StrAllocCopy(new_obj->new_format, new_format); - new_obj->is_encoding_converter = FALSE; - - /* register the routine - */ - NET_RegisterContentTypeConverter(format_in, format_out, new_obj, NET_ExtConverterConverter); -} - -/* register an external program to act as a content-encoding - * converter - */ -PUBLIC void -NET_RegisterExternalDecoderCommand (char * format_in, - char * format_out, - char * system_command) -{ - CV_ExtConverterStruct * new_obj = PR_NEW(CV_ExtConverterStruct); - - if(!new_obj) - return; - - memset(new_obj, 0, sizeof(CV_ExtConverterStruct)); - - /* make a new copy of the command so it can be passed - * as the data object - */ - StrAllocCopy(new_obj->command, system_command); - StrAllocCopy(new_obj->new_format, format_out); - new_obj->is_encoding_converter = TRUE; - - /* register the routine - */ - NET_RegisterEncodingConverter (format_in, new_obj, - NET_ExtConverterConverter); -} - - -#endif /* XP_UNIX */ -#endif /* MOZILLA_CLIENT */ - -/* NewMKStream - * Utility to create a new initialized NET_StreamClass object - */ -NET_StreamClass * -NET_NewStream (char *name, - MKStreamWriteFunc process, - MKStreamCompleteFunc complete, - MKStreamAbortFunc abort, - MKStreamWriteReadyFunc ready, - void *streamData, - MWContext *windowID) -{ - NET_StreamClass *stream = PR_NEW (NET_StreamClass); - if (!stream) - return nil; - - stream->name = name; - stream->window_id = windowID; - stream->data_object = streamData; - stream->put_block = process; - stream->complete = complete; - stream->abort = abort; - stream->is_write_ready = ready; - - return stream; -} - -PRIVATE XP_List * -net_GetConverterOrDecoderList(XP_List ** conv_list, - char * format_in, - char * encoding_in, - FO_Present_Types format_out) -{ - XP_List * list_ptr = *conv_list; - net_ConverterStruct * converter_struct_ptr; - - while((converter_struct_ptr = (net_ConverterStruct *) XP_ListNextObject(list_ptr)) != 0) - if(format_out == converter_struct_ptr->format_out) - if(!PL_strcasecmp(format_in, converter_struct_ptr->format_in) - && ((!encoding_in && !converter_struct_ptr->encoding_in) || - (encoding_in && converter_struct_ptr->encoding_in && - !PL_strcmp (encoding_in, - converter_struct_ptr->encoding_in))) - ) - { - return converter_struct_ptr->converter_stack; - } - - return (XP_List *)0; -} - -PUBLIC void -NET_DeregisterContentTypeConverter(char *format_in, FO_Present_Types format_out) -{ - XP_List *l; - net_ConverterElement *elem; - - l = net_GetConverterOrDecoderList(net_converter_list, format_in, 0, format_out); - if( l == (XP_List *)0 ) return; - - elem = XP_ListRemoveTopObject(l); -# ifdef XP_UNIX - /* total kludge!! */ - if( elem->converter == NET_ExtViewerConverter ) - PR_FREEIF(elem->data_obj); -# endif - PR_Free(elem); - - return; -} - -#ifdef DEBUG -MODULE_PRIVATE void -NET_DisplayStreamInfoAsHTML(ActiveEntry *cur_entry) -{ - char *buffer = (char*)PR_Malloc(2048); - NET_StreamClass * stream; - int i; - - static char *fo_names[] = { - /* 0 */ "(unknown)", - /* 1 */ "Present", - /* 2 */ "Internal Image", - /* 3 */ "Out to Proxy Client", - /* 4 */ "View Source", - /* 5 */ "Save As", - /* 6 */ "Save as Text", - /* 7 */ "Save as Postscript", - /* 8 */ "Quote Message", - /* 9 */ "Mail To", - /* 10 */ "OLE Network", - /* 11 */ "Multipart Image", - /* 12 */ "Embed", - /* 13 */ "Print", - /* 14 */ "Plugin", - /* 15 */ "Append to Folder", - /* 16 */ "Do Java", - /* 17 */ "Byterange", - /* 18 */ "EDT Save Image", - /* 19 */ "Edit", - /* 20 */ "Load HTML Help Map File", - /* 21 */ "Save to News DB", - /* 22 */ "Open Draft", - }; - - if(!buffer) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - return; - } - - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, - cur_entry->window_id); - - if(!stream) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - FREE(buffer); - return; - } - - - /* define a macro to push a string up the stream - * and handle errors - */ -#define PUT_PART(part) \ -cur_entry->status = (*stream->put_block)(stream, \ - part ? part : "Unknown", \ - part ? PL_strlen(part) : 7); \ -if(cur_entry->status < 0) \ - goto END; - - sprintf(buffer, -"<html><head><title>Information about the Netscape streams configuration</title></head>\n" -"<body><h1>Information about the Netscape streams configuration</h1>\n" -); - - PUT_PART(buffer); - - sprintf(buffer, "<h2>Converter List</h2>\n<ul>"); - PUT_PART(buffer); - - for( i = 0; i < MAX_FORMATS_OUT; i++ ) - { - int j = i & ~FO_CACHE_ONLY & ~FO_ONLY_FROM_CACHE; - XP_List *list_ptr = net_converter_list[i]; - net_ConverterStruct *csp; - - sprintf(buffer, "<li><ul><p>%s", j < sizeof(fo_names)/sizeof(fo_names[0]) ? - fo_names[j] : fo_names[0]); - PUT_PART(buffer); - - if( i & FO_CACHE_ONLY ) - { - sprintf(buffer, " | Cache Only"); - PUT_PART(buffer); - } - - if( i & FO_ONLY_FROM_CACHE ) - { - sprintf(buffer, " | Only From Cache"); - PUT_PART(buffer); - } - - sprintf(buffer, " [%d]</p>", i); - PUT_PART(buffer); - - while( (csp = (net_ConverterStruct *)XP_ListNextObject(list_ptr)) != (net_ConverterStruct *)0 ) - { - XP_List *stack = csp->converter_stack; - int stack_count = XP_ListCount(stack); - net_ConverterElement *elem; - sprintf(buffer, - "<li>Format In: %s<br>\n" - "Encoding In: %s<br>\n" - "Present Type: %d<br>\n" - "%s<br><ol>%d Converter%s:\n", - (csp->format_in != (char *)0) ? csp->format_in : "(null)", - (csp->encoding_in != (char *)0) ? csp->encoding_in : "(null)", - csp->format_out, - csp->bAutomated ? "Automated" : "Not automated", - stack_count, (stack_count == 1) ? "" : "s"); - PUT_PART(buffer); - - while( (elem = (net_ConverterElement *)XP_ListNextObject(stack)) != (net_ConverterElement *)0 ) - { -#if defined(__sun) && !defined(SVR4) - sprintf(buffer, "<li>Converter: %lu<br>Object: %lu<br>\n", - elem->converter, elem->data_obj); -#else - sprintf(buffer, "<li>Converter: %p<br>Object: %p<br>\n", - elem->converter, elem->data_obj); -#endif - PUT_PART(buffer); - } - - sprintf(buffer, "<br></ol>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - - sprintf(buffer, "<h2>Decoder List</h2>\n<ul>"); - PUT_PART(buffer); - - for( i = 0; i < MAX_FORMATS_OUT; i++ ) - { - int j = i & ~FO_CACHE_ONLY & ~FO_ONLY_FROM_CACHE; - XP_List *list_ptr = net_decoder_list[i]; - net_ConverterStruct *csp; - - sprintf(buffer, "<li><ul><p>%s", j < sizeof(fo_names)/sizeof(fo_names[0]) ? - fo_names[j] : fo_names[0]); - PUT_PART(buffer); - - if( i & FO_CACHE_ONLY ) - { - sprintf(buffer, " | Cache Only"); - PUT_PART(buffer); - } - - if( i & FO_ONLY_FROM_CACHE ) - { - sprintf(buffer, " | Only From Cache"); - PUT_PART(buffer); - } - - sprintf(buffer, " [%d]</p>", i); - PUT_PART(buffer); - - while( (csp = (net_ConverterStruct *)XP_ListNextObject(list_ptr)) != (net_ConverterStruct *)0 ) - { - XP_List *stack = csp->converter_stack; - int stack_count = XP_ListCount(stack); - net_ConverterElement *elem; - sprintf(buffer, - "<li>Format In: %s<br>\n" - "Encoding In: %s<br>\n" - "Present Type: %d<br>\n" - "%s<br><ol>%d Converter%s:\n", - (csp->format_in != (char *)0) ? csp->format_in : "(null)", - (csp->encoding_in != (char *)0) ? csp->encoding_in : "(null)", - csp->format_out, - csp->bAutomated ? "Automated" : "Not automated", - stack_count, (stack_count == 1) ? "" : "s"); - PUT_PART(buffer); - - while( (elem = (net_ConverterElement *)XP_ListNextObject(stack)) != (net_ConverterElement *)0 ) - { -#if defined(__sun) && !defined(SVR4) - sprintf(buffer, "<li>Converter: %lu<br>Object: %lu<br>\n", - elem->converter, elem->data_obj); -#else - sprintf(buffer, "<li>Converter: %p<br>Object: %p<br>\n", - elem->converter, elem->data_obj); -#endif - PUT_PART(buffer); - } - - sprintf(buffer, "<br></ol>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - } - - sprintf(buffer, "</ul>\n"); - PUT_PART(buffer); - - END: - PR_Free(buffer); - if( cur_entry->status < 0 ) - (*stream->abort)(stream, cur_entry->status); - else - (*stream->complete)(stream); - - return; -} - -#endif /* DEBUG */ - -#ifdef PROFILE -#pragma profile off -#endif - diff --git a/mozilla/network/main/mkstream.h b/mozilla/network/main/mkstream.h deleted file mode 100644 index 6ec7b768f39..00000000000 --- a/mozilla/network/main/mkstream.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKSTREAM_H -#define MKSTREAM_H - -/* prints out all converter mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -extern char * -XP_ListNextPresentationType(PRBool first); - -/* prints out all encoding mime types during successive calls - * call with first equal true to reset to the beginning - * and with first equal false to print out the next - * converter in the list. Returns zero when all converters - * are printed out. - */ -extern char * -XP_ListNextEncodingType(PRBool first); - -/* register a mime type and a command to be executed - */ -extern PUBLIC void -NET_RegisterExternalViewerCommand(char * format_in, - char * system_command, - unsigned int stream_block_size); - -/* removes all external viewer commands - */ -extern void NET_ClearExternalViewerConverters(void); - -MODULE_PRIVATE void -NET_RegisterExternalConverterCommand(char * format_in, - FO_Present_Types format_out, - char * system_command, - char * new_format); - -#ifdef DEBUG -extern void NET_DisplayStreamInfoAsHTML(ActiveEntry *cur_entry); -#endif /* DEBUG */ - -void -NET_RegisterAllEncodingConverters (char *format_in, - FO_Present_Types format_out); - -/* register an encoding converter that is used for everything, - * no exeptions - * this is necessary for chunked encoding - */ -void -NET_RegisterUniversalEncodingConverter(char *encoding_in, - void * data_obj, - NET_Converter * converter_func); - -void -NET_DumpDecoders(); - -#endif /* MKSTREAM.h */ diff --git a/mozilla/network/main/mktcp.h b/mozilla/network/main/mktcp.h deleted file mode 100644 index 5a0dffafc4c..00000000000 --- a/mozilla/network/main/mktcp.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKTCP_H -#define MKTCP_H - -#include "rosetta.h" - -PR_BEGIN_EXTERN_C - -/* state machine data for host connect */ -typedef struct _TCP_ConData TCP_ConData; - -/* the socks host in U long form - */ -extern unsigned long NET_SocksHost; -extern short NET_SocksPort; -extern char *NET_SocksHostName; - -/* socket buffer and socket buffer size - * used for reading from sockets - */ -extern char * NET_Socket_Buffer; -extern int NET_Socket_Buffer_Size; - -extern int NET_InGetHostByName; /* global semaphore */ - -/* free any cached data in preperation - * for shutdown or to free up memory - */ -extern void NET_CleanupTCP (void); - -/* - * do a standard netwrite but echo it to stderr as well - */ -extern int -NET_DebugNetWrite (PRFileDesc *fildes, CONST void *buf, unsigned nbyte); - -/* make sure the whole buffer is written in one call - */ -extern int32 -NET_BlockingWrite (PRFileDesc *filedes, CONST void * buf, unsigned int nbyte); - -/* free left over tcp connection data if there is any - */ -extern void NET_FreeTCPConData(TCP_ConData * data); - -/* - * Non blocking connect begin function. It will most likely - * return negative. If it does the NET_ConnectFinish() will - * need to be called repeatably until a connect is established - * - * return's negative on error - * return's MK_WAITING_FOR_CONNECTION when continue is neccessary - * return's MK_CONNECTED on true connect - */ -extern int -NET_BeginConnect (CONST char *url, - char *ip_address_string, - char *protocol, - int default_port, - PRFileDesc **s, - HG92743 - TCP_ConData **tcp_con_data, - MWContext *window_id, - char **error_msg, - unsigned long socks_host, - short socks_port, - PRUint32 localIP); - - -/* - * Non blocking connect finishing function. This routine polls - * the socket until a connection finally takes place or until - * an error occurs. NET_ConnectFinish() will need to be called - * repeatably until a connect is established. - * - * return's negative on error - * return's MK_WAITING_FOR_CONNECTION when continue is neccessary - * return's MK_CONNECTED on true connect - */ -extern int -NET_FinishConnect (CONST char *url, - char *protocol, - int default_port, - PRFileDesc **s, - TCP_ConData **tcp_con_data, - MWContext *window_id, - char **error_msg, - PRUint32 localIP); - -/* - * Echo to stderr as well as the socket - */ -extern int -NET_DebugNetRead (PRFileDesc *fildes, void *buf, unsigned nbyte); - -/* this is a very standard network write routine. - * - * the only thing special about it is that - * it returns MK_HTTP_TYPE_CONFLICT on special error codes - * - */ -extern int -NET_HTTPNetWrite (PRFileDesc *fildes, CONST void * buf, unsigned nbyte); - -/* - * - * trys to get a line of data from the socket or from the buffer - * that was passed in - */ -extern int NET_BufferedReadLine(PRFileDesc *sock, - char ** line, - char ** buffer, - int32 * buffer_size, - Bool * pause_for_next_read); - - -extern void NET_SanityCheckDNS (MWContext *context); - -PR_END_EXTERN_C -#endif /* MKTCP_H */ diff --git a/mozilla/network/main/mktrace.c b/mozilla/network/main/mktrace.c deleted file mode 100644 index 570ddde4dcb..00000000000 --- a/mozilla/network/main/mktrace.c +++ /dev/null @@ -1,444 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#define FORCE_PR_LOG /* So that this works in an optimized build */ - -#include "mkutils.h" -#include "mktrace.h" -#include "timing.h" -#include "prprf.h" -#include "plstr.h" -#include "prlog.h" -#include "prsystem.h" -#include "prtime.h" -#include "plhash.h" - -/* If you want to trace netlib, set this to 1, or use CTRL-ALT-T - * stroke (preferred method) to toggle it on and off */ -int MKLib_trace_flag=0; - -PUBLIC void NET_ToggleTrace(void) { - if(MKLib_trace_flag) - MKLib_trace_flag = 0; - else - MKLib_trace_flag = 1; -} - -/* Map netlib trace messages into nspr logger so that they are - * thread safe. */ -#if defined(DEBUG) || defined(NETLIB_TRACE_ON) - -PRLogModuleInfo* NETLIB=NULL; - -/* Used by NET_NTrace() */ -PRIVATE void net_Trace(char *msg) { - /* Only trace if the user explicitly told us to. */ - if(MKLib_trace_flag) { - /* PR_LogPrint prints to stderr which doesn't exist in a windows app. - * Use the win32 routine OutputDebugString to get text to goto the - * debug console. */ -#if defined(WIN32) && defined(DEBUG) - OutputDebugString(msg); - OutputDebugString("\n"); -#else - PR_LogPrint(msg); -#endif - } else { - PR_LOG(NETLIB, PR_LOG_ALWAYS, (msg)); - } -} - - -/* Called to trace a message */ -void NET_NTrace(char *msg, int32 length) { - char * new_string = PR_Malloc(length+1); - if(!new_string) - return; - strncpy(new_string, msg, length); - new_string[length] = '\0'; - - net_Trace(new_string); - FREE(new_string); -} - - -/* #define'd in mktrace.h to TRACEMSG */ -void ns_MK_TraceMsg(char *fmt, ...) { - va_list ap; - char buf[512]; - - va_start(ap, fmt); - PR_vsnprintf(buf, sizeof(buf), fmt, ap); - - net_Trace(buf); -} - -#endif /* DEBUG || NETLIB_TRACE_ON */ - - -/************************************************ - * - * Runtime performance tracing stubs. - * - */ - - -static PRLogModuleInfo* gTimingLog = NULL; -static const char* gTimingModuleName = "nsTiming"; - -/** - * Rev this if the output format changes significantly - */ -#define TIMING_VERSION 0x10000 - -/** - * Ensure that the log module actually exists before trying to use it. - * @return <tt>FALSE</tt> if something goes wrong. - */ -static PRBool -EnsureLogModule(void) -{ - if (gTimingLog == NULL) { - if ((gTimingLog = PR_NewLogModule(gTimingModuleName)) == NULL) - return PR_FALSE; - - /* _On_ to start with -- if the env is set up */ - gTimingLog->level = PR_LOG_NOTICE; - - { - /* Dump the session info */ - char hostname[SYS_INFO_BUFFER_LENGTH]; - char sysname[SYS_INFO_BUFFER_LENGTH]; - char release[SYS_INFO_BUFFER_LENGTH]; - char arch[SYS_INFO_BUFFER_LENGTH]; - - if (PR_GetSystemInfo(PR_SI_HOSTNAME, hostname, sizeof(hostname)) != PR_SUCCESS) - hostname[0] = '\0'; - - if (PR_GetSystemInfo(PR_SI_SYSNAME, sysname, sizeof(sysname)) != PR_SUCCESS) - sysname[0] = '\0'; - - /* PR_SI_RELEASE only works for unix and it will still return success. */ -#ifdef XP_UNIX - if (PR_GetSystemInfo(PR_SI_RELEASE, release, sizeof(release)) != PR_SUCCESS) - release[0] = '\0'; -#else - release[0] = '\0'; -#endif - - if (PR_GetSystemInfo(PR_SI_ARCHITECTURE, arch, sizeof(arch)) != PR_SUCCESS) - arch[0] = '\0'; - - TimingWriteMessage("begin-session,%08x,%s,%s,%s,%s,%s,%ld", - TIMING_VERSION, hostname, sysname, - release, arch, -#ifdef DEBUG - "debug", -#else - "opt", -#endif - 0 /* XXX build number */ - ); - - } - } - - return (gTimingLog != NULL) ? PR_TRUE : PR_FALSE; -} - -/** - * Write a message to the log. You should use the TIMING_MSG() macro, - * rather than calling this directly. - */ -PR_IMPLEMENT(void) -TimingWriteMessage(const char* fmtstr, ...) -{ - char line[256]; - va_list ap; - PRUint32 nb; - - if (! EnsureLogModule()) - return; - - if (gTimingLog->level == PR_LOG_NONE) - return; - - { - PRExplodedTime now; - PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &now); - - /* Print out "YYYYMMDD.HHMMSS.UUUUUU: " */ - nb = PR_snprintf(line, sizeof(line) - 1, - "%04d%02d%02d.%02d%02d%02d.%06d: ", - now.tm_year, now.tm_month + 1, now.tm_mday, - now.tm_hour, now.tm_min, now.tm_sec, - now.tm_usec); - } - - /* ...followed by the "real" message */ - va_start(ap, fmtstr); - nb += PR_vsnprintf(line + nb, sizeof(line) - nb - 1, fmtstr, ap); - - PR_LOG(gTimingLog, PR_LOG_NOTICE, ("%s", line)); -} - - -/** - * Enable or disable the timing log. - */ -PR_IMPLEMENT(void) -TimingSetEnabled(PRBool enabled) -{ - if (! EnsureLogModule()) - return; - - if (enabled) { - if (gTimingLog->level == PR_LOG_NONE) { - gTimingLog->level = PR_LOG_NOTICE; - TimingWriteMessage("(tracing enabled)"); - } - } else { - if (gTimingLog->level != PR_LOG_NONE) { - TimingWriteMessage("(tracing disabled)"); - gTimingLog->level = PR_LOG_NONE; - } - } -} - -/** - * Query whether the timing log is enabled. - */ -PR_IMPLEMENT(PRBool) -TimingIsEnabled(void) -{ - if (! EnsureLogModule()) - return PR_FALSE; - - return (gTimingLog->level == PR_LOG_NONE) ? PR_FALSE : PR_TRUE; -} - - - -/************************************************************************* - * - * Clocking functions - * - */ - -/* - * Allocation routines - */ - -static PR_CALLBACK void* -_timingClockAllocTable(void* pool, PRSize size) -{ - return PR_MALLOC(size); -} - -static PR_CALLBACK void -_timingClockFreeTable(void* pool, void* item) -{ - PR_DELETE(item); -} - -static PR_CALLBACK PLHashEntry* -_timingClockAllocEntry(void* pool, const void* key) -{ - return PR_NEW(PLHashEntry); -} - -static PR_CALLBACK void -_timingClockFreeEntry(void* pool, PLHashEntry* he, PRUintn flag) -{ - if (flag == HT_FREE_VALUE) { - if (he->value) - PR_DELETE(he->value); - } - else if (flag == HT_FREE_ENTRY) { - if (he->key) - PL_strfree((char*) he->key); - if (he->value) - PR_DELETE(he->value); - PR_DELETE(he); - } -} - - -static PLHashAllocOps _timingClockAllocOps = { - _timingClockAllocTable, - _timingClockFreeTable, - _timingClockAllocEntry, - _timingClockFreeEntry -}; - - -/** - * The initial size of the clock table - */ -#define CLOCK_TABLE_INIT_SIZE 13 - - -/** - * The clock table. - */ -static PLHashTable *_timingClockTable = NULL; - - -/** - * Ensure that the clock table exists and is initialized. - */ -static PRBool -EnsureTimingTable() -{ - if (! _timingClockTable) { - _timingClockTable = - PL_NewHashTable(CLOCK_TABLE_INIT_SIZE, - PL_HashString, - PL_CompareStrings, - PL_CompareValues, - &_timingClockAllocOps, - NULL); - } - - return (_timingClockTable != NULL); -} - - -/** - * Start a clock - */ -PR_IMPLEMENT(void) -TimingStartClock(const char* clock) -{ - char* key = NULL; - PRTime* value = NULL; - - if (! TimingIsEnabled()) - return; - - if (! EnsureTimingTable()) - return; - - if (PL_HashTableLookup(_timingClockTable, clock) != NULL) - /* The clock is already running... */ - return; - - if ((key = PL_strdup(clock)) == NULL) - goto error; - - if ((value = PR_NEW(PRTime)) == NULL) - goto error; - - *value = PR_Now(); - PL_HashTableAdd(_timingClockTable, key, value); - return; - -error: - if (key) - PL_strfree(key); - PR_DELETE(value); -} - - -PR_EXTERN(PRBool) -TimingStopClock(PRTime* result, const char* clock) -{ - PRTime* start; - PRTime stop = PR_Now(); - - if (! TimingIsEnabled()) - return PR_FALSE; - - if (! EnsureTimingTable()) - return PR_FALSE; - - if ((start = PL_HashTableLookup(_timingClockTable, clock)) != NULL) { - if (result != NULL) - LL_SUB(*result, stop, *start); - PL_HashTableRemove(_timingClockTable, clock); - return PR_TRUE; - } else { - *result = LL_ZERO; - return PR_FALSE; - } -} - - -PR_EXTERN(PRBool) -TimingIsClockRunning(const char* clock) -{ - if (! TimingIsEnabled()) - return PR_FALSE; - - if (! EnsureTimingTable()) - return PR_FALSE; - - if (PL_HashTableLookup(_timingClockTable, clock) != NULL) { - return PR_TRUE; - } else { - return PR_FALSE; - } -} - - -PR_EXTERN(char*) -TimingElapsedTimeToString(PRTime time, char* buffer, PRUint32 size) -{ - PRTime tmUSec; - PRTime tmSec; - PRTime tmMin; - - { - PRTime n; - LL_UI2L(n, 1000000L); - LL_MOD(tmUSec, time, n); - LL_DIV(time, time, n); - } - - { - PRTime n; - LL_UI2L(n, 60L); - LL_MOD(tmSec, time, n); - LL_DIV(time, time, n); - - LL_MOD(tmMin, time, n); - LL_DIV(time, time, n); - } - - { - PRUint32 nHours; - PRUint32 nMin; - PRUint32 nSec; - PRUint32 nUSec; - - LL_L2UI(nHours, time); - LL_L2UI(nMin, tmMin); - LL_L2UI(nSec, tmSec); - LL_L2UI(nUSec, tmUSec); - - /* Print out "HHMMSS.UUUUUU" */ - PR_snprintf(buffer, size, "%02d%02d%02d.%06d", - nHours, nMin, nSec, nUSec); - } - - return buffer; -} diff --git a/mozilla/network/main/mktrace.h b/mozilla/network/main/mktrace.h deleted file mode 100644 index 975e21f6c6a..00000000000 --- a/mozilla/network/main/mktrace.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKTRACE_H -#define MKTRACE_H - -extern int MKLib_trace_flag; - -extern void NET_ToggleTrace(void); - -/* define NETLIB_TRACE_ON to trace netlib in optimized build */ - -#if defined(DEBUG) || defined(NETLIB_TRACE_ON) - -extern PRLogModuleInfo* NETLIB; - -#ifdef TRACEMSG -#undef TRACEMSG -#endif - -PR_BEGIN_EXTERN_C -extern void NET_NTrace(char *msg, int32 length); -extern void ns_MK_TraceMsg(char *fmt, ...); -PR_END_EXTERN_C - -#define TRACEMSG(msg) ns_MK_TraceMsg msg -#else -#define TRACEMSG(msg) -#endif /* DEBUG || NETLIB_TRACE_ON */ - -#endif /* MKTRACE_H */ diff --git a/mozilla/network/main/mkutils.c b/mozilla/network/main/mkutils.c deleted file mode 100644 index 973f3a46581..00000000000 --- a/mozilla/network/main/mkutils.c +++ /dev/null @@ -1,3555 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * - * Implemented by Lou Montulli '94-'98 - * - * this is the dumping grounds for random Netlib functions - * Home for utility functions and anything else that - * doesn't fit elsewhere. - */ -#if defined(CookieManagement) -/* #define TRUST_LABELS 1 */ -#endif - -#include "rosetta.h" -#include "mkutils.h" -#include "net_xp_file.h" -#include "mkprefs.h" -#include "gui.h" -#include "mkparse.h" -#include "mkgeturl.h" -#include "cookies.h" -#include "httpauth.h" -#include "libi18n.h" -#include "msgcom.h" -#include "mime.h" -#include "secrng.h" -#include HG38763 -#include "prefapi.h" -#include "secnav.h" -#include "preenc.h" -#include "mkselect.h" -#include "prerror.h" -#include "netcache.h" -#include "mktcp.h" -#include "netutils.h" - -#include "xpgetstr.h" - -#include "mimeenc.h" -#include "intl_csi.h" - -#ifdef XP_MAC -#include "MacBinSupport.h" -#endif - -#ifdef TRUST_LABELS -#include "mkaccess.h" -#include "pics.h" -#endif - -#ifdef NU_CACHE -#include "CacheStubs.h" -#endif - -typedef struct { - char *buffer; - int32 size; - int32 pos; -} BufferStruct; - -#ifndef MAX -#define MAX(x, y) (((x) > (y)) ? (x) : (y)) -#endif - -static int -net_buffer_output_fn ( const char *buf, int32 size, void *closure); - -extern int MK_OUT_OF_MEMORY; -extern int MK_UNABLE_TO_LOCATE_FILE; -extern int XP_ERRNO_EWOULDBLOCK; -extern int MK_TCP_WRITE_ERROR; -extern int XP_ERRNO_EALREADY; -extern int XP_ALERT_URN_USEHTTP; -extern int XP_ALERT_NFS_USEHTTP; -extern int MK_NO_WAIS_PROXY; - -/* print network progress to the front end - */ -MODULE_PRIVATE void -NET_Progress(MWContext *context, char *msg) -{ - FE_Progress(context, msg); -} - -/* note: on the Macintosh local_dir_name will be in the following format: */ -/* file:///Hard%20Disk/Folder%20Name/File.html */ -PUBLIC char ** -NET_AssembleAllFilesInDirectory(MWContext *context, char * local_dir_name) -{ - PRDir *dir_ptr; - PRDirEntry *dir_entry; - XP_StatStruct stat_entry; - char **files_to_post; - char *file_to_post = 0; - int32 i, cur_array_size; - int end; - Bool have_slash; -#define INITIAL_ARRAY_SIZE 10 -#define EXPAND_ARRAY_BY 5 - - PR_ASSERT(local_dir_name); - -#ifdef XP_MAC - local_dir_name += 7; // chop-off "file://" -#endif - - if(NULL == (dir_ptr = PR_OpenDir(local_dir_name))) - { - FE_Alert(context, "Unable to open local directory"); - return NULL; - } - - /* make sure local_dir_name doesn't have a slash at the end */ - end = PL_strlen(local_dir_name)-1; - have_slash = (local_dir_name[end] == '/') || (local_dir_name[end] == '\\'); - - files_to_post = (char**) PR_Malloc(INITIAL_ARRAY_SIZE * sizeof(char*)); - if(!files_to_post) - return NULL; - cur_array_size = INITIAL_ARRAY_SIZE; - - i=0; - while((dir_entry = PR_ReadDir(dir_ptr, PR_SKIP_BOTH)) != NULL) - { - /* assemble full pathname first so we can test if its a directory */ - file_to_post = PL_strdup(local_dir_name); - if ( ! file_to_post ){ - PR_CloseDir(dir_ptr); - return NULL; - } - - /* Append slash to directory if we don't already have one */ - if( !have_slash ) - { -#ifdef XP_WIN - StrAllocCat(file_to_post, "\\"); -#else - StrAllocCat(file_to_post, "/"); -#endif - } - if ( ! file_to_post ) - { - PR_CloseDir(dir_ptr); - return NULL; - } - - StrAllocCat(file_to_post, dir_entry->name); - - if ( ! file_to_post ) - { - PR_CloseDir(dir_ptr); - return NULL; - } - - /* skip over subdirectory names */ - if(-1 != NET_XP_Stat(file_to_post, &stat_entry, xpFileToPost) && S_ISDIR(stat_entry.st_mode) ) - { - PR_Free(file_to_post); - continue; - } - - /* expand array if necessary - * always leave room for the NULL terminator */ - if(i >= cur_array_size-1) - { - files_to_post = (char**) PR_Realloc(files_to_post, (cur_array_size + EXPAND_ARRAY_BY) * sizeof(char*)); - if(!files_to_post) { - PR_CloseDir(dir_ptr); - return NULL; - } - cur_array_size += EXPAND_ARRAY_BY; - } - - files_to_post[i++] = PL_strdup(file_to_post); - - PR_Free(file_to_post); - } - - PR_CloseDir(dir_ptr); - - /* NULL terminate the array, space is guarenteed above */ - files_to_post[i] = NULL; - - return(files_to_post); -} - -/********KILL this, use NET_PublishFilesTo ************/ -/* upload a set of local files (array of char*) - * all files must have full path name - * first file is primary html document, - * others are included images or other files - * in the same directory as main file - */ -PUBLIC void -NET_PublishFiles(MWContext *context, - char **files_to_publish, - char *remote_directory) -{ - URL_Struct *URL_s; - - PR_ASSERT(context && files_to_publish && remote_directory); - if(!context || !files_to_publish || !*files_to_publish || !remote_directory) - return; - - /* create a URL struct */ - URL_s = NET_CreateURLStruct(remote_directory, NET_SUPER_RELOAD); - if(!URL_s) - { - FE_Alert(context, "Error: not enough memory for file upload"); - return; /* does not exist */ - } - - FREE_AND_CLEAR(URL_s->content_type); - - /* add the files that we are posting and set the method to POST */ - URL_s->files_to_post = files_to_publish; - URL_s->method = URL_POST_METHOD; - - /* start the load */ - FE_GetURL(context, URL_s); -} - -/* upload a set of local files (array of char*) - * first file is primary html document, - * others are included images or other files. - * - * It is legal to pass in NULL as the value of publish_to. This will duplicate - the functionality of the old NET_PublishFiles. - * files_to_publish and publish_to are used by and will be freed by NET_PublishFilesTo, - * base_url is copied */ -PUBLIC void -NET_PublishFilesTo(MWContext *context, - char **files_to_publish, - char **publish_to, /* Absolute URLs of the location to - * publish the files to. Used only if HTTP. - * Ignored if FTP (except to delete memory.)*/ - XP_Bool *add_crlf, /* For each file in files_to_publish, should every line - end in a CRLF. */ - char *base_url, /* Directory to publish to, or the destination - * URL of the root HTML document. */ - char *username, - char *password, - Net_GetUrlExitFunc *exit_func, - void *fe_data) -{ - URL_Struct *URL_s; - - if(!context || !files_to_publish || !*files_to_publish || !base_url) { - PR_ASSERT(0); - return; - } - - /* create a URL struct */ - URL_s = NET_CreateURLStruct(base_url, NET_SUPER_RELOAD); - if(!URL_s) - { - FE_Alert(context, "Error: not enough memory for file upload"); - return; /* does not exist */ - } - - if (username) - URL_s->username = PL_strdup(username); - if (password) - URL_s->password = PL_strdup(password); - - FREE_AND_CLEAR(URL_s->content_type); - - /* add the files that we are posting and set the method to POST */ - URL_s->files_to_post = files_to_publish; - URL_s->post_to = publish_to; - URL_s->add_crlf = add_crlf; - URL_s->method = URL_POST_METHOD; - URL_s->pre_exit_fn = exit_func; /* May be NULL */ - URL_s->fe_data = fe_data; - - /* start the load */ - FE_GetURL(context, URL_s); -} - -/* assemble username, password, and ftp:// or http:// URL into - * ftp://user:password@/blah format for uploading -*/ -PUBLIC Bool -NET_MakeUploadURL( char **full_location, char *location, - char *user_name, char *password ) -{ - char *start; - char *pSrc; - char *destination; - char *at_ptr; - int iSize; - - if( !full_location || !location ) return FALSE; - if( *full_location ) PR_Free(*full_location); - - iSize = strlen(location) + 4; - if( user_name ) iSize += strlen(user_name); - if( password ) iSize += strlen(password); - - *full_location = (char*)PR_Malloc(iSize); - if( !*full_location ){ - /* Return an empty string */ - *full_location = strdup(""); - return FALSE; - } - **full_location = '\0'; - - /* Find start just past http:// or ftp:// */ - start = PL_strstr(location, "//"); - if( !start ) return FALSE; - - /* Point to just past the host part */ - start += 2; - pSrc = location; - destination = *full_location; - /* Copy up to and including "//" */ - while( pSrc < start ) *destination++ = *pSrc++; - *destination = '\0'; - - /* Skip over any user:password in supplied location */ - at_ptr = PL_strchr(start, '@'); - if( at_ptr ){ - start = at_ptr + 1; - } - /* Append supplied "user:password@" - * (This can be used without password) - */ - if( user_name && PL_strlen(user_name) > 0 ){ - PL_strcat(*full_location, user_name); - if ( password && PL_strlen(password) > 0 ){ - PL_strcat(*full_location,":"); - PL_strcat(*full_location, password); - } - PL_strcat(*full_location, "@"); - } - /* Append the rest of location */ - PL_strcat(*full_location, start); - - return TRUE; -} - -/* extract the username, password, and reassembled location string - * from an ftp:// or http:// URL -*/ -PUBLIC Bool -NET_ParseUploadURL( char *full_location, char **location, - char **user_name, char **password ) -{ - char *unamePwd; - char *username = NULL; - char *password_ = NULL; - char *colon; - - if( full_location == NULL || location == NULL ) - return FALSE; - - /* Empty exitisting strings... */ - if(*location) PR_Free(*location); - if( user_name && *user_name) PR_Free(*user_name); - if( password && *password) PR_Free(*password); - - /* Separate the username and password from the full URL */ - *location = NET_ParseURL(full_location, GET_PROTOCOL_PART | GET_HOST_PART | GET_PATH_PART); - unamePwd = NET_ParseURL(full_location, GET_USERNAME_PART | GET_PASSWORD_PART); - - /* get the username & password out of the combo string */ - if( (colon = PL_strchr(unamePwd, ':')) != NULL ) - { - *colon='\0'; - username = PL_strdup(unamePwd); - password_ = PL_strdup(colon+1); - - *colon=':'; - PR_Free(unamePwd); - } else { - username=unamePwd; - } - if( user_name ) - *user_name = username; - else - PR_Free(username); - - if( password ) - { - /* we always return at least an empty string */ - if( password_ ) - *password = password_; - else - *password = PL_strdup(""); - } - else if( password_ ) - PR_Free(password_); - - return TRUE; -} - - -/* returns a malloc'd string containing a unique id - * generated from the sec random stuff. - */ -PUBLIC char * -NET_GetUniqueIdString(void) -{ -#define BYTES_OF_RANDOMNESS 20 - char rand_buf[BYTES_OF_RANDOMNESS+10]; - char *rv=0; - - - RNG_GenerateGlobalRandomBytes(rand_buf, BYTES_OF_RANDOMNESS); - - /* now uuencode it so it goes across the wire right */ - rv = (char *) PR_Malloc((BYTES_OF_RANDOMNESS * (4/3)) + 10); - - if(rv) - NET_UUEncode((unsigned char *)rand_buf, (unsigned char *)rv, BYTES_OF_RANDOMNESS); - - return(rv); - -#undef BYTES_OF_RANDOMNESS -} - - -/* The magic set of 64 chars in the uuencoded data */ -PRIVATE unsigned char uuset[] = { -'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+' -,'/' }; - -MODULE_PRIVATE int -NET_UUEncode(unsigned char *src, unsigned char *dst, int srclen) -{ - int i, r; - unsigned char *p; - -/* To uuencode, we snip 8 bits from 3 bytes and store them as -6 bits in 4 bytes. 6*4 == 8*3 (get it?) and 6 bits per byte -yields nice clean bytes - -It goes like this: - AAAAAAAA BBBBBBBB CCCCCCCC -turns into the standard set of uuencode ascii chars indexed by numbers: - 00AAAAAA 00AABBBB 00BBBBCC 00CCCCCC - -Snip-n-shift, snip-n-shift, etc.... - -*/ - - for (p=dst,i=0; i < srclen; i += 3) { - /* Do 3 bytes of src */ - register unsigned char b0, b1, b2; - - b0 = src[0]; - if (i==srclen-1) - b1 = b2 = '\0'; - else if (i==srclen-2) { - b1 = src[1]; - b2 = '\0'; - } - else { - b1 = src[1]; - b2 = src[2]; - } - - *p++ = uuset[b0>>2]; - *p++ = uuset[(((b0 & 0x03) << 4) | ((b1 & 0xf0) >> 4))]; - *p++ = uuset[(((b1 & 0x0f) << 2) | ((b2 & 0xc0) >> 6))]; - *p++ = uuset[b2 & 0x3f]; - src += 3; - } - *p = 0; /* terminate the string */ - r = (unsigned char *)p - (unsigned char *)dst; /* remember how many we -did */ - - /* Always do 4-for-3, but if not round threesome, have to go - clean up the last extra bytes */ - - for( ; i != srclen; i--) - *--p = '='; - - return r; -} - - -PRIVATE char * -NET_RemoveQuotes(char * string) -{ - char *rv; - char *end; - - rv = XP_StripLine(string); - - if(*rv == '"' || *rv == '\'') - rv++; - - end = &rv[PL_strlen(rv)-1]; - - if(*end == '"' || *end == '\'') - *end = '\0'; - - return(rv); } - -#define POST_DATA_BUFFER_SIZE 2048 - -struct WritePostDataData { - char *buffer; - XP_Bool last_line_was_complete; - int32 amt_in_buffer; - int32 amt_sent; - int32 total_amt_sent; - int32 file_size; - XP_File fp; - int32 headerSize; - int32 headerAmountSent; - XP_Bool CRSent; - XP_Bool LFSent; -}; - -PUBLIC void -NET_free_write_post_data_object(struct WritePostDataData *obj) -{ - PR_ASSERT(obj); - - if(!obj) - return; - - if (obj->fp) - NET_XP_FileClose(obj->fp); - - FREEIF(obj->buffer); - FREE(obj); -} - -/* returns whether or not the socket error was expected. If it was not, all the write post data - object was free'd, and the url_s->error_msg was set */ -PRIVATE XP_Bool -net_expected_error(URL_Struct *URL_s, struct WritePostDataData **data_obj) -{ - int err = PR_GetError(); - if(err == PR_WOULD_BLOCK_ERROR || err == PR_IS_CONNECTED_ERROR) - return TRUE; - URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, err); - NET_free_write_post_data_object(*data_obj); - *data_obj = NULL; - return FALSE; -} - -/* this function is called repeatably to write - * the post data body and headers onto the network. - * - * Returns negative on fatal error - * Returns zero when done - * Returns positive if not yet completed - */ -PUBLIC int -NET_WritePostData(MWContext *context, - URL_Struct *URL_s, - PRFileDesc *sock, - void **write_post_data_data, - PRBool add_crlf_to_line_endings) -{ - struct WritePostDataData *data_obj = (struct WritePostDataData *) - *write_post_data_data; - - /* init the data object */ - if(!data_obj) - { - data_obj = PR_NEW(struct WritePostDataData); - *write_post_data_data = data_obj; - - if(!data_obj) - return(MK_OUT_OF_MEMORY); - - memset(data_obj, 0, sizeof(struct WritePostDataData)); - - data_obj->last_line_was_complete = TRUE; - data_obj->buffer = (char *) PR_Calloc(1, POST_DATA_BUFFER_SIZE); - - if(!data_obj->buffer) - { - NET_free_write_post_data_object(data_obj); - *write_post_data_data=NULL; - return 0; - } - - if(URL_s->post_headers) - data_obj->headerSize = PL_strlen(URL_s->post_headers); - else - data_obj->headerSize = 0; - - data_obj->headerAmountSent = 0; - data_obj->CRSent = FALSE; - data_obj->LFSent = FALSE; - data_obj->amt_sent = 0; - } - - if(!data_obj->fp && URL_s->post_data_is_file) - { - XP_StatStruct stat_entry; - - /* Send the headers */ - if( URL_s->post_headers && - (data_obj->headerSize > data_obj->headerAmountSent) ) - { - int32 amtWritten = 0; - amtWritten = PR_Write(sock, - URL_s->post_headers + data_obj->headerAmountSent, - data_obj->headerSize - data_obj->headerAmountSent); - - /* if there was a problem */ - if( amtWritten < 0 ) { - /* determine whether it was expected */ - if( net_expected_error(URL_s, (struct WritePostDataData **) write_post_data_data) ) - return 1; - else - return(MK_TCP_WRITE_ERROR); - } - -#ifdef DEBUG - NET_NTrace("Tx: ", 4); - NET_NTrace(URL_s->post_headers + data_obj->headerAmountSent, - amtWritten); -#endif - - data_obj->headerAmountSent += amtWritten; - - if(data_obj->headerSize > data_obj->headerAmountSent) - return 1; - - } /* END: URL_s->post_headers ... */ - - /* stat the file to get the size - */ - if(-1 != NET_XP_Stat(URL_s->post_data, &stat_entry, xpFileToPost)) - { - data_obj->file_size = stat_entry.st_size; - } - - /* open the post data file - */ - data_obj->fp = NET_XP_FileOpen(URL_s->post_data, xpFileToPost, XP_FILE_READ_BIN); - - if(!data_obj->fp) - { - URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_LOCATE_FILE, - URL_s->post_data); - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - return(MK_UNABLE_TO_LOCATE_FILE); - } - } - - if(URL_s->post_data_is_file) - { - int32 amt_to_wrt; - int32 amt_wrt; - - int type = NET_URL_Type (URL_s->address); - XP_Bool quote_lines_p = (type == MAILTO_TYPE_URL || - type == NEWS_TYPE_URL); - - /* do file based operations - */ - if(data_obj->amt_in_buffer < 1 || data_obj->amt_sent >= data_obj->amt_in_buffer) - { - /* read more data from the file - */ - if (quote_lines_p || add_crlf_to_line_endings) - { - char *line; - char *b = data_obj->buffer; - int32 bsize = POST_DATA_BUFFER_SIZE; - data_obj->amt_in_buffer = 0; - do { - int L; - - line = NET_XP_FileReadLine(b, bsize-5, data_obj->fp); - - if (!line) - break; - - L = PL_strlen(line); - - /* escape periods only if quote_lines_p is set - */ - if (quote_lines_p && - data_obj->last_line_was_complete && line[0] == '.') - { - /* This line begins with "." so we need to quote it - by adding another "." to the beginning of the line. - */ - int i; - line[L+1] = 0; - for (i = L; i > 0; i--) - line[i] = line[i-1]; - L++; - } - - /* set default */ - data_obj->last_line_was_complete = TRUE; - - if (L > 1 && line[L-2] == CR && line[L-1] == LF) - { - /* already ok */ - } - else if(L > 0 && (line[L-1] == LF || line[L-1] == CR)) - { - /* only add the crlf if required - * we still need to do all the - * if comparisons here to know - * if the line was complete - */ - if(add_crlf_to_line_endings) - { - /* Change newline to CRLF. */ - L--; - line[L++] = CR; - line[L++] = LF; - line[L] = 0; - } - } - else - { - data_obj->last_line_was_complete = FALSE; - } - - bsize -= L; - b += L; - data_obj->amt_in_buffer += L; - } while (line && bsize > 100); - } - else - { - data_obj->amt_in_buffer = NET_XP_FileRead(data_obj->buffer, - POST_DATA_BUFFER_SIZE-1, - data_obj->fp); - } - -HG29784 - - if(data_obj->amt_in_buffer < 1) - { - /* end of file, all done - */ - /* - * handled by NET_free_write_post_data_object - * - NET_XP_FileClose(data_obj->fp); - */ - PR_ASSERT(data_obj->total_amt_sent >= data_obj->file_size); - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - return(0); - } - - data_obj->amt_sent = 0; - } - - amt_to_wrt = data_obj->amt_in_buffer-data_obj->amt_sent; - - /* write some data to the socket - */ - amt_wrt = PR_Write(sock, - data_obj->buffer+data_obj->amt_sent, - amt_to_wrt); - -#ifdef DEBUG - NET_NTrace("Tx: ", 4); - NET_NTrace(data_obj->buffer+data_obj->amt_sent, - amt_to_wrt); -#endif /* DEBUG */ - - if(amt_wrt < 0) - { - int err = PR_GetError(); - if(err == PR_WOULD_BLOCK_ERROR - || err == PR_IS_CONNECTED_ERROR) - return(1); /* continue */ - - URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, err); - /* - * handled by net_free_write_post_data - NET_XP_FileClose(data_obj->fp); - */ - - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - - return(MK_TCP_WRITE_ERROR); - } - -#if defined(XP_UNIX) && defined(DEBUG) - if(amt_wrt < amt_to_wrt) - fprintf(stderr, "Fwrite wrote less than requested!\n"); -#endif - - /* safety for broken write */ - if(amt_wrt > amt_to_wrt) - amt_wrt = amt_to_wrt; - -#if defined(XP_UNIX) && defined(DEBUG) - if(MKLib_trace_flag) - { - fwrite("Tx: ", 1, 4, stderr); - fwrite(data_obj->buffer+data_obj->amt_sent, 1, amt_wrt, stderr); - fwrite("\n", 1, 1, stderr); - } -#endif - - data_obj->amt_sent += amt_wrt; - data_obj->total_amt_sent += amt_wrt; - - /* return the amount of data written - * so that callers can provide progress - * if necessary. If the amt_wrt was - * zero (I don't think it can ever happen) - * return 1 because zero means all done - */ - if(amt_wrt > 0) - return(amt_wrt); - else - return(1); - } - else - { - /* do memory based operations */ - int32 amtWritten; - - /* send the headers if there are any && and they haven't been sent */ - if( URL_s->post_headers && (data_obj->headerSize > data_obj->headerAmountSent) ) - { - amtWritten = PR_Write(sock, - URL_s->post_headers + data_obj->headerAmountSent, - data_obj->headerSize - data_obj->headerAmountSent); - - /* if there was a problem */ - if(amtWritten < 0) { - /* determine whether it was expected */ - if( net_expected_error(URL_s, (struct WritePostDataData **) write_post_data_data) ) - return 1; - else - return(MK_TCP_WRITE_ERROR); - } - -#ifdef DEBUG - NET_NTrace("Tx: ", 4); - NET_NTrace(URL_s->post_headers + data_obj->headerAmountSent, - amtWritten); - NET_NTrace("\n", 1); -#endif - - data_obj->headerAmountSent += amtWritten; - - /* If all the header data hasn't been sent, return 1 (not done). */ - if(data_obj->headerSize > data_obj->headerAmountSent) - return 1; - } - - /* Separate the headers from the data with a CR and LF. */ - if(URL_s->post_headers && !data_obj->CRSent) { - data_obj->buffer[0] = CR; - data_obj->buffer[1] = LF; - data_obj->buffer[2] = '\0'; - amtWritten = PR_Write(sock, data_obj->buffer, PL_strlen(data_obj->buffer)); - - if(amtWritten < 0) { - /* determine whether it was expected */ - if( net_expected_error(URL_s, (struct WritePostDataData **) write_post_data_data) ) - return 1; - else - return(MK_TCP_WRITE_ERROR); - } - /* If no data was sent, return 1 (not done). */ - if(amtWritten == 0) - return 1; - - if(amtWritten >= 1) - data_obj->CRSent = TRUE; - if(amtWritten >= 2) - data_obj->LFSent = TRUE; - } - - if(URL_s->post_headers && !data_obj->LFSent) { - data_obj->buffer[0] = LF; - data_obj->buffer[1] = '\0'; - amtWritten = PR_Write(sock, data_obj->buffer, PL_strlen(data_obj->buffer)); - - if(amtWritten < 0) { - /* determine whether it was expected */ - if( net_expected_error(URL_s, (struct WritePostDataData **) write_post_data_data) ) - return 1; - else - return(MK_TCP_WRITE_ERROR); - } - /* If no data was sent, return 1 (not done). */ - if(amtWritten == 0) - return 1; - data_obj->LFSent = TRUE; - - TRACEMSG(("Adding \\n to command")); - } - - if(!URL_s->post_data) - { - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - return(MK_OUT_OF_MEMORY); - } - - /* Send the data if we haven't already sent it */ - if(URL_s->post_data_size > data_obj->amt_sent) { - amtWritten = PR_Write(sock, - URL_s->post_data+data_obj->amt_sent, - URL_s->post_data_size-data_obj->amt_sent); - - if(amtWritten < 0) { - /* determine whether it was expected */ - if( net_expected_error(URL_s, (struct WritePostDataData **) write_post_data_data) ) - return 1; - else - return(MK_TCP_WRITE_ERROR); - } - /* If no data was sent, return 1 (not done). */ - if(amtWritten == 0) - return 1; - -#ifdef DEBUG - NET_NTrace("Tx: ", 4); - NET_NTrace(URL_s->post_data+data_obj->amt_sent, - amtWritten); - NET_NTrace("\n", 1); -#endif - - data_obj->amt_sent += amtWritten; - - /* if all data has been written, return done */ - if(data_obj->amt_sent >= URL_s->post_data_size) { - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - return 0; - } - else { - return amtWritten; - } - } - else { - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - return 0; - } - } - - /* By this time all headers and data should have been sent, shouldn't get here */ - PR_ASSERT(0); - NET_free_write_post_data_object(data_obj); - *write_post_data_data = NULL; - return(-1); /* shouldn't ever get here */ - -} - -void -NET_ParseContentTypeHeader(MWContext *context, char *value, URL_Struct *URL_s, PRBool is_http) -{ - char *first_arg, *next_arg; - - if(URL_s->preset_content_type) - return; - - first_arg = strtok(value, ";"); - - StrAllocCopy(URL_s->content_type, XP_StripLine(value)); - TRACEMSG(("Found content_type: %s",URL_s->content_type)); - - /* assign and compare - * - * search for charset - * and boundry - */ - while((next_arg = strtok(NULL, ";")) != NULL) - { - next_arg = XP_StripLine(next_arg); - - if(!PL_strncasecmp(next_arg,"CHARSET=", 8)) - { -#ifdef MOZILLA_CLIENT - char *charset_tag = NET_RemoveQuotes(next_arg+8); - /* - * To make http LOAD-FROM-NET and LOAD-FROM-CACHE - * charset tag handling consistant just put the http - * charset info in the url struct. - * We will use this later when setting up charset converter. - * (we do this because: on a reload from cache this code will not get called) - */ - if (is_http) - { - /* record HTTP charset tag so we can: */ - /* 1) use it to figure out the doc_csid */ - /* 2) report it to the user */ - StrAllocCopy(URL_s->charset, charset_tag); - TRACEMSG(("Found HTTP charset: %s", charset_tag)); - } - else - { - INTL_CCCReportMetaCharsetTag(context, charset_tag); - TRACEMSG(("Found Meta charset: %s", charset_tag)); - } -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } - else if(!PL_strncasecmp(next_arg,"BOUNDARY=", 9)) - { - StrAllocCopy(URL_s->boundary, NET_RemoveQuotes(next_arg+9)); - TRACEMSG(("Found boundary: %s", URL_s->boundary)); - } - else if(!PL_strncasecmp(next_arg,"AUTOSCROLL", 10)) - { - -#define DEFAULT_AUTO_SCROLL_BUFFER 100 - if(*next_arg+10 == '=') - URL_s->auto_scroll = atoi(NET_RemoveQuotes(next_arg+11)); - - if(!URL_s->auto_scroll) - URL_s->auto_scroll = DEFAULT_AUTO_SCROLL_BUFFER; - - TRACEMSG(("Found autoscroll attr.: %ud", URL_s->auto_scroll)); - } - } -} - -/* parse a mime header. - * - * Both name and value strings will be modified during - * parsing. If you need to retain your strings make a - * copy before passing them in. - * - * Values will be placed in the URL struct. - * - * returns TRUE if it found a valid header - * and FALSE if it didn't - */ - -PUBLIC Bool -NET_ParseMimeHeader(FO_Present_Types outputFormat, - MWContext *context, - URL_Struct *URL_s, - char *name, - char *value, - XP_Bool is_http) -{ - Bool found_one = FALSE; - Bool ret_value = FALSE; - char empty_string[2]; - char *colon_ptr; - - if(!name || !URL_s) - return(FALSE); - - name = XP_StripLine(name); - - if(value) - { - value = XP_StripLine(value); - } - else - { - *empty_string = '\0'; - value = empty_string; - } - - colon_ptr = PL_strchr(name, ':'); - if (colon_ptr) { - *colon_ptr = '\0'; - } - ret_value = NET_AddToAllHeaders(URL_s, name, value); - if (colon_ptr) { - *colon_ptr = ':'; - } - if (!ret_value) { - return(FALSE); - } - - switch(toupper(*name)) - { - case 'A': - if(!PL_strncasecmp(name,"ACCEPT-RANGES:",14) - || !PL_strncasecmp(name, "ALLOW-RANGES:",13)) - { - char * next_arg = strtok(value, ";"); - - found_one = TRUE; - - while(next_arg) - { - next_arg = XP_StripLine(next_arg); - - if(!PL_strncasecmp(next_arg,"BYTES", 5)) - { - TRACEMSG(("Document Allows for BYTERANGES!")); - URL_s->server_can_do_byteranges = TRUE; - } - - next_arg = strtok(NULL, ";"); - } - } - else if(!PL_strncasecmp(name, "AGE:",4)) - { - long age; - - strtok(value, ";"); /* terminate at ';' */ - - age = atol(value); - /* Small deviation from the spec. Assumption being made- - Req. time ~= Resp Time ~= now */ - if (URL_s->server_date) - { - time_t now = time(NULL); - time_t correction = now - MAX(age, MAX(0, now- URL_s->server_date)); - if (URL_s->expires) - URL_s->expires += correction; - } - } - case 'C': - if (!PL_strncasecmp(name,"CACHE-CONTROL:",14)) - { - /* Potential values include */ - /* public */ - /* private[=field-name] */ - /* no-cache [=field-name] */ - /* no-store */ - /* no-transform - this is only applicable for proxies and hence not put here*/ - /* must-revalidate */ - /* proxy-revalidate */ - /* max-age=delta-seconds */ - /* s-maxage=delta-seconds */ - - /* any cache extension */ - - char * control = NET_RemoveQuotes(value); - - if (!PL_strncasecmp(control, "NO-CACHE", 8)) - { - /* same as pragma=no-cache */ - URL_s->dont_cache = TRUE; - } - else if (!PL_strncasecmp(control, "MAX-AGE=", 8)) - { - /* Takes precedence over the Expires header. - Corrected Expires is Max-age + Server Date */ - if (URL_s->server_date) - { - URL_s->expires = URL_s->server_date + atol(strtok(control+8,";")); - } - } -#if 0 /* Unimplemented */ - else if (!PL_strncasecmp(control, "PUBLIC", 6)) - { - /* Place holder for shared cache concepts */ - } - else if (!PL_strncasecmp(control, "PRIVATE", 7)) - { - /* Place holder for shared cache concepts */ - } - else if (!PL_strncasecmp(control, "NO-STORE", 8)) - { - /* According to the spec this "should" disable explicit saving - of the document outside the caching system, eg. in "Save As..." - dialogs. Since this idea sucks, this is a place holder. */ - } - else if (!PL_strncasecmp(control, "MUST-REVALIDATE", 15)) - { - /* The cache must do an end-to-end revalidation every time, if - the response headers suggest an entity is stale. We do this - anyway. */ - } - else if (!PL_strncasecmp(control, "PROXY-REVALIDATE", 16)) - { - /* Same as must-revalidate except that it does not apply to - non-shared user agents (like us) */ - } - else if (!PL_strncasecmp(control, "S-MAXAGE", 8)) - { - /* Applicable for shared caches. Place holder. */ - } - else - { - /* A new cache extension */ - } -#endif /* Unimplemented */ - } - else if(!PL_strncasecmp(name,"CONTENT-DISPOSITION:",20)) - { - char *next_arg; - - found_one = TRUE; - - next_arg = strtok(value, ";"); - - while(next_arg) - { - next_arg = XP_StripLine(next_arg); - - if(!PL_strncasecmp(next_arg,"filename=", 9)) - { - StrAllocCopy(URL_s->content_name, - NET_RemoveQuotes(next_arg+9)); - } - next_arg = strtok(NULL, ";"); - } - - } - else if(!PL_strncasecmp(name,"CONTENT-TYPE:",13)) - { - found_one = TRUE; - NET_ParseContentTypeHeader(context, value, URL_s, is_http); - } - else if(!PL_strncasecmp(name,"CONTENT-LENGTH:",15)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - - /* don't reset the content-length if - * we have already set it from the content-range - * header. If high_range is set then we must - * have seen a content-range header. - */ - if(!URL_s->high_range) - URL_s->content_length = atol(value); - } - else if(!PL_strncasecmp(name,"CONTENT-ENCODING:",17)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - StrAllocCopy(URL_s->content_encoding, value); - } - else if(!PL_strncasecmp(name,"CONTENT-RANGE:",14)) - { - unsigned long low, high, length; - strtok(value, ";"); /* terminate at ';' */ - - /* range header looks like: - * Range: bytes x-y/z - * where: - * - * X is the number of the first byte returned - * (the first byte is byte number zero). - * - * Y is the number of the last byte returned - * (in case of the end of the document this - * is one smaller than the size of the document - * in bytes). - * - * Z is the total size of the document in bytes. - * - * Scan through temp variables because %l is 64 bits on OSF1 - */ - sscanf(value, "bytes %lu-%lu/%lu", &low, &high, &length); - URL_s->low_range = (int32) low; - URL_s->high_range = (int32) high; - URL_s->content_length = (int32) length; - - /* if we get a range header set the "can-do-byteranges" - * since it must be doing byteranges - */ - URL_s->server_can_do_byteranges = TRUE; - } - else if(!PL_strncasecmp(name,"CONNECTION:",11)) - { - strtok(value, ";"); /* terminate at ';' */ - strtok(value, ","); /* terminate at ',' */ - if(!PL_strcasecmp("KEEP-ALIVE", XP_StripLine(value))) - URL_s->can_reuse_connection = TRUE; - if(!PL_strcasecmp("CLOSE", XP_StripLine(value))) - URL_s->can_reuse_connection = FALSE; - } - break; - - case 'D': - if(!PL_strncasecmp(name,"DATE:",5)) - { - found_one = TRUE; - URL_s->server_date = NET_ParseDate(value); - } -#if 0 - else if(!PL_strncasecmp(name,"DEST-IP:",8)) - { - found_one = TRUE; - URL_s->destIP = PL_strdup(value); - } -#endif - break; - case 'E': - if(!PL_strncasecmp(name,"EXPIRES:",8)) - { - char *cp, *expires = NET_RemoveQuotes(value); - Bool is_number=TRUE; - - /* Expires: 123 - number of seconds - * Expires: date - absolute date - */ - - strtok(value, ";"); /* terminate at ';' */ - - /* check to see if the expires date is just a - * value in seconds - */ - for(cp = expires; *cp != '\0'; cp++) - if(!isdigit(*cp)) - { - is_number=FALSE; - break; - } - - if(is_number) - URL_s->expires = time(NULL) + atol(expires); - else - URL_s->expires = NET_ParseDate(expires); - - /* if we couldn't parse the date correctly - * make it already expired, as per the HTTP spec - */ - if(!URL_s->expires) - URL_s->expires = 1; - - found_one = TRUE; - } - else if(!PL_strncasecmp(name,"EXT-CACHE:",10)) -#ifdef NU_CACHE - { - PR_ASSERT(0); - /* Cool find... somebody uses this? let me know -Gagan */ - } -#else - { -#ifdef MOZILLA_CLIENT - char * next_arg = strtok(value, ";"); - char * name=0; - char * instructions=0; - found_one = TRUE; - - while(next_arg) - { - next_arg = XP_StripLine(next_arg); - - if(!PL_strncasecmp(next_arg,"name=", 5)) - { - TRACEMSG(("Found external cache name: %s", next_arg+5)); - name = NET_RemoveQuotes(next_arg+5); - } - else if(!PL_strncasecmp(next_arg,"instructions=", 13)) - { - TRACEMSG(("Found external cache instructions: %s", - next_arg+13)); - instructions = NET_RemoveQuotes(next_arg+13); - } - - next_arg = strtok(NULL, ";"); - } - - if(name) - NET_OpenExtCacheFAT(context, name, instructions); -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } -#endif /* NU_CACHE */ - else if (!PL_strncasecmp(name, "ETAG:",5)) - { - /* Weak Validators are skipped for now*/ - char* etag; - if (!PL_strncasecmp(value, "W/", 2)) - etag = NET_RemoveQuotes(value+2); - else - etag = NET_RemoveQuotes(value); - - StrAllocCopy(URL_s->etag,etag); - } - break; - - case 'L': - if(!PL_strncasecmp(name,"LOCATION:",9)) - { - found_one = TRUE; - - /* don't do this here because a url can - * contain a ';' - * strtok(value, ";"); - */ - - URL_s->redirecting_url = NET_MakeAbsoluteURL( - URL_s->address, - XP_StripLine(value)); - - TRACEMSG(("Found location: %s\n",URL_s->redirecting_url)); - - if(MOCHA_TYPE_URL == NET_URL_Type(URL_s->redirecting_url)) - { - /* don't allow mocha URL's as refresh - */ - FREE_AND_CLEAR(URL_s->redirecting_url); - } - } - else if(!PL_strncasecmp(name,"LAST-MODIFIED:",14)) - { - found_one = TRUE; - - URL_s->last_modified = NET_ParseDate(value); - TRACEMSG(("Found last modified date: %d\n",URL_s->last_modified)); - } - else if(!PL_strncasecmp(name,"LINK:",5)) - { -#define PAGE_SERVICES_REL "pageServices" - -#define PRIVACY_POLICY_REL "privacyPolicy" - enum { UNKNOWN_REL_TYPE, PRIVACY_POLICY_REL_TYPE, - PAGE_SERVICES_REL_TYPE } rel_type; - - char * next_arg = strtok(value, ";"); - char * link_val; - - found_one = TRUE; - - rel_type = UNKNOWN_REL_TYPE; - - /* strip the < and > from the url */ - if(*value == '<') - { - value++; - /* strip the end one too */ - value[PL_strlen(value)-1] = '\0'; - } - - /* ok if malloc fails */ - link_val = NET_MakeAbsoluteURL(URL_s->address, - XP_StripLine(value)); - while(next_arg) - { - next_arg = XP_StripLine(next_arg); - - if(!PL_strncasecmp(next_arg,"rel=", 4)) - { - char * rel = NET_RemoveQuotes(next_arg+4); - - if(!PL_strcasecmp(rel, PAGE_SERVICES_REL)) - rel_type = PAGE_SERVICES_REL_TYPE; - else if (!PL_strcasecmp(rel, PRIVACY_POLICY_REL)) - rel_type = PRIVACY_POLICY_REL_TYPE; - } - - next_arg = strtok(NULL, ";"); - } - - /* if we fount a rel for page services assign it */ - if(rel_type == PAGE_SERVICES_REL_TYPE) - URL_s->page_services_url = link_val; - else if (rel_type == PRIVACY_POLICY_REL_TYPE) - URL_s->privacy_policy_url = link_val; - else - PR_FREEIF(link_val); - - } - break; - - case 'P': - if(!PL_strncasecmp(name,"PROXY-AUTHENTICATE:",19)) - { - char *auth = value; - - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - - if (net_IsBetterAuth(auth, URL_s->proxy_authenticate)) - StrAllocCopy(URL_s->proxy_authenticate, auth); - } - else if(!PL_strncasecmp(name,"PROXY-CONNECTION:",17)) - { - strtok(value, ";"); /* terminate at ';' */ - strtok(value, ","); /* terminate at ',' */ - if(!PL_strcasecmp("KEEP-ALIVE", XP_StripLine(value))) - URL_s->can_reuse_connection = TRUE; - if(!PL_strcasecmp("CLOSE", XP_StripLine(value))) - URL_s->can_reuse_connection = FALSE; - } - else if(!PL_strncasecmp(name,"PRAGMA:",7)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - - if(!PL_strcasecmp(value, "NO-CACHE")) - URL_s->dont_cache = TRUE; -#ifdef TRUST_LABELS - } - else if ( IsTrustLabelsEnabled() && !PL_strncasecmp(name,"PICS-LABEL:",11)) - { - /* we are looking for trust labels and a PICS-label was found - * Parse the label to see if it is a trust label. If it is a - * trust label then it will be added to the TrustList in URL_s. - */ - PICS_ExtractTrustLabel( URL_s, value ); - /* Then when we are all done with the header the Set-Cookie fields - * will be processed and matched to the trust labels. - */ -#endif - } - break; - - case 'R': - - if(!PL_strncasecmp(name,"RANGE:",6)) - { - unsigned long low, high, length; - strtok(value, ";"); /* terminate at ';' */ - - /* range header looks like: - * Range: bytes x-y/z - * where: - * - * X is the number of the first byte returned - * (the first byte is byte number zero). - * - * Y is the number of the last byte returned - * (in case of the end of the document this - * is one smaller than the size of the document - * in bytes). - * - * Z is the total size of the document in bytes. - * - * Scan through temp variables because %l is 64 bits on OSF1 - */ - sscanf(value, "bytes %lu-%lu/%lu", &low, &high, &length); - URL_s->low_range = (int32) low; - URL_s->high_range = (int32) high; - URL_s->content_length = (int32) length; - - /* if we get a range header set the "can-do-byteranges" - * since it must be doing byteranges - */ - URL_s->server_can_do_byteranges = TRUE; - } - else if(!PL_strncasecmp(name,"REFRESH:",8) && !EDT_IS_EDITOR(context)) - { - char *first_arg, *next_arg; - - found_one = TRUE; - - /* clear any previous refresh URL */ - if(URL_s->refresh_url) - { - FREE(URL_s->refresh_url); - URL_s->refresh_url=0; - } - - first_arg = strtok(value, ";"); - - URL_s->refresh = atol(value); - TRACEMSG(("Found refresh header: %d",URL_s->refresh)); - - /* assign and compare - */ - while((next_arg = strtok(NULL, ";")) != NULL) - { - next_arg = XP_StripLine(next_arg); - - - if(!PL_strncasecmp(next_arg,"URL=", 4)) - { - URL_s->refresh_url = NET_MakeAbsoluteURL( - URL_s->address, - NET_RemoveQuotes(next_arg+4)); - TRACEMSG(("Found refresh url: %s", - URL_s->refresh_url)); - - if(MOCHA_TYPE_URL == NET_URL_Type(URL_s->refresh_url)) - { - /* don't allow mocha URL's as refresh - */ - FREE_AND_CLEAR(URL_s->refresh_url); - } - } - } - - if(!URL_s->refresh_url) - StrAllocCopy(URL_s->refresh_url, URL_s->address); - } - break; - - case 'S': -#ifdef TRUST_LABELS - if( !IsTrustLabelsEnabled() && !PL_strncasecmp(name,"SET-COOKIE:",11)) -#else - if(!PL_strncasecmp(name,"SET-COOKIE:",11)) -#endif - { - found_one = TRUE; - NET_SetCookieStringFromHttp(outputFormat, URL_s, context, URL_s->address, value); - } - else if(!PL_strncasecmp(name, "SERVER:", 7)) - { - found_one = TRUE; - - if(PL_strcasestr(value, "NETSITE")) - URL_s->is_netsite = TRUE; - else if(PL_strcasestr(value, "NETSCAPE")) - URL_s->is_netsite = TRUE; - } - break; - - case 'T': - if(!PL_strncasecmp(name,"TRANSFER-ENCODING:",18)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - StrAllocCopy(URL_s->transfer_encoding, value); - } - - case 'W': - if(!PL_strncasecmp(name,"WWW-AUTHENTICATE:",17)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - - StrAllocCopy(URL_s->authenticate, value); - } - else if(!PL_strncasecmp(name, "WWW-PROTECTION-TEMPLATE:", 24)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - - StrAllocCopy(URL_s->protection_template, value); - } - else if(!PL_strncasecmp(name, "WINDOW-TARGET:", 14)) - { - found_one = TRUE; - - strtok(value, ";"); /* terminate at ';' */ - - if (URL_s->window_target == NULL) - { - if ((NET_IS_ALPHA(value[0]) != FALSE)|| - (NET_IS_DIGIT(value[0]) != FALSE)|| - (value[0] == '_')) - { - StrAllocCopy(URL_s->window_target, value); - } - } - } - break; - - default: - /* ignore other headers */ - break; - } - - return(found_one); -} - - - -/* scans a line for references to URL's and turns them into active - * links. If the output size is exceeded the line will be - * truncated. "output" must be at least "output_size" characters - * long - * - * This also quotes other HTML forms, and italicizes citations, - * unless `urls_only' is true. - */ - -#ifndef MOZILLA_CLIENT - /* If we're not in the client, stub out the libmsg interface to the - citation-highlighting code. - */ -# define MSG_PlainFont 0 -# define MSG_BoldFont 1 -# define MSG_ItalicFont 2 -# define MSG_BoldItalicFont 3 -# define MSG_NormalSize 4 -# define MSG_Bigger 5 -# define MSG_Smaller 6 -#endif /* MOZILLA_CLIENT */ - -static MSG_FONT CitationFont = MSG_ItalicFont; -static PRInt32 CitationSize = 0; -static char *CitationColor = 0; -static int CitationDataValid = -1; /* -1=first time, 0=changed; 1=data ok */ - - - -/* fix Mac warning about missing prototype */ -int PR_CALLBACK -net_citation_style_changed(const char* name, void* closure); - -int PR_CALLBACK -net_citation_style_changed(const char* name, void* closure) -{ - CitationDataValid = 0; - return 0; -} - - - - - -PUBLIC int -NET_ScanForURLs(MSG_Pane* pane, const char *input, int32 input_size, - char *output, int output_size, XP_Bool urls_only) -{ - int col = 0; - const char *cp; - const char *end = input + input_size; - char *output_ptr = output; - char *end_of_buffer = output + output_size - 40; /* add safty zone :( */ - Bool line_is_citation = FALSE; - const char *cite_open1, *cite_close1; - const char *cite_open2, *cite_close2; - - if (urls_only) - { - cite_open1 = cite_close1 = ""; - cite_open2 = cite_close2 = ""; - } - else - { -#ifdef MOZILLA_CLIENT - if (CitationDataValid != 1) { - PRInt32 value = (PRInt32) MSG_ItalicFont; - if (CitationDataValid < 0) { - PREF_RegisterCallback("mail.quoted_style", - net_citation_style_changed, - NULL); - PREF_RegisterCallback("mail.quoted_size", - net_citation_style_changed, - NULL); - PREF_RegisterCallback("mail.citation_color", - net_citation_style_changed, - NULL); - } - if ( (PREF_OK == PREF_GetIntPref(pref_mailQuotedStyle, &value)) ) { - CitationFont = (MSG_FONT) value; - } else { - CitationFont = MSG_ItalicFont; - } - - CitationSize = 0; - if ( (PREF_OK != PREF_GetIntPref(pref_mailQuotedStyle, &CitationSize)) ) { - CitationSize = 0; - } - FREEIF(CitationColor); - CitationColor = NULL; - PREF_CopyCharPref("mail.citation_color", &CitationColor); - CitationDataValid = 1; - } - - switch (CitationFont) - { - case MSG_PlainFont: - cite_open1 = "", cite_close1 = ""; - break; - case MSG_BoldFont: - cite_open1 = "<B>", cite_close1 = "</B>"; - break; - case MSG_ItalicFont: - cite_open1 = "<I>", cite_close1 = "</I>"; - break; - case MSG_BoldItalicFont: - cite_open1 = "<B><I>", cite_close1 = "</I></B>"; - break; - default: - PR_ASSERT(0); - cite_open1 = cite_close1 = ""; - break; - } - switch (CitationSize) { - case 0: /* Normal */ - cite_open2 = "", cite_close2 = ""; - break; - case 1: /* Bigger */ - cite_open2 = "<FONT SIZE=+1>", cite_close2 = "</FONT>"; - break; - case 2: /* Smaller */ - case -1: /* backwards compatability with some old code */ - cite_open2 = "<FONT SIZE=-1>", cite_close2 = "</FONT>"; - break; - default: - PR_ASSERT(0); - cite_open2 = cite_close2 = ""; - break; - } - -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } - - if (!urls_only) - { - /* Decide whether this line is a quotation, and should be italicized. - This implements the following case-sensitive regular expression: - - ^[ \t]*[A-Z]*[]>] - - Which matches these lines: - - > blah blah blah - > blah blah blah - LOSER> blah blah blah - LOSER] blah blah blah - */ - const char *s = input; - while (s < end && NET_IS_SPACE (*s)) s++; - while (s < end && *s >= 'A' && *s <= 'Z') s++; - - if (s >= end) - ; - else if (input_size >= 6 && *s == '>' && - !PL_strncmp (input, ">From ", 6)) /* sendmail... */ - ; - else if (*s == '>' || *s == ']') - { - line_is_citation = TRUE; - PL_strcpy(output_ptr, cite_open1); - output_ptr += PL_strlen(cite_open1); - PL_strcpy(output_ptr, cite_open2); - output_ptr += PL_strlen(cite_open2); - if (CitationColor && - output_ptr + PL_strlen(CitationColor) + 20 < end_of_buffer) { - PL_strcpy(output_ptr, "<FONT COLOR="); - output_ptr += PL_strlen(output_ptr); - PL_strcpy(output_ptr, CitationColor); - output_ptr += PL_strlen(output_ptr); - PL_strcpy(output_ptr, ">"); - output_ptr += PL_strlen(output_ptr); - } - } - } - - /* Normal lines are scanned for buried references to URL's - Unfortunately, it may screw up once in a while (nobody's perfect) - */ - for(cp = input; cp < end && output_ptr < end_of_buffer; cp++) - { - /* if NET_URL_Type returns true then it is most likely a URL - But only match protocol names if at the very beginning of - the string, or if the preceeding character was not alphanumeric; - this lets us match inside "---HTTP://XXX" but not inside of - things like "NotHTTP://xxx" - */ - int type = 0; - if(!NET_IS_SPACE(*cp) && - (cp == input || (!NET_IS_ALPHA(cp[-1]) && !NET_IS_DIGIT(cp[-1]))) && - (type = NET_URL_Type(cp)) != 0) - { - const char *cp2; - - for(cp2=cp; cp2 < end; cp2++) - { - /* These characters always mark the end of the URL. */ - if (NET_IS_SPACE(*cp2) || - *cp2 == '<' || *cp2 == '>' || - *cp2 == '`' || *cp2 == ')' || - *cp2 == '\'' || *cp2 == '"' || - *cp2 == ']' || *cp2 == '}') break; - } - - /* Check for certain punctuation characters on the end, and strip - them off. */ - while (cp2 > cp && - (cp2[-1] == '.' || cp2[-1] == ',' || cp2[-1] == '!' || - cp2[-1] == ';' || cp2[-1] == '-' || cp2[-1] == '?' || - cp2[-1] == '#')) - cp2--; - - col += (cp2 - cp); - - /* if the url is less than 7 characters then we screwed up - * and got a "news:" url or something which is worthless - * to us. Exclude the A tag in this case. - * - * Also exclude any URL that ends in a colon; those tend - * to be internal and magic and uninteresting. - * - * And also exclude the builtin icons, whose URLs look - * like "internal-gopher-binary". - */ - if (cp2-cp < 7 || - (cp2 > cp && cp2[-1] == ':') || - !PL_strncmp(cp, "internal-", 9)) - { - memcpy(output_ptr, cp, cp2-cp); - output_ptr += (cp2-cp); - *output_ptr = 0; - } - else - { - char *quoted_url; - int32 size_left = output_size - (output_ptr-output); - - if(cp2-cp > size_left) - return MK_OUT_OF_MEMORY; - - memcpy(output_ptr, cp, cp2-cp); - output_ptr[cp2-cp] = 0; - quoted_url = NET_EscapeHTML(output_ptr); - if (!quoted_url) return MK_OUT_OF_MEMORY; - PR_snprintf(output_ptr, size_left, - "<A HREF=\"%s\">%s</A>", - quoted_url, - quoted_url); - output_ptr += PL_strlen(output_ptr); - PR_Free(quoted_url); - } - - cp = cp2-1; /* go to next word */ - } - else - { - /* Make sure that special symbols don't screw up the HTML parser - */ - if(*cp == '<') - { - PL_strcpy(output_ptr, "&lt;"); - output_ptr += 4; - col++; - } - else if(*cp == '>') - { - PL_strcpy(output_ptr, "&gt;"); - output_ptr += 4; - col++; - } - else if(*cp == '&') - { - PL_strcpy(output_ptr, "&amp;"); - output_ptr += 5; - col++; - } - else - { - *output_ptr++ = *cp; - col++; - } - } - } - - *output_ptr = 0; - - if (line_is_citation) /* Close off the highlighting */ - { - if (CitationColor) { - PL_strcpy(output_ptr, "</FONT>"); - output_ptr += PL_strlen(output_ptr); - } - - PL_strcpy(output_ptr, cite_close2); - output_ptr += PL_strlen (cite_close2); - PL_strcpy(output_ptr, cite_close1); - output_ptr += PL_strlen (cite_close1); - } - - return 0; -} - - -static void -Append(char** output, int32* output_max, char** curoutput, const char* buf, - int32 length) -{ - if (length + (*curoutput) - (*output) >= *output_max) { - int offset = (*curoutput) - (*output); - do { - (*output_max) += 1024; - } while (length + (*curoutput) - (*output) >= *output_max); - *output = PR_Realloc(*output, *output_max); - if (!*output) return; - *curoutput = *output + offset; - } - memcpy(*curoutput, buf, length); - *curoutput += length; -} - - -char* -NET_ScanHTMLForURLs(const char* input) -{ - char* output = NULL; - char* curoutput; - int32 output_max; - char* tmpbuf = NULL; - int32 tmpbuf_max; - int32 inputlength; - const char* inputend; - const char* linestart; - const char* lineend; - - PR_ASSERT(input); - if (!input) return NULL; - inputlength = PL_strlen(input); - - output_max = inputlength + 1024; /* 1024 bytes ought to be enough to quote - several URLs, which ought to be as many - as most docs use. */ - output = PR_Malloc(output_max); - if (!output) goto FAIL; - - tmpbuf_max = 1024; - tmpbuf = PR_Malloc(tmpbuf_max); - if (!tmpbuf) goto FAIL; - - inputend = input + inputlength; - - linestart = input; - curoutput = output; - - - /* Here's the strategy. We find a chunk of plainish looking text -- no - embedded CR or LF, no "<" or "&". We feed that off to NET_ScanForURLs, - and append the result. Then we skip to the next bit of plain text. If - we stopped at an "&", go to the terminating ";". If we stopped at a - "<", well, if it was a "<A>" tag, then skip to the closing "</A>". - Otherwise, skip to the end of the tag. - */ - - - lineend = linestart; - while (linestart < inputend && lineend <= inputend) { - switch (*lineend) { - case '<': - case '>': - case '&': - case CR: - case LF: - case '\0': - if (lineend > linestart) { - int length = lineend - linestart; - if (length * 3 > tmpbuf_max) { - tmpbuf_max = length * 3 + 512; - PR_Free(tmpbuf); - tmpbuf = PR_Malloc(tmpbuf_max); - if (!tmpbuf) goto FAIL; - } - if (NET_ScanForURLs(NULL, linestart, length, - tmpbuf, tmpbuf_max, TRUE) < 0) { - goto FAIL; - } - length = PL_strlen(tmpbuf); - Append(&output, &output_max, &curoutput, tmpbuf, length); - if (!output) goto FAIL; - - } - linestart = lineend; - lineend = NULL; - if (inputend - linestart < 5) { - /* Too little to worry about; shove the rest out. */ - lineend = inputend; - } else { - switch (*linestart) { - case '<': - if ((linestart[1] == 'a' || linestart[1] == 'A') && - linestart[2] == ' ') { - lineend = PL_strcasestr(linestart, "</a"); - if (lineend) { - lineend = PL_strchr(lineend, '>'); - if (lineend) lineend++; - } - } else { - lineend = PL_strchr(linestart, '>'); - if (lineend) lineend++; - } - break; - case '&': - lineend = PL_strchr(linestart, ';'); - if (lineend) lineend++; - break; - default: - lineend = linestart + 1; - break; - } - } - if (!lineend) lineend = inputend; - Append(&output, &output_max, &curoutput, linestart, - lineend - linestart); - if (!output) goto FAIL; - linestart = lineend; - break; - default: - lineend++; - } - } - PR_Free(tmpbuf); - *curoutput = '\0'; - return output; - -FAIL: - if (tmpbuf) PR_Free(tmpbuf); - if (output) PR_Free(output); - return NULL; -} - - -/* try to make sure that this is a fully qualified - * email address including a host and domain - */ -PUBLIC Bool -NET_IsFQDNMailAddress(const char * string) -{ - /* first make sure that an @ exists - */ - char * at_sign = PL_strchr(string, '@'); - - if(at_sign) - { - /* make sure it has at least one period - */ - if(PL_strchr(at_sign, '.')) - return(TRUE); - } - - return(FALSE); -} - -HG83778 - - - - -/* returns true if the URL is a secure URL address - */ -PUBLIC Bool -NET_IsURLSecure(char * address) -{ - int type = NET_URL_Type (address); - - TRACEMSG(("NET_IsURLSecure called, type: %d", type)); - - if(HG83773 type == INTERNAL_IMAGE_TYPE_URL - || type == SECURE_LDAP_TYPE_URL) - return(TRUE); - - if(!PL_strncasecmp(address, "/mc-icons/", 10) || - !PL_strncasecmp(address, "/ns-icons/", 10)) - return(TRUE); - - if(!PL_strncasecmp(address, "internal-external-reconnect:", 28)) - return(TRUE); - - if(!PL_strcasecmp(address, "internal-external-plugin")) - return(TRUE); - - if(!PL_strncasecmp(address, "snews:", 6)) - return TRUE; - - /* - * IMAP URLs begin with "mailbox://" unlike POP URLs which begin - * with "mailbox:". - */ - HG35632 - - - TRACEMSG(("NET_IsURLSecure: URL NOT SECURE")); - - return(FALSE); -} - -/* escapes all '<', '>' and '&' characters in a string - * returns a string that must be freed - */ -PUBLIC char * -NET_EscapeHTML(const char * string) -{ - char *rv = (char *) PR_Malloc(PL_strlen(string)*4 + 1); /* The +1 is for - the trailing - null! */ - char *ptr = rv; - - if(rv) - { - for(; *string != '\0'; string++) - { - if(*string == '<') - { - *ptr++ = '&'; - *ptr++ = 'l'; - *ptr++ = 't'; - *ptr++ = ';'; - } - else if(*string == '>') - { - *ptr++ = '&'; - *ptr++ = 'g'; - *ptr++ = 't'; - *ptr++ = ';'; - } - else if(*string == '&') - { - *ptr++ = '&'; - *ptr++ = 'a'; - *ptr++ = 'm'; - *ptr++ = 'p'; - *ptr++ = ';'; - } - else - { - *ptr++ = *string; - } - } - *ptr = '\0'; - } - - return(rv); -} - -/* URL-encode all '"' characters in a string into %22. - * returns a string that must be freed - */ -PUBLIC char * -NET_EscapeDoubleQuote(const char * string) -{ - char *rv = (char *) PR_Malloc(PL_strlen(string)*3 + 1); - char *ptr = rv; - if (rv) - { - for (; *string != '\0'; string++) - { - if (*string == '"') - { - *ptr++ = '%'; - *ptr++ = '2'; - *ptr++ = '2'; - } - else - { - *ptr++ = *string; - } - } - *ptr = '\0'; - } - return rv; -} - - -PUBLIC char * -NET_SpaceToPlus(char * string) -{ - - char * ptr = string; - - if(!ptr) - return(NULL); - - for(; *ptr != '\0'; ptr++) - if(*ptr == ' ') - *ptr = '+'; - - return(string); -} - - -/* returns true if the functions thinks the string contains - * HTML - */ -PUBLIC PRBool -NET_ContainsHTML(char * string, int32 length) -{ - char * ptr = string; - register int32 count=length; - - /* restrict searching to first K to limit false positives */ - if(count > 1024) - count = 1024; - - /* if the string begins with "#!" or "%!" then it's a script of some kind, - and it doesn't matter how many HTML tags that program references in its - source -- it ain't HTML. This false match happened all the time with, - for example, CGI scripts written in sh or perl that emit HTML. */ - if (count > 2 && - (string[0] == '#' || string[0] == '%') && - string[1] == '!') - return FALSE; - - /* If it begins with a mailbox delimiter, it's not HTML. */ - if (count > 5 && - (!PL_strncmp(string, "From ", 5) || - !PL_strncmp(string, ">From ", 6))) - return FALSE; - - for(; count > 0; ptr++, count--) - if(*ptr == '<') - { - if(count > 3 && !PL_strncasecmp(ptr+1, "HTML", 4)) - return(TRUE); - - if(count > 4 && !PL_strncasecmp(ptr+1, "TITLE", 5)) - return(TRUE); - - if(count > 3 && !PL_strncasecmp(ptr+1, "FRAMESET", 8)) - return(TRUE); - - if(count > 2 && - toupper(*(ptr+1)) == 'H' - && isdigit(*(ptr+2)) && *(ptr+3) == '>') - return(TRUE); - } - - return(FALSE); -} - -/* take a Layout generated LO_FormSubmitData_struct - * and use it to add post data to the URL Structure - * generated by CreateURLStruct - * - * DOES NOT Generate the URL Struct, it must be created prior to - * calling this function - * - * returns 0 on failure and 1 on success - */ - -PUBLIC int -NET_AddLOSubmitDataToURLStruct(LO_FormSubmitData * sub_data, - URL_Struct * url_struct) -{ -#if 0 - int32 i; - int32 total_size; - char *end, *tmp_ptr; - char *encoding; - char *target; - char **name_array; - char **value_array; - uint8 *type_array; - uint8 *encoding_array; - char *esc_string; - int32 len = 0; - - if(!sub_data || !url_struct) - return(0); - - if(sub_data->method == FORM_METHOD_GET) - url_struct->method = URL_GET_METHOD; - else - url_struct->method = URL_POST_METHOD; - if (!PL_strncasecmp(url_struct->address, "mailto:", 7)) { - url_struct->mailto_post = TRUE; - } - - /* free any previous url_struct->post_data - */ - FREEIF(url_struct->post_data); - - PA_LOCK(name_array, char**, sub_data->name_array); - PA_LOCK(value_array, char**, sub_data->value_array); - PA_LOCK(type_array, uint8*, sub_data->type_array); - PA_LOCK(encoding_array, uint8*, sub_data->encoding_array); - PA_LOCK(encoding, char*, sub_data->encoding); - - /* free any previous target - */ - FREEIF(url_struct->window_target); - PA_LOCK(target, char*, sub_data->window_target); - if (target == NULL) - url_struct->window_target = NULL; - else - url_struct->window_target = PL_strdup (target); - - FREEIF (url_struct->post_headers); - - /* If we're posting to mailto, then generate the full complement - of mail headers; and allow the url to specify additional headers - as well. */ -#if defined(OLD_MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) - if (!PL_strncasecmp(url_struct->address, "mailto:", 7)) - { -#ifdef MOZILLA_CLIENT - int status; - char *new_url = 0; - char *headers = 0; - - status = MIME_GenerateMailtoFormPostHeaders (url_struct->address, - url_struct->referer, - &new_url, &headers); - if (status < 0) - { - FREEIF (new_url); - FREEIF (headers); - return status; - } - PR_ASSERT (new_url); - PR_ASSERT (headers); - url_struct->address_modified = TRUE; - PR_Free (url_struct->address); - url_struct->address = new_url; - url_struct->post_headers = headers; -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } -#endif /* OLD_MOZ_MAIL_NEWS || MOZ_MAIL_COMPOSE */ - - if(encoding && !PL_strcasecmp(encoding, "text/plain")) - { - char *tmpfilename; - char buffer[512]; - XP_File fp; - - /* always use post for this encoding type - */ - url_struct->method = URL_POST_METHOD; - - /* write all the post data to a file first - * so that we can send really big stuff - */ - tmpfilename = WH_TempName (xpFileToPost, "nsform"); - if (!tmpfilename) return 0; - fp = NET_XP_FileOpen (tmpfilename, xpFileToPost, XP_FILE_WRITE_BIN); - if (!fp) { - PR_Free(tmpfilename); - return 0; - } - - if (url_struct->post_headers) - { - len = NET_XP_FileWrite(url_struct->post_headers, - PL_strlen (url_struct->post_headers), - fp); - PR_Free (url_struct->post_headers); - url_struct->post_headers = 0; - if (len < 0) - { - NET_XP_FileClose(fp); - return 0; - } - } - - PL_strcpy (buffer, - "Content-type: text/plain" CRLF - "Content-Disposition: inline; form-data" CRLF CRLF); - len = NET_XP_FileWrite(buffer, PL_strlen(buffer), fp); - - for(i=0; (len >= 0) && (i < sub_data->value_cnt); i++) - { - if(name_array[i]) - NET_XP_FileWrite(name_array[i], PL_strlen(name_array[i]), fp); - NET_XP_FileWrite("=", 1, fp); - if(value_array[i]) - NET_XP_FileWrite(value_array[i], PL_strlen(value_array[i]), fp); - len = NET_XP_FileWrite(CRLF, 2, fp); - } - NET_XP_FileClose(fp); - - StrAllocCopy(url_struct->post_data, tmpfilename); - PR_Free(tmpfilename); - if (len < 0) - return 0; - url_struct->post_data_is_file = TRUE; - } - else if(encoding && !PL_strcasecmp(encoding, "multipart/form-data")) - { - /* encoding using a variant of multipart/mixed - * and add files to it as well - */ - char *tmpfilename; - char separator[80]; - char buffer[512]; - XP_File fp; - int boundary_len; - int cont_disp_len; - NET_cinfo * ctype; - - - /* always use post for this encoding type - */ - url_struct->method = URL_POST_METHOD; - - /* write all the post data to a file first - * so that we can send really big stuff - */ - tmpfilename = WH_TempName (xpFileToPost, "nsform"); - if (!tmpfilename) return 0; - fp = NET_XP_FileOpen (tmpfilename, xpFileToPost, XP_FILE_WRITE_BIN); - if (!fp) { - PR_Free(tmpfilename); - return 0; - } - - sprintf(separator, "---------------------------%d%d%d", - rand(), rand(), rand()); - - if(url_struct->post_headers) - { - len = NET_XP_FileWrite(url_struct->post_headers, - PL_strlen (url_struct->post_headers), - fp); - PR_Free (url_struct->post_headers); - url_struct->post_headers = 0; - if (len < 0) - return 0; - } - - sprintf(buffer, - "Content-type: multipart/form-data;" - " boundary=%s" CRLF, - separator); - len = NET_XP_FileWrite(buffer, PL_strlen(buffer), fp); - -#define CONTENT_DISPOSITION "Content-Disposition: form-data; name=\"" -#define PLUS_FILENAME "\"; filename=\"" -#define CONTENT_TYPE_HEADER "Content-Type: " -#define CONTENT_ENCODING_HEADER "Content-Encoding: " - - /* compute the content length */ - total_size = -2; /* start at negative 2 to disregard the - * CRLF that act as a header separator - */ - boundary_len = PL_strlen(separator) + 6; - cont_disp_len = PL_strlen(CONTENT_DISPOSITION); - - for(i=0; (len >= 0) && (i < sub_data->value_cnt); i++) - { - total_size += boundary_len; - - /* The size of the content-disposition line is hard - * coded and must be modified any time you change - * the sprintf in the next for loop - */ - total_size += cont_disp_len; - if(name_array[i]) - total_size += PL_strlen(name_array[i]); - total_size += 5; /* quote plus two CRLF's */ - - if(type_array[i] == FORM_TYPE_FILE) - { - XP_StatStruct stat_entry; - - /* in this case we are going to send an extra - * ; filename="value_array[i]" - */ - total_size += PL_strlen(PLUS_FILENAME); - if(value_array[i]) - { - /* only write the filename, not the whole path */ - char * slash = PL_strrchr(value_array[i], '/'); - if(slash) - slash++; - else - slash = value_array[i]; - total_size += PL_strlen(slash); - -#ifdef XP_MAC - if(encoding_array[i] == INPUT_TYPE_ENCODING_MACBIN) - { - /* add the size of the content type header */ - /* NOTE - even though MacBinary is technically an encoding type we send - it as a content type and skip the normal routine of trying - to determine the actual file type - */ - total_size += sizeof(CONTENT_TYPE_HEADER)-1; - total_size += sizeof(APPLICATION_MACBINARY)-1; - total_size += 2; /* for the CRLF terminator */ - } - else -#endif /* XP_MAC */ - { - - /* try and determine the content-type of the file - */ - ctype = NET_cinfo_find_type(value_array[i]); - - if(!ctype->is_default) - { - /* we have determined it's type. Add enough - * space for it - */ - total_size += sizeof(CONTENT_TYPE_HEADER)-1; - total_size += PL_strlen(ctype->type); - total_size += 2; /* for the CRLF terminator */ - } - } - } -#ifdef XP_MAC - if(encoding_array[i] == INPUT_TYPE_ENCODING_MACBIN) - { - /* figure out the size of the macbinary encoded file - * and add it to total_size - */ - if(value_array[i] && *value_array[i]) - if(-1 != MB_Stat (value_array[i], &stat_entry, xpFileToPost)) - total_size += stat_entry.st_size; - } - else -#endif /* XP_MAC */ - { - /* if the type is a FILE type then we - * need to stat the file to get the size - */ - if(value_array[i] && *value_array[i]) - if(-1 != NET_XP_Stat (value_array[i], &stat_entry, xpFileToPost)) - total_size += stat_entry.st_size; - - /* if we can't stat the file just add zero */ - } - } - else - { - if(value_array[i]) - total_size += PL_strlen(value_array[i]); - } - } - /* add the size of the last separator plus - * two for the extra two dashes - */ - total_size += boundary_len+2; - - sprintf(buffer, "Content-Length: %ld%s", total_size, CRLF); - len = NET_XP_FileWrite(buffer, PL_strlen(buffer), fp); - - for(i=0; (len >= 0) && (i < sub_data->value_cnt); i++) - { - sprintf(buffer, "%s--%s%s", CRLF, separator, CRLF); - NET_XP_FileWrite(buffer, PL_strlen(buffer), fp); - - /* WARNING!!! If you change the size of any of the - * sprintf's here you must change the size - * in the counting for loop above - */ - NET_XP_FileWrite(CONTENT_DISPOSITION, cont_disp_len, fp); - if(name_array[i]) - NET_XP_FileWrite(name_array[i], PL_strlen(name_array[i]), fp); - - if(type_array[i] == FORM_TYPE_FILE) - { - NET_XP_FileWrite(PLUS_FILENAME, PL_strlen(PLUS_FILENAME), fp); - if(value_array[i]) - { - /* only write the filename, not the whole path */ - char * slash = PL_strrchr(value_array[i], '/'); - if(slash) - slash++; - else - slash = value_array[i]; - NET_XP_FileWrite(slash, PL_strlen(slash), fp); - - } - } - /* end the content disposition line */ - len = NET_XP_FileWrite("\"" CRLF, PL_strlen("\"" CRLF), fp); - - if(type_array[i] == FORM_TYPE_FILE && value_array[i]) - { -#ifdef XP_MAC - if(encoding_array[i] == INPUT_TYPE_ENCODING_MACBIN) - { - /* add the content_type header */ - NET_XP_FileWrite(CONTENT_TYPE_HEADER, - PL_strlen(CONTENT_TYPE_HEADER), - fp); - NET_XP_FileWrite(APPLICATION_MACBINARY, - PL_strlen(APPLICATION_MACBINARY), - fp); - len = NET_XP_FileWrite(CRLF, PL_strlen(CRLF), fp); - } - else -#endif /* XP_MAC */ - { - /* try and determine the content-type of the file - */ - ctype = NET_cinfo_find_type(value_array[i]); - - if(!ctype->is_default) - { - /* we have determined it's type. Send the - * content-type - */ - NET_XP_FileWrite(CONTENT_TYPE_HEADER, - PL_strlen(CONTENT_TYPE_HEADER), - fp); - NET_XP_FileWrite(ctype->type, - PL_strlen(ctype->type), - fp); - len = NET_XP_FileWrite(CRLF, PL_strlen(CRLF), fp); - } - } - } - - /* end the header */ - len = NET_XP_FileWrite(CRLF, PL_strlen(CRLF), fp); - - /* send the value of the form field */ - - /* if the type is a FILE type, send the whole file, - * the filename is in the value field - */ - if(type_array[i] == FORM_TYPE_FILE) - { -#ifdef XP_MAC - if(encoding_array[i] == INPUT_TYPE_ENCODING_MACBIN) - { - MB_FileSpec mbFile; - int32 size; - OSErr theErr; - - if (value_array[i] && *value_array[i]) - { - theErr = MB_Open(value_array[i], &mbFile); - - if (theErr == noErr) - { - while((size = MB_Read(NET_Socket_Buffer, - NET_Socket_Buffer_Size, - &mbFile)) != 0) - { - NET_XP_FileWrite(NET_Socket_Buffer, size, fp); - } - MB_Close(&mbFile); - } - } - } - else -#endif /* XP_MAC */ - { - XP_File ext_fp=0; - int32 size; - - if(value_array[i] && *value_array[i]) - ext_fp = NET_XP_FileOpen(value_array[i], - xpFileToPost, - XP_FILE_READ_BIN); - - - if(ext_fp) - { - while((size = NET_XP_FileRead(NET_Socket_Buffer, - NET_Socket_Buffer_Size, - ext_fp)) != 0) - { - NET_XP_FileWrite(NET_Socket_Buffer, size, fp); - } - NET_XP_FileClose(ext_fp); - } - } - } - else - { - if(value_array[i]) - NET_XP_FileWrite(value_array[i], PL_strlen(value_array[i]), fp); - } - } - - sprintf(buffer, "%s--%s--%s", CRLF, separator, CRLF); - NET_XP_FileWrite(buffer, PL_strlen(buffer), fp); - - NET_XP_FileClose(fp); - - StrAllocCopy(url_struct->post_data, tmpfilename); - PR_Free(tmpfilename); - url_struct->post_data_is_file = TRUE; - - } - else - { - total_size=1; /* start at one for the terminator char */ - - /* find out how much space we need total - * - * and also convert all spaces to pluses at the same time - */ - for(i=0; i<sub_data->value_cnt; i++) - { - total_size += NET_EscapedSize(name_array[i], URL_XPALPHAS); - total_size += NET_EscapedSize(value_array[i], URL_XPALPHAS); - total_size += 2; /* & = */ - } - - if(sub_data->method == FORM_METHOD_GET) - { - char *punc; - - if(!url_struct->address) - return(0); - - /* get rid of ? or # in the url string since we are adding it - */ - punc = PL_strchr(url_struct->address, '?'); - if(punc) - *punc = '\0'; /* terminate here */ - punc = PL_strchr(url_struct->address, '#'); - if(punc) - *punc = '\0'; /* terminate here */ - - /* add the size of the url plus one for the '?' - */ - total_size += PL_strlen(url_struct->address)+1; - } - - url_struct->post_data = (char *) PR_Malloc(total_size); - - if(!url_struct->post_data) - { - PA_UNLOCK(sub_data->name_array); - PA_UNLOCK(sub_data->value_array); - PA_UNLOCK(sub_data->type_array); - PA_UNLOCK(sub_data->encoding); - return(0); - } - - if(sub_data->method == FORM_METHOD_GET) - { - end = url_struct->post_data; - for(tmp_ptr = url_struct->address; *tmp_ptr != '\0'; tmp_ptr++) - *end++ = *tmp_ptr; - - /* add the '?' - */ - *end++ = '?'; - - /* swap the post data and address data */ - FREE(url_struct->address); - url_struct->address = url_struct->post_data; - url_struct->post_data = 0; - - /* perform hack: - * To be compatible with old pre-form - * indexes, other web browsers had a hack - * wherein if a form was being submitted, - * and its method was get, and it - * had only one name/value pair, and the - * name of that pair was "isindex", then - * it would create the query url - * - * URL?value instead of URL?name=value - */ - if(sub_data->value_cnt == 1 && !PL_strcasecmp(name_array[0], "isindex")) - { - if(value_array && value_array[0]) - PL_strcpy(end, NET_Escape(value_array[0], URL_XPALPHAS)); - else - *end = '\0'; - PA_UNLOCK(sub_data->name_array); - PA_UNLOCK(sub_data->value_array); - PA_UNLOCK(sub_data->type_array); - PA_UNLOCK(sub_data->encoding); - return(1); - } - - /* the end ptr is still set to the correct address! - */ - - } - else - { - StrAllocCat(url_struct->post_headers, - "Content-type: application/x-www-form-urlencoded" CRLF); - - if(!url_struct->post_headers) - { - FREE_AND_CLEAR(url_struct->post_data); - PA_UNLOCK(sub_data->name_array); - PA_UNLOCK(sub_data->value_array); - PA_UNLOCK(sub_data->type_array); - PA_UNLOCK(sub_data->encoding); - return(0); - } - - end = url_struct->post_data; - - } - - /* build the string - */ - for(i=0; i<sub_data->value_cnt; i++) - { - /* add the name - */ - esc_string = NET_Escape(name_array[i], URL_XPALPHAS); - if(esc_string) - { - for(tmp_ptr = esc_string; *tmp_ptr != '\0'; tmp_ptr++) - *end++ = *tmp_ptr; - PR_Free(esc_string); - } - - /* join the name and value with a '=' - */ - *end++ = '='; - - /* add the value - */ - esc_string = NET_Escape(value_array[i], URL_XPALPHAS); - if(esc_string) - { - for(tmp_ptr = esc_string; *tmp_ptr != '\0'; tmp_ptr++) - *end++ = *tmp_ptr; - PR_Free(esc_string); - } - - /* join pairs with a '&' - * make sure there is another pair before adding - */ - if(i+1 < sub_data->value_cnt) - *end++ = '&'; - } - - /* terminate the string - */ - *end = '\0'; - - if(sub_data->method == FORM_METHOD_POST) - { - char buffer[64]; - url_struct->post_data_size = PL_strlen(url_struct->post_data); - sprintf(buffer, - "Content-length: %ld" CRLF, - url_struct->post_data_size); - StrAllocCat(url_struct->post_headers, buffer); - -#ifdef ADD_EXTRA_CRLF_TO_POSTS - /* munge for broken CGIs. Add an extra CRLF to the - * post data. - */ - BlockAllocCat(url_struct->post_data, - url_struct->post_data_size, - CRLF, - 3); - /* don't add the eol terminator */ - url_struct->post_data_size += 2; -#endif /* ADD_EXTRA_CRLF_TO_POSTS */ - - } - } - - PA_UNLOCK(sub_data->name_array); - PA_UNLOCK(sub_data->value_array); - PA_UNLOCK(sub_data->type_array); - PA_UNLOCK(sub_data->encoding); - - return(1); /* success */ -#endif - return 0; -} - -PUBLIC int -NET_AddCoordinatesToURLStruct(URL_Struct * url_struct, int32 x_coord, int32 y_coord) -{ - - if(url_struct->address) - { - char buffer[32]; - - sprintf(buffer, "?%ld,%ld", x_coord, y_coord); - - /* get rid of ? or # in the url string since we are adding it - */ -#undef STRIP_SEARCH_DATA_FROM_ISMAP_URLS -#ifdef STRIP_SEARCH_DATA_FROM_ISMAP_URLS - { - char *punc; - punc = PL_strchr(url_struct->address, '?'); - if(punc) - *punc = '\0'; /* terminate here */ - punc = PL_strchr(url_struct->address, '#'); - if(punc) - *punc = '\0'; /* terminate here */ - } -#endif /* STRIP_SEARCH_DATA_FROM_ISMAP_URLS */ - - StrAllocCat(url_struct->address, buffer); - } - - return(1); /* success */ -} - -/* FREE_AND_CLEAR will free a pointer if it is non-zero and - * then set it to zero - */ -MODULE_PRIVATE void -NET_f_a_c (char **pointer) -{ - if(*pointer) { - PR_Free(*pointer); - *pointer = 0; - } -} - -/* recognizes URLs and their types. Returns 0 (zero) if - * it is unrecognized. - */ -PUBLIC int -NET_URL_Type (CONST char *URL) -{ - /* Protect from SEGV */ - /* Rhapsody compiler needed to break up this || statement into two if's. */ - if (!URL) - return(0); - if (URL && *URL == '\0') - return(0); - - switch(*URL) { - case 'a': - case 'A': - HG83787 - if(!PL_strncasecmp(URL,"about:",6)) - return(ABOUT_TYPE_URL); - else if(!PL_strncasecmp(URL,"addbook:",8)) - return(ADDRESS_BOOK_TYPE_URL); - else if (!PL_strncasecmp(URL, "addbook-ldap", 12)) /*no colon includes addbook-ldaps:*/ - return(ADDRESS_BOOK_LDAP_TYPE_URL); - break; - - case 'd': - case 'D': - if(!PL_strncasecmp(URL,"data:",5)) - return(DATA_TYPE_URL); - break; - - case 'c': - case 'C': - if(!PL_strncasecmp(URL,"castanet:",9)) - return(0); - break; - - case 'f': - case 'F': - if(!PL_strncasecmp(URL,"ftp:",4)) - return(FTP_TYPE_URL); - else if(!PL_strncasecmp(URL,"file:",5)) - return(FILE_TYPE_URL); - break; - case 'g': - case 'G': - if(!PL_strncasecmp(URL,"gopher:",7)) - return(GOPHER_TYPE_URL); - break; - case 'h': - case 'H': - if(!PL_strncasecmp(URL,"http:",5)) - return(HTTP_TYPE_URL); - HG73678 - break; - case 'i': - case 'I': - if(!PL_strncasecmp(URL,"internal-gopher-",16)) - return(INTERNAL_IMAGE_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-news-",14)) - return(INTERNAL_IMAGE_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-edit-",14)) - return(INTERNAL_IMAGE_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-attachment-",20)) - return(INTERNAL_IMAGE_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-sa-",12)) - return(INTERNAL_IMAGE_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-smime-",15)) - return(INTERNAL_IMAGE_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-dialog-handler",23)) - return(HTML_DIALOG_HANDLER_TYPE_URL); - else if(!PL_strncasecmp(URL,"internal-panel-handler",22)) - return(HTML_PANEL_HANDLER_TYPE_URL); - HG84378 - else if(!PL_strncasecmp(URL,"IMAP:",5)) - return(IMAP_TYPE_URL); - break; - case 'j': - case 'J': - if(!PL_strncasecmp(URL, "javascript:",11)) - return(MOCHA_TYPE_URL); - break; - case 'l': - case 'L': - if(!PL_strncasecmp(URL, "livescript:",11)) - return(MOCHA_TYPE_URL); - else if (!PL_strncasecmp(URL, "ldap:",5)) - return(LDAP_TYPE_URL); - HG84772 - break; - case 'm': - case 'M': - if(!PL_strncasecmp(URL,"mailto:",7)) - return(MAILTO_TYPE_URL); - else if(!PL_strncasecmp(URL,"mailbox:",8)) - return(MAILBOX_TYPE_URL); - else if(!PL_strncasecmp(URL, "mocha:",6)) - return(MOCHA_TYPE_URL); - break; - case 'n': - case 'N': - if(!PL_strncasecmp(URL,"news:",5)) - return(NEWS_TYPE_URL); - else if(!PL_strncasecmp(URL,"nfs:",4)) - return(NFS_TYPE_URL); - else if(!PL_strncasecmp(URL, NETHELP_URL_PREFIX, sizeof(NETHELP_URL_PREFIX)-1)) - return(NETHELP_TYPE_URL); - break; - case 'p': - case 'P': - if(!PL_strncasecmp(URL,"pop3:",5)) - return(POP3_TYPE_URL); - break; - case 'r': - case 'R': - if(!PL_strncasecmp(URL,"rlogin:",7)) - return(RLOGIN_TYPE_URL); - break; - case 's': - case 'S': - if(!PL_strncasecmp(URL,"sockstub:",9)) - return(SOCKSTUB_TYPE_URL); - else if(!PL_strncasecmp(URL,"snews:",6)) - return(NEWS_TYPE_URL); - else if (!PL_strncasecmp(URL,"search-libmsg:",14)) - return(MSG_SEARCH_TYPE_URL); - case 't': - case 'T': - if(!PL_strncasecmp(URL,"telnet:",7)) - return(TELNET_TYPE_URL); - else if(!PL_strncasecmp(URL,"tn3270:",7)) - return(TN3270_TYPE_URL); - break; - case 'u': - case 'U': - if(!PL_strncasecmp(URL,"URN:",4)) - return(URN_TYPE_URL); - break; - case 'v': - case 'V': - if(!PL_strncasecmp(URL, VIEW_SOURCE_URL_PREFIX, - sizeof(VIEW_SOURCE_URL_PREFIX)-1)) - return(VIEW_SOURCE_TYPE_URL); - break; - case 'w': - case 'W': - if(!PL_strncasecmp(URL,"wais:",5)) - return(WAIS_TYPE_URL); - if(!PL_strncasecmp(URL,"wysiwyg:",8)) - return(WYSIWYG_TYPE_URL); - break; - } - - /* no type match :( */ - return(0); -} - -PUBLIC void -NET_PlusToSpace(char *str) -{ - for (; *str != '\0'; str++) - if (*str == '+') - *str = ' '; -} - -/* if the url is a local file this function returns - * the portion of the url that represents the - * file path as a malloc'd string. If the - * url is not a local file url this function - * returns NULL - */ -PRIVATE char * -net_return_local_file_part_from_url(char *address) -{ - char *host; -#ifdef XP_WIN - char *new_address; - char *rv; -#endif - - if (address == NULL) - return NULL; - - /* imap urls are never local */ - if (!PL_strncasecmp(address,"mailbox://",10)) - return NULL; - - /* mailbox url's are always local, but don't always point to a file */ - if(!PL_strncasecmp(address, "mailbox:", 8)) - { - char *filename = NET_ParseURL(address, GET_PATH_PART); - if (!filename) - filename = PL_strdup(""); - return filename; - } - - if(PL_strncasecmp(address, "file:", 5)) - return(NULL); - - host = NET_ParseURL(address, GET_HOST_PART); - - if(!host || *host == '\0' || !PL_strcasecmp(host, "LOCALHOST")) - { - PR_FREEIF(host); - return(NET_UnEscape(NET_ParseURL(address, GET_PATH_PART))); - } - -#ifdef XP_WIN - /* get the address minus the search and hash data */ - new_address = NET_ParseURL(address, - GET_PROTOCOL_PART | GET_HOST_PART | GET_PATH_PART); - NET_UnEscape(new_address); - - /* check for local drives as hostnames - */ - if(PL_strlen(host) == 2 - && isalpha(host[0]) - && (host[1] == '|' || host[1] == ':')) - { - PR_Free(host); - /* skip "file:/" */ - rv = PL_strdup(new_address+6); - PR_Free(new_address); - return(rv); - } - - if(1) - { - XP_StatStruct stat_entry; - /* try stating the url just in case since - * the local file system can - * have url's of the form \\prydain\dist - */ - if(-1 != NET_XP_Stat(address+5, &stat_entry, xpURL)) - { - PR_Free(host); - /* skip "file:" */ - rv = PL_strdup(address+5); - PR_Free(new_address); - return(rv); - } - } -#endif /* XP_WIN */ - - PR_Free(host); - - return(NULL); -} - -/* returns TRUE if the url is a local file - * url - */ -PUBLIC XP_Bool -NET_IsLocalFileURL(char *address) -{ - char * cp = net_return_local_file_part_from_url(address); - - if(cp) - { - PR_Free(cp); - return(TRUE); - } - else - { - return(FALSE); - } -} - -static int -net_buffer_output_fn ( const char *buf, int32 size, void *closure) -{ - BufferStruct *bs = (BufferStruct *) closure; - /* if the size greater or equal to the available buffer size - * reallocate the buffer - */ - PR_ASSERT (buf && bs && size > 0); - if ( !buf || !bs || size <= 0 ) - return -1; - - if (size >= bs->size - bs->pos) - { - int32 len; - char *newBuffer; - - len = (bs->size << 1) - bs->pos + size + 1; /* null terminated */ - if (bs->buffer) - newBuffer = PR_Realloc (bs->buffer, len); - else - newBuffer = PR_Malloc(len); - if (!newBuffer) - return MK_OUT_OF_MEMORY; - memset(newBuffer+bs->pos, 0, len-bs->pos); - bs->size = len; - bs->buffer = newBuffer; - } - memcpy (bs->buffer+bs->pos, buf, size); - bs->pos += size; - return 0; -} - -PRIVATE int32 -net_URNProtoLoad(ActiveEntry *ce) -{ - char buffer[256]; - - PL_strcpy(buffer, XP_GetString(XP_ALERT_URN_USEHTTP)); - PL_strncat(buffer, ce->URL_s->address, 150); - buffer[255] = '\0'; /* in case strncat doesn't add one */ - FE_Alert(ce->window_id, buffer); - - return -1; -} - -PRIVATE int32 -net_URNProtoStub(ActiveEntry *ce) -{ - PR_ASSERT(0); - return -1; -} - -PRIVATE void -net_URNProtoCleanupStub(void) -{ -} - -/* a stub function for URN protocol converter. - * right now we only proxy URN's - * if URN's ever get worked on move this to another file - */ -PUBLIC void -NET_InitURNProtocol(void) -{ - static NET_ProtoImpl urn_proto_impl; - - urn_proto_impl.init = net_URNProtoLoad; - urn_proto_impl.process = net_URNProtoStub; - urn_proto_impl.interrupt = net_URNProtoStub; - urn_proto_impl.resume = NULL; - urn_proto_impl.cleanup = net_URNProtoCleanupStub; - - NET_RegisterProtocolImplementation(&urn_proto_impl, URN_TYPE_URL); -} - -PRIVATE int32 -net_NFSProtoLoad(ActiveEntry *ce) -{ - char buffer[256]; - - PL_strcpy(buffer, XP_GetString(XP_ALERT_NFS_USEHTTP)); - PL_strncat(buffer, ce->URL_s->address, 150); - buffer[255] = '\0'; /* in case strncat doesn't add one */ - FE_Alert(ce->window_id, buffer); - - return -1; -} - -PRIVATE int32 -net_NFSProtoStub(ActiveEntry *ce) -{ - PR_ASSERT(0); - return -1; -} - -PRIVATE void -net_NFSProtoCleanupStub(void) -{ -} - -/* a stub function for NFS protocol converter. - * right now we only proxy NFS's - * if NFS's ever get worked on move this to another file - */ -PUBLIC void -NET_InitNFSProtocol(void) -{ - static NET_ProtoImpl nfs_proto_impl; - - nfs_proto_impl.init = net_NFSProtoLoad; - nfs_proto_impl.process = net_NFSProtoStub; - nfs_proto_impl.interrupt = net_NFSProtoStub; - nfs_proto_impl.resume = NULL; - nfs_proto_impl.cleanup = net_NFSProtoCleanupStub; - - NET_RegisterProtocolImplementation(&nfs_proto_impl, NFS_TYPE_URL); -} - -PRIVATE int32 -net_WAISProtoLoad(ActiveEntry *ce) -{ - char * alert = NET_ExplainErrorDetails(MK_NO_WAIS_PROXY); - - FE_Alert(ce->window_id, alert); - FREE(alert); - - return -1; -} - -PRIVATE int32 -net_WAISProtoStub(ActiveEntry *ce) -{ - PR_ASSERT(0); - return -1; -} - -PRIVATE void -net_WAISProtoCleanupStub(void) -{ -} - -/* a stub function for WAIS protocol converter. - * right now we only proxy WAIS's - * if WAIS's ever get worked on move this to another file - */ -PUBLIC void -NET_InitWAISProtocol(void) -{ - static NET_ProtoImpl wais_proto_impl; - - wais_proto_impl.init = net_WAISProtoLoad; - wais_proto_impl.process = net_WAISProtoStub; - wais_proto_impl.interrupt = net_WAISProtoStub; - wais_proto_impl.resume = NULL; - wais_proto_impl.cleanup = net_WAISProtoCleanupStub; - - NET_RegisterProtocolImplementation(&wais_proto_impl, WAIS_TYPE_URL); -} -#if defined(OLD_MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) - -PUBLIC char * -NET_Base64Encode (char *src, int32 srclen) -{ - BufferStruct bs; - MimeEncoderData *encoder_data = NULL; - - PR_ASSERT (src); - if (!src) - return NULL; - else if (srclen == 0) - return PL_strdup(""); - - memset (&bs, 0, sizeof (BufferStruct)); - encoder_data = MimeB64EncoderInit(net_buffer_output_fn, (void *) &bs); - if (!encoder_data) - return NULL; - - if (MimeEncoderWrite(encoder_data, src, srclen) < 0) - { - MimeEncoderDestroy(encoder_data, FALSE); - PR_FREEIF(bs.buffer); - return NULL; - } - - MimeEncoderDestroy(encoder_data, FALSE); - /* caller must free the returned pointer to prevent - * memory leak problem. - */ - return bs.buffer; -} - - - -PUBLIC char * -NET_Base64Decode (char *src, - int32 srclen) -{ - BufferStruct bs; - MimeDecoderData *decoder_data = NULL; - - PR_ASSERT (src); - if (!src) - return NULL; - else if (srclen == 0) - return PL_strdup(""); - - memset (&bs, 0, sizeof (BufferStruct)); - decoder_data = MimeB64DecoderInit(net_buffer_output_fn, (void *) &bs); - if (!decoder_data) - return NULL; - - if (MimeDecoderWrite(decoder_data, src, srclen) < 0) - { - MimeDecoderDestroy(decoder_data, FALSE); - PR_FREEIF(bs.buffer); - return NULL; - } - - MimeDecoderDestroy(decoder_data, FALSE); - /* caller must free the returned pointer to prevent - * memory leak problem. - */ - return bs.buffer; -} - -#endif /* OLD_MOZ_MAIL_NEWS || MOZ_MAIL_COMPOSE */ - -/* A utility function to fetch a file from cache right away, - * and update it (from the original server) after its used. - * Used in/Required by Mr. R.D.F. Guha - * - * Note that if the item is not in the cache, this defaults - * to retrieving it from the server. - * - * Variables and returns : see NET_GetURL in include/net.h - * - * Warning: Possibility of a stale copy! - * - */ -PUBLIC int -NET_GetURLQuick (URL_Struct * URL_s, - FO_Present_Types output_format, - MWContext * context, - Net_GetUrlExitFunc* exit_routine) -{ -#ifdef NU_CACHE - if (!CacheManager_Contains(URL_s->address)) -#else - if (!NET_FindURLInMemCache(URL_s, context) && - !NET_FindURLInExtCache(URL_s, context)) -#endif - { - /* default */ - return NET_GetURL( - URL_s, - output_format, - context, - exit_routine); - } - else - { - /* Only from cache */ - int status = - NET_GetURL( - URL_s, - FO_ONLY_FROM_CACHE || output_format, - context, - exit_routine); - - /* Update request */ - NET_GetURL( - URL_s, - FO_CACHE_ONLY, - context, - NULL); - - return status; - } -} - - diff --git a/mozilla/network/main/mkutils.h b/mozilla/network/main/mkutils.h deleted file mode 100644 index fb7ad86ff82..00000000000 --- a/mozilla/network/main/mkutils.h +++ /dev/null @@ -1,157 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKUTILS_H -#define MKUTILS_H - -#include "net.h" -#include "xp.h" /* The cross-platform API */ -#include "plstr.h" -#include "prlog.h" -#include "prmem.h" -#include "mktrace.h" -#include "mkselect.h" /* needed by all files in netlib */ - -/* Used throughout netlib. */ -#ifndef MAXHOSTNAMELEN -#define MAXHOSTNAMELEN 64 -#endif - -#define CONST const /* "const" only exists in STDC? */ - -#include <stdlib.h> -#include <stdio.h> -#include <ctype.h> -#ifdef XP_UNIX -#include <unistd.h> -#include <signal.h> -#endif /* XP_UNIX */ -/*#include "version.h"*/ - -#define FREE_AND_CLEAR(x) NET_f_a_c(&x) - -PR_BEGIN_EXTERN_C - -PUBLIC void -NET_SetDNSExpirationPref(int32 n); -MODULE_PRIVATE int PR_CALLBACK -NET_DNSExpirationPrefChanged(const char * newpref, void * data); - -extern int NET_URL_Type (CONST char *URL); -extern void del_front_spaces (char *string); -extern void NET_f_a_c (char **obj); - -/* - * This function takes an error code and associated error data - * and creates a string containing a textual description of - * what the error is and why it happened. - * - * The returned string is allocated and thus should be freed - * once it has been used. - * - * This function is defined in mkmessag.c. - */ -extern char * NET_ExplainErrorDetails (int code, ...); - -/* Find an Author's mail address - * - * THE EMAIL ADDRESS IS CORRUPTED - * - * For example, returns "montulli@netscape.com" if given any of - * " Lou Montullism <montulli@netscape.com> " - * or " montulli@netscape.com ( Lou "The Stud :)" Montulli ) " - * or "montulli@netscape.com" -*/ -extern char * NET_EmailAddress (char *email); - -extern char * NET_SpaceToPlus(char * string); - -/* try to make sure that this is a fully qualified - * email address including a host and domain - */ -extern Bool NET_IsFQDNMailAddress(const char * string); - -/* -#define AUTH_SKEY_DEFINED -*/ -#ifdef AUTH_SKEY_DEFINED -/* MD4 SKEY 64-bit password crunching and hashing function - * see skey.h for more details information. - */ -extern int keycrunch(char *result, char *seed, char *passwd); -extern void f(char *x); -#endif - -/* returns Base64 encoded string - * caller must free - */ -extern char * NET_Base64Encode(char *src, int32 srclen); - -/* returns Base64 decoded string - * caller must free - */ -extern char * NET_Base64Decode(char *src, int32 srclen); - -/* a stub function for URN protocol converter. - * right now we only proxy URN's - * if URN's ever get worked on move this to another file - */ -extern void NET_InitURNProtocol(void); - -/* a stub function for NFS protocol converter. - * right now we only proxy NFS's - * if NFS ever gets worked on move this to another file - */ -extern void NET_InitNFSProtocol(void); - -/* a stub function for WAIS protocol converter. - * right now we only proxy WAIS - * if WAIS ever gets worked on move this to another file - */ -extern void NET_InitWAISProtocol(void); - -PR_END_EXTERN_C -#ifndef FREE -#define FREE(obj) PR_Free(obj) -#endif -#ifndef FREEIF -#define FREEIF(obj) {if(obj) {PR_Free(obj); obj=0;}} -#endif - -/* A utility function to fetch a file from cache right away, - * and update it (from the original server) after its used. - * Used in/Required by Mr. R.D.F. Guha - * - * Note that if the item is not in the cache, this defaults - * to retrieving it from the server. - * - * Variables and returns : see NET_GetURL in include/net.h - * - */ -extern int -NET_GetURLQuick (URL_Struct * URL_s, - FO_Present_Types output_format, - MWContext * context, - Net_GetUrlExitFunc* exit_routine); - -#endif /* MKUTILS_H */ - - diff --git a/mozilla/network/main/net_xp_file.h b/mozilla/network/main/net_xp_file.h deleted file mode 100644 index a838ba179f8..00000000000 --- a/mozilla/network/main/net_xp_file.h +++ /dev/null @@ -1,97 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "xp_file.h" - -#ifndef _net_xp_file_h -#define _net_xp_file_h - - -/* The puropse of this file is simply to add a level of abstraction between netlib - * and the XP_File* api. */ - -#if defined(NS_NET_FILE) - -extern int NET_I_XP_Stat(const char * name, XP_StatStruct * outStat, XP_FileType type); -#define NET_XP_Stat(name, out, type) NET_I_XP_Stat(name, out, type) - -extern XP_Dir NET_I_XP_OpenDir(const char * name, XP_FileType type); -#define NET_XP_OpenDir(name, type) NET_I_XP_OpenDir(name, type) - -extern void NET_I_XP_CloseDir(XP_Dir dir); -#define NET_XP_CloseDir(dir) NET_I_XP_CloseDir(dir) - -extern XP_DirEntryStruct *NET_I_XP_ReadDir(XP_Dir dir); -#define NET_XP_ReadDir(dir) NET_I_XP_ReadDir(dir) - -extern int NET_I_XP_Fileno(XP_File fp); -#define NET_XP_Fileno(fp) NET_I_XP_Fileno(fp) - -extern int NET_I_XP_FileSeek(XP_File file, long offset, int origin); -#define NET_XP_FileSeek(file,offset,whence) NET_I_XP_FileSeek ((file), (offset), (whence)) - -extern XP_File NET_I_XP_FileOpen(const char *name, XP_FileType type, const XP_FilePerm perm); -#define NET_XP_FileOpen(name, type, perm) NET_I_XP_FileOpen(name, type, perm) - -extern int NET_I_XP_FileRead(char *outBuf, int outBufLen, XP_File fp); -#define NET_XP_FileRead(dest, count, file) NET_I_XP_FileRead(dest, count, file) - -extern char *NET_I_XP_FileReadLine(char *outBuf, int outBufLen, XP_File fp); -#define NET_XP_FileReadLine(destBuf, bufSize, file) NET_I_XP_FileReadLine(destBuf, bufSize, file) - -extern int NET_I_XP_FileWrite(char *buf, int bufLen, XP_File fp); -#define NET_XP_FileWrite(source, count, file) NET_I_XP_FileWrite(source, count, file) - -extern int NET_I_XP_FileClose(XP_File file); -#define NET_XP_FileClose(fp) NET_I_XP_FileClose(fp) - -extern int NET_I_XP_FileRemove(const char * name, XP_FileType type); -#define NET_XP_FileRemove(name, type) NET_I_XP_FileRemove(name, type) - -#else - -#define NET_XP_Stat(name, outStat, type) XP_Stat(name, outStat, type) - -#define NET_XP_OpenDir(name, type) XP_OpenDir(name, type) - -#define NET_XP_CloseDir(dir) XP_CloseDir(dir) - -#define NET_XP_ReadDir(dir) XP_ReadDir(dir) - -#define NET_XP_Fileno(fp) XP_Fileno(fp) - -#define NET_XP_FileSeek(file,offset,whence) XP_FileSeek ((file), (offset), (whence)) - -#define NET_XP_FileOpen(name, type, perm) XP_FileOpen(name, type, perm) - -#define NET_XP_FileRead(dest,count,file) XP_FileRead(dest,count,file) - -#define NET_XP_FileReadLine(destBuf, bufSize, file) XP_FileReadLine(destBuf, bufSize, file) - -#define NET_XP_FileWrite(source, count, file) XP_FileWrite(source, count, file) - -#define NET_XP_FileClose(fp) XP_FileClose(fp) - -#define NET_XP_FileRemove(name, type) XP_FileRemove(name, type) -#endif /* NS_NET_FILE */ - -#endif /* _net_xp_file_h */ diff --git a/mozilla/network/main/netstream.h b/mozilla/network/main/netstream.h deleted file mode 100644 index fdbe87101b1..00000000000 --- a/mozilla/network/main/netstream.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef NETSTREAM_H -#define NETSTREAM_H - -typedef struct _NET_VoidStreamClass NET_VoidStreamClass; - -NET_VoidStreamClass * NET_VoidStreamBuilder(FO_Present_Types format_out, - URL_Struct * anchor, - MWContext * window_id); - -NET_VoidStreamClass * NET_CStreamToVoidStream(void *cstream); - -uint32 NET_StreamIsWriteReady(NET_VoidStreamClass *stream); - -int32 NET_StreamPutBlock(NET_VoidStreamClass *stream, char *block, int32 l); - -void NET_StreamComplete(NET_VoidStreamClass *stream); - -void NET_StreamAbort(NET_VoidStreamClass *stream, int32 status); - -char * NET_StreamName(NET_VoidStreamClass *stream); - -int NET_SetStreamData(NET_VoidStreamClass *stream, void *data); -void * NET_GetStreamData(NET_VoidStreamClass *stream); - -void NET_StreamFree(NET_VoidStreamClass *stream); - -#endif /* NETSTREAM.h */ diff --git a/mozilla/network/main/netutils.h b/mozilla/network/main/netutils.h deleted file mode 100644 index 74041c6b598..00000000000 --- a/mozilla/network/main/netutils.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef NETUTILS_H -#define NETUTILS_H - -/* Keep TRACEMSG consistant throughout libnet */ -#include "mktrace.h" - -/* Used throughout netlib. */ -#ifndef MAXHOSTNAMELEN -#define MAXHOSTNAMELEN 64 -#endif - -#ifndef CONST -#define CONST const -#endif - -PR_BEGIN_EXTERN_C - -/* - * This function takes an error code and associated error data - * and creates a string containing a textual description of - * what the error is and why it happened. - * - * The returned string is allocated and thus should be freed - * once it has been used. - * - * This function is defined in mkmessag.c. - */ -extern char * NET_ExplainErrorDetails (int code, ...); - -extern void NET_Progress(MWContext *context, char *msg); - -/* returns true if the functions thinks the string contains - * HTML - */ -extern PRBool NET_ContainsHTML(char * string, int32 length); - -extern void NET_ParseContentTypeHeader(MWContext *context, char *value, - URL_Struct *URL_s, PRBool is_http); - -typedef struct WritePostDataData WritePostDataData; -extern void NET_free_write_post_data_object(struct WritePostDataData *obj); - -/* this function is called repeatably to write - * the post data body onto the network. - * - * Returns negative on fatal error - * Returns zero when done - * Returns positive if not yet completed - */ -extern int -NET_WritePostData(MWContext *context, - URL_Struct *URL_s, - PRFileDesc *sock, - void **write_post_data_data, - PRBool add_crlf_to_line_endings); - -extern int NET_UUEncode(unsigned char *src, unsigned char *dst, int srclen); - -/* - * Various character macros - */ - -#define NET_TO_UPPER(x) ((((unsigned int) (x)) > 0x7f) ? x : toupper(x)) -#define NET_TO_LOWER(x) ((((unsigned int) (x)) > 0x7f) ? x : tolower(x)) - -#define NET_IS_ALPHA(x) ((((unsigned int) (x)) > 0x7f) ? 0 : isalpha(x)) -#define NET_IS_DIGIT(x) ((((unsigned int) (x)) > 0x7f) ? 0 : isdigit(x)) -#define NET_IS_SPACE(x) ((((unsigned int) (x)) > 0x7f) ? 0 : isspace(x)) - -PR_END_EXTERN_C - -#endif /* NETUTILS_H */ - - diff --git a/mozilla/network/main/pagescan.c b/mozilla/network/main/pagescan.c deleted file mode 100644 index 64f4194edab..00000000000 --- a/mozilla/network/main/pagescan.c +++ /dev/null @@ -1,687 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** pagescan.h ***************************************************/ -/* description: implementation of page scanning. Adds links */ -/* in a page to one of three lists depending on */ -/* the tag and its parameters: html links, */ -/* images, or resources. */ - - - /******************************************************************** - - Here's a list of the tags currently handled: - - Links: - <A HREF=?> - <AREA HREF=?> - <FRAME SRC=?> - <LAYER SRC=?> - - Images: - <IMG SRC=?> - <BODY BACKGROUND=?> - <LAYER BACKGROUND=?> - - Resources: - <EMBED SRC=?> - - Special: - <SCRIPT ARCHIVE=? SRC=?> - <APPLET CODEBASE=? ARCHIVE=? CODE=?> - <META HTTP-EQUIV="refresh" CONTENT=?> - <META NAME="robots" CONTENT="NOINDEX,NOFOLLOW"> - <LINK REL="stylesheet" TYPE="text/javascript" HREF=?> - <STYLE TYPE="text/javascript" SRC=?> - <STYLE TYPE="text/css" SRC=?> - <STYLE SRC=?> - - - $Revision: 1.4 $ - $Date: 1999-11-06 02:32:42 $ - - *********************************************************************/ - -#include "xp.h" -#include "xp_str.h" -#include "ntypes.h" /* for MWContext */ -#include "prmem.h" -#include "net.h" -#include "pa_tags.h" /* lib/libparse */ -#include "pagescan.h" -#include "htmparse.h" - -typedef uint8 CRAWL_LinkContext; -#define LINK_CONTEXT_HREF 1 -#define LINK_CONTEXT_FRAME 2 -#define LINK_CONTEXT_LAYER 3 - -typedef uint8 CRAWL_TagError; -#define CRAWL_TAG_NO_ERR 0 -#define CRAWL_TAG_NO_MEMORY 1 -#define CRAWL_TAG_SYNTAX_ERR 2 - -extern PRBool crawl_startsWith (char *pattern, char *uuid); -extern PRBool crawl_endsWith (char *pattern, char *uuid); -extern int crawl_appendStringList(char ***list, uint16 *len, uint16 *size, char *str); - -typedef struct _CRAWL_PageInfoStruct { - char *url; - char *siteURL; - char *baseURL; - URL_Struct *url_s; - - PRBool dontIndex; /* don't index (cache) this page */ - PRBool dontFollow; /* don't follow links in this page (effectively causes page not to be parsed) */ - - CRAWL_ItemList images; - CRAWL_ItemList links; - CRAWL_ItemList resources; /* applets */ - CRAWL_ItemList requiredResources; /* script src, and text/javascript or text/css stylesheets */ - CRAWL_ItemList frames; - CRAWL_ItemList layers; - - uint16 numImages; - uint16 numLinks; - uint16 numResources; - uint16 numRequiredResources; - uint16 numFrames; - uint16 numLayers; - - uint16 sizeImages; - uint16 sizeLinks; - uint16 sizeResources; - uint16 sizeRequiredResources; - uint16 sizeFrames; - uint16 sizeLayers; - - time_t lastModified; - - void *page_owner; - CRAWL_ScanPageStatusFunc scan_complete_func; -} CRAWL_PageInfoStruct; - -/* prototypes */ -static char* crawl_makeAbsoluteURL(CRAWL_PageInfo pageInfo, char *relURL); -static CRAWL_TagError crawl_addPageLink(CRAWL_PageInfo pageInfo, char *link, CRAWL_LinkContext context); -static CRAWL_TagError crawl_addPageImage(CRAWL_PageInfo pageInfo, char *image); -static CRAWL_TagError crawl_addPageResource(CRAWL_PageInfo pageInfo, char *resource); -static CRAWL_TagError crawl_addPageRequiredResource(CRAWL_PageInfo pageInfo, char *resource); -static CRAWL_TagError crawl_addPageFrame(CRAWL_PageInfo pageInfo, char *frame); -static CRAWL_TagError crawl_addPageLayer(CRAWL_PageInfo pageInfo, char *layer); -static CRAWL_TagError crawl_addPageApplet(CRAWL_PageInfo pageInfo, char *codebase, char *archive, char *code); -static CRAWL_TagError crawl_addPageMetaRefresh(CRAWL_PageInfo page, char *content); -static CRAWL_TagError crawl_processURL(CRAWL_PageInfo page, char *url, CRAWL_LinkContext context); -static void crawl_get_page_url_exit(URL_Struct *URL_s, int status, MWContext *window_id); -int crawl_processToken(CRAWL_ParseObj obj, PRBool isTag, void *data); - -/****************************************************************************************/ -/* accessors */ -/****************************************************************************************/ - -PRBool crawl_pageCanBeIndexed(CRAWL_PageInfo pageInfo) { - return ((pageInfo->dontIndex) ? PR_FALSE : PR_TRUE); -} - -char* crawl_getPageURL(CRAWL_PageInfo pageInfo) { - return pageInfo->url; -} - -/* returns the last modified date given by the server */ -time_t crawl_getPageLastModified(CRAWL_PageInfo pageInfo) { - return pageInfo->lastModified; -} - -URL_Struct* crawl_getPageURL_Struct(CRAWL_PageInfo pageInfo) { - return pageInfo->url_s; -} - -CRAWL_ItemList crawl_getPageLinks(CRAWL_PageInfo pageInfo) { - return pageInfo->links; -} - -uint16 crawl_getPageLinkCount(CRAWL_PageInfo pageInfo) { - return pageInfo->numLinks; -} - -/* - makes an absolute URL from relURL using the base url if it exists, otherwise uses the - page's url as a base. -*/ -static char* -crawl_makeAbsoluteURL(CRAWL_PageInfo pageInfo, char *relURL) { - if ((pageInfo->baseURL != NULL) && (*pageInfo->baseURL != '\0')) - return NET_MakeAbsoluteURL(pageInfo->baseURL, relURL); - else return NET_MakeAbsoluteURL(pageInfo->url_s->address, relURL); -} - -static CRAWL_TagError -crawl_addPageLink(CRAWL_PageInfo pageInfo, char *link, CRAWL_LinkContext context) { - char *fullURL = crawl_makeAbsoluteURL(pageInfo, link); - if (fullURL == NULL) return(CRAWL_TAG_NO_MEMORY); - switch (context) { - case LINK_CONTEXT_HREF: - if (crawl_appendStringList(&pageInfo->links, &pageInfo->numLinks, &pageInfo->sizeLinks, fullURL) != 0) - return CRAWL_TAG_NO_MEMORY; - break; - case LINK_CONTEXT_FRAME: - if (crawl_appendStringList(&pageInfo->frames, &pageInfo->numFrames, &pageInfo->sizeFrames, fullURL) != 0) - return CRAWL_TAG_NO_MEMORY; - break; - case LINK_CONTEXT_LAYER: - if (crawl_appendStringList(&pageInfo->layers, &pageInfo->numLayers, &pageInfo->sizeLayers, fullURL) != 0) - return CRAWL_TAG_NO_MEMORY; - break; - default: - break; - } - return CRAWL_TAG_NO_ERR; -} - -CRAWL_ItemList crawl_getPageImages(CRAWL_PageInfo pageInfo) { - return pageInfo->images; -} - -uint16 crawl_getPageImageCount(CRAWL_PageInfo pageInfo) { - return pageInfo->numImages; -} - -static CRAWL_TagError -crawl_addPageImage(CRAWL_PageInfo pageInfo, char *image) { - char *fullURL = crawl_makeAbsoluteURL(pageInfo, image); - if (fullURL == NULL) return(CRAWL_TAG_NO_MEMORY); - if (crawl_appendStringList(&pageInfo->images, &pageInfo->numImages, &pageInfo->sizeImages, fullURL) != 0) - return(CRAWL_TAG_NO_MEMORY); - else return(CRAWL_TAG_NO_ERR); -} - -CRAWL_ItemList crawl_getPageResources(CRAWL_PageInfo pageInfo) { - return pageInfo->resources; -} - -uint16 crawl_getPageResourceCount(CRAWL_PageInfo pageInfo) { - return pageInfo->numResources; -} - -static CRAWL_TagError -crawl_addPageResource(CRAWL_PageInfo pageInfo, char *resource) { - char *fullURL = crawl_makeAbsoluteURL(pageInfo, resource); - if (fullURL == NULL) return(CRAWL_TAG_NO_MEMORY); - if (crawl_appendStringList(&pageInfo->resources, &pageInfo->numResources, &pageInfo->sizeResources, fullURL) != 0) - return(CRAWL_TAG_NO_MEMORY); - else return(CRAWL_TAG_NO_ERR); -} - -CRAWL_ItemList crawl_getPageRequiredResources(CRAWL_PageInfo pageInfo) { - return pageInfo->requiredResources; -} - -uint16 crawl_getPageRequiredResourceCount(CRAWL_PageInfo pageInfo) { - return pageInfo->numRequiredResources; -} - -static CRAWL_TagError -crawl_addPageRequiredResource(CRAWL_PageInfo pageInfo, char *resource) { - char *fullURL = crawl_makeAbsoluteURL(pageInfo, resource); - if (fullURL == NULL) return(CRAWL_TAG_NO_MEMORY); - if (crawl_appendStringList(&pageInfo->requiredResources, &pageInfo->numRequiredResources, &pageInfo->sizeRequiredResources, fullURL) != 0) - return(CRAWL_TAG_NO_MEMORY); - else return(CRAWL_TAG_NO_ERR); -} - -CRAWL_ItemList crawl_getPageFrames(CRAWL_PageInfo pageInfo) { - return pageInfo->frames; -} - -uint16 crawl_getPageFrameCount(CRAWL_PageInfo pageInfo) { - return pageInfo->numFrames; -} - -static CRAWL_TagError -crawl_addPageFrame(CRAWL_PageInfo pageInfo, char *frame) { - char *fullURL = crawl_makeAbsoluteURL(pageInfo, frame); - if (fullURL == NULL) return(CRAWL_TAG_NO_MEMORY); - if (crawl_appendStringList(&pageInfo->frames, &pageInfo->numFrames, &pageInfo->sizeFrames, fullURL) != 0) - return(CRAWL_TAG_NO_MEMORY); - else return(CRAWL_TAG_NO_ERR); -} - -CRAWL_ItemList crawl_getPageLayers(CRAWL_PageInfo pageInfo) { - return pageInfo->layers; -} - -uint16 crawl_getPageLayerCount(CRAWL_PageInfo pageInfo) { - return pageInfo->numLayers; -} - -static CRAWL_TagError -crawl_addPageLayer(CRAWL_PageInfo pageInfo, char *layer) { - char *fullURL = crawl_makeAbsoluteURL(pageInfo, layer); - if (fullURL == NULL) return(CRAWL_TAG_NO_MEMORY); - if (crawl_appendStringList(&pageInfo->layers, &pageInfo->numLayers, &pageInfo->sizeLayers, fullURL) != 0) - return(CRAWL_TAG_NO_MEMORY); - else return(CRAWL_TAG_NO_ERR); -} - -/* process the codebase, archive, and code attributes of an APPLET tag. -*/ -static CRAWL_TagError -crawl_addPageApplet(CRAWL_PageInfo pageInfo, char *codebase, char *archive, char *code) { - char *fullCodebase; - if (codebase != NULL) { - fullCodebase = crawl_makeAbsoluteURL(pageInfo, codebase); - if (fullCodebase == NULL) return(CRAWL_TAG_NO_MEMORY); - } - if (archive != NULL) { - char *fullArchive; - if (fullCodebase != NULL) { - fullArchive = NET_MakeAbsoluteURL(fullCodebase, archive); - } else { - fullArchive = crawl_makeAbsoluteURL(pageInfo, archive); - } - if (fullArchive == NULL) return(CRAWL_TAG_NO_MEMORY); - - if (crawl_addPageResource(pageInfo, fullArchive) == CRAWL_TAG_NO_MEMORY) return(CRAWL_TAG_NO_MEMORY); - } - if (code != NULL) { - char *fullCode; - /* FIXME can code still be specified with fully qualified package names? */ - if (fullCodebase != NULL) fullCode = NET_MakeAbsoluteURL(fullCodebase, code); - else fullCode = crawl_makeAbsoluteURL(pageInfo, code); - if (fullCode == NULL) return(CRAWL_TAG_NO_MEMORY); - if (crawl_addPageResource(pageInfo, fullCode) == CRAWL_TAG_NO_MEMORY) return(CRAWL_TAG_NO_MEMORY); - } else return(CRAWL_TAG_SYNTAX_ERR); - - return(CRAWL_TAG_NO_ERR); -} - -/* process a url specified in a META refresh tag */ -static CRAWL_TagError -crawl_addPageMetaRefresh(CRAWL_PageInfo page, char *content) { - /* look for the url= */ - char *url = PL_strcasestr(content, "url="); - if (url != NULL) { - url += 4; /* go past the url= */ - url = strtok(url, " '\""); - return(crawl_addPageLink(page, url, LINK_CONTEXT_HREF)); - } else return CRAWL_TAG_SYNTAX_ERR; -} - -CRAWL_PageInfo crawl_makePage(char *siteURL, char *pageURL, ExtCacheDBInfo *cache) { - CRAWL_PageInfo pageInfo = PR_NEWZAP(CRAWL_PageInfoStruct); - if (pageInfo == NULL) return NULL; - pageInfo->url = pageURL; - pageInfo->siteURL = siteURL; - pageInfo->url = NET_MakeAbsoluteURL(siteURL, pageURL); /* complete a partial url if necessary */ - if (pageInfo->url != NULL) { - pageInfo->url_s = NET_CreateURLStruct(pageInfo->url, NET_NORMAL_RELOAD); /* freed in the exit function */ - if (pageInfo->url_s != NULL) { - pageInfo->url_s->load_background = PR_TRUE; - pageInfo->url_s->SARCache = cache; - pageInfo->url_s->owner_data = pageInfo; /* so we can recover the CRAWL_PageInfo in the converter */ - } else { - PR_Free(pageInfo->url); - PR_Free(pageInfo); - return NULL; - } - } else { - PR_Free(pageInfo); - return NULL; - } - return pageInfo; -} - -void crawl_destroyPage(CRAWL_PageInfo page) { - if (page->images != NULL) { - PR_Free(page->images); - page->sizeImages = 0; - } - if (page->links != NULL) { - PR_Free(page->links); - page->sizeLinks = 0; - } - if (page->resources != NULL) { - PR_Free(page->resources); - page->sizeResources = 0; - } - if (page->requiredResources != NULL) { - PR_Free(page->requiredResources); - page->sizeRequiredResources = 0; - } - if (page->frames != NULL) { - PR_Free(page->frames); - page->sizeFrames = 0; - } - if (page->layers != NULL) { - PR_Free(page->layers); - page->sizeLayers = 0; - } - /* if (page->url_s != NULL) NET_FreeURLStruct(page->url_s); */ - if (page->url != NULL) PR_Free(page->url); - if (page->baseURL != NULL) PR_Free(page->baseURL); - PR_Free(page); -} - -/* - adds the url to the appropriate list (link, image, or resource). - FIXME ALERT! still need to deal with file extensions - those which are alphanumeric are resources. -*/ -static CRAWL_TagError -crawl_processURL(CRAWL_PageInfo page, char *url, CRAWL_LinkContext context) { - /* NET_TO_LOWER(url); */ - if (crawl_startsWith("mailto:", url)) return(CRAWL_TAG_NO_ERR); - else if (crawl_startsWith("mailbox:", url)) return(CRAWL_TAG_NO_ERR); - else if (crawl_startsWith("news:", url)) return(CRAWL_TAG_NO_ERR); - else if (crawl_startsWith("javascript:", url)) return(CRAWL_TAG_NO_ERR); - - if (crawl_endsWith(".jpg", url) || - crawl_endsWith(".jpeg", url) || - crawl_endsWith(".gif", url) || - crawl_endsWith(".xbm", url)) { - crawl_addPageImage(page, url); - return(CRAWL_TAG_NO_ERR); - } else return(crawl_addPageLink(page, url, context)); -} - -/* - Process a tag, adding urls to the lists of links, images, or resources. - The parser calls this routine whenever a tag or between-tag data has been read. -*/ -int crawl_processToken(CRAWL_ParseObj obj, PRBool isTag, void *data) { - CRAWL_TagError err = CRAWL_TAG_NO_ERR; - CRAWL_PageInfo page = (CRAWL_PageInfo)data; - if (isTag) { - CRAWL_Tag tag = CRAWL_GetTagParsed(obj); - char *name = CRAWL_GetTagName(tag); - char *att1, *att2, *att3; - if (CRAWL_IsEndTag(tag)) return PARSE_GET_NEXT_TOKEN; - switch (CRAWL_GetTagToken(tag)) { - case P_ANCHOR: - att1 = CRAWL_GetAttributeValue(tag, PARAM_HREF); /* <A HREF=?> */ - if (att1 != NULL) err = crawl_processURL(page, att1, LINK_CONTEXT_HREF); - break; - case P_AREA: - att1 = CRAWL_GetAttributeValue(tag, PARAM_HREF); /* <AREA HREF=?> */ - if (att1 != NULL) err = crawl_processURL(page, att1, LINK_CONTEXT_HREF); - break; - case P_BASE: - att1 = CRAWL_GetAttributeValue(tag, PARAM_HREF); - if (att1 != NULL) { - page->baseURL = NET_MakeAbsoluteURL(page->url_s->address, att1); /* PL_strdup(att1); */ - if (page->baseURL == NULL) err = CRAWL_TAG_NO_MEMORY; - } - break; - case P_IMAGE: - att1 = CRAWL_GetAttributeValue(tag, PARAM_SRC); /* <IMG SRC=?> */ - if (att1 != NULL) err = crawl_addPageImage(page, att1); - break; - case P_BODY: - att1 = CRAWL_GetAttributeValue(tag, PARAM_BACKGROUND); /* <BODY BACKGROUND=?> */ - if (att1 != NULL) err = crawl_addPageImage(page, att1); - break; - case P_GRID_CELL: - att1 = CRAWL_GetAttributeValue(tag, PARAM_SRC); /* <FRAME SRC=?> */ - if (att1 != NULL) err = crawl_processURL(page, att1, LINK_CONTEXT_FRAME); - break; - case P_LAYER: - att1 = CRAWL_GetAttributeValue(tag, PARAM_SRC); /* <LAYER SRC=?> */ - if (att1 != NULL) err = crawl_processURL(page, att1, LINK_CONTEXT_LAYER); - att2 = CRAWL_GetAttributeValue(tag, "background"); /* <LAYER BACKGROUND=?> */ - if ((att2 != NULL) && (err == CRAWL_TAG_NO_ERR)) err = crawl_addPageImage(page, att2); - break; - case P_EMBED: - att1 = CRAWL_GetAttributeValue(tag, PARAM_SRC); /* <EMBED SRC=?> */ - if (att1 != NULL) err = crawl_addPageResource(page, att1); - break; - case P_SCRIPT: - att1 = CRAWL_GetAttributeValue(tag, PARAM_ARCHIVE); - if (att1 != NULL) err = crawl_addPageRequiredResource(page, att1); - att2 = CRAWL_GetAttributeValue(tag, PARAM_SRC); - if ((att2 != NULL) && (err == CRAWL_TAG_NO_ERR)) err = crawl_addPageRequiredResource(page, att2); - break; - case P_JAVA_APPLET: - att1 = CRAWL_GetAttributeValue(tag, PARAM_CODEBASE); - att2 = CRAWL_GetAttributeValue(tag, PARAM_ARCHIVE); - att3 = CRAWL_GetAttributeValue(tag, PARAM_CODE); - err = crawl_addPageApplet(page, att1, att2, att3); - break; - case P_META: - att1 = CRAWL_GetAttributeValue(tag, PARAM_HTTP_EQUIV); - if ((att1 != NULL) && (PL_strcasecmp(att1, "refresh") == 0)) { - att2 = CRAWL_GetAttributeValue(tag, PARAM_CONTENT); - if (att2 != NULL) err = crawl_addPageMetaRefresh(page, att2); - } else { - /* robots meta tag: we take NOINDEX to mean don't cache (the document is already - cached so we need to remove it from the cache. NOFOLLOW means don't follow the - links, which we'll do by aborting the parsing of this page. - See http://info.webcrawler.com/mak/projects/robots/exclusion.html - */ - att1 = CRAWL_GetAttributeValue(tag, PARAM_NAME); - if ((att1 != NULL) && (PL_strcasecmp(att1, "robots") == 0)) { - att2 = CRAWL_GetAttributeValue(tag, PARAM_CONTENT); - if (att2 != NULL) { - if (PL_strcasestr(att2, "noindex")) { - page->dontIndex = PR_TRUE; - } - if (PL_strcasestr(att2, "nofollow")) { - page->dontFollow = PR_TRUE; - return PARSE_STOP; - } - } - } - } - break; - case P_LINK: - att1 = CRAWL_GetAttributeValue(tag, PARAM_REL); - if ((att1 != NULL) && (PL_strcasecmp(att1, "stylesheet") == 0)) { - att2 = CRAWL_GetAttributeValue(tag, PARAM_HREF); - if (att2 != NULL) { - att3 = CRAWL_GetAttributeValue(tag, PARAM_TYPE); - if ((att3 != NULL) && ((PL_strcasecmp(att3, "text/javascript") == 0) || (PL_strcasecmp(att3, "text/css") == 0))) { - err = crawl_addPageRequiredResource(page, att2); - } else err = crawl_addPageResource(page, att2); - } - } - break; - case P_STYLE: - att1 = CRAWL_GetAttributeValue(tag, PARAM_SRC); - if (att1 != NULL) { - att2 = CRAWL_GetAttributeValue(tag, PARAM_TYPE); - if ((att2 != NULL) && ((PL_strcasecmp(att2, "text/javascript") == 0) || (PL_strcasecmp(att2, "text/css") == 0))) { - err = crawl_addPageRequiredResource(page, att1); - } else err = crawl_addPageResource(page, att1); - } - break; - default: - break; - } - } - if (err == CRAWL_TAG_NO_MEMORY) return PARSE_OUT_OF_MEMORY; - else return PARSE_GET_NEXT_TOKEN; -} - -/* exit routine for NET_GetURL */ -static void -crawl_get_page_url_exit(URL_Struct *URL_s, int status, MWContext *window_id) -{ -#if defined(XP_MAC) -#pragma unused(window_id) -#endif - if(status != MK_CHANGING_CONTEXT) - NET_FreeURLStruct(URL_s); -} - -void crawl_scanPage(CRAWL_PageInfo page, MWContext *context, CRAWL_ScanPageStatusFunc complete_func, void *data) { - - page->page_owner = data; - page->scan_complete_func = complete_func; - NET_GetURL(page->url_s, FO_CACHE_AND_CRAWL_PAGE, context, crawl_get_page_url_exit); -} - -/****************************************************************************************/ -/* stream routines */ -/****************************************************************************************/ - -typedef struct { - CRAWL_ParseObj parse_obj; - CRAWL_PageInfo page; -} crawl_page_scan_stream; - -/* prototypes */ -PRIVATE int crawl_PageScanConvPut(NET_StreamClass *stream, char *s, int32 l); -PRIVATE int crawl_PageScanConvWriteReady(NET_StreamClass *stream); -PRIVATE void crawl_PageScanConvComplete(NET_StreamClass *stream); -PRIVATE void crawl_PageScanConvAbort(NET_StreamClass *stream, int status); - -PRIVATE int -crawl_PageScanConvPut(NET_StreamClass *stream, char *s, int32 l) -{ - crawl_page_scan_stream *obj=stream->data_object; - int status; - - PR_ASSERT(obj->parse_obj != NULL); - PR_ASSERT(obj->page != NULL); - - if (!obj->page->dontFollow) /* no directive to cache without parsing */ - status = CRAWL_ParserPut(obj->parse_obj, s, l, crawl_processToken, obj->page); - else status = CRAWL_PARSE_NO_ERROR; - - switch (status) { - case CRAWL_PARSE_NO_ERROR: - return(0); - case CRAWL_PARSE_ERROR: - obj->page->dontFollow = PR_TRUE; - return(0); - case CRAWL_PARSE_TERMINATE: - obj->page->dontFollow = PR_TRUE; - return(0); - case CRAWL_PARSE_OUT_OF_MEMORY: - return(MK_UNABLE_TO_CONVERT); - default: - PR_ASSERT(0); - break; - } - return(status); -} - -PRIVATE int -crawl_PageScanConvWriteReady(NET_StreamClass *stream) -{ -#if defined(XP_MAC) -#pragma unused(stream) -#endif - return(MAX_WRITE_READY); -} - -PRIVATE void -crawl_PageScanConvComplete(NET_StreamClass *stream) -{ - crawl_page_scan_stream *obj=stream->data_object; - CRAWL_PageInfo page = (CRAWL_PageInfo)obj->page; - PR_ASSERT(page != NULL); - if ((page->scan_complete_func != NULL) && (page->page_owner != NULL)) - page->scan_complete_func(page->page_owner, page); - CRAWL_DestroyParseObj(obj->parse_obj); - crawl_destroyPage(page); - obj->page = NULL; -} - -PRIVATE void -crawl_PageScanConvAbort(NET_StreamClass *stream, int status) -{ -#if defined(XP_MAC) -#pragma unused(status) -#endif - crawl_page_scan_stream *obj=stream->data_object; - /* we got an error (status always negative here) but should call completion function */ - CRAWL_PageInfo page = (CRAWL_PageInfo)obj->page; - PR_ASSERT(page != NULL); - if ((page->scan_complete_func != NULL) && (page->page_owner != NULL)) - page->scan_complete_func(page->page_owner, page); - - CRAWL_DestroyParseObj(obj->parse_obj); - crawl_destroyPage(obj->page); - obj->page = NULL; -} - -PUBLIC NET_StreamClass * -CRAWL_CrawlerConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id) -{ -#if defined(XP_MAC) -#pragma unused(format_out, data_object) -#endif - NET_StreamClass *stream = NULL; - - crawl_page_scan_stream *obj; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - PR_LogPrint(("CRAWL_CrawlerConverter: %d %s", URL_s->server_status, URL_s->address)); - - if (URL_s->SARCache != NULL) { - /* if the content length would exceed the cache limit, don't convert this */ - if (((uint32)URL_s->content_length >= (URL_s->SARCache->MaxSize - URL_s->SARCache->DiskCacheSize)) && - ((uint32)URL_s->content_length < BOGUS_CONTENT_LENGTH)) { - CRAWL_PageInfo page = URL_s->owner_data; - PR_LogPrint(("not converting %s", URL_s->address)); - if ((page->scan_complete_func != NULL) && (page->page_owner != NULL)) { - page->scan_complete_func(page->page_owner, page); - return(NULL); - } - } - } - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEW(crawl_page_scan_stream); - if (obj == NULL) - { - PR_Free(stream); - return(NULL); - } - obj->parse_obj = CRAWL_MakeParseObj(); /* this object used to parse the page and destroyed - in completion or abort function */ - if (obj->parse_obj == NULL) return(NULL); - obj->page = URL_s->owner_data; /* this data was set in crawl_makePage */ - obj->page->lastModified = URL_s->last_modified; - /* if there was a server error, read but don't parse the document */ - if ((URL_s->server_status >= 400) || - /* don't attempt to parse non-html */ - ((PL_strstr(URL_s->content_type, TEXT_HTML) == NULL) && - (PL_strstr(URL_s->content_type, INTERNAL_PARSER) == NULL))) { - /* URL_s->dont_cache = PR_FALSE; */ - obj->page->dontFollow = PR_TRUE; - } - - stream->name = "Crawler Converter"; - stream->complete = (MKStreamCompleteFunc) crawl_PageScanConvComplete; - stream->abort = (MKStreamAbortFunc) crawl_PageScanConvAbort; - stream->put_block = (MKStreamWriteFunc) crawl_PageScanConvPut; - stream->is_write_ready = (MKStreamWriteReadyFunc) crawl_PageScanConvWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - return(stream); -} diff --git a/mozilla/network/main/pagescan.h b/mozilla/network/main/pagescan.h deleted file mode 100644 index 12a08ebb30d..00000000000 --- a/mozilla/network/main/pagescan.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** pagescan.h ***************************************************/ -/* description: page scanning */ -/* - not dependent on the crawler */ - - - /******************************************************************** - - $Revision: 1.2 $ - $Date: 1999-11-06 02:32:42 $ - - *********************************************************************/ - -#ifndef pagescan_h___ -#define pagescan_h___ -#include "prtypes.h" -#include "ntypes.h" /* for MWContext */ -#include "net.h" /* for URLStruct */ - -/* any content length over this number is assumed to be a bogus content length field. This - is sometimes used to keep a connection open. If we encounter a content length this size or - greater we won't automatically reject it because it's larger than the remaining cache size. -*/ -#define BOGUS_CONTENT_LENGTH ((uint32)100000000) - -typedef char **CRAWL_ItemList; - -typedef char *CRAWL_Item; - -/* Most APIs require a CRAWL_PageInfo reference, which is created in crawl_makePage. */ -typedef struct _CRAWL_PageInfoStruct *CRAWL_PageInfo; - -/* Prototype describing callback function for when a page is done. */ - typedef void -(*CRAWL_ScanPageStatusFunc)(void *data, CRAWL_PageInfo pageInfo); - -/* Creates a page object which will be freed by the completion or abort stream routines (the - URL_Struct is freed by the exit routine). Returns NULL if there is not enough memory. - Parameters: - - siteURL - url of the site (used to make absolute url). Note this may be different than the -site that the page is on (in case we are crawling), in which case the pageURL should be absolute. - pageURL - url of the page. - cache - external cache. If non-null, the url will be cached here. - */ -CRAWL_PageInfo crawl_makePage(char *siteURL, char *pageURL, ExtCacheDBInfo *db); - -/* Deallocates the list structures but not the list content (which should be done by the consumer). - This is normally called internally by the completion and abort stream routines. -*/ -void crawl_destroyPage(CRAWL_PageInfo page); - - -/* Requests the url from netlib and begins scanning. This function returns after the request - to netlib is issued. The callback function is called when page scanning is complete or aborts. - It is not guaranteed to be called in an out of memory situation. -*/ -void crawl_scanPage(CRAWL_PageInfo page, MWContext *context, CRAWL_ScanPageStatusFunc func, void *data); - -/****************************************************************************************/ -/* accessors */ -/****************************************************************************************/ - -/* returns true if the page does not have a META tag that specifies that the page should - not be indexed. -*/ -PRBool crawl_pageCanBeIndexed(CRAWL_PageInfo pageInfo); - -char* crawl_getPageURL(CRAWL_PageInfo pageInfo); - -time_t crawl_getPageLastModified(CRAWL_PageInfo pageInfo); - -URL_Struct* crawl_getPageURL_Struct(CRAWL_PageInfo pageInfo); - -CRAWL_ItemList crawl_getPageLinks(CRAWL_PageInfo pageInfo); -uint16 crawl_getPageLinkCount(CRAWL_PageInfo pageInfo); - -CRAWL_ItemList crawl_getPageImages(CRAWL_PageInfo pageInfo); -uint16 crawl_getPageImageCount(CRAWL_PageInfo pageInfo); - -CRAWL_ItemList crawl_getPageResources(CRAWL_PageInfo pageInfo); -uint16 crawl_getPageResourceCount(CRAWL_PageInfo pageInfo); - -CRAWL_ItemList crawl_getPageRequiredResources(CRAWL_PageInfo pageInfo); -uint16 crawl_getPageRequiredResourceCount(CRAWL_PageInfo pageInfo); - -CRAWL_ItemList crawl_getPageFrames(CRAWL_PageInfo pageInfo); -uint16 crawl_getPageFrameCount(CRAWL_PageInfo pageInfo); - -CRAWL_ItemList crawl_getPageLayers(CRAWL_PageInfo pageInfo); -uint16 crawl_getPageLayerCount(CRAWL_PageInfo pageInfo); - -/****************************************************************************************/ -/* stream function */ -/****************************************************************************************/ - -PUBLIC NET_StreamClass* -CRAWL_CrawlerConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id); -#endif diff --git a/mozilla/network/main/prefetch.c b/mozilla/network/main/prefetch.c deleted file mode 100644 index afc055199f1..00000000000 --- a/mozilla/network/main/prefetch.c +++ /dev/null @@ -1,157 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* designed/implemented by Gagan Saksena */ - -#include "mkutils.h" -#include "xp.h" -#include "prefetch.h" -#include "net.h" -#include "xp_list.h" -#include "prefapi.h" - -PRIVATE XP_List* prefetch_list = 0; - -MODULE_PRIVATE Bool pre_OKToPrefetch(char* url); -MODULE_PRIVATE void pre_Finished(URL_Struct* url_struct, int status, MWContext* context); - -PRIVATE XP_Bool pre_enabled = TRUE; -PRIVATE void pre_ProcessList(MWContext* context); - -/* Constructs a URL_Struct from the the specified URL to the prefetch_list based - on the value of the pre subtag. -*/ -PUBLIC void -PRE_AddToList(MWContext* context, char* url) -{ - /* Construct a new URL_Struct with this url, and Prefetch priority */ - URL_Struct* urls; - - if (!pre_enabled || !pre_OKToPrefetch(url)) - return; - - urls = NET_CreateURLStruct(url, NET_DONT_RELOAD); - if (!urls) - return; - - urls->priority = Prefetch_priority; - urls->load_background = TRUE; - - if (prefetch_list == NULL) - { - prefetch_list = XP_ListNew(); - } - - XP_ListAddObjectToEnd(prefetch_list, urls); -} - - -/* The main process for each MWContext, should be called after - a page is finished loading. This basically extracts all the - links on the current page and eliminates the non relevant ones - and adds the elements to the prefetch_list. If something - has been added, then it is passed on to NET_GetURL function - for prefetching and storing in cache. -*/ -PUBLIC void -PRE_Fetch(MWContext* context) -{ - pre_ProcessList(context); -} - -/* Returns bool to indicate if its OK to prefetch the specified URL. - we don't prefetch mailto:, file:, etc. -*/ -MODULE_PRIVATE Bool -pre_OKToPrefetch(char* url) -{ - int type; - if (url == NULL) - return FALSE; - - /* Skip interpreted cgi-bin's for now... */ - if (PL_strchr(url, '?') || - PL_strstr(url, "cgi-bin") || - PL_strstr(url, ".cgi") || - PL_strstr(url, ".shtml")) - return FALSE; - - /* approve only HTTP and Gopher for now (skip about:/mailto:/telnet:/gopher:/ etc.) */ - /* TODO add FTP directories only! */ - type = NET_URL_Type(url); - if (type && ( - (type == HTTP_TYPE_URL) || - (type == GOPHER_TYPE_URL))) - return TRUE; - - return FALSE; -} - -MODULE_PRIVATE void -pre_Finished(URL_Struct* url_struct, int status, MWContext* context) -{ - /* this should change to update the colors of - the prefetched links */ - if (prefetch_list) - { - XP_ListRemoveObject(prefetch_list, url_struct); - - if (XP_ListCount(prefetch_list) == 0) - { - XP_ListDestroy(prefetch_list); - prefetch_list = 0; - } - } - XP_FREEIF(url_struct); -} - -PRIVATE void -pre_ProcessList(MWContext* context) -{ - if (XP_ListCount(prefetch_list)>0) - { - XP_List* pList = prefetch_list; - URL_Struct* urls = (URL_Struct*)XP_ListNextObject(pList); - - while (urls) - { - NET_GetURL(urls, - FO_CACHE_ONLY, - context, - pre_Finished); - - urls = (URL_Struct*)XP_ListNextObject(pList); - } - } -} - -/* Enable or disable the prefetching, called from NET_SetupPrefs in mkgeturl.c */ -PUBLIC void -PRE_Enable(PRUint8 nNumber) -{ - if (nNumber > 0) - { - pre_enabled = TRUE; - /* TODO - set max number here */ - } - else - pre_enabled = FALSE; -} diff --git a/mozilla/network/main/robotxt.c b/mozilla/network/main/robotxt.c deleted file mode 100644 index 3509f2748d5..00000000000 --- a/mozilla/network/main/robotxt.c +++ /dev/null @@ -1,555 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** robotxt.c ****************************************************/ -/* description: implementation of robots.txt parser */ - - - /******************************************************************** - - $Revision: 1.4 $ - $Date: 1999-11-06 02:32:43 $ - - *********************************************************************/ - -#include "xp.h" -#include "xp_str.h" -#include "ntypes.h" /* for MWContext */ -#include "net.h" -#include "robotxt.h" -#include "prmem.h" -#include "prthread.h" -#include "prinrval.h" -#include "prio.h" /* for testing */ - -#define USER_AGENT "User-agent" -#define DISALLOW "Disallow" -#define ALLOW "Allow" -#define ASTERISK "*" -#define MOZILLA "mozilla" - -typedef uint8 CRAWL_RobotControlAvailability; - -#define ROBOT_CONTROL_AVAILABLE ((CRAWL_RobotControlAvailability)0x00) -#define ROBOT_CONTROL_NOT_AVAILABLE ((CRAWL_RobotControlAvailability)0x01) -#define ROBOT_CONTROL_NOT_YET_QUERIED ((CRAWL_RobotControlAvailability)0x02) - -#define PARSE_STATE_ALLOW 1 -#define PARSE_STATE_DISALLOW 2 -#define PARSE_STATE_AGENT 3 - -#define PARSE_NO_ERR 0 -#define PARSE_ERR 1 -#define PARSE_NO_MEMORY 2 -#define MOZILLA_RECORD_READ 3 /* found the Mozilla record so we're done */ - -extern int crawl_appendString(char **str, uint16 *len, uint16 *size, char c); - -typedef struct _CRAWL_RobotControlStruct { - /* char *host; */ - char *siteURL; - CRAWL_RobotControlAvailability status; - char **line; - uint16 numLines; - uint16 sizeLines; - PRBool *allowed; - MWContext *context; - CRAWL_RobotControlStatusFunc completion_func; - void *owner_data; - PRBool freeData; - /* char *requested_url; */ -} CRAWL_RobotControlStruct; - -typedef struct _CRAWL_RobotParseStruct { - uint8 state; - char *token; - uint16 lenToken; - uint16 sizeToken; - PRBool inComment; - PRBool isProcessing; - PRBool skipWhitespace; - PRBool mozillaSeen; /* true if we saw a mozilla user agent */ - PRBool defaultSeen; /* true if we saw a default user agent */ - PRBool foundRecord; /* true if we read a mozilla or default record */ -} CRAWL_RobotParseStruct; - -typedef CRAWL_RobotParseStruct *CRAWL_RobotParse; - -/* prototypes */ -static int crawl_unescape (char *str, char *reserved, int numReserved); -PRBool crawl_startsWith (char *pattern, char *uuid); -PRBool crawl_endsWith (char *pattern, char *uuid); -void crawl_stringToLower(char *str); -static void crawl_destroyLines(CRAWL_RobotControl control); -static void crawl_addRobotControlDirective(CRAWL_RobotControl control, char *token, PRBool isAllowed); -static int crawl_parseRobotControlInfo(CRAWL_RobotControl control, CRAWL_RobotParse parse, char *str, uint32 len); -static CRAWL_RobotControlStatus crawl_isRobotAllowed(CRAWL_RobotControl control, char *url); - -/* this stuff is adapted from mkparse.c */ -#define HEX_ESCAPE '%' -#define RESERVED_CHARS ";/:@=&" -#define NUM_RESERVED 6 - -/* decode % escaped hex codes into character values - */ -#define UNHEX(C) \ - ((C >= '0' && C <= '9') ? C - '0' : \ - ((C >= 'A' && C <= 'F') ? C - 'A' + 10 : \ - ((C >= 'a' && C <= 'f') ? C - 'a' + 10 : 0))) - -/* unescapes a string, but leaves octets encoded if they match one of the supplied reserved characters. - this was adapted from NET_UnescapeCnt */ -static int -crawl_unescape (char *str, char *reserved, int numReserved) -{ - int i; - register char *src = str; - register char *dst = str; - - while(*src) - if (*src != HEX_ESCAPE) - { - *dst++ = *src++; - } - else - { - src++; /* walk over escape */ - if (*src) - { - *dst = UNHEX(*src) << 4; - src++; - } - if (*src) - { - *dst = (*dst + UNHEX(*src)); - src++; - } - /* check if it belongs to the reserved characters */ - for (i = 0; i < numReserved; i++) { - if (*dst == reserved[i]) { - /* put it back */ - *dst++ = HEX_ESCAPE; - *dst++ = *(src-2); - *dst = *(src-1); - } - } - dst++; - } - - *dst = 0; - - return (int)(dst - str); -} - -#define CHAR_CMP(x, y) ((x == y) || (NET_TO_LOWER(x) == NET_TO_LOWER(y))) - -PRBool crawl_startsWith (char *pattern, char *uuid) { - short l1 = strlen(pattern); - short l2 = strlen(uuid); - short index; - - if (l2 < l1) return PR_FALSE; - - for (index = 0; index < l1; index++) { - if (!(CHAR_CMP(pattern[index], uuid[index]))) return PR_FALSE; - } - - return PR_TRUE; -} - -PRBool crawl_endsWith (char *pattern, char *uuid) { - short l1 = strlen(pattern); - short l2 = strlen(uuid); - short index; - - if (l2 < l1) return PR_FALSE; - - for (index = 0; index < l1; index++) { - if (!(CHAR_CMP(pattern[l1-index], uuid[l2-index]))) return PR_FALSE; - } - - return PR_TRUE; -} - -void crawl_stringToLower(char *str) { - register char *src = str; - register char *dst = str; - while(*src) { - *dst++ = tolower(*src++); - } - *dst = 0; -} - -PR_IMPLEMENT(CRAWL_RobotControl) CRAWL_MakeRobotControl(MWContext *context, char *siteURL) { - CRAWL_RobotControl control = PR_NEWZAP(CRAWL_RobotControlStruct); - if (control == NULL) return(NULL); - control->siteURL = PL_strdup(siteURL); - if (siteURL == NULL) return(NULL); - control->status = ROBOT_CONTROL_NOT_YET_QUERIED; - control->context = context; - return control; -} - -static void -crawl_destroyLines(CRAWL_RobotControl control) { - uint16 i; - for (i = 0; i < control->numLines; i++) { - PR_Free(control->line[i]); - } - if (control->line != NULL) PR_Free(control->line); - if (control->allowed != NULL) PR_Free(control->allowed); - control->allowed = NULL; - control->line = NULL; - control->numLines = control->sizeLines = 0; -} - -PR_IMPLEMENT(void) CRAWL_DestroyRobotControl(CRAWL_RobotControl control) { - if (control->siteURL != NULL) PR_Free(control->siteURL); - crawl_destroyLines(control); - PR_Free(control); -} - -static void -crawl_addRobotControlDirective(CRAWL_RobotControl control, char *token, PRBool isAllowed) { - /* convert token to lower case and unescape it */ - crawl_stringToLower(token); - crawl_unescape(token, RESERVED_CHARS, NUM_RESERVED); - if (control->numLines == control->sizeLines) { - char **newLines; - char **old; - PRBool *newAllowed; - PRBool *oldAllowed; - /* copy the paths array */ - newLines = (char**)PR_MALLOC(sizeof(char**) * (control->sizeLines + 10)); - if (newLines == NULL) return; - old = control->line; - memcpy((char*)newLines, (char*)control->line, (sizeof(char**) * control->numLines)); - control->line = newLines; - if (old != NULL) PR_Free(old); - /* copy the boolean array */ - newAllowed = (PRBool*)PR_MALLOC(sizeof(PRBool) * (control->sizeLines + 10)); - if (newAllowed == NULL) return; - oldAllowed = control->allowed; - memcpy((char*)newAllowed, (char*)control->allowed, (sizeof(PRBool) * control->numLines)); - control->allowed = newAllowed; - if (oldAllowed != NULL) PR_Free(oldAllowed); - control->sizeLines += 10; - } - *(control->line + control->numLines) = token; - *(control->allowed + control->numLines) = isAllowed; - control->numLines++; -} - -static int -crawl_parseRobotControlInfo(CRAWL_RobotControl control, CRAWL_RobotParse parse, char *str, uint32 len) { - uint32 n = 0; /* where we are in the buffer */ - char c; - while (n < len) { - c = *(str + n); - if (parse->skipWhitespace) { - if ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')) { - n++; - } else parse->skipWhitespace = PR_FALSE; - } else { - if (c == '#') { - parse->inComment = PR_TRUE; - n++; - } else if (parse->inComment) { - if ((c == '\n') || (c == '\r')) { - parse->inComment = PR_FALSE; - parse->skipWhitespace = PR_TRUE; - n++; - } else n++; /* skip all other characters */ - } else if (c == ':') { /* directive */ - PRBool mozillaRecordRead = PR_FALSE; - if (crawl_appendString(&parse->token, &parse->lenToken, &parse->sizeToken, '\0') != 0) /* null terminate */ - return PARSE_NO_MEMORY; - if (PL_strcasecmp(parse->token, USER_AGENT) == 0) { - if ((parse->state == PARSE_STATE_DISALLOW) || (parse->state == PARSE_STATE_ALLOW)) { - /* already read a disallow or allow directive so the previous record is done */ - if (parse->isProcessing) { - if (parse->mozillaSeen) mozillaRecordRead = PR_TRUE; - if (parse->mozillaSeen || parse->defaultSeen) parse->foundRecord = PR_TRUE; - parse->isProcessing = PR_FALSE; - } - } - parse->state = PARSE_STATE_AGENT; - } else if (PL_strcasecmp(parse->token, DISALLOW) == 0) { - parse->state = PARSE_STATE_DISALLOW; - } else if (PL_strcasecmp(parse->token, ALLOW) == 0) - parse->state = PARSE_STATE_ALLOW; - /* else it is an unknown directive */ - PR_Free(parse->token); - parse->token = NULL; - parse->lenToken = parse->sizeToken = 0; - parse->skipWhitespace = PR_TRUE; - n++; - if (mozillaRecordRead) return MOZILLA_RECORD_READ; /* read the mozilla record so we're outta here */ - } else if ((c == '\n') || (c == '\r')) { - if (crawl_appendString(&parse->token, &parse->lenToken, &parse->sizeToken, '\0') != 0) /* null terminate */ - return PARSE_NO_MEMORY; - switch (parse->state) { - case PARSE_STATE_AGENT: - if (PL_strcasestr(parse->token, MOZILLA) != NULL) { - parse->mozillaSeen = PR_TRUE; - crawl_destroyLines(control); /* destroy previous default data */ - parse->isProcessing = PR_TRUE; /* start processing */ - } else if ((PL_strcmp(parse->token, ASTERISK) == 0) && (!parse->mozillaSeen)) { - parse->defaultSeen = PR_TRUE; - parse->isProcessing = PR_TRUE; /* start processing */ - } - PR_Free(parse->token); - break; - case PARSE_STATE_DISALLOW: - /* if processing, add to disallowed */ - if (parse->isProcessing) { - crawl_addRobotControlDirective(control, parse->token, PR_FALSE); - } - break; - case PARSE_STATE_ALLOW: - /* if processing, add to allowed */ - if (parse->isProcessing) { - crawl_addRobotControlDirective(control, parse->token, PR_TRUE); - } - break; - default: - PR_Free(parse->token); - break; - } - parse->token = NULL; - parse->lenToken = parse->sizeToken = 0; - parse->skipWhitespace = PR_TRUE; - } else { - if (crawl_appendString(&parse->token, &parse->lenToken, &parse->sizeToken, c) != 0) - return PARSE_NO_MEMORY; - n++; - } - } - } - return PARSE_NO_ERR; -} - -static CRAWL_RobotControlStatus -crawl_isRobotAllowed(CRAWL_RobotControl control, char *url) { - /* extract file component (after host) from url and decode it */ - uint16 i; - char *file = NET_ParseURL(url, GET_PATH_PART); - if (file == NULL) return CRAWL_ROBOT_ALLOWED; - crawl_unescape(file, RESERVED_CHARS, NUM_RESERVED); - - for (i = 0; i < control->numLines; i++) { - if (crawl_startsWith(control->line[i], file)) - return (control->allowed[i] ? CRAWL_ROBOT_ALLOWED : CRAWL_ROBOT_DISALLOWED); - } - PR_Free(file); - return CRAWL_ROBOT_ALLOWED; /* no matches */ -} - -static void -crawl_get_robots_txt_exit(URL_Struct *URL_s, int status, MWContext *window_id) -{ -#if defined(XP_MAC) -#pragma unused(window_id) -#endif - CRAWL_RobotControl control = (CRAWL_RobotControl)URL_s->owner_data; - if (status < 0) { - control->status = ROBOT_CONTROL_NOT_AVAILABLE; - if (control->owner_data != NULL) { - (control->completion_func)(control->owner_data); - if (control->freeData) PR_DELETE(control->owner_data); - } - } - if(status != MK_CHANGING_CONTEXT) - NET_FreeURLStruct(URL_s); -} - -/* issues a request for the robots.txt file. - returns PR_TRUE if the request was issued succesfully, PR_FALSE if not. -*/ -PR_IMPLEMENT(PRBool) CRAWL_ReadRobotControlFile(CRAWL_RobotControl control, CRAWL_RobotControlStatusFunc func, void *data, PRBool freeData) { - /* create new cache request for site + /robots.txt" */ - char *url = NET_MakeAbsoluteURL(control->siteURL, "/robots.txt"); - if (url != NULL) { - URL_Struct *url_s = NET_CreateURLStruct(url, NET_NORMAL_RELOAD); - if (url_s != NULL) { - control->completion_func = func; - control->owner_data = data; - control->freeData = freeData; - url_s->owner_data = control; - NET_GetURL(url_s, FO_CACHE_AND_ROBOTS_TXT, control->context, crawl_get_robots_txt_exit); - /* func(data); */ - return PR_TRUE; - } - } - control->status = ROBOT_CONTROL_NOT_AVAILABLE; - return PR_FALSE; -} - -PR_IMPLEMENT(CRAWL_RobotControlStatus) CRAWL_GetRobotControl(CRAWL_RobotControl control, char *url) { - /* return ROBOT_ALLOWED; */ - switch (control->status) { - case ROBOT_CONTROL_NOT_YET_QUERIED: - return CRAWL_ROBOTS_TXT_NOT_QUERIED; - case ROBOT_CONTROL_AVAILABLE: - return crawl_isRobotAllowed(control, url); - break; - case ROBOT_CONTROL_NOT_AVAILABLE: - return CRAWL_ROBOT_ALLOWED; /* no robots.txt file found so assume we can crawl */ - break; - default: - return CRAWL_ROBOT_ALLOWED; - break; - } -} - -/* content type conversion */ -typedef struct { - CRAWL_RobotParse parse_obj; - CRAWL_RobotControl control; -} crawl_robots_txt_stream; - -PRIVATE int -crawl_RobotsTxtConvPut(NET_StreamClass *stream, char *s, int32 l) -{ - crawl_robots_txt_stream *obj=stream->data_object; - int status = crawl_parseRobotControlInfo(obj->control, obj->parse_obj, s, l); - - if ((status == MOZILLA_RECORD_READ) || - (status == PARSE_NO_MEMORY)) { - return (MK_UNABLE_TO_CONVERT); /* abort since we read the mozilla record, no need to read any others */ - } - - return(status); -} - -PRIVATE int -crawl_RobotsTxtConvWriteReady(NET_StreamClass *stream) -{ -#if defined(XP_MAC) -#pragma unused(stream) -#endif - return(MAX_WRITE_READY); -} - -PRIVATE void -crawl_RobotsTxtConvComplete(NET_StreamClass *stream) -{ - crwal_robots_txt_stream*obj=stream->data_object; - if (obj->parse_obj->foundRecord) obj->control->status = ROBOT_CONTROL_AVAILABLE; - if (obj->control->owner_data != NULL) { - (obj->control->completion_func)(obj->control->owner_data); - if (obj->control->freeData) PR_DELETE(obj->control->owner_data); - } - PR_Free(obj->parse_obj); -} - -PRIVATE void -crawl_RobotsTxtConvAbort(NET_StreamClass *stream, int status) -{ - crawl_robots_txt_stream *obj=stream->data_object; - if(status == MK_UNABLE_TO_CONVERT) { /* special case, we read the mozilla record and exited early */ - obj->control->status = ROBOT_CONTROL_AVAILABLE; - } else obj->control->status = ROBOT_CONTROL_NOT_AVAILABLE; - if (obj->control->owner_data != NULL) { - (obj->control->completion_func)(obj->control->owner_data); - if (obj->control->freeData) PR_DELETE(obj->control->owner_data); - } - PR_Free(obj->parse_obj); -} - -PUBLIC NET_StreamClass * -CRAWL_RobotsTxtConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id) -{ -#if defined(XP_MAC) -#pragma unused(format_out, data_object) -#endif - crawl_robots_txt_stream *obj; - NET_StreamClass *stream; - CRAWL_RobotControl control = (CRAWL_RobotControl)URL_s->owner_data; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - if (URL_s->server_status < 400) { - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) { - control->status = ROBOT_CONTROL_NOT_AVAILABLE; - return(NULL); - } - - obj = PR_NEW(crawl_robots_txt_stream); - if (obj == NULL) - { - PR_Free(stream); - control->status = ROBOT_CONTROL_NOT_AVAILABLE; - return(NULL); - } - obj->parse_obj = PR_NEWZAP(CRAWL_RobotParseStruct); - if (obj->parse_obj == NULL) return(NULL); - obj->control = URL_s->owner_data; - - stream->name = "robots.txt Converter"; - stream->complete = (MKStreamCompleteFunc) crawl_RobotsTxtConvComplete; - stream->abort = (MKStreamAbortFunc) crawl_RobotsTxtConvAbort; - stream->put_block = (MKStreamWriteFunc) crawl_RobotsTxtConvPut; - stream->is_write_ready = (MKStreamWriteReadyFunc) crawl_RobotsTxtConvWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - return(stream); - } else { - control->status = ROBOT_CONTROL_NOT_AVAILABLE; - if (control->owner_data != NULL) { - control->completion_func(control->owner_data); - if (control->freeData) PR_DELETE(control->owner_data); - } - return (NULL); - } -} - -#if DEBUG_TEST_ROBOT -void testRobotControlParser(char *url) { - /* this will be done through libnet but for now use PR_OpenFile */ - PRFileDesc *fp; - int32 len; - char *path; - static char buf[512]; /* xxx alloc */ - CRAWL_RobotParse parse; - CRAWL_RobotControl control = MakeRobotControl("foo"); - /* XXX need to unescape URL */ - path=&(url[8]); - fp = PR_Open(path, PR_RDONLY, 0644); - if(fp == NULL) - { - return; - } - parse = PR_NEWZAP(CRAWL_RobotParseStruct); - while((len=PR_Read(fp, buf, 512))>0) { - if (crawl_parseRobotControlInfo(control, parse, buf, len) == MOZILLA_RECORD_READ) break; - } - PR_Close(fp); - PR_Free(parse); - DestroyRobotControl(control); - return; -} -#endif diff --git a/mozilla/network/main/robotxt.h b/mozilla/network/main/robotxt.h deleted file mode 100644 index 1a1101a6b84..00000000000 --- a/mozilla/network/main/robotxt.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/*** robotxt.h ****************************************************/ -/* description: parses the robots.txt file */ -/* - not dependent on the crawler */ - - - /******************************************************************** - See the robots.txt specification at: - - http://info.webcrawler.com/mak/projects/robots/norobots.html (original spec) - http://info.webcrawler.com/mak/projects/robots/norobots-rfc.html - - Note: the original spec says that at least one Disallow field must be present - in a record. That is what I am following. - - $Revision: 1.2 $ - $Date: 1999-11-06 02:32:43 $ - - *********************************************************************/ - -#ifndef robotctl_h___ -#define robotctl_h___ - -#include "prtypes.h" -#include "ntypes.h" -#include "net.h" - -typedef uint8 CRAWL_RobotControlStatus; -#define CRAWL_ROBOT_DISALLOWED ((CRAWL_RobotControlStatus)0x00) -#define CRAWL_ROBOT_ALLOWED ((CRAWL_RobotControlStatus)0x01) -#define CRAWL_ROBOTS_TXT_NOT_QUERIED ((CRAWL_RobotControlStatus)0x02) - -typedef struct _CRAWL_RobotControlStruct *CRAWL_RobotControl; - -/* - * Typedef for function callback called after robots.txt is read. - */ - typedef void -(PR_CALLBACK *CRAWL_RobotControlStatusFunc)(void *data); - -/* stream function */ -PUBLIC NET_StreamClass* -CRAWL_RobotsTxtConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id); - -/****************************************************************************************/ -/* public API */ -/****************************************************************************************/ - -NSPR_BEGIN_EXTERN_C - -/* Creates a robot control for the site. - Parameters: - context - context for libnet - site - protocol and host portion of url. "/robots.txt" will be appended to this to get the - location of robots.txt. -*/ -PR_EXTERN(CRAWL_RobotControl) -CRAWL_MakeRobotControl(MWContext *context, char *site); - -/* Destroys a robot control and all memory associated with it (except for the context or the - opaque data supplied to CRAWL_ReadRobotControlFile) -*/ -PR_EXTERN(void) -CRAWL_DestroyRobotControl(CRAWL_RobotControl control); - -/* Parses the robots.txt at the site specified in the control, and performs a callback when - it is done. This function returns after issuing a request to netlib. - Parameters: - control - the robot control for the site - func - completion callback - data - data to provide to the callback which is opaque to the robots.txt parser - freeData - if true, frees data (previous param) on completion -*/ -PR_EXTERN(PRBool) -CRAWL_ReadRobotControlFile(CRAWL_RobotControl control, CRAWL_RobotControlStatusFunc func, void *data, PRBool freeData); - -/* Returns a status code indicating the robot directive for the url supplied */ -PR_EXTERN(CRAWL_RobotControlStatus) -CRAWL_GetRobotControl(CRAWL_RobotControl, char *url); - -NSPR_END_EXTERN_C - -#endif - diff --git a/mozilla/network/main/singsign.c b/mozilla/network/main/singsign.c deleted file mode 100644 index e952a9f6dfa..00000000000 --- a/mozilla/network/main/singsign.c +++ /dev/null @@ -1,3147 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#if defined(SingleSignon) - -#define alphabetize 1 -#include "libi18n.h" /* For the character code set conversions */ -#include "secnav.h" /* For SECNAV_UnMungeString and SECNAV_MungeString */ - -#ifdef XP_MAC -#include "prpriv.h" /* for NewNamedMonitor */ -#include "prinrval.h" /* for PR_IntervalNow */ -#ifdef APPLE_KEYCHAIN /* APPLE */ -#include "Keychain.h" /* APPLE */ -#define kNetscapeProtocolType 'form' /* APPLE */ -#endif /* APPLE */ -#else -#include "private/prpriv.h" /* for NewNamedMonitor */ -#endif - -#ifdef PROFILE -#pragma profile on -#endif - -#include "prefapi.h" -#include "xpgetstr.h" -#include "xpgetstr.h" - -extern int MK_SIGNON_PASSWORDS_GENERATE; -extern int MK_SIGNON_PASSWORDS_REMEMBER; -extern int MK_SIGNON_PASSWORDS_FETCH; -extern int MK_SIGNON_YOUR_SIGNONS; -extern int MK_SIGNON_YOUR_SIGNON_REJECTS; -extern int MK_SIGNON_NOTIFICATION; -extern int MK_SIGNON_NOTIFICATION_1; -extern int MK_SIGNON_NAG; -extern int MK_SIGNON_REMEMBER; -extern int MK_SIGNON_SELECTUSER; -extern int MK_SIGNON_CHANGE; - -/* locks for signon cache */ - -static PRMonitor * signon_lock_monitor = NULL; -static PRThread * signon_lock_owner = NULL; -static int signon_lock_count = 0; -static Bool si_anonymous = FALSE; - -#ifdef APPLE_KEYCHAIN -static Bool si_list_invalid = FALSE; -static KCCallbackUPP si_kcUPP = NULL; -PRIVATE int -si_SaveSignonDataInKeychain(); - -#endif - -/* the following is from the now-defunct lo_ele.h */ -struct LO_FormSubmitData_struct { - int32 value_cnt; - PA_Block name_array; - PA_Block value_array; - PA_Block type_array; -}; -#define FORM_TYPE_TEXT 1 -#define FORM_TYPE_PASSWORD 7 - -/* temporary */ -/* - * Need this for now because the normal call to FE_Confirm goes through - * a pointer in the context (context->func->confirm) and the context - * doesn't exist when we get control from layout, namely when SI_RememberSignonData - * is called - * - * Same applies to FE_SelectDialog because context doesn't exist when - * SI_RestoreSignonData is called - */ -static const char *pref_useDialogs = - "wallet.useDialogs"; -PRIVATE Bool si_useDialogs = FALSE; - -PRIVATE void -si_SetUsingDialogsPref(Bool x) -{ - /* do nothing if new value of pref is same as current value */ - if (x == si_useDialogs) { - return; - } - - /* change the pref */ - si_useDialogs = x; -} - -MODULE_PRIVATE int PR_CALLBACK -si_UsingDialogsPrefChanged(const char * newpref, void * data) -{ - Bool x; - PREF_GetBoolPref(pref_useDialogs, &x); - si_SetUsingDialogsPref(x); - return PREF_NOERROR; -} - -void -si_RegisterUsingDialogsPrefCallbacks(void) -{ - Bool x = FALSE; /* initialize to default value in case PREF_GetBoolPref fails */ - static Bool first_time = TRUE; - - if(first_time) - { - first_time = FALSE; - PREF_GetBoolPref(pref_useDialogs, &x); - si_SetUsingDialogsPref(x); - PREF_RegisterCallback(pref_useDialogs, si_UsingDialogsPrefChanged, NULL); - } -} - -PRIVATE Bool -si_GetUsingDialogsPref(void) -{ - si_RegisterUsingDialogsPrefCallbacks(); - return si_useDialogs; -} - -Bool -MyFE_Confirm(const char* szMessage) -{ - char c; - - if (!si_GetUsingDialogsPref()) { - return JS_TRUE; - } - - fprintf(stdout, "%c%s (y/n)? ", '\007', szMessage); /* \007 is BELL */ - for (;;) { - c = getchar(); - if (tolower(c) == 'y') { - return JS_TRUE; - } - if (tolower(c) == 'n') { - return JS_FALSE; - } - } -} - -Bool -MyFE_SelectDialog - (const char* szMessage, const char** pList, int16* pCount) -{ - char c; - int i; - - if (!si_GetUsingDialogsPref()) { - *pCount = 0; - return JS_TRUE; - } - - fprintf(stdout, "%s\n", szMessage); - for (i=0; i<*pCount; i++) { - fprintf(stdout, "%d: %s\n", i, pList[i]); - } - fprintf(stdout, "%cType user number (max=9) or type n to cancel. ", '\007'); /* \007 is BELL */ - for (;;) { - c = getchar(); - if (c >= '0' && c <= '9') { - *pCount = c - '0'; - return JS_TRUE; - } - if (tolower(c) == 'n') { - return JS_FALSE; - } - } -} - -/* end of temporary */ - -PRIVATE void -si_lock_signon_list(void) -{ - if(!signon_lock_monitor) { - signon_lock_monitor = - PR_NewNamedMonitor("signon-lock"); - } - - PR_EnterMonitor(signon_lock_monitor); - - while(TRUE) { - - /* no current owner or owned by this thread */ - PRThread * t = PR_CurrentThread(); - if(signon_lock_owner == NULL || signon_lock_owner == t) { - signon_lock_owner = t; - signon_lock_count++; - - PR_ExitMonitor(signon_lock_monitor); - return; - } - - /* owned by someone else -- wait till we can get it */ - PR_Wait(signon_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} - -PRIVATE void -si_unlock_signon_list(void) -{ - PR_EnterMonitor(signon_lock_monitor); - -#ifdef DEBUG - /* make sure someone doesn't try to free a lock they don't own */ - PR_ASSERT(signon_lock_owner == PR_CurrentThread()); -#endif - - signon_lock_count--; - - if(signon_lock_count == 0) { - signon_lock_owner = NULL; - PR_Notify(signon_lock_monitor); - } - PR_ExitMonitor(signon_lock_monitor); - -} - - -/* - * Data and procedures for rememberSignons preference - */ - -static const char *pref_rememberSignons = - "network.signon.rememberSignons"; -PRIVATE Bool si_RememberSignons = FALSE; - -PRIVATE int -si_SaveSignonDataLocked(char * filename); - -PRIVATE void -si_SetSignonRememberingPref(Bool x) -{ - /* do nothing if new value of pref is same as current value */ - if (x == si_RememberSignons) { - return; - } - - /* if pref is being turned off, save the current signons to a file */ - if (x == 0) { - si_lock_signon_list(); - si_SaveSignonDataLocked(NULL); - si_unlock_signon_list(); -#ifdef APPLE_KEYCHAIN - /* We no longer need the Keychain callback installed */ - KCRemoveCallback( si_kcUPP ); - DisposeRoutineDescriptor( si_kcUPP ); - si_kcUPP = NULL; -#endif - } - - /* change the pref */ - si_RememberSignons = x; - - /* if pref is being turned on, load the signon file into memory */ - if (x == 1) { - SI_RemoveAllSignonData(); - SI_LoadSignonData(NULL); - } -} - -MODULE_PRIVATE int PR_CALLBACK -si_SignonRememberingPrefChanged(const char * newpref, void * data) -{ - Bool x; - PREF_GetBoolPref(pref_rememberSignons, &x); - si_SetSignonRememberingPref(x); - return PREF_NOERROR; -} - -void -si_RegisterSignonPrefCallbacks(void) -{ - Bool x = TRUE; /* initialize to default value in case PREF_GetBoolPref fails */ - static Bool first_time = TRUE; - - if(first_time) - { - first_time = FALSE; - PREF_GetBoolPref(pref_rememberSignons, &x); - si_SetSignonRememberingPref(x); - PREF_RegisterCallback(pref_rememberSignons, si_SignonRememberingPrefChanged, NULL); - } -} - -PRIVATE Bool -si_GetSignonRememberingPref(void) -{ -#ifdef APPLE_KEYCHAIN - /* If the Keychain has been locked or an item deleted or updated, - we need to reload the signon data */ - if (si_list_invalid) - { - /* - * set si_list_invalid to FALSE first because SI_RemoveAllSignonData - * calls si_GetSignonRememberingPref - */ - si_list_invalid = FALSE; - SI_RemoveAllSignonData(); - SI_LoadSignonData(NULL); - } -#endif - - si_RegisterSignonPrefCallbacks(); - return si_RememberSignons; -} - -/* - * Data and procedures for signon cache - */ - -typedef struct _SignonDataStruct { - char * name; - char * value; - Bool isPassword; -} si_SignonDataStruct; - -typedef struct _SignonUserStruct { - XP_List * signonData_list; -} si_SignonUserStruct; - -typedef struct _SignonURLStruct { - char * URLName; - si_SignonUserStruct* chosen_user; /* this is a state variable */ - XP_List * signonUser_list; -} si_SignonURLStruct; - - -typedef struct _RejectStruct { - char * URLName; - char * userName; -} si_Reject; - -PRIVATE XP_List * si_signon_list=0; -PRIVATE XP_List * si_reject_list=0; - -PRIVATE Bool si_signon_list_changed = FALSE; -PRIVATE int si_TagCount = 0; -PRIVATE Bool si_NoticeGiven = FALSE; - - -/* Remove misleading portions from URL name */ -PRIVATE char* -si_StrippedURL (char* URLName) { - char *result = 0; - char *s, *t; - - /* check for null URLName */ - if (URLName == NULL || XP_STRLEN(URLName) == 0) { - return NULL; - } - - /* check for protocol at head of URL */ - s = URLName; - s = (char*) XP_STRCHR(s+1, '/'); - if (s) { - if (*(s+1) == '/') { - /* looks good, let's parse it */ - return NET_ParseURL(URLName, GET_HOST_PART); - } else { - /* not a valid URL, leave it as is */ - StrAllocCopy(result, URLName); - return result; - } - } - - /* initialize result */ - StrAllocCopy(result, URLName); - - /* remove everything in result after and including first question mark */ - s = result; - s = (char*) XP_STRCHR(s, '?'); - if (s) { - *s = '\0'; - } - - /* remove everything in result after last slash (e.g., index.html) */ - s = result; - t = 0; - while ((s = (char*) XP_STRCHR(s+1, '/'))) { - t = s; - } - if (t) { - *(t+1) = '\0'; - } - - /* remove socket number from result */ - s = result; - while ((s = (char*) XP_STRCHR(s+1, ':'))) { - /* s is at next colon */ - if (*(s+1) != '/') { - /* and it's not :// so it must be start of socket number */ - if ((t = (char*) XP_STRCHR(s+1, '/'))) { - /* t is at slash terminating the socket number */ - do { - /* copy remainder of t to s */ - *s++ = *t; - } while (*(t++)); - } - break; - } - } - - /* alll done */ - return result; -} - -/* remove terminating CRs or LFs */ -PRIVATE void -si_StripLF(char* buffer) { - while ((buffer[XP_STRLEN(buffer)-1] == '\n') || - (buffer[XP_STRLEN(buffer)-1] == '\r')) { - buffer[XP_STRLEN(buffer)-1] = '\0'; - } -} - -/* If user-entered password is "generate", then generate a random password */ -PRIVATE void -si_Randomize(char * password) { - PRIntervalTime random; - int i; - const char * hexDigits = "0123456789AbCdEf"; - if (XP_STRCMP(password, XP_GetString(MK_SIGNON_PASSWORDS_GENERATE)) == 0) { - random = PR_IntervalNow(); - for (i=0; i<8; i++) { - password[i] = hexDigits[random%16]; - random = random/16; - } - } -} - -/* - * Get the URL node for a given URL name - * - * This routine is called only when holding the signon lock!!! - */ -PRIVATE si_SignonURLStruct * -si_GetURL(char * URLName) { - XP_List * list_ptr = si_signon_list; - si_SignonURLStruct * url; - char *strippedURLName = 0; - - if (!URLName) { - /* no URLName specified, return first URL (returns NULL if not URLs) */ - return (si_SignonURLStruct *) XP_ListNextObject(list_ptr); - } - - strippedURLName = si_StrippedURL(URLName); - while((url = (si_SignonURLStruct *) XP_ListNextObject(list_ptr))!=0) { - if(url->URLName && !XP_STRCMP(strippedURLName, url->URLName)) { - XP_FREE(strippedURLName); - return url; - } - } - XP_FREE(strippedURLName); - return (NULL); -} - -/* Remove a user node from a given URL node */ -PUBLIC Bool -SI_RemoveUser(char *URLName, char *userName, Bool save) { - si_SignonURLStruct * url; - si_SignonUserStruct * user; - si_SignonDataStruct * data; - XP_List * user_ptr; - XP_List * data_ptr; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()) { - return FALSE; - } - - si_lock_signon_list(); - - /* get URL corresponding to URLName (or first URL if URLName is NULL) */ - url = si_GetURL(URLName); - if (!url) { - /* URL not found */ - si_unlock_signon_list(); - return FALSE; - } - - /* free the data in each node of the specified user node for this URL */ - user_ptr = url->signonUser_list; - - if (userName == NULL) { - - /* no user specified so remove the first one */ - user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr); - - } else { - - /* find the specified user */ - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - data_ptr = user->signonData_list; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if (XP_STRCMP(data->value, userName)==0) { - goto foundUser; - } - } - } - si_unlock_signon_list(); - return FALSE; /* user not found so nothing to remove */ - foundUser: ; - } - - /* free the items in the data list */ - data_ptr = user->signonData_list; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - XP_FREE(data->name); - XP_FREE(data->value); - } - - /* free the data list */ - XP_ListDestroy(user->signonData_list); - - /* free the user node */ - XP_ListRemoveObject(url->signonUser_list, user); - - /* remove this URL if it contains no more users */ - if (XP_ListCount(url->signonUser_list) == 0) { - XP_FREE(url->URLName); - XP_ListRemoveObject(si_signon_list, url); - } - - /* write out the change to disk */ - if (save) { - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - } - - si_unlock_signon_list(); - return TRUE; -} - -/* Determine if a specified url/user exists */ -PRIVATE Bool -si_CheckForUser(char *URLName, char *userName) { - si_SignonURLStruct * url; - si_SignonUserStruct * user; - si_SignonDataStruct * data; - XP_List * user_ptr; - XP_List * data_ptr; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()) { - return FALSE; - } - - si_lock_signon_list(); - - /* get URL corresponding to URLName */ - url = si_GetURL(URLName); - if (!url) { - /* URL not found */ - si_unlock_signon_list(); - return FALSE; - } - - /* find the specified user */ - user_ptr = url->signonUser_list; - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - data_ptr = user->signonData_list; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if (XP_STRCMP(data->value, userName)==0) { - si_unlock_signon_list(); - return TRUE; - } - } - } - si_unlock_signon_list(); - return FALSE; /* user not found */ -} - -/* - * Get the user node for a given URL - * - * This routine is called only when holding the signon lock!!! - * - * This routine is called only if signon pref is enabled!!! - */ -PRIVATE si_SignonUserStruct* -si_GetUser(char* URLName, Bool pickFirstUser, char* userText) { - si_SignonURLStruct* url; - si_SignonUserStruct* user; - si_SignonDataStruct* data; - XP_List * data_ptr=0; - XP_List * user_ptr=0; - - /* get to node for this URL */ - url = si_GetURL(URLName); - if (url != NULL) { - - /* node for this URL was found */ - int16 user_count; - user_ptr = url->signonUser_list; - if ((user_count = XP_ListCount(user_ptr)) == 1) { - - /* only one set of data exists for this URL so select it */ - user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr); - url->chosen_user = user; - - } else if (pickFirstUser) { - user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr); - - } else { - /* multiple users for this URL so a choice needs to be made */ - char ** list; - char ** list2; - si_SignonUserStruct** users; - si_SignonUserStruct** users2; - list = XP_ALLOC(user_count*sizeof(char*)); - users = XP_ALLOC(user_count*sizeof(si_SignonUserStruct*)); - list2 = list; - users2 = users; - - /* step through set of user nodes for this URL and create list of - * first data node of each (presumably that is the user name). - * Note that the user nodes are already ordered by - * most-recently-used so the first one in the list is the most - * likely one to be chosen. - */ - user_count = 0; - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - data_ptr = user->signonData_list; - /* consider first data node to be the identifying item */ - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - if (PL_strcmp(data->name, userText)) { - /* name of current data item does not match name in data node */ - continue; - } - *(list2++) = data->value; - *(users2++) = user; - user_count++; - } - - /* have user select a username from the list */ - if (user_count == 0) { - /* not first data node for any saved user, so simply pick first user */ - user_ptr = url->signonUser_list; - user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr); - } else if (user_count == 1) { - /* only one user for this form at this url, so select it */ - user = users[0]; - } else if ((user_count > 1) && MyFE_SelectDialog( - XP_GetString(MK_SIGNON_SELECTUSER), - list, &user_count)) { - /* user pressed OK */ - if (user_count == -1) { - user_count = 0; /* user didn't select, so use first one */ - } - user = users[user_count]; /* this is the selected item */ - /* item selected is now most-recently used, put at head of list */ - XP_ListRemoveObject(url->signonUser_list, user); - XP_ListAddObject(url->signonUser_list, user); - } else { - user = NULL; - } - url->chosen_user = user; - XP_FREE(list); - XP_FREE(users); - - /* if we don't remove the URL from the cache at this point, the - * cached copy will be brought in containing the last-used username - * rather than the username that was just selected - */ - NET_RemoveURLFromCache - (NET_CreateURLStruct((char *)URLName, NET_DONT_RELOAD)); - - } - } else { - user = NULL; - } - return user; -} - -/* - * Get the user for which a change-of-password is to be applied - * - * This routine is called only when holding the signon lock!!! - * - * This routine is called only if signon pref is enabled!!! - */ -PRIVATE si_SignonUserStruct* -si_GetUserForChangeForm(char* URLName, int messageNumber) -{ - si_SignonURLStruct* url; - si_SignonUserStruct* user; - si_SignonDataStruct * data; - XP_List * user_ptr = 0; - XP_List * data_ptr = 0; - char *message = 0; - - /* get to node for this URL */ - url = si_GetURL(URLName); - if (url != NULL) { - - /* node for this URL was found */ - user_ptr = url->signonUser_list; - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - char *strippedURLName = si_StrippedURL(URLName); - data_ptr = user->signonData_list; - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - message = PR_smprintf(XP_GetString(messageNumber), - data->value, - strippedURLName); - XP_FREE(strippedURLName); - if (MyFE_Confirm(message)) { - /* - * since this user node is now the most-recently-used one, move it - * to the head of the user list so that it can be favored for - * re-use the next time this form is encountered - */ - XP_ListRemoveObject(url->signonUser_list, user); - XP_ListAddObject(url->signonUser_list, user); - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - XP_FREE(message); - return user; - } - } - } - XP_FREE(message); - return NULL; -} - -/* - * Get the url and user for which a change-of-password is to be applied - * - * This routine is called only when holding the signon lock!!! - * - * This routine is called only if signon pref is enabled!!! - */ -PRIVATE si_SignonUserStruct* -si_GetURLAndUserForChangeForm(char* password) -{ - si_SignonURLStruct* url; - si_SignonUserStruct* user; - si_SignonDataStruct * data; - XP_List * url_ptr = 0; - XP_List * user_ptr = 0; - XP_List * data_ptr = 0; - char *message = 0; - int16 user_count; - - char ** list; - char ** list2; - si_SignonUserStruct** users; - si_SignonUserStruct** users2; - si_SignonURLStruct** urls; - si_SignonURLStruct** urls2; - - /* get count of total number of user nodes at all url nodes */ - user_count = 0; - url_ptr = si_signon_list; - while((url = (si_SignonURLStruct *) XP_ListNextObject(url_ptr))!=0) { - user_ptr = url->signonUser_list; - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - user_count++; - } - } - - /* allocate lists for maximumum possible url and user names */ - list = XP_ALLOC(user_count*sizeof(char*)); - users = XP_ALLOC(user_count*sizeof(si_SignonUserStruct*)); - urls = XP_ALLOC(user_count*sizeof(si_SignonUserStruct*)); - list2 = list; - users2 = users; - urls2 = urls; - - /* step through set of URLs and users and create list of each */ - user_count = 0; - url_ptr = si_signon_list; - while((url = (si_SignonURLStruct *) XP_ListNextObject(url_ptr))!=0) { - user_ptr = url->signonUser_list; - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - data_ptr = user->signonData_list; - /* find saved password and see if it matches password user just entered */ - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if (data->isPassword && !PL_strcmp(data->value, password)) { - /* passwords match so add entry to list */ - /* consider first data node to be the identifying item */ - data_ptr = user->signonData_list; - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - *list2 = 0; - StrAllocCopy(*list2, url->URLName); - StrAllocCat(*list2,": "); - StrAllocCat(*list2, data->value); - list2++; - *(users2++) = user; - *(urls2++) = url; - user_count++; - break; - } - } - } - } - - /* query user */ - if (user_count && MyFE_SelectDialog - (XP_GetString(MK_SIGNON_CHANGE), - list, - &user_count)) { - user = users[user_count]; - url = urls[user_count]; - /* - * since this user node is now the most-recently-used one, move it - * to the head of the user list so that it can be favored for - * re-use the next time this form is encountered - */ - XP_ListRemoveObject(url->signonUser_list, user); - XP_ListAddObject(url->signonUser_list, user); - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - } else { - user = NULL; - } - - /* free allocated strings */ - while (--list2 > list) { - XP_FREE(*list2); - } - XP_FREE(list); - XP_FREE(users); - XP_FREE(urls); - - return user; - -} - -PRIVATE void -si_FreeReject(si_Reject * reject) { - - /* - * This routine should only be called while holding the - * signon list lock - */ - - if(!reject) { - return; - } - XP_ListRemoveObject(si_reject_list, reject); - PR_FREEIF(reject->URLName); - PR_FREEIF(reject->userName); - PR_Free(reject); -} - -PRIVATE Bool -si_CheckForReject(char * URLName, char * userName) { - XP_List * list_ptr; - si_Reject * reject; - - si_lock_signon_list(); - if (si_reject_list) { - list_ptr = si_reject_list; - while((reject = (si_Reject *) XP_ListNextObject(list_ptr))!=0) { - if(!PL_strcmp(userName, reject->userName) && - !PL_strcmp(URLName, reject->URLName)) { - si_unlock_signon_list(); - return TRUE; - } - } - } - si_unlock_signon_list(); - return FALSE; -} - -PRIVATE void -si_PutReject(char * URLName, char * userName, Bool save) { - si_Reject * reject; - char * URLName2=NULL; - char * userName2=NULL; - - reject = PR_NEW(si_Reject); - if (reject) { - /* - * lock the signon list - * Note that, for efficiency, SI_LoadSignonData already sets the lock - * before calling this routine whereas none of the other callers do. - * So we need to determine whether or not we were called from - * SI_LoadSignonData before setting or clearing the lock. We can - * determine this by testing "save" since only SI_LoadSignonData - * passes in a value of FALSE for "save". - */ - XP_List * list_ptr; - if (save) { - si_lock_signon_list(); - } - list_ptr = si_reject_list; - - StrAllocCopy(URLName2, URLName); - StrAllocCopy(userName2, userName); - reject->URLName = URLName2; - reject->userName = userName2; - - if(!si_reject_list) { - si_reject_list = XP_ListNew(); - if(!si_reject_list) { - PR_Free(reject->URLName); - PR_Free(reject->userName); - PR_Free(reject); - if (save) { - si_unlock_signon_list(); - } - return; - } - } -#ifdef alphabetize - /* add it to the list in alphabetical order */ - { - si_Reject * tmp_reject; - Bool rejectAdded = FALSE; - while((tmp_reject = (si_Reject *) XP_ListNextObject(list_ptr))!=0) { - if (PL_strcmp (reject->URLName, tmp_reject->URLName)<0) { - XP_ListInsertObject (si_reject_list, tmp_reject, reject); - rejectAdded = TRUE; - break; - } - } - if (!rejectAdded) { - XP_ListAddObjectToEnd (si_reject_list, reject); - } - } -#else - /* add it to the end of the list */ - XP_ListAddObjectToEnd (si_reject_list, reject); -#endif - - if (save) { - si_signon_list_changed = TRUE; - SI_SaveSignonData(NULL); - } - if (save) { - si_unlock_signon_list(); - } - } -} - -/* Ask user if it is ok to save the signon data */ -PRIVATE Bool -si_OkToSave(char *URLName, char *userName) { - Bool remember_checked = TRUE; - char *strippedURLName = 0; - - /* if url/user already exists, then it is safe to save it again */ - if (si_CheckForUser(URLName, userName)) { - return TRUE; - } - - if (!si_NoticeGiven) { - char* notification = 0; - si_NoticeGiven = TRUE; - si_signon_list_changed = TRUE; - SI_SaveSignonData(NULL); - StrAllocCopy(notification, XP_GetString(MK_SIGNON_NOTIFICATION)); - StrAllocCat(notification, XP_GetString(MK_SIGNON_NOTIFICATION_1)); - if (!MyFE_Confirm(notification)) { - XP_FREE (notification); - PREF_SetBoolPref(pref_rememberSignons, FALSE); - return FALSE; - } - XP_FREE (notification); - } - - strippedURLName = si_StrippedURL(URLName); - if (si_CheckForReject(strippedURLName, userName)) { - XP_FREE(strippedURLName); - return FALSE; - } - - if (!MyFE_Confirm(XP_GetString(MK_SIGNON_NAG))) { - si_PutReject(strippedURLName, userName, TRUE); - XP_FREE(strippedURLName); - return FALSE; - } - XP_FREE(strippedURLName); - return TRUE; -} - -/* - * Put data obtained from a submit form into the data structure for - * the specified URL - * - * See comments below about state of signon lock when routine is called!!! - * - * This routine is called only if signon pref is enabled!!! - */ -PRIVATE void -si_PutData(char * URLName, LO_FormSubmitData * submit, Bool save) { - char * name; - char * value; - Bool added_to_list = FALSE; - si_SignonURLStruct * url; - si_SignonUserStruct * user; - si_SignonDataStruct * data; - int j; - XP_List * list_ptr; - XP_List * user_ptr; - XP_List * data_ptr; - si_SignonURLStruct * tmp_URL_ptr; - Bool mismatch; - int i; - - /* discard this if the password is empty */ - for (i=0; i<submit->value_cnt; i++) { - if ((((uint8*)submit->type_array)[i] == FORM_TYPE_PASSWORD) && - (!((char **)(submit->value_array))[i] || - !XP_STRLEN( ((char **)(submit->value_array)) [i])) ) { - return; - } - } - - /* - * lock the signon list - * Note that, for efficiency, SI_LoadSignonData already sets the lock - * before calling this routine whereas none of the other callers do. - * So we need to determine whether or not we were called from - * SI_LoadSignonData before setting or clearing the lock. We can - * determine this by testing "save" since only SI_LoadSignonData passes - * in a value of FALSE for "save". - */ - if (save) { - si_lock_signon_list(); - } - - /* make sure the signon list exists */ - if(!si_signon_list) { - si_signon_list = XP_ListNew(); - if(!si_signon_list) { - if (save) { - si_unlock_signon_list(); - } - return; - } - } - - /* find node in signon list having the same URL */ - if ((url = si_GetURL(URLName)) == NULL) { - - /* doesn't exist so allocate new node to be put into signon list */ - url = XP_NEW(si_SignonURLStruct); - if (!url) { - if (save) { - si_unlock_signon_list(); - } - return; - } - - /* fill in fields of new node */ - url->URLName = si_StrippedURL(URLName); - if (!url->URLName) { - XP_FREE(url); - if (save) { - si_unlock_signon_list(); - } - return; - } - - url->signonUser_list = XP_ListNew(); - if(!url->signonUser_list) { - XP_FREE(url->URLName); - XP_FREE(url); - } - - /* put new node into signon list */ - -#ifdef alphabetize - /* add it to the list in alphabetical order */ - list_ptr = si_signon_list; - while((tmp_URL_ptr = - (si_SignonURLStruct *) XP_ListNextObject(list_ptr))!=0) { - if(PL_strcmp(url->URLName,tmp_URL_ptr->URLName)<0) { - XP_ListInsertObject - (si_signon_list, tmp_URL_ptr, url); - added_to_list = TRUE; - break; - } - } - if (!added_to_list) { - XP_ListAddObjectToEnd (si_signon_list, url); - } - } -#else - /* add it to the end of the list */ - XP_ListAddObjectToEnd (si_signon_list, url); -#endif - - /* initialize state variables in URL node */ - url->chosen_user = NULL; - - /* - * see if a user node with data list matching new data already exists - * (password fields will not be checked for in this matching) - */ - user_ptr = url->signonUser_list; - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr))!=0) { - data_ptr = user->signonData_list; - j = 0; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - mismatch = FALSE; - - /* skip non text/password fields */ - while ((j < submit->value_cnt) && - (((uint8*)submit->type_array)[j]!=FORM_TYPE_TEXT) && - (((uint8*)submit->type_array)[j]!=FORM_TYPE_PASSWORD)) { - j++; - } - - /* check for match on name field and type field */ - if ((j < submit->value_cnt) && - (data->isPassword == - (((uint8*)submit->type_array)[j]==FORM_TYPE_PASSWORD)) && - (!XP_STRCMP(data->name, ((char **)submit->name_array)[j]))) { - - /* success, now check for match on value field if not password */ - if (!submit->value_array[j]) { - /* special case a null value */ - if (!XP_STRCMP(data->value, "")) { - j++; /* success */ - } else { - mismatch = TRUE; - break; /* value mismatch, try next user */ - } - } else if (!XP_STRCMP(data->value, ((char **)submit->value_array)[j]) - || data->isPassword) { - j++; /* success */ - } else { - mismatch = TRUE; - break; /* value mismatch, try next user */ - } - } else { - mismatch = TRUE; - break; /* name or type mismatch, try next user */ - } - - } - if (!mismatch) { - - /* all names and types matched and all non-password values matched */ - - /* - * note: it is ok for password values not to match; it means - * that the user has either changed his password behind our - * back or that he previously mis-entered the password - */ - - /* update the saved password values */ - data_ptr = user->signonData_list; - j = 0; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - - /* skip non text/password fields */ - while ((j < submit->value_cnt) && - (((uint8*)submit->type_array)[j]!=FORM_TYPE_TEXT) && - (((uint8*)submit->type_array)[j]!=FORM_TYPE_PASSWORD)) { - j++; - } - - /* update saved password */ - if ((j < submit->value_cnt) && data->isPassword) { - if (XP_STRCMP(data->value, ((char **)submit->value_array)[j])) { - si_signon_list_changed = TRUE; - StrAllocCopy(data->value, ((char **)submit->value_array)[j]); - si_Randomize(data->value); - } - } - j++; - } - - /* - * since this user node is now the most-recently-used one, move it - * to the head of the user list so that it can be favored for - * re-use the next time this form is encountered - */ - XP_ListRemoveObject(url->signonUser_list, user); - XP_ListAddObject(url->signonUser_list, user); - - /* return */ - if (save) { - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - si_unlock_signon_list(); - } - return; /* nothing more to do since data already exists */ - } - } - - /* user node with current data not found so create one */ - user = XP_NEW(si_SignonUserStruct); - if (!user) { - if (save) { - si_unlock_signon_list(); - } - return; - } - user->signonData_list = XP_ListNew(); - if(!user->signonData_list) { - XP_FREE(user); - if (save) { - si_unlock_signon_list(); - } - return; - } - - - /* create and fill in data nodes for new user node */ - for (j=0; j<submit->value_cnt; j++) { - - /* skip non text/password fields */ - if((((uint8*)submit->type_array)[j]!=FORM_TYPE_TEXT) && - (((uint8*)submit->type_array)[j]!=FORM_TYPE_PASSWORD)) { - continue; - } - - /* create signon data node */ - data = XP_NEW(si_SignonDataStruct); - if (!data) { - XP_ListDestroy(user->signonData_list); - XP_FREE(user); - } - data->isPassword = - (((uint8 *)submit->type_array)[j] == FORM_TYPE_PASSWORD); - name = 0; /* so that StrAllocCopy doesn't free previous name */ - StrAllocCopy(name, ((char **)submit->name_array)[j]); - data->name = name; - value = 0; /* so that StrAllocCopy doesn't free previous name */ - if (submit->value_array[j]) { - StrAllocCopy(value, ((char **)submit->value_array)[j]); - } else { - StrAllocCopy(value, ""); /* insures that value is not null */ - } - data->value = value; - if (data->isPassword) { - si_Randomize(data->value); - } - - /* append new data node to end of data list */ - XP_ListAddObjectToEnd (user->signonData_list, data); - } - - /* append new user node to front of user list for matching URL */ - /* - * Note that by appending to the front, we assure that if there are - * several users, the most recently used one will be favored for - * reuse the next time this form is encountered. But don't do this - * when reading in signons.txt (i.e., when save is false), otherwise - * we will be reversing the order when reading in. - */ - if (save) { - XP_ListAddObject(url->signonUser_list, user); - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - si_unlock_signon_list(); - } else { - XP_ListAddObjectToEnd(url->signonUser_list, user); - } -} - -/* - * When a new form is started, set the tagCount to 0 - */ -PUBLIC void -SI_StartOfForm() { - si_TagCount = 0; -} - -/* - * APPLE - * The Keychain callback. This routine will be called whenever a lock, - * delete, or update event occurs in the Keychain. The only action taken - * is to make the signon list invalid, so it will be read in again the - * next time it is accessed. - */ -#ifdef APPLE_KEYCHAIN -OSStatus PR_CALLBACK -si_KeychainCallback( KCEvent keychainEvent, KCCallbackInfo *info, void *userContext) { - Bool *listInvalid = (Bool*)userContext; - *listInvalid = TRUE; -} -#endif - -#define BUFFER_SIZE 4096 -#define MAX_ARRAY_SIZE 50 -/* - * APPLE - * Get the signon data from the keychain - * - * This routine is called only if signon pref is enabled!!! - */ -#ifdef APPLE_KEYCHAIN -PRIVATE int -si_LoadSignonDataFromKeychain() { - char * URLName; - LO_FormSubmitData submit; - char* name_array[MAX_ARRAY_SIZE]; - char* value_array[MAX_ARRAY_SIZE]; - uint8 type_array[MAX_ARRAY_SIZE]; - char buffer[BUFFER_SIZE]; - XP_File fp; - Bool badInput = FALSE; - int i; - char* unmungedValue; - KCItemRef itemRef; - KCAttributeList attrList; - KCAttribute attr[2]; - KCItemClass itemClass = kInternetPasswordKCItemClass; - KCProtocolType protocol = kNetscapeProtocolType; - OSStatus status = noErr; - KCSearchRef searchRef = NULL; - - /* initialize the submit structure */ - submit.name_array = (PA_Block)name_array; - submit.value_array = (PA_Block)value_array; - submit.type_array = (PA_Block)type_array; - - /* set up the attribute list */ - attrList.count = 2; - attrList.attr = attr; - attr[0].tag = kClassKCItemAttr; - attr[0].data = &itemClass; - attr[0].length = sizeof(itemClass); - - attr[1].tag = kProtocolKCItemAttr; - attr[1].data = &protocol; - attr[1].length = sizeof(protocol); - - status = KCFindFirstItem( &attrList, &searchRef, &itemRef ); - - if (status == noErr) { - /* if we found a Netscape item, let's assume notice has been given */ - si_NoticeGiven = TRUE; - } else { - si_NoticeGiven = FALSE; - } - - si_lock_signon_list(); - while(status == noErr) { - char *value; - uint16 i = 0; - uint32 actualSize; - KCItemFlags flags; - Boolean reject = FALSE; - - submit.value_cnt = 0; - - /* first find out if it is a reject entry */ - attr[0].tag = kFlagsKCItemAttr; - attr[0].length = sizeof(KCItemFlags); - attr[0].data = &flags; - - status = KCGetAttribute( itemRef, attr, nil ); - if (status != noErr) { - break; - } - - if (flags & kNegativeKCItemFlag) { - reject = TRUE; - } - - /* get the server name */ - attr[0].tag = kServerKCItemAttr; - attr[0].length = BUFFER_SIZE; - attr[0].data = buffer; - - status = KCGetAttribute( itemRef, attr, &actualSize ); - if (status != noErr) { - break; - { - - /* null terminate */ - buffer[actualSize] = 0; - - URLName = NULL; - StrAllocCopy(URLName, buffer); - - if (!reject) { - /* get the password data */ - status = KCGetData(itemRef, BUFFER_SIZE, buffer, &actualSize); - if (status != noErr) { - break; - } - - /* null terminate */ - buffer[actualSize] = 0; - - /* parse for '=' which separates the name and value */ - for (i = 0; i < XP_STRLEN(buffer); i++) { - if (buffer[i] == '=') { - value = &buffer[i+1]; - buffer[i] = 0; - break; - } - } - name_array[submit.value_cnt] = NULL; - value_array[submit.value_cnt] = NULL; - - type_array[submit.value_cnt] = FORM_TYPE_PASSWORD; - StrAllocCopy(name_array[submit.value_cnt], buffer); - StrAllocCopy(value_array[submit.value_cnt], value); - } - - /* get the account attribute */ - attr[0].tag = kAccountKCItemAttr; - attr[0].length = BUFFER_SIZE; - attr[0].data = buffer; - - status = KCGetAttribute( itemRef, attr, &actualSize ); - if (status != noErr) { - break; - } - - /* null terminate */ - buffer[actualSize] = 0; - - if (!reject) { - /* parse for '=' which separates the name and value */ - for (i = 0; i < XP_STRLEN(buffer); i++) { - if (buffer[i] == '=') { - value = &buffer[i+1]; - buffer[i] = 0; - break; - } - } - - submit.value_cnt++; - name_array[submit.value_cnt] = NULL; - value_array[submit.value_cnt] = NULL; - - type_array[submit.value_cnt] = FORM_TYPE_TEXT; - StrAllocCopy(name_array[submit.value_cnt], buffer); - StrAllocCopy(value_array[submit.value_cnt], value); - - /* check for overruning of the arrays */ - if (submit.value_cnt >= MAX_ARRAY_SIZE) { - break; - } - - submit.value_cnt++; - /* store the info for this URL into memory-resident data structure */ - if (!URLName || XP_STRLEN(URLName) == 0) { - badInput = TRUE; - } - if (!badInput) { - si_PutData(URLName, &submit, FALSE); - } - - /* free up all the allocations done for processing this URL */ - for (i = 0; i < submit.value_cnt; i++) { - XP_FREE(name_array[i]); - XP_FREE(value_array[i]); - } - } else { - /* reject */ - si_PutReject(URLName, buffer, FALSE); - } - - reject = FALSE; /* reset reject flag */ - XP_FREE(URLName); - KCReleaseItemRef( &itemRef ); - - status = KCFindNextItem( searchRef, &itemRef ); - - } - si_unlock_signon_list(); - - if (searchRef) { - KCReleaseSearchRef( &searchRef ); - } - - /* Register a callback with the Keychain if we haven't already done so. */ - - if (si_kcUPP == NULL) - { - si_kcUPP = NewKCCallbackProc( si_KeychainCallback ); - if (!si_kcUPP) { - return memFullErr; - } - - KCAddCallback( si_kcUPP, kLockKCEventMask + kDeleteKCEventMask + kUpdateKCEventMask, &si_list_invalid ); - /* - * Note that the callback is not necessarily removed. We take advantage - * of the fact that the Keychain will clean up the callback when the app - * goes away. It is explicitly removed when the signon preference is turned off. - */ - } - - if (status == errKCItemNotFound) { - status = 0; - } - - return (status); -} -#endif - -/* - * Temporary routines until real encryption routines become available - */ -char * -MY_SECNAV_UnMungeString(char * text) { - char * result = NULL; - char* p; - StrAllocCopy(result, text); - p = result; - while (*p) { - *(p++) ^= 0xff; - } - return result; -} - -char * -MY_SECNAV_MungeString(char * text) { - char * result = NULL; - char* p; - StrAllocCopy(result, text); - p = result; - while (*p) { - *(p++) ^= 0xff; - } - return result; -} - -/* - * Load signon data from disk file - * The parameter passed in on entry is ignored - */ - -PUBLIC int -SI_LoadSignonData(char * filename) { - char * URLName; - LO_FormSubmitData submit; - char* name_array[MAX_ARRAY_SIZE]; - char* value_array[MAX_ARRAY_SIZE]; - uint8 type_array[MAX_ARRAY_SIZE]; - char buffer[BUFFER_SIZE]; - XP_File fp; - Bool badInput; - int i; - char* unmungedValue; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()) { - return 0; - } - -#ifdef APPLE_KEYCHAIN - if (KeychainManagerAvailable()) { - return si_LoadSignonDataFromKeychain(); - } -#endif - - /* open the signon file */ - if(!(fp = XP_FileOpen(filename, xpHTTPSingleSignon, XP_FILE_READ))) { - return(-1); - } - - /* skip the initial comment lines */ - do { - XP_FileReadLine(buffer, BUFFER_SIZE, fp); - } while (buffer[0] == '#'); - - /* first line after comment indicates if notice was given */ - si_NoticeGiven = (buffer[0] == 'T'); - - /* read the reject list */ - si_lock_signon_list(); - while(XP_FileReadLine(buffer, BUFFER_SIZE, fp)) { - if (buffer[0] == '.') { - break; /* end of reject list */ - } - si_StripLF(buffer); - URLName = NULL; - StrAllocCopy(URLName, buffer); - XP_FileReadLine(buffer, BUFFER_SIZE, fp); /* get username */ - si_StripLF(buffer); - si_PutReject(URLName, buffer, FALSE); - XP_FREE (URLName); - } - - /* initialize the submit structure */ - submit.name_array = (PA_Block)name_array; - submit.value_array = (PA_Block)value_array; - submit.type_array = (PA_Block)type_array; - - /* read the URL line */ - while(XP_FileReadLine(buffer, BUFFER_SIZE, fp)) { - - si_StripLF(buffer); - URLName = NULL; - StrAllocCopy(URLName, buffer); - - /* preparre to read the name/value pairs */ - submit.value_cnt = 0; - badInput = FALSE; - - while(XP_FileReadLine(buffer, BUFFER_SIZE, fp)) { - - /* line starting with . terminates the pairs for this URL entry */ - if (buffer[0] == '.') { - break; /* end of URL entry */ - } - - /* line just read is the name part */ - - /* save the name part and determine if it is a password */ - si_StripLF(buffer); - name_array[submit.value_cnt] = NULL; - if (buffer[0] == '*') { - type_array[submit.value_cnt] = FORM_TYPE_PASSWORD; - StrAllocCopy(name_array[submit.value_cnt], buffer+1); - } else { - type_array[submit.value_cnt] = FORM_TYPE_TEXT; - StrAllocCopy(name_array[submit.value_cnt], buffer); - } - - /* read in and save the value part */ - if(!XP_FileReadLine(buffer, BUFFER_SIZE, fp)) { - /* error in input file so give up */ - badInput = TRUE; - break; - } - si_StripLF(buffer); - value_array[submit.value_cnt] = NULL; - /* note that we need to skip over leading '=' of value */ - if (type_array[submit.value_cnt] == FORM_TYPE_PASSWORD) { - if ((unmungedValue=MY_SECNAV_UnMungeString(buffer+1)) == NULL) { - /* this is the free source and there is no obscuring of passwords */ - unmungedValue = buffer+1; - StrAllocCopy(value_array[submit.value_cnt++], buffer+1); - } else { - StrAllocCopy(value_array[submit.value_cnt++], unmungedValue); - XP_FREE(unmungedValue); - } - } else { - StrAllocCopy(value_array[submit.value_cnt++], buffer+1); - } - - /* check for overruning of the arrays */ - if (submit.value_cnt >= MAX_ARRAY_SIZE) { - break; - } - } - - /* store the info for this URL into memory-resident data structure */ - if (!URLName || XP_STRLEN(URLName) == 0) { - badInput = TRUE; - } - if (!badInput) { - si_PutData(URLName, &submit, FALSE); - } - - /* free up all the allocations done for processing this URL */ - XP_FREE(URLName); - for (i=0; i<submit.value_cnt; i++) { - XP_FREE(name_array[i]); - XP_FREE(value_array[i]); - } - if (badInput) { - si_unlock_signon_list(); - return (1); - } - } - si_unlock_signon_list(); - return(0); -} - - - -/* - * APPLE - * Save signon data to Apple Keychain - * - * This routine is called only if signon pref is enabled!!! - */ -#ifdef APPLE_KEYCHAIN -PRIVATE int -si_SaveSignonDataInKeychain() { - char* account = nil; - char* password = nil; - XP_List * list_ptr; - XP_List * user_ptr; - XP_List * data_ptr; - si_SignonURLStruct * URL; - si_SignonUserStruct * user; - si_SignonDataStruct * data; - si_Reject * reject; - OSStatus status; - KCItemRef itemRef; - KCAttribute attr; - KCItemFlags flags = kInvisibleKCItemFlag + kNegativeKCItemFlag; - uint32 actualLength; - - /* save off the reject list */ - if (si_reject_list) { - list_ptr = si_reject_list; - while((reject = (si_Reject *) XP_ListNextObject(list_ptr))!=0) { - status = kcaddinternetpassword - (reject->URLName, nil, - reject->userName, - kAnyPort, - kNetscapeProtocolType, - kAnyAuthType, - 0, - nil, - &itemRef); - if (status != noErr && status != errKCDuplicateItem) { - return(status); - } - if (status == noErr) { - /* - * make the item invisible so the user doesn't see it and - * negative so we know that it is a reject entry - */ - attr.tag = kFlagsKCItemAttr; - attr.data = &flags; - attr.length = sizeof( flags ); - - status = KCSetAttribute( itemRef, &attr ); - if (status != noErr) { - return(status); - } - status = KCUpdateItem(itemRef); - if (status != noErr) { - return(status); - } - KCReleaseItemRef(&itemRef); - } - } - } - - /* save off the passwords */ - if((si_signon_list)) { - list_ptr = si_signon_list; - while((URL = (si_SignonURLStruct *) XP_ListNextObject(list_ptr)) != NULL) { - - user_ptr = URL->signonUser_list; - - /* add each user node of the URL node */ - while((user = (si_SignonUserStruct *) XP_ListNextObject(user_ptr)) != NULL) { - - data_ptr = user->signonData_list; - - /* write out each data node of the user node */ - while((data=(si_SignonDataStruct *) XP_ListNextObject(data_ptr)) != NULL) { - char* attribute = nil; - if (data->isPassword) { - password = XP_ALLOC(XP_STRLEN(data->value) + - XP_STRLEN(data->name) + 2); - if (!password) { - return (-1); - } - attribute = password; - } else { - account = XP_ALLOC( XP_STRLEN(data->value) + - XP_STRLEN(data->name) + 2); - if (!account) { - XP_FREE(password); - return (-1); - } - attribute = account; - } - - XP_STRCPY(attribute, data->name); - XP_STRCAT(attribute, "="); - XP_STRCAT(attribute, data->value); - - } - /* if it's already there, we just want to change the password */ - status = kcfindinternetpassword - (URL->URLName, - nil, - account, - kAnyPort, - kNetscapeProtocolType, - kAnyAuthType, - 0, - nil, - &actualLength, - &itemRef); - if (status == noErr) { - status = KCSetData(itemRef, XP_STRLEN(password), password); - if (status != noErr) { - return(status); - } - status = KCUpdateItem(itemRef); - KCReleaseItemRef(&itemRef); - } else { - /* wasn't there, let's add it */ - status = kcaddinternetpassword - (URL->URLName, - nil, - account, - kAnyPort, - kNetscapeProtocolType, - kAnyAuthType, - XP_STRLEN(password), - password, - nil); - } - if (account) { - XP_FREE(account); - } - if (password) { - XP_FREE(password); - } - account = password = nil; - if (status != noErr) { - return(status); - } - } - } - } - - si_signon_list_changed = FALSE; - return (0); -} -#endif - -/* - * Save signon data to disk file - * The parameter passed in on entry is ignored - * - * This routine is called only when holding the signon lock!!! - * - * This routine is called only if signon pref is enabled!!! - */ - -PRIVATE int -si_SaveSignonDataLocked(char * filename) { - XP_List * list_ptr; - XP_List * user_ptr; - XP_List * data_ptr; - si_SignonURLStruct * url; - si_SignonUserStruct * user; - si_SignonDataStruct * data; - si_Reject * reject; - XP_File fp; - - /* do nothing if signon list has not changed */ - if(!si_signon_list_changed) { - return(-1); - } - - /* do not save signons if in anonymous mode */ - if(si_anonymous) { - return(-1); - } - -#ifdef APPLE_KEYCHAIN - if (KeychainManagerAvailable()) { - return si_SaveSignonDataInKeychain(); - } -#endif - - /* do nothing if we are unable to open file that contains signon list */ - if(!(fp = XP_FileOpen(filename, xpHTTPSingleSignon, XP_FILE_WRITE))) { - return(-1); - } - - /* format for head of file shall be: - * # comment - * # comment - * # comment - * TRUE -- indicates if notification has already been given to user - * URLName -- first url/username on reject list - * userName - * URLName -- second url/username on reject list - * userName - * ... -- etc. - * . -- end of list - */ - - /* write out leading comments */ - XP_FileWrite("# Netscape HTTP Signons File" LINEBREAK - "# This is a generated file! Do not edit." - LINEBREAK "#" LINEBREAK, -1, fp); - - /* write out si_NoticeGiven */ - if (si_NoticeGiven) { - XP_FileWrite("TRUE" LINEBREAK, -1, fp); - } else { - XP_FileWrite("FALSE" LINEBREAK, -1, fp); - } - - /* write out reject list */ - if (si_reject_list) { - list_ptr = si_reject_list; - while((reject = (si_Reject *) XP_ListNextObject(list_ptr))!=0) { - XP_FileWrite(reject->URLName, -1, fp); - XP_FileWrite(LINEBREAK, -1, fp); - XP_FileWrite(reject->userName, -1, fp); - XP_FileWrite(LINEBREAK, -1, fp); - } - } - XP_FileWrite("." LINEBREAK, -1, fp); - - /* format for cached logins shall be: - * url LINEBREAK {name LINEBREAK value LINEBREAK}* . LINEBREAK - * if type is password, name is preceded by an asterisk (*) - */ - - /* write out each URL node */ - if((si_signon_list)) { - list_ptr = si_signon_list; - while((url = (si_SignonURLStruct *) - XP_ListNextObject(list_ptr)) != NULL) { - - user_ptr = url->signonUser_list; - - /* write out each user node of the URL node */ - while((user = (si_SignonUserStruct *) - XP_ListNextObject(user_ptr)) != NULL) { - XP_FileWrite(url->URLName, -1, fp); - XP_FileWrite(LINEBREAK, -1, fp); - - data_ptr = user->signonData_list; - - /* write out each data node of the user node */ - while((data = (si_SignonDataStruct *) - XP_ListNextObject(data_ptr)) != NULL) { - char* mungedValue; - if (data->isPassword) { - XP_FileWrite("*", -1, fp); - } - XP_FileWrite(data->name, -1, fp); - XP_FileWrite(LINEBREAK, -1, fp); - XP_FileWrite("=", -1, fp); /* precede values with '=' */ - if (data->isPassword) { - if ((mungedValue = MY_SECNAV_MungeString(data->value))) { - XP_FileWrite(mungedValue, -1, fp); - XP_FREE(mungedValue); - } else { - /* in free source, passwords are not obscured */ - XP_FileWrite(data->value, -1, fp); - } - } else { - XP_FileWrite(data->value, -1, fp); - } - XP_FileWrite(LINEBREAK, -1, fp); - } - XP_FileWrite(".", -1, fp); - XP_FileWrite(LINEBREAK, -1, fp); - } - } - } - - si_signon_list_changed = FALSE; - XP_FileClose(fp); - return(0); -} - - -/* - * Save signon data to disk file - * The parameter passed in on entry is ignored - */ - -PUBLIC int -SI_SaveSignonData(char * filename) { - int retval; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()) { - return FALSE; - } - - /* lock and call common save routine */ - si_lock_signon_list(); - retval = si_SaveSignonDataLocked(filename); - si_unlock_signon_list(); - return retval; -} - -/* - * Remove all the signons and free everything - */ - -PUBLIC void -SI_RemoveAllSignonData() { - - /* repeatedly remove first user node of first URL node */ - while (SI_RemoveUser(NULL, NULL, FALSE)) { - } -} - -/* - * Check for a signon submission and remember the data if so - */ -PUBLIC void -SI_RememberSignonData - (char* URLName, char** name_array, char** value_array, char** type_array, PRInt32 value_cnt) -{ - int i, j; - int passwordCount = 0; - int pswd[3]; - - LO_FormSubmitData submit; - submit.name_array = (PA_Block)name_array; - submit.value_array = (PA_Block)value_array; - submit.type_array = (PA_Block)type_array; - submit.value_cnt = value_cnt; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()){ - return; - } - - /* determine how many passwords are in the form and where they are */ - for (i=0; i<submit.value_cnt; i++) { - if (((uint8 *)submit.type_array)[i] == FORM_TYPE_PASSWORD) { - if (passwordCount < 3 ) { - pswd[passwordCount] = i; - } - passwordCount++; - } - } - - /* process the form according to how many passwords it has */ - if (passwordCount == 1) { - /* one-password form is a log-in so remember it */ - - /* obtain the index of the first input field (that is the username) */ - for (j=0; j<submit.value_cnt; j++) { - if (((uint8 *)submit.type_array)[j] == FORM_TYPE_TEXT) { - break; - } - } - - if ((j<submit.value_cnt) && si_OkToSave(URLName, /* urlname */ - ((char **)submit.value_array)[j] /* username */)) { - si_PutData(URLName, &submit, TRUE); - } - } else if (passwordCount == 2) { - /* two-password form is a registration */ - - } else if (passwordCount == 3) { - /* three-password form is a change-of-password request */ - - XP_List * data_ptr; - si_SignonDataStruct* data; - si_SignonUserStruct* user; - - /* make sure all passwords are non-null and 2nd and 3rd are identical */ - if (!submit.value_array[pswd[0]] || ! submit.value_array[pswd[1]] || - !submit.value_array[pswd[2]] || - XP_STRCMP(((char **)submit.value_array)[pswd[1]], - ((char **)submit.value_array)[pswd[2]])) { - return; - } - - /* ask user if this is a password change */ - si_lock_signon_list(); - user = si_GetURLAndUserForChangeForm - (((char **)submit.value_array)[pswd[0]]); - - /* return if user said no */ - if (!user) { - si_unlock_signon_list(); - return; - } - - /* get to password being saved */ - data_ptr = user->signonData_list; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if (data->isPassword) { - break; - } - } - - /* - * if second password is "generate" then generate a random - * password for it and use same random value for third password - * as well (Note: this all works because we already know that - * second and third passwords are identical so third password - * must also be "generate". Furthermore si_Randomize() will - * create a random password of exactly eight characters -- the - * same length as "generate".) - */ - si_Randomize(((char **)submit.value_array)[pswd[1]]); - XP_STRCPY(((char **)submit.value_array)[pswd[2]], - ((char **)submit.value_array)[pswd[1]]); - StrAllocCopy(data->value, ((char **)submit.value_array)[pswd[1]]); - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - si_unlock_signon_list(); - } -} - -PUBLIC void -SI_RestoreSignonData - (char* URLName, char* name, char** value) -{ - si_SignonUserStruct* user; - si_SignonDataStruct* data; - XP_List * data_ptr=0; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()){ - return; - } - - si_lock_signon_list(); - -#ifdef xxx - /* - * determine if it is a change-of-password field - * the heuristic that we will use is that if this is the first - * item on the form and it is a password, this is probably a - * change-of-password form - */ - /* see if this is first item in form and is a password */ - /* get first saved user just so we can see the name of the first item on the form */ - user = si_GetUser(URLName, TRUE, NULL); /* this is the first saved user */ - if (user) { - data_ptr = user->signonData_list; /* this is first item on form */ - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - if(data->isPassword && name && XP_STRCMP(data->name, name)==0) { - /* current item is first item on form and is a password */ - user = (URLName, MK_SIGNON_PASSWORDS_FETCH); - if (user) { - /* user has confirmed it's a change-of-password form */ - data_ptr = user->signonData_list; - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if (data->isPassword) { - *value = data->value; - si_unlock_signon_list(); - return; - } - } - } - } - } -#endif - - /* restore the data from previous time this URL was visited */ - user = si_GetUser(URLName, FALSE, name); - if (user) { - data_ptr = user->signonData_list; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if(name && XP_STRCMP(data->name, name)==0) { - *value = data->value; - si_unlock_signon_list(); - return; - } - } - } - si_unlock_signon_list(); -} - -/* - * Remember signon data from a browser-generated password dialog - */ -PRIVATE void -si_RememberSignonDataFromBrowser(char* URLName, char* username, char* password) -{ - LO_FormSubmitData submit; - char* USERNAME = "username"; - char* PASSWORD = "password"; - char* name_array[2]; - char* value_array[2]; - uint8 type_array[2]; - - /* do nothing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()){ - return; - } - - /* initialize a temporary submit structure */ - submit.name_array = (PA_Block)name_array; - submit.value_array = (PA_Block)value_array; - submit.type_array = (PA_Block)type_array; - submit.value_cnt = 2; - - name_array[0] = USERNAME; - value_array[0] = NULL; - StrAllocCopy(value_array[0], username); - type_array[0] = FORM_TYPE_TEXT; - - name_array[1] = PASSWORD; - value_array[1] = NULL; - StrAllocCopy(value_array[1], password); - type_array[1] = FORM_TYPE_PASSWORD; - - /* Save the signon data */ - si_PutData(URLName, &submit, TRUE); - - /* Free up the data memory just allocated */ - XP_FREE(value_array[0]); - XP_FREE(value_array[1]); -} - -PUBLIC void -SI_RememberSignonDataFromBrowser - (char* URLName, char* username, char* password) -{ - if (si_OkToSave(URLName, username)) { - si_RememberSignonDataFromBrowser (URLName, username, password); - } -} - -/* - * Check for remembered data from a previous browser-generated password dialog - * restore it if so - */ -PRIVATE void -si_RestoreOldSignonDataFromBrowser - (char* URLName, Bool pickFirstUser, - char** username, char** password) -{ - si_SignonUserStruct* user; - si_SignonDataStruct* data; - XP_List * data_ptr=0; - - /* get the data from previous time this URL was visited */ - si_lock_signon_list(); - user = si_GetUser(URLName, pickFirstUser, "username"); - if (!user) { - /* leave original username and password from caller unchanged */ - /* username = 0; */ - /* *password = 0; */ - si_unlock_signon_list(); - return; - } - - /* restore the data from previous time this URL was visited */ - data_ptr = user->signonData_list; - while((data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr))!=0) { - if(XP_STRCMP(data->name, "username")==0) { - StrAllocCopy(*username, data->value); - } else if(XP_STRCMP(data->name, "password")==0) { - StrAllocCopy(*password, data->value); - } - } - si_unlock_signon_list(); -} - -/* Browser-generated prompt for user-name and password */ -PUBLIC int -SI_PromptUsernameAndPassword - (MWContext *context, char *prompt, - char **username, char **password, char *URLName) -{ - int status; - char *copyOfPrompt=0; - - /* just for safety -- really is a problem in SI_Prompt */ - StrAllocCopy(copyOfPrompt, prompt); - - /* do the FE thing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()){ - status = FE_PromptUsernameAndPassword - (context, copyOfPrompt, username, password); - XP_FREEIF(copyOfPrompt); - return status; - } - - /* prefill with previous username/password if any */ - si_RestoreOldSignonDataFromBrowser - (URLName, FALSE, username, password); - - /* get new username/password from user */ - status = FE_PromptUsernameAndPassword - (context, copyOfPrompt, username, password); - - /* remember these values for next time */ - if (status && si_OkToSave(URLName, *username)) { - si_RememberSignonDataFromBrowser (URLName, *username, *password); - } - - /* cleanup and return */ - XP_FREEIF(copyOfPrompt); - return status; -} - -/* Browser-generated prompt for password */ -PUBLIC char * -SI_PromptPassword - (MWContext *context, char *prompt, char *URLName, Bool pickFirstUser) -{ - char *password=0, *username=0, *copyOfPrompt=0, *result; - char *urlname = URLName; - char *s; - - /* just for safety -- really is a problem in SI_Prompt */ - StrAllocCopy(copyOfPrompt, prompt); - - /* do the FE thing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()){ - result = FE_PromptPassword(context, copyOfPrompt); - XP_FREEIF(copyOfPrompt); - return result; - } - - /* get host part of URL which is of form user@host */ - s = URLName; - while (*s && (*s != '@')) { - s++; - } - if (*s) { - /* @ found, host is URL part following the @ */ - urlname = s+1; /* urlname is part of URL after the @ */ - } - - /* get previous password used with this username */ - si_RestoreOldSignonDataFromBrowser - (urlname, pickFirstUser, &username, &password); - - /* return if a password was found */ - /* - * Note that we reject a password of " ". It is a dummy password - * that was put in by a preceding call to SI_Prompt. This occurs - * in mknews which calls on SI_Prompt to get the username and then - * SI_PromptPassword to get the password (why they didn't simply - * call on SI_PromptUsernameAndPassword is beyond me). So the call - * to SI_Prompt will save the username along with the dummy password. - * In this call to SI_Password, the real password gets saved in place - * of the dummy one. - */ - if (password && XP_STRLEN(password) && XP_STRCMP(password, " ")) { - XP_FREEIF(copyOfPrompt); - return password; - } - - /* if no password found, get new password from user */ - password = FE_PromptPassword(context, copyOfPrompt); - - /* if username wasn't even found, extract it from URLName */ - if (!username) { - s = URLName; - - /* get to @ in URL if any */ - while (*s && (*s != '@')) { - s++; - } - if (*s) { - /* @ found, username is URL part preceding the @ */ - *s = '\0'; - StrAllocCopy(username, URLName); - *s = '@'; - } else { - /* no @ found, use entire URL as uername */ - StrAllocCopy(username, URLName); - } - } - - /* remember these values for next time */ - if (password && XP_STRLEN(password) && - si_OkToSave(urlname, username)) { - si_RememberSignonDataFromBrowser (urlname, username, password); - } - - /* cleanup and return */ - XP_FREEIF(username); - XP_FREEIF(copyOfPrompt); - return password; -} - -/* Browser-generated prompt for username */ -PUBLIC char * -SI_Prompt (MWContext *context, char *prompt, - char* defaultUsername, char *URLName) -{ - char *password=0, *username=0, *copyOfPrompt=0, *result; - - /* - * make copy of prompt because it is currently in a temporary buffer in - * the caller (from GetString) which will be destroyed if GetString() is - * called again before prompt is used - */ - StrAllocCopy(copyOfPrompt, prompt); - - /* do the FE thing if signon preference is not enabled */ - if (!si_GetSignonRememberingPref()){ - result = FE_Prompt(context, copyOfPrompt, defaultUsername); - XP_FREEIF(copyOfPrompt); - return result; - } - - /* get previous username used */ - if (!defaultUsername || !XP_STRLEN(defaultUsername)) { - si_RestoreOldSignonDataFromBrowser - (URLName, FALSE, &username, &password); - } else { - StrAllocCopy(username, defaultUsername); - } - - /* prompt for new username */ - result = FE_Prompt(context, copyOfPrompt, username); - - /* remember this username for next time */ - if (result && XP_STRLEN(result)) { - if (username && (XP_STRCMP(username, result) == 0)) { - /* - * User is re-using the same user name as from previous time - * so keep the previous password as well - */ - si_RememberSignonDataFromBrowser (URLName, result, password); - } else { - /* - * We put in a dummy password of " " which we will test - * for in a following call to SI_PromptPassword. See comments - * in that routine. - */ - si_RememberSignonDataFromBrowser (URLName, result, " "); - } - } - - /* cleanup and return */ - XP_FREEIF(username); - XP_FREEIF(password); - XP_FREEIF(copyOfPrompt); - return result; -} - -PRIVATE XP_List * si_dormant_signon_list=0; - -PUBLIC void -SI_AnonymizeSignons() -{ - if (!si_anonymous) { - si_lock_signon_list(); - si_dormant_signon_list = si_signon_list; - si_signon_list = XP_ListNew(); - si_unlock_signon_list(); - si_anonymous = TRUE; - } -} - -PUBLIC void -SI_UnanonymizeSignons() -{ - if (si_anonymous) { - SI_RemoveAllSignonData(); - si_lock_signon_list(); - si_signon_list = si_dormant_signon_list; - si_unlock_signon_list(); - si_dormant_signon_list = 0; - si_anonymous = FALSE; - } -} - -#ifdef HTMLDialogs -#include "htmldlgs.h" -#else -#define XP_DIALOG_CANCEL_BUTTON (1<<0) -#define XP_DIALOG_OK_BUTTON (1<<2) -#define XP_STRINGS_CHUNKSIZE 512 -typedef struct _XPDialogState XPDialogState; -typedef struct _XPDialogInfo XPDialogInfo; -typedef struct _XPDialogStrings XPDialogStrings; -typedef PRBool (* XP_HTMLDialogHandler)(XPDialogState *state, char **argv, - int argc, unsigned int button); -struct _XPDialogState { - PRArenaPool *arena; - void *window; - void *proto_win; - XPDialogInfo *dialogInfo; - void *arg; - void (* deleteCallback)(void *arg); - void *cbarg; - PRBool deleted; -}; -struct _XPDialogInfo { - unsigned int buttonFlags; - XP_HTMLDialogHandler handler; - int width; - int height; -}; -struct _XPDialogStrings -{ - PRArenaPool *arena; - int basestringnum; - int nargs; - char **args; - char *contents; -}; - -extern time_t CookieTime(); -extern XPDialogState * - XP_MakeRawHTMLDialog(void *proto_win, XPDialogInfo *dialogInfo, - int titlenum, XPDialogStrings *strings, - int handlestring, void *arg); -extern XPDialogStrings *XP_GetDialogStrings(int stringnum); -extern void - XP_SetDialogString(XPDialogStrings *strings, int argNum, char *string); -extern char * - XP_FindValueInArgs(const char *name, char **av, int ac); - -#endif - -extern int XP_CERT_PAGE_STRINGS; -extern int SA_REMOVE_BUTTON_LABEL; -extern int MK_SIGNON_VIEW_SIGNONS; -extern int MK_SIGNON_VIEW_REJECTS; - -#define BUFLEN 5000 - -#define FLUSH_BUFFER \ - if (buffer) { \ - StrAllocCat(buffer2, buffer); \ - buffer[0] = '\0'; \ - g = 0; \ - } - -/* return TRUE if "number" is in sequence of comma-separated numbers */ -Bool si_InSequence(char* sequence, int number) { - char* ptr; - char* endptr; - char* undo = NULL; - Bool retval = FALSE; - int i; - - /* not necessary -- routine will work even with null sequence */ - if (!*sequence) { - return FALSE; - } - - for (ptr = sequence ; ptr ; ptr = endptr) { - - /* get to next comma */ - endptr = PL_strchr(ptr, ','); - - /* if comma found, process it */ - if (endptr) { - - /* restore last comma-to-null back to comma */ - if (undo) { - *undo = ','; - } - - /* set the comma to a null */ - undo = endptr; - *endptr++ = '\0'; - - /* compare the number before the comma with "number" */ - if (*ptr) { - i = atoi(ptr); - if (i == number) { - - /* "number" was in the sequence so return TRUE */ - retval = TRUE; - break; - } - } - } - } - - /* restore last comma-to-null back to comma */ - if (undo) { - *undo = ','; - } - return retval; -} - -PR_STATIC_CALLBACK(PRBool) -si_SignonInfoDialogDone(XPDialogState* state, char** argv, int argc, - unsigned int button) -{ - XP_List *url_ptr; - XP_List *user_ptr; - XP_List *data_ptr; - XP_List *reject_ptr; - si_SignonURLStruct *url; - si_SignonURLStruct *URLToDelete = 0; - si_SignonUserStruct* user; - si_SignonUserStruct* userToDelete = 0; - si_SignonDataStruct* data; - si_Reject* reject; - si_Reject* rejectToDelete = 0; - - char *buttonName; - int userNumber; - int rejectNumber; - char* gone; - - buttonName = XP_FindValueInArgs("button", argv, argc); - if (button != XP_DIALOG_OK_BUTTON) { - /* OK button not pressed (must be cancel button that was pressed) */ - return PR_FALSE; - } - - /* OK was pressed, do the deletions */ - - /* get the comma-separated sequence of signons to be deleted */ - gone = XP_FindValueInArgs("goneS", argv, argc); - XP_ASSERT(gone); - if (!gone) { - return PR_FALSE; - } - - /* - * step through all users and delete those that are in the sequence - * Note: we can't delete user while "user_ptr" is pointing to it because - * that would destroy "user_ptr". So we do a lazy deletion - */ - userNumber = 0; - url_ptr = si_signon_list; - while ((url = (si_SignonURLStruct *) XP_ListNextObject(url_ptr))) { - user_ptr = url->signonUser_list; - while ((user = (si_SignonUserStruct *) - XP_ListNextObject(user_ptr))) { - if (si_InSequence(gone, userNumber)) { - if (userToDelete) { - - /* get to first data item -- that's the user name */ - data_ptr = userToDelete->signonData_list; - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - /* do the deletion */ - SI_RemoveUser(URLToDelete->URLName, data->value, TRUE); - } - userToDelete = user; - URLToDelete = url; - } - userNumber++; - } - } - if (userToDelete) { - /* get to first data item -- that's the user name */ - data_ptr = userToDelete->signonData_list; - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - - /* do the deletion */ - SI_RemoveUser(URLToDelete->URLName, data->value, TRUE); - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - } - - /* get the comma-separated sequence of rejections to be deleted */ - gone = XP_FindValueInArgs("goneR", argv, argc); - XP_ASSERT(gone); - if (!gone) { - return PR_FALSE; - } - - /* step through all rejects and delete those that are in the sequence - * Note: we can't delete reject while "reject_ptr" is pointing to it because - * that would destroy "reject_ptr". So we do a lazy deletion - */ - rejectNumber = 0; - si_lock_signon_list(); - reject_ptr = si_reject_list; - while ((reject = (si_Reject *) XP_ListNextObject(reject_ptr))) { - if (si_InSequence(gone, rejectNumber)) { - if (rejectToDelete) { - si_FreeReject(rejectToDelete); - } - rejectToDelete = reject; - } - rejectNumber++; - } - if (rejectToDelete) { - si_FreeReject(rejectToDelete); - si_signon_list_changed = TRUE; - si_SaveSignonDataLocked(NULL); - } - si_unlock_signon_list(); - return PR_FALSE; -} - -typedef struct _SignonViewerDialog SignonViewerDialog; - -struct _SignonViewerDialog { - void *window; - void *parent_window; - PRBool dialogUp; - XPDialogState *state; -}; - -PUBLIC void -SI_DisplaySignonInfoAsHTML(MWContext *context) -{ - char *buffer = (char*)XP_ALLOC(BUFLEN); - char *buffer2 = 0; - int g = 0, signonNum, count; - XP_List *url_ptr; - XP_List *user_ptr; - XP_List *data_ptr; - XP_List *reject_ptr; - si_SignonURLStruct *url; - si_SignonUserStruct * user; - si_SignonDataStruct* data; - si_Reject *reject; - SignonViewerDialog *dlg; - int i; - char * view_signons = NULL; - char * view_rejects = NULL; - char * heading = NULL; - - static XPDialogInfo dialogInfo = { - 0, - si_SignonInfoDialogDone, - 350, - 400 - }; - - XPDialogStrings* strings; - strings = XP_GetDialogStrings(XP_CERT_PAGE_STRINGS); - if (!strings) { - return; - } - -#ifdef APPLE_KEYCHAIN - /* If the Keychain has been locked or an item deleted or updated, - we need to reload the signon data */ - if (si_list_invalid) - { - /* set si_list_invalid to FALSE first because SI_RemoveAllSignonData - calls si_GetSignonRememberingPref */ - si_list_invalid = FALSE; - SI_RemoveAllSignonData(); - SI_LoadSignonData(NULL); - } -#endif - - StrAllocCopy(buffer2, ""); - StrAllocCopy (view_signons, XP_GetString(MK_SIGNON_VIEW_SIGNONS)); - StrAllocCopy (view_rejects, XP_GetString(MK_SIGNON_VIEW_REJECTS)); - - /* generate initial section of html file */ - g += PR_snprintf(buffer+g, BUFLEN-g, -"<HTML>\n" -"<HEAD>\n" -" <TITLE>Signons</TITLE>\n" -" <SCRIPT>\n" -" index_frame = 0;\n" -" title_frame = 1;\n" -" spacer1_frame = 2;\n" -" list_frame = 3;\n" -" spacer2_frame = 4;\n" -" button_frame = 5;\n" -"\n" -" var signon_mode;\n" -" var goneS;\n" -" var goneR;\n" -" deleted_signons = new Array (0" - ); - FLUSH_BUFFER - - - /* force loading of the signons file */ - si_RegisterSignonPrefCallbacks(); - si_lock_signon_list(); - - /* fill in initial 0's for deleted_signons and deleted_rejects arrays */ - url_ptr = si_signon_list; - i = 0; - while ( (url=(si_SignonURLStruct *) XP_ListNextObject(url_ptr)) ) { - user_ptr = url->signonUser_list; - while ( (user=(si_SignonUserStruct *) XP_ListNextObject(user_ptr)) ) { - /* this actually gives one 0 too many but that doesn't hurt */ - g += PR_snprintf(buffer+g, BUFLEN-g, -",0" - ); - if (((++i)%50) == 0) { - g += PR_snprintf(buffer+g, BUFLEN-g, -"\n " - ); - } - } - } - - g += PR_snprintf(buffer+g, BUFLEN-g, -");\n" -" deleted_rejects = new Array (0" - ); - count = XP_ListCount(si_reject_list); - for (i=1; i<count; i++) { - g += PR_snprintf(buffer+g, BUFLEN-g, -",0" - ); - if ((i%50) == 0) { - g += PR_snprintf(buffer+g, BUFLEN-g, -"\n " - ); - } - } - FLUSH_BUFFER - - StrAllocCopy (heading, XP_GetString(MK_SIGNON_YOUR_SIGNONS)); - g += PR_snprintf(buffer+g, BUFLEN-g, -");\n" -"\n" -" function DeleteItemSelected() {\n" -" if (signon_mode) {\n" -" DeleteSignonSelected();\n" -" } else {\n" -" DeleteRejectSelected();\n" -" }\n" -" }\n" -"\n" -" function DeleteSignonSelected() {\n" -" selname = top.frames[list_frame].document.fSelectSignon.selname;\n" -" goneS = top.frames[button_frame].document.buttons.goneS;\n" -" var p;\n" -" var i;\n" -" for (i=selname.options.length; i>0; i--) {\n" -" if (selname.options[i-1].selected) {\n" -" selname.options[i-1].selected = 0;\n" -" goneS.value = goneS.value + selname.options[i-1].value + \",\";\n" -" deleted_signons[selname.options[i-1].value] = 1;\n" -" for (j=i ; j<selname.options.length ; j++) {\n" -" selname.options[j-1] = selname.options[j];\n" -" }\n" -" selname.options[selname.options.length-1] = null;\n" -" }\n" -" }\n" -" }\n" -"\n" -" function DeleteRejectSelected() {\n" -" selname = top.frames[list_frame].document.fSelectReject.selname;\n" -" goneR = top.frames[button_frame].document.buttons.goneR;\n" -" var p;\n" -" var i;\n" -" for (i=selname.options.length; i>0; i--) {\n" -" if (selname.options[i-1].selected) {\n" -" selname.options[i-1].selected = 0;\n" -" goneR.value = goneR.value + selname.options[i-1].value + \",\";\n" -" deleted_rejects[selname.options[i-1].value] = 1;\n" -" for (j=i; j < selname.options.length; j++) {\n" -" selname.options[j-1] = selname.options[j];\n" -" }\n" -" selname.options[selname.options.length-1] = null;\n" -" }\n" -" }\n" -" }\n" -"\n" -" function loadSignons(){\n" -" signon_mode = 1;\n" -" top.frames[index_frame].document.open();\n" -" top.frames[index_frame].document.write(\n" -" \"<BODY BGCOLOR=#C0C0C0>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100%>\" +\n" -" \"<TR>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#FFFFFF>\" +\n" -" \"<FONT SIZE=2 COLOR=#666666>\" +\n" -" \"<B>%s</B>\" +\n" -" \"</FONT>\" +\n" -" \"</TD>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#C0C0C0>\" +\n" -" \"<A HREF=javascript:top.loadRejects();>\" +\n" -" \"<FONT SIZE=2>%s</FONT>\" +\n" -" \"</A>\" +\n" -" \"</TD>\" +\n" -" \"<TD>&nbsp;&nbsp;&nbsp;</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</BODY>\"\n" -" );\n" -" top.frames[index_frame].document.close();\n" -"\n" -" top.frames[title_frame].document.open();\n" -" top.frames[title_frame].document.write\n" -" (\"&nbsp;%s\");\n" -" top.frames[title_frame].document.close();\n" -"\n" -" top.frames[list_frame].document.open();\n" -" top.frames[list_frame].document.write(\n" -" \"<FORM name=fSelectSignon>\" +\n" -" \"<P>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100% HEIGHT=95%>\" +\n" -" \"<TR>\" +\n" -" \"<TD WIDTH=100% VALIGN=TOP>\" +\n" -" \"<CENTER>\" +\n" -" \"<P>\" +\n" -" \"<SELECT NAME=selname SIZE=15 MULTIPLE> \"\n" -" );\n", - view_signons, view_rejects, heading); - FLUSH_BUFFER - PR_FREEIF(heading); - - /* generate the html for the list of signons */ - url_ptr = si_signon_list; - signonNum = 0; - while ( (url=(si_SignonURLStruct *) XP_ListNextObject(url_ptr)) ) { - user_ptr = url->signonUser_list; - while ( (user=(si_SignonUserStruct *) XP_ListNextObject(user_ptr)) ) { - /* first data item for user is the username */ - data_ptr = user->signonData_list; - data = (si_SignonDataStruct *) XP_ListNextObject(data_ptr); - g += PR_snprintf(buffer+g, BUFLEN-g, -" if (!deleted_signons[%d]) {\n" -" top.frames[list_frame].document.write(\n" -" \"<OPTION value=%d>\" +\n" -" \"%s:%s\" +\n" -" \"</OPTION>\"\n" -" );\n" -" }\n", - signonNum, signonNum, - url->URLName, - data->value - ); - FLUSH_BUFFER - signonNum++; - } - } - - /* generate next section of html file */ - StrAllocCopy (heading, XP_GetString(MK_SIGNON_YOUR_SIGNON_REJECTS)); - g += PR_snprintf(buffer+g, BUFLEN-g, -" top.frames[list_frame].document.write(\n" -" \"</SELECT>\" +\n" -" \"</CENTER>\" +\n" -" \"</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</FORM>\"\n" -" );\n" -" top.frames[list_frame].document.close();\n" -" }\n" -"\n" -" function loadRejects(){\n" -" signon_mode = 0;\n" -" top.frames[index_frame].document.open();\n" -" top.frames[index_frame].document.write(\n" -" \"<BODY BGCOLOR=#C0C0C0>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100%>\" +\n" -" \"<TR>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#C0C0C0>\" +\n" -" \"<A HREF=javascript:top.loadSignons();>\" +\n" -" \"<FONT SIZE=2>%s</FONT>\" +\n" -" \"</A>\" +\n" -" \"</TD>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#FFFFFF>\" +\n" -" \"<FONT SIZE=2 COLOR=#666666>\" +\n" -" \"<B>%s</B>\" +\n" -" \"</FONT>\" +\n" -" \"</TD>\" +\n" -" \"<TD>&nbsp;&nbsp;&nbsp;</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</BODY>\"\n" -" );\n" -" top.frames[index_frame].document.close();\n" -"\n" -" top.frames[title_frame].document.open();\n" -" top.frames[title_frame].document.write\n" -" (\"&nbsp;%s\");\n" -" top.frames[title_frame].document.close();\n" -"\n" -" top.frames[list_frame].document.open();\n" -" top.frames[list_frame].document.write(\n" -" \"<FORM name=fSelectReject>\" +\n" -" \"<P>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100% HEIGHT=95%>\" +\n" -" \"<TR>\" +\n" -" \"<TD WIDTH=100% VALIGN=TOP>\" +\n" -" \"<CENTER>\" +\n" -" \"<P>\" +\n" -" \"<SELECT NAME=selname SIZE=15 MULTIPLE> \"\n" -" );\n", - view_signons, view_rejects, heading); - FLUSH_BUFFER - PR_FREEIF(heading); - - /* generate the html for the list of rejects */ - signonNum = 0; - reject_ptr=si_reject_list; - while ( (reject=(si_Reject *) - XP_ListNextObject(reject_ptr)) ) { - g += PR_snprintf(buffer+g, BUFLEN-g, -" if (!deleted_rejects[%d]) {\n" -" top.frames[list_frame].document.write(\n" -" \"<OPTION value=\" +\n" -" \"%d>\" +\n" -" \"%s: %s\" +\n" -" \"</OPTION>\"\n" -" );\n" -" }\n", - signonNum, signonNum, - reject->URLName, - reject->userName); - FLUSH_BUFFER - signonNum++; - } - - /* generate next section of html file */ - g += PR_snprintf(buffer+g, BUFLEN-g, -" top.frames[list_frame].document.write(\n" -" \"</SELECT>\" +\n" -" \"</CENTER>\" +\n" -" \"</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</FORM>\"\n" -" );\n" -" top.frames[list_frame].document.close();\n" -" }\n" -"\n" -" function loadButtons(){\n" -" top.frames[button_frame].document.open();\n" -" top.frames[button_frame].document.write(\n" -" \"<FORM name=buttons action=internal-dialog-handler method=post>\" +\n" -" \"<BR>\" +\n" -" \"&nbsp;\" +\n" -" \"<INPUT type=BUTTON \" +\n" -" \"value=Remove \" +\n" -" \"onclick=top.DeleteItemSelected();>\" +\n" -" \"<DIV align=right>\" +\n" -" \"<INPUT type=BUTTON value=OK width=80 onclick=parent.clicker(this,window.parent)>\" +\n" -" \" &nbsp;&nbsp;\" +\n" -" \"<INPUT type=BUTTON value=Cancel width=80 onclick=parent.clicker(this,window.parent)>\" +\n" -" \"</DIV>\" +\n" -" \"<INPUT type=HIDDEN name=xxxbuttonxxx>\" +\n" -" \"<INPUT type=HIDDEN name=handle value=" - ); - FLUSH_BUFFER - - /* transfer what we have so far into strings->args[0] */ - if (buffer2) { - XP_SetDialogString(strings, 0, buffer2); - buffer2 = NULL; - } - - /* Note: strings->args[1] will later be filled in with value of handle */ - - /* generate remainder of html, it will go into strings->arg[2] */ - g += PR_snprintf(buffer+g, BUFLEN-g, -">\" +\n" -" \"<INPUT TYPE=HIDDEN NAME=goneS SIZE=-1>\" +\n" -" \"<INPUT TYPE=HIDDEN NAME=goneR SIZE=-1>\" +\n" -" \"</FORM>\"\n" -" );\n" -" top.frames[button_frame].document.close();\n" -" }\n" -"\n" -" function loadFrames(){\n" -" loadSignons();\n" -" loadButtons();\n" -" }\n" -"\n" -" function clicker(but,win){\n" -#ifndef HTMLDialogs -" var goneS = top.frames[button_frame].document.buttons.goneS;\n" -" var goneR = top.frames[button_frame].document.buttons.goneR;\n" -" var expires = new Date();\n" -" expires.setTime(expires.getTime() + 1000*60*60*24*365);\n" -" document.cookie = \"htmldlgs=|\" + but.value +\n" -" \"|goneS|\" + goneS.value + \"|goneR|\" + goneR.value + \"|\" +\n" -" \"; expires=\" + expires.toGMTString();\n" -#endif -" top.frames[button_frame].document.buttons.xxxbuttonxxx.value = but.value;\n" -" top.frames[button_frame].document.buttons.xxxbuttonxxx.name = 'button';\n" -" top.frames[button_frame].document.buttons.submit();\n" -" }\n" -"\n" -" </SCRIPT>\n" -"</HEAD>\n" -"<FRAMESET ROWS = 25,25,*,75\n" -" BORDER=0\n" -" FRAMESPACING=0\n" -" onLoad=loadFrames()>\n" -" <FRAME SRC=about:blank\n" -" NAME=index_frame\n" -" SCROLLING=NO\n" -" MARGINWIDTH=1\n" -" MARGINHEIGHT=1\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=title_frame\n" -" SCROLLING=NO\n" -" MARGINWIDTH=1\n" -" MARGINHEIGHT=1\n" -" NORESIZE>\n" -" <FRAMESET COLS=5,*,5\n" -" BORDER=0\n" -" FRAMESPACING=0>\n" -" <FRAME SRC=about:blank\n" -" NAME=spacer1_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=list_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=spacer2_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" </FRAMESET>\n" -" <FRAME SRC=about:blank\n" -" NAME=button_frame\n" -" SCROLLING=NO\n" -" MARGINWIDTH=1\n" -" MARGINHEIGHT=1\n" -" NORESIZE>\n" -"</FRAMESET>\n" -"\n" -"<NOFRAMES>\n" -" <BODY> <P> </BODY>\n" -"</NOFRAMES>\n" -"</HTML>\n" - ); - FLUSH_BUFFER - - si_unlock_signon_list(); - - /* free some strings that are no longer needed */ - PR_FREEIF(view_signons); - PR_FREEIF(view_rejects); - PR_FREEIF(buffer); - - /* put html just generated into strings->arg[2] and invoke HTML dialog */ - if (buffer2) { - XP_SetDialogString(strings, 2, buffer2); - buffer2 = NULL; - } - dlg = PORT_ZAlloc(sizeof(SignonViewerDialog)); - if ( dlg == NULL ) { - return; - } - dlg->parent_window = (void *)NULL; - dlg->dialogUp = PR_TRUE; - dlg->state =XP_MakeRawHTMLDialog(NULL, &dialogInfo, MK_SIGNON_YOUR_SIGNONS, - strings, 1, (void *)dlg); - - return; -} -#endif diff --git a/mozilla/network/main/singsignStub.cpp b/mozilla/network/main/singsignStub.cpp deleted file mode 100644 index f245a739b6a..00000000000 --- a/mozilla/network/main/singsignStub.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "libi18n.h" -#include "nsIServiceManager.h" -#include "nsIWalletService.h" -static NS_DEFINE_IID(kIWalletServiceIID, NS_IWALLETSERVICE_IID); -static NS_DEFINE_IID(kWalletServiceCID, NS_WALLETSERVICE_CID); - -PUBLIC int -SI_SaveSignonData(char * filename) { - return 0; -} - -PUBLIC Bool -SI_RemoveUser(char *URLName, char *userName, Bool save) { - return FALSE; -} - -PUBLIC void -SI_RemoveAllSignonData() { -} - -PUBLIC PRBool -SI_PromptUsernameAndPassword - (MWContext *context, char *prompt, - char **username, char **password, char *URLName) -{ - nsIWalletService *walletservice; - nsresult res; - PRBool status; - res = nsServiceManager::GetService(kWalletServiceCID, - kIWalletServiceIID, - (nsISupports **)&walletservice); - if ((NS_OK == res) && (nsnull != walletservice)) { - res = walletservice-> - SI_PromptUsernameAndPassword(prompt, username, password, URLName, status); - NS_RELEASE(walletservice); - } - return status; -} - -PUBLIC char * -SI_PromptPassword - (MWContext *context, char *prompt, char *URLName, Bool pickFirstUser) -{ - nsIWalletService *walletservice; - nsresult res; - char * password; - res = nsServiceManager::GetService(kWalletServiceCID, - kIWalletServiceIID, - (nsISupports **)&walletservice); - if ((NS_OK == res) && (nsnull != walletservice)) { - res = walletservice->SI_PromptPassword(prompt, &password, URLName, pickFirstUser); - NS_RELEASE(walletservice); - } - return password; -} - -PUBLIC char * -SI_Prompt (MWContext *context, char *prompt, - char* defaultUsername, char *URLName) -{ - nsIWalletService *walletservice; - nsresult res; - res = nsServiceManager::GetService(kWalletServiceCID, - kIWalletServiceIID, - (nsISupports **)&walletservice); - if ((NS_OK == res) && (nsnull != walletservice)) { - res = walletservice->SI_Prompt(prompt, &defaultUsername, URLName); - NS_RELEASE(walletservice); - } - return defaultUsername; -} - -PUBLIC void -SI_AnonymizeSignons() -{ -} - -PUBLIC void -SI_UnanonymizeSignons() -{ -} - -PUBLIC void -SI_DisplaySignonInfoAsHTML(MWContext *context) -{ -} - -#ifdef xxx -PUBLIC void -SI_StartOfForm() { -} - -PUBLIC int -SI_LoadSignonData(char * filename) { - return 0; -} - -PUBLIC void -SI_RememberSignonData - (char* URLName, char** name_array, char** value_array, char** type_array, PRInt32 value_cnt) -{ -} - -PUBLIC void -SI_RestoreSignonData - (char* URLName, char* name, char** value) -{ -} - -PUBLIC void -SI_RememberSignonDataFromBrowser - (char* URLName, char* username, char* password) -{ -} - -#endif diff --git a/mozilla/network/main/unix-dns.c b/mozilla/network/main/unix-dns.c deleted file mode 100644 index 708345162d0..00000000000 --- a/mozilla/network/main/unix-dns.c +++ /dev/null @@ -1,1763 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * unix-dns.c --- portable nonblocking DNS for Unix - * Created: Jamie Zawinski <jwz@netscape.com>, 19-Dec-96. - */ - -#if defined(XP_UNIX) && defined(UNIX_ASYNC_DNS) - -static void dns_socks_kludge(void); - -/* Todo: - - = Should we actually use the CHANGING_ARGV_WORKS code, on systems where - that is true, or just always do the exec() hack? If we use it, it - needs to be debugged more, and the exact set of systems on which it - works needs to be determined. (Works on: SunOS 4, Linux, AIX, OSF; - doesn't work on: Solaris, Irix, UnixWare, HPUX.) (But HPUX has an - undocumented ioctl that lets you change a proc's name.) (Unix sucks - a lot.) - */ - - -/* Compile-time options: - -DDNS_EXPLICITLY_FLUSH_PIPES - to do ioctls() to flush out the pipes after each write(). - at one point I thought I needed this, but it doesn't - actually seem to be necessary. - - -DGETHOSTBYNAME_DELAY=N - to insert an artificial delay of N seconds before each - call to gethostbyname (in order to simulate DNS lossage.) - - -DNO_SOCKS_NS_KLUDGE - Set this to *disable* the $SOCKS_NS kludge. Otherwise, - that environment variable will be consulted for use as an - alternate DNS root. It's historical; don't ask me... - - -DRANDOMIZE_ADDRESSES - This code only deals with one IP address per host; if this - is set, then that host will be randomly selected from among - all the addresses of the host; otherwise, it will be the - first address. - - -DCHANGING_ARGV_WORKS - (This option isn't fully implemented yet, and can't work - on some systems anyway.) - - The code in this file wants to fork(), and then change the - name of the second process as reported by `ps'. Some systems - let you do that by overwriting argv[0], but some do not. - - If this isn't defined, we effect this change by re-execing - after the fork (since you can pass a new name that way.) - This depends on exec(argv[0] ... ) working, which it might - not if argv[0] has a non-absolute path in it, and the user - has played stupid games with $PATH or something. Those - users probably deserve to lose. - - -DSTANDALONE - to include a main() for interactive command-line testing. - - -DPROC3_DEBUG_PRINT - to cause proc3 (the gethostbyname() processes) to print - diagnostics to stderr. - - -DPROC2_DEBUG_PRINT - to cause proc2 (the looping, dispatching process) to print - diagnostics to stderr. - - -DPROC1_DEBUG_PRINT - to cause proc1 (the main thread) to print diagnostics to - stderr. */ - - -#include "unix-dns.h" - -#include <stdlib.h> -#include <unistd.h> -#include <string.h> -#include <stdio.h> -#include <assert.h> -#include <netdb.h> /* for gethostbyname() */ -#include <signal.h> /* for kill() */ -#include <sys/param.h> /* for MAXHOSTNAMELEN */ -#include <sys/wait.h> /* for waitpid() */ -#include <sys/time.h> /* for gettimeofday() */ -#include <signal.h> /* for signal() and the signal names */ - -#ifdef AIX -#include <sys/select.h> /* for fd_set */ -#endif - -#ifndef NO_SOCKS_NS_KLUDGE -# include <netinet/in.h> /* for sockaddr_in (from inet.h) */ -# include <arpa/inet.h> /* for in_addr (from nameser.h) */ -# include <arpa/nameser.h> /* for MAXDNAME (from resolv.h) */ -# include <resolv.h> /* for res_init() and _res */ -#endif - -#if !defined(__irix) - /* Looks like Irix is the only one that has getdtablehi()? */ -# define getdtablehi() getdtablesize() -#endif - -#if !defined(__irix) - /* Looks like Irix and Solaris 5.5 are the only ones that have - getdtablesize()... but since Solaris 5.4 doesn't have it, - Solaris is out. (If you find a system that doesn't even - have FD_SETSIZE, just grab your ankles and set it to 255.) - */ -# define getdtablesize() (FD_SETSIZE) -#endif - - -#ifdef DNS_EXPLICITLY_FLUSH_PIPES -# include <stropts.h> /* for I_FLUSH and FLUSHRW */ -#endif - -/* Rumor has it that some systems lie about this value, and actually accept - host names longer than sys/param.h claims. But it's definitely the case - that some systems (and again I don't know which) crash if you pass a - too-long hostname into gethostbyname(). So better safe than sorry. - */ -#ifndef MAXHOSTNAMELEN -# define MAXHOSTNAMELEN 64 -#endif - -#define ASSERT(x) assert(x) - -#ifdef DNS_EXPLICITLY_FLUSH_PIPES -# define FLUSH(fd) ioctl(fd, I_FLUSH, FLUSHRW) -#else -# define FLUSH(x) -#endif - -/* We use fdopen() to get the more convenient stdio interface on the pipes - we use; but we don't want the stdio library to provide *any* buffering; - just use the buffering that the pipe itself provides, so that when - select() says there is no input available, fgetc() agrees. - */ -#define SET_BUFFERING(file) setvbuf((file), NULL, _IONBF, 0) - - -#ifdef RANDOMIZE_ADDRESSES - /* Unix is Random. */ -# if defined(UNIXWARE) || defined(_INCLUDE_HPUX_SOURCE) || (defined(__sun) && defined(__svr4__)) -# define RANDOM rand -# define SRANDOM srand -# else /* !BSD-incompatible-Unixes */ -# define RANDOM random -# define SRANDOM srandom -# endif /* !BSD-incompatible-Unixes */ -#endif /* RANDOMIZE_ADDRESSES */ - - -/* Way kludgy debugging/logging interface, since gdb's support - for debugging fork'ed processes is pathetic. - */ -#define LOG_PROCn(PROC,PREFIX,BUF,SUFFIX,QL) do{\ - fprintf(stderr, \ - "\t" PROC " (%lu): " PREFIX ": (ql=%ld) %s" SUFFIX, \ - ((unsigned long) getpid()), QL, BUF); \ - } while(0) - -#ifdef PROC3_DEBUG_PRINT -# define LOG_PROC3(PREFIX,BUF,SUFFIX) LOG_PROCn("proc3",PREFIX,BUF,SUFFIX,0L) -#else -# define LOG_PROC3(PREFIX,BUF,SUFFIX) -#endif - -#ifdef PROC2_DEBUG_PRINT -# define LOG_PROC2(PREFIX,BUF,SUFFIX) LOG_PROCn("proc2",PREFIX,BUF,SUFFIX,\ - proc2_queue_length()) -#else -# define LOG_PROC2(PREFIX,BUF,SUFFIX) -#endif - -#ifdef PROC1_DEBUG_PRINT -# define LOG_PROC1(PREFIX,BUF,SUFFIX) LOG_PROCn("proc1",PREFIX,BUF,SUFFIX,\ - proc1_queue_length()) -#else -# define LOG_PROC1(PREFIX,BUF,SUFFIX) -#endif - - -/* The internal status codes that are used; these follow the basic - SMTP/NNTP model of three-digit codes. - */ -#define DNS_STATUS_GETHOSTBYNAME_OK 101 /* proc3 -> proc2 */ -#define DNS_STATUS_LOOKUP_OK 102 /* proc2 -> proc1 */ -#define DNS_STATUS_KILLED_OK 103 /* proc2 -> proc1 */ -#define DNS_STATUS_LOOKUP_STARTED 201 /* proc2 -> proc1 */ -#define DNS_STATUS_GETHOSTBYNAME_FAILED 501 /* proc3 -> proc2 */ -#define DNS_STATUS_LOOKUP_FAILED 502 /* proc2 -> proc1 */ -#define DNS_STATUS_LOOKUP_NOT_STARTED 503 /* proc2 -> proc1 */ -#define DNS_STATUS_KILL_FAILED 504 /* proc2 -> proc1 */ -#define DNS_STATUS_UNIMPLEMENTED 601 /* unimplemented (ha ha) */ -#define DNS_STATUS_INTERNAL_ERROR 602 /* assertion failure */ - -#define DNS_PROC2_NAME "(dns helper)" - - -static char * -string_trim(char *s) -{ - char *s2; - if (!s) return 0; - s2 = s + strlen(s) - 1; - while (s2 > s && (*s2 == '\n' || *s2 == '\r' || *s2 == ' ' || *s2 == '\t')) - *s2-- = 0; - while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') - s++; - return s; -} - - -/* Process 3. - Inherits a string (hostname) from the spawner. - Writes "1xx: a.b.c.d\n" or "5xx: error msg\n". - */ - -static void -blocking_gethostbyname (const char *name, int out_fd, - unsigned long random_number) -{ - char buf[MAXHOSTNAMELEN + 100]; - struct hostent *h; - unsigned long which_addr = 0; - - static int firstTime=1; - if (firstTime) { - firstTime=0; - dns_socks_kludge(); - } - -#if GETHOSTBYNAME_DELAY - { - int i = GETHOSTBYNAME_DELAY; - LOG_PROC3("sleeping","","\n"); - sleep(i); - } -#endif /* GETHOSTBYNAME_DELAY */ - - LOG_PROC3("gethostbyname",name,"\n"); - - h = gethostbyname(name); - -#ifdef RANDOMIZE_ADDRESSES - if (h) - { - unsigned long n_addrs; - for (n_addrs = 0; h->h_addr_list[n_addrs]; n_addrs++) - ; - if (n_addrs > 0) - which_addr = (random_number % n_addrs); - else - h = 0; - } -#endif /* RANDOMIZE_ADDRESSES */ - - if (h) - sprintf(buf, "%d: %d.%d.%d.%d\n", - DNS_STATUS_GETHOSTBYNAME_OK, - ((unsigned char *) h->h_addr_list[which_addr])[0], - ((unsigned char *) h->h_addr_list[which_addr])[1], - ((unsigned char *) h->h_addr_list[which_addr])[2], - ((unsigned char *) h->h_addr_list[which_addr])[3]); - else - sprintf(buf, "%d: host %s not found\n", - DNS_STATUS_GETHOSTBYNAME_FAILED, name); - - LOG_PROC3("writing response",buf,""); - - write(out_fd, buf, strlen(buf)); - FLUSH(out_fd); -} - - - -/* Process 2. - Loops forever. - - Reads "lookup: hostname\n". - Writes "2xx: id\n" or "5xx: error msg\n". - Some time later, writes "1xx: id: a.b.c.d\n" or "5xx: id: error msg\n". - - -or- - - Reads "kill: id\n". - Writes "1xx: killed" or "5xx: kill failed" - */ - -typedef struct dns_lookup { - long id; - pid_t pid; - FILE *fd; - char *name; - struct dns_lookup *next, *prev; -} dns_lookup; - -static long dns_id_tick; -static dns_lookup *proc2_queue = 0; - - -static long -proc2_queue_length(void) -{ - dns_lookup *obj; - long i = 0; - for (obj = proc2_queue; obj; obj = obj->next) i++; - return i; -} - - -static dns_lookup * -new_lookup_object (const char *name) -{ - dns_lookup *obj; - char *n2; - ASSERT(name); - if (!name) return 0; - - n2 = strdup(name); - if (!n2) return 0; /* MK_OUT_OF_MEMORY */ - - obj = (dns_lookup *) malloc(sizeof(*obj)); - if (!obj) return 0; - memset(obj, 0, sizeof(*obj)); - obj->id = ++dns_id_tick; - obj->name = n2; - obj->fd = 0; - - ASSERT(!proc2_queue || proc2_queue->prev == 0); - obj->next = proc2_queue; - if (proc2_queue) - proc2_queue->prev = obj; - proc2_queue = obj; - - return obj; -} - - -/* Frees the object associated with a host lookup on which proc2 is waiting, - and writes the result to proc1. Returns 0 if everything went ok, negative - otherwise. Status should be 0 (for "ok") or negative (the inverse of one - of the three-digit response codes that *proc1* is expecting (not the codes - that *proc3* returns.)n - */ -static int -free_lookup_object (dns_lookup *obj, - int out_fd, - int status, const char *error_msg, - const unsigned char ip_addr[4]) -{ - char buf[MAXHOSTNAMELEN + 100]; - - ASSERT(status == 0 || (status < -100 && status > -700)); - - ASSERT(obj); - if (!obj) return -1; - - if (status >= 0 && ip_addr) - { - sprintf(buf, "%d: %lu: %d.%d.%d.%d\n", - DNS_STATUS_LOOKUP_OK, - obj->id, ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]); - } - else - { - ASSERT(error_msg); - sprintf(buf, "%d: %lu: %s\n", - ((status < -100) ? -status : DNS_STATUS_INTERNAL_ERROR), - obj->id, (error_msg ? error_msg : "???")); - } - - LOG_PROC2("writing response",buf,""); - - write(out_fd, buf, strlen(buf)); - FLUSH(out_fd); - - if (obj->fd) - { - fclose(obj->fd); - obj->fd = 0; - } - if (obj->prev) - { - ASSERT(obj->prev->next != obj->next); - obj->prev->next = obj->next; - } - if (obj->next) - { - ASSERT(obj->next->prev != obj->prev); - obj->next->prev = obj->prev; - } - if (proc2_queue == obj) - proc2_queue = obj->next; - - memset(obj, ~0, sizeof(obj)); - free(obj); - - return 0; -} - - -static dns_lookup * -spawn_lookup_process (const char *name, int out_fd) -{ - dns_lookup *obj = new_lookup_object(name); - pid_t forked; - int fds[2]; /* one reads from [0] and writes to [1]. */ - unsigned long random_number = 0; - - if (pipe (fds)) - { - free_lookup_object(obj, out_fd, - -DNS_STATUS_LOOKUP_NOT_STARTED, - "can't make pipe", 0); - obj = 0; - return 0; - } - - /* Save the fd from which we should read from the forked proc. */ - obj->fd = fdopen(fds[0], "r"); - if (!obj->fd) - { - close(fds[0]); - close(fds[1]); - free_lookup_object(obj, out_fd, - -DNS_STATUS_LOOKUP_NOT_STARTED, - "out of memory", 0); - obj = 0; - return 0; - } - SET_BUFFERING(obj->fd); - -#ifdef RANDOMIZE_ADDRESSES - /* Generate the random numbers in proc2 for use by proc3, so that the - PRNG actually gets permuted. */ - random_number = (unsigned long) RANDOM(); -#endif /* RANDOMIZE_ADDRESSES */ - - - switch (forked = fork ()) - { - case -1: - { - close (fds[1]); - free_lookup_object(obj, out_fd, - -DNS_STATUS_LOOKUP_NOT_STARTED, - "can't fork", 0); - obj = 0; - return 0; - } - break; - - case 0: /* This is the forked process. */ - { - /* Close the other side of the pipe (it's used by the main fork.) */ - close (fds[0]); - - /* Call gethostbyname, then write the result down the pipe. */ - blocking_gethostbyname(name, fds[1], random_number); - - /* Now exit this process. */ - close (fds[1]); - exit(0); - } - break; - - default: - { - /* This is the "old" process (subproc pid is in `forked'.) */ - obj->pid = forked; - - /* This is the file descriptor we created for the benefit - of the child process - we don't need it in the parent. */ - close (fds[1]); - - return obj; /* ok. */ - } - break; - } - - /* shouldn't get here. */ - ASSERT(0); - return 0; -} - - -/* Given a line which is an asynchronous response from proc3, find the - associated lookup object, feed the response on to proc1, and free - the dns_lookup object. - */ -static void -handle_subproc_response(dns_lookup *obj, const char *line, int out_fd) -{ - int iip[4]; - char *s; - int code = 0; - int i; - - i = sscanf(line, "%d: %d.%d.%d.%d\n", - &code, &iip[0], &iip[1], &iip[2], &iip[3]); - if (i != 5) - { - i = sscanf(line, "%d:", &code); - if (i != 1 || code <= 100) - code = DNS_STATUS_INTERNAL_ERROR; - } - - switch (code) - { - case DNS_STATUS_GETHOSTBYNAME_OK: - { - unsigned char ip[5]; - ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3]; - ip[4] = 0; /* just in case */ - free_lookup_object (obj, out_fd, 0, 0, ip); - obj = 0; - break; - } - - case DNS_STATUS_GETHOSTBYNAME_FAILED: - default: - { - ASSERT(code == DNS_STATUS_GETHOSTBYNAME_FAILED); - if (code == DNS_STATUS_GETHOSTBYNAME_FAILED) - code = DNS_STATUS_LOOKUP_FAILED; - s = strchr(line, ':'); - if (s) s++; - free_lookup_object (obj, out_fd, - (code > 100 - ? -code - : -DNS_STATUS_INTERNAL_ERROR), - (s ? string_trim(s) : "???"), 0); - obj = 0; - break; - } - } -} - - -static void -cancel_lookup(long id, int out_fd) -{ - dns_lookup *obj = 0; - - if (proc2_queue) - for (obj = proc2_queue; obj; obj = obj->next) - if (obj->id == id) break; - - if (obj) - { - if (obj->pid) - { - pid_t pid2; - - /* - * SIGKILL causes the browser to hang if the user clicks on the stop - * button while a long/bogus dns lookup is in progress. According - * to signal guru asharma, we should use SIGQUIT instead. -re - */ -/* kill(obj->pid, SIGKILL); */ - kill(obj->pid, SIGQUIT); - pid2 = waitpid(obj->pid, 0, 0); - ASSERT(obj->pid == pid2); - } - free_lookup_object(obj, out_fd, -DNS_STATUS_KILLED_OK, "cancelled", 0); - obj = 0; - } - else - { - char buf[200]; - sprintf (buf, "%d: %lu: unable to cancel\n", DNS_STATUS_KILL_FAILED, id); - LOG_PROC2("writing (kill) response",buf,""); - write(out_fd, buf, strlen(buf)); - } - - FLUSH(out_fd); -} - - -static void -dns_socks_kludge(void) -{ -#ifndef NO_SOCKS_NS_KLUDGE - /* Gross historical kludge. - If the environment variable $SOCKS_NS is defined, stomp on the host that - the DNS code uses for host lookup to be a specific ip address. - */ - char *ns = getenv("SOCKS_NS"); - if (ns && *ns) - { - /* Gross hack added to Gross historical kludge - need to - * initialize resolv.h structure first with low-cost call - * to gethostbyname() before hacking _res. Subsequent call - * to gethostbyname() will then pick up $SOCKS_NS address. - */ - gethostbyname("localhost"); - - res_init(); - _res.nsaddr_list[0].sin_addr.s_addr = inet_addr(ns); - _res.nscount = 1; - } -#endif /* !NO_SOCKS_NS_KLUDGE */ -} - - -#ifdef PROC2_DEBUG_PRINT -static void -dns_signal_handler_dfl (int sig) -{ - char buf[100]; - signal (sig, SIG_DFL); - sprintf(buf,"caught signal %d!\n",sig); - LOG_PROC2("dns_signal_handler",buf,""); - kill (getpid(), sig); -} -#endif /* PROC2_DEBUG_PRINT */ - -static void -dns_signal_handler_ign (int sig) -{ -#ifdef PROC2_DEBUG_PRINT - char buf[100]; - sprintf(buf,"caught signal %d -- ignoring.\n",sig); - LOG_PROC2("dns_signal_handler",buf,""); -#endif /* PROC2_DEBUG_PRINT */ - signal (sig, dns_signal_handler_ign); -} - - -static void -dns_catch_signals(void) -{ -#ifndef SIG_ERR -# define SIG_ERR -1 -#endif - -#ifdef PROC2_DEBUG_PRINT - int sig; - char buf[255]; - LOG_PROC2("dns_catch_signals","plugging in...\n",""); -# define CATCH_SIGNAL_DFL(SIG) sig = SIG; \ - if (((int)signal(SIG, dns_signal_handler_dfl)) == ((int)SIG_ERR)) \ - goto FAIL -# define CATCH_SIGNAL_IGN(SIG) sig = SIG; \ - if (((int)signal(SIG, dns_signal_handler_ign)) == ((int)SIG_ERR)) \ - goto FAIL -#else /* !PROC2_DEBUG_PRINT */ -# define CATCH_SIGNAL_DFL(SIG) \ - if ((int)signal(SIG,SIG_DFL) == ((int)SIG_ERR)) goto FAIL -# define CATCH_SIGNAL_IGN(SIG) \ - if ((int)signal(SIG,SIG_IGN) == ((int)SIG_ERR)) goto FAIL -#endif /* !PROC2_DEBUG_PRINT */ - - CATCH_SIGNAL_IGN(SIGHUP); - CATCH_SIGNAL_IGN(SIGINT); - CATCH_SIGNAL_IGN(SIGQUIT); - CATCH_SIGNAL_DFL(SIGILL); - CATCH_SIGNAL_DFL(SIGTRAP); - CATCH_SIGNAL_DFL(SIGIOT); - CATCH_SIGNAL_DFL(SIGABRT); -# ifdef SIGEMT - CATCH_SIGNAL_DFL(SIGEMT); -# endif - CATCH_SIGNAL_DFL(SIGFPE); - CATCH_SIGNAL_DFL(SIGBUS); - CATCH_SIGNAL_DFL(SIGSEGV); -# ifdef SIGSYS - CATCH_SIGNAL_DFL(SIGSYS); -# endif - CATCH_SIGNAL_DFL(SIGPIPE); - CATCH_SIGNAL_DFL(SIGTERM); /* ignore this one? hmm... */ - CATCH_SIGNAL_IGN(SIGUSR1); - CATCH_SIGNAL_IGN(SIGUSR2); -# ifdef SIGXCPU - CATCH_SIGNAL_DFL(SIGXCPU); -# endif -# ifdef SIGDANGER - CATCH_SIGNAL_DFL(SIGDANGER); -# endif -# undef CATCH_SIGNAL - - return; - - FAIL: -#ifdef PROC2_DEBUG_PRINT - sprintf(buf,"\tproc2 (%lu): error handling signal %d", - (unsigned long) getpid(), sig); - perror(buf); -#endif /* PROC2_DEBUG_PRINT */ - exit(1); -} - - -static void dns_driver_init(int argc, char **argv, int in_fd, int out_fd); -static void dns_driver_main_loop(int in_fd, int out_fd); - -/* Essentially, this is the main() of the forked dns-helper process. - */ -static void -dns_driver(int argc, char **argv, int in_fd, int out_fd) -{ - /* Might not return, if we fork-and-exec. */ - dns_driver_init(argc, argv, in_fd, out_fd); - - /* Shouldn't return until proc1 has closed its end of the pipe. */ - dns_driver_main_loop(in_fd, out_fd); -} - - -static void -dns_driver_init(int argc, char **argv, int in_fd, int out_fd) -{ -#ifdef CHANGING_ARGV_WORKS - { - LOG_PROC2("launched","","\n"); - ERROR! Write me! (This should overwrite argv.) - } -#else /* !CHANGING_ARGV_WORKS */ - { - char proc2_name[] = DNS_PROC2_NAME "\000"; - - /* If argv[0] is already the proc2 name, then we're already in proc2, - so there's nothing else to do. - - Otherwise, re-exec the running program with a different name. - Kludge, kludge, kludge. - */ - if (!strcmp(argv[0], proc2_name)) - { - LOG_PROC2("dns_driver_init","not respawning.\n",""); - } - else - { - char *new_argv[2]; - new_argv[0] = proc2_name; - new_argv[1] = 0; - - LOG_PROC2("dns_driver_init", - "execvp(... \"" DNS_PROC2_NAME "\")\n", ""); - - /* Copy in_fd and out_fd onto stdin/stdout, in order to pass them - to the newly-exec'ed process. */ - dup2(in_fd, fileno(stdin)); - dup2(out_fd, fileno(stdout)); - - execvp(argv[0], new_argv); - - fprintf(stderr, - "\nMozilla: execvp(\"%s\") failed!\n" - "\tThis means that we were unable to fork() the dns-helper process,\n" - "\tand so host-name lookups will happen in the foreground instead\n" - "\tof in the background (and therefore won't be interruptible.)\n\n", - argv[0]); - exit(0); - } - } -#endif /* !CHANGING_ARGV_WORKS */ - - - /* Close any streams we're not using. - */ - if (fileno(stdin) != in_fd && fileno(stdin) != out_fd) - fclose(stdin); - if (fileno(stdout) != in_fd && fileno(stdout) != out_fd) - fclose(stdout); - /* Never close stderr -- proc2 needs it in case the execvp() fails. */ - - dns_socks_kludge(); - dns_catch_signals(); - -#ifdef RANDOMIZE_ADDRESSES - { - struct timeval tp; - struct timezone tzp; - int seed; - gettimeofday(&tp, &tzp); - seed = (999*tp.tv_sec) + (1001*tp.tv_usec) + (1003 * getpid()); - SRANDOM(seed); - } -#endif /* RANDOMIZE_ADDRESSES */ - -} - - -static void -dns_driver_main_loop(int in_fd, int out_fd) -{ - int status = 0; - FILE *in = fdopen(in_fd, "r"); - ASSERT(in); - if (!in) return; /* out of memory *already*? We lost real bad... */ - SET_BUFFERING(in); - - while (1) - { - fd_set fdset; - char line[MAXHOSTNAMELEN + 100]; - dns_lookup *obj = 0; - dns_lookup *next = 0; - - FD_ZERO(&fdset); - - /* Select on our parent's input stream. */ - FD_SET(in_fd, &fdset); - - /* And select on the pipe associated with each child process. */ - if (proc2_queue) - for (obj = proc2_queue; obj; obj = obj->next) - { - int fd; - ASSERT(obj->fd); - if (!obj->fd) continue; - fd = fileno(obj->fd); - ASSERT(fd >= 0 && - fd != in_fd && - fd != out_fd && - !FD_ISSET(fd, &fdset)); - FD_SET(fd, &fdset); - } - -#ifdef PROC2_DEBUG_PRINT - { - int i = 0, j = 0; - fprintf(stderr, "\tproc2 (%lu): entering select(", - (unsigned long) getpid()); - for (i = 0; i < getdtablehi(); i++) - if (FD_ISSET(i, &fdset)) - { - fprintf(stderr, "%s%d", (j == 0 ? "" : ", "), i); - j++; - } - fprintf(stderr, ")\n"); - } -#endif /* PROC2_DEBUG_PRINT */ - - status = select(getdtablehi(), &fdset, 0, 0, 0); - - LOG_PROC2("select returned","","\n"); - - ASSERT(status > 0); - if (status <= 0) continue; - - - /* Handle input from our parent. - */ - - if (FD_ISSET (in_fd, &fdset)) - { - /* Read one line from the parent (blocking if necessary, which - it shouldn't be except for a trivial amount of time.) */ - *line = 0; - fgets(line, sizeof(line)-1, in); - - if (!*line) - { - LOG_PROC2("got EOF from proc1; exiting","","\n"); - return; - } - - LOG_PROC2("read command",line,""); - - string_trim(line); - - if (!strncmp(line, "kill: ", 6)) - { - long id = 0; - status = sscanf(line+6, "%ld\n", &id); - ASSERT(status == 1); - if (id) - cancel_lookup(id, out_fd); - } - else if (!strncmp(line, "lookup: ", 8)) - { - char *name = line + 8; - obj = spawn_lookup_process(name, out_fd); - /* Write a response to the parent immediately (to assign an id.) - */ - if (obj) - sprintf(line, "%d: %lu\n", - DNS_STATUS_LOOKUP_STARTED, - obj->id); - else - sprintf(line, "%d: %lu\n", - DNS_STATUS_LOOKUP_NOT_STARTED, - obj->id); - - LOG_PROC2("writing initial",line,""); - write(out_fd, line, strlen(line)); - FLUSH(out_fd); - } - } - - - /* Handle input from our kids. - */ - - for (obj = proc2_queue; obj; obj = next) - { - next=obj->next; - if (FD_ISSET(fileno(obj->fd), &fdset)) - { - pid_t pid = obj->pid; - pid_t pid2; - - /* Read one line from the subprocess (blocking if necessary, - which it shouldn't be except for a trivial amount of time.) */ - *line = 0; - fgets(line, sizeof(line)-1, obj->fd); - -#ifdef PROC2_DEBUG_PRINT - fprintf(stderr, "\tproc2 (%lu): read from proc3 (%ld): %s", - (unsigned long) getpid(), obj->id, line); -#endif /* PROC2_DEBUG_PRINT */ - - handle_subproc_response(obj, line, out_fd); - - /* `obj' has now been freed. After having written one line, the - process should exit. Wait for it now (we saved `pid' before - `obj' got freed.) - - The thing that confuses me is, if I *don't* do the waitpid() - here, zombies don't seem to get left around. I expected them - to, and don't know why they don't. (On Irix 6.2, at least.) - */ - pid2 = waitpid(pid, 0, 0); - } - } - } - - ASSERT(0); /* not reached */ -} - - - -/* Process 1 (the user-called code.) - */ - - -static FILE *dns_in_fd = 0; -static FILE *dns_out_fd = 0; - - -typedef struct queued_response { - long id; - int (*cb) (void *id, void *closure, int status, const char *result); - void *closure; - struct queued_response *next, *prev; -} queued_response; - -static queued_response *proc1_queue = 0; - - -static long -proc1_queue_length(void) -{ - queued_response *obj; - long i = 0; - for (obj = proc1_queue; obj; obj = obj->next) i++; - return i; -} - - -/* Call this from main() to initialize the async DNS library. - Returns a file descriptor that should be selected for, or - negative if something went wrong. Pass it the argc/argv - that your `main' was called with (it needs these pointers - in order to give its forked subprocesses sensible names.) - */ -int -DNS_SpawnProcess(int argc, char **argv) -{ - static int already_spawned_p = 0; - pid_t forked; - int infds[2]; /* "in" and "out" are from the p.o.v. of proc2. */ - int outfds[2]; /* one reads from [0] and writes to [1]. */ - - ASSERT(!already_spawned_p); - if (already_spawned_p) return -1; - already_spawned_p = 1; - -#ifndef CHANGING_ARGV_WORKS - if (!strcmp(argv[0], DNS_PROC2_NAME)) - { - /* Oh look, we're already in proc2, so don't fork again. - Assume our side of the pipe is on stdin/stdout. - */ - LOG_PROC2("DNS_SpawnProcess","reconnecting to stdin/stdout.\n",""); - - /* doesn't return until the other side closes the pipe. */ - dns_driver(argc, argv, fileno(stdin), fileno(stdout)); - exit(0); - } -#endif /* !CHANGING_ARGV_WORKS */ - - LOG_PROC1("DNS_SpawnProcess","forking proc2.\n",""); - - if (pipe (infds)) - { - return -1; /* pipe error: return better error code? */ - } - if (pipe (outfds)) - { - close(infds[0]); - close(infds[1]); - return -1; /* pipe error: return better error code? */ - } - - switch (forked = fork ()) - { - case -1: - { - close (infds[0]); - close (infds[1]); - close (outfds[0]); - close (outfds[1]); - return -1; /* fork error: return better error code? */ - } - break; - - case 0: /* This is the forked process. */ - { - /* Close the other sides of the pipes (used by the main fork.) */ - close (infds[1]); - close (outfds[0]); - - /* doesn't return until the other side closes the pipe. */ - dns_driver(argc, argv, infds[0], outfds[1]); - - close (infds[0]); - close (outfds[1]); - exit(-1); - } - break; - - default: - { - /* This is the "old" process (subproc pid is in `forked'.) - (Save that somewhere?) - */ - - /* This is the file descriptor we created for the benefit - of the child process - we don't need it in the parent. */ - close (infds[0]); - close (outfds[1]); - - /* Set up FILE objects for the proc3 side of the pipes. - (Note that the words "out" in `dns_out_fd' and `outfds' - have opposite senses here.) - */ - dns_out_fd = fdopen(infds[1], "w"); - dns_in_fd = fdopen(outfds[0], "r"); - - SET_BUFFERING(dns_out_fd); - SET_BUFFERING(dns_in_fd); - - return fileno(dns_in_fd); /* ok! */ - } - break; - } -} - - -static queued_response * -new_queued_response (int (*cb) (void *, void *closure, int, const char *), - void *closure) -{ - queued_response *obj; - - obj = (queued_response *) malloc(sizeof(*obj)); - if (!obj) return 0; - memset(obj, 0, sizeof(*obj)); - obj->id = 0; - obj->cb = cb; - obj->closure = closure; - - ASSERT(!proc1_queue || proc1_queue->prev == 0); - obj->next = proc1_queue; - if (proc1_queue) - proc1_queue->prev = obj; - proc1_queue = obj; - - return obj; -} - - -/* Frees the object associated with a host lookup on which proc1 is waiting, - and runs the callback function. The returned value is that of the callback. - */ -static int -free_queued_response (queued_response *obj, int status, const char *result) -{ - long id = obj->id; - int (*cb) (void *id, void *closure, int status, const char *result) - = obj->cb; - void *closure = obj->closure; - - if( -1 == id ) return 0; - - if (obj->prev) - { - ASSERT(obj->prev->next != obj->next); - obj->prev->next = obj->next; - } - if (obj->next) - { - ASSERT(obj->next->prev != obj->prev); - obj->next->prev = obj->prev; - } - if (proc1_queue == obj) - proc1_queue = obj->next; - - ASSERT(closure != (void *) obj); - memset(obj, ~0, sizeof(*obj)); - free(obj); - - ASSERT(status < -100 && status > -700); - if (status == -DNS_STATUS_LOOKUP_OK) status = 1; - else if (status == -DNS_STATUS_KILL_FAILED) status = 0; - - if (cb) - return cb((void *) id, closure, status, result); - else - return 0; -} - - -/* Given a line which is an asynchronous response from proc2, find the - associated lookup object, run the callback, return the status that - the callback returned, and free the queued_response object. - */ -static int -handle_async_response(char *line) -{ - int i; - int code = 0; - queued_response *obj = 0; - long id = 0; - int iip[4]; - - ASSERT(line); - if (!line || !*line) return -1; - - i = sscanf(line, "%d: %lu: %d.%d.%d.%d\n", - &code, &id, - &iip[0], &iip[1], &iip[2], &iip[3]); - if (i != 6) - { - i = sscanf(line, "%d: %lu:", &code, &id); - if (i != 2) - { - i = sscanf(line, "%d:", &code); - if (i != 1) - code = DNS_STATUS_INTERNAL_ERROR; - } - } - - if (id) - for (obj = proc1_queue; obj; obj = obj->next) - if (obj->id == id) break; - - if (!obj) /* got an id that we don't know about? */ - return -1; - - switch (code) - { - case DNS_STATUS_LOOKUP_OK: /* "1xx: id: a.b.c.d\n" */ - { - unsigned char ip[5]; - ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3]; - ip[4] = 0; /* just in case */ - return free_queued_response(obj, -DNS_STATUS_LOOKUP_OK, (char *) ip); - break; - } - case DNS_STATUS_LOOKUP_FAILED: /* "5xx: id: host not found\n" */ - default: - { - char *msg = 0; - ASSERT(code == DNS_STATUS_LOOKUP_FAILED); - msg = strchr(line, ':'); - if (msg) - { - char *s = strchr(msg, ':'); - if (s) msg = s+1; - } - else - { - msg = line; - } - - code = (code > 100 ? -code : -DNS_STATUS_INTERNAL_ERROR); - free_queued_response(obj, code, string_trim(msg)); - return code; - break; - } - } - ASSERT(0); /* not reached */ -} - - - -/* Kick off an async DNS lookup; - The returned value is an id representing this transaction; - the result_callback will be run (in the main process) when we - have a result. Returns negative if something went wrong. - If `status' is negative,`result' is an error message. - If `status' is positive, `result' is a 4-character string of - the IP address. - If `status' is 0, then the lookup was prematurely aborted - via a call to DNS_AbortHostLookup(). - */ -int -DNS_AsyncLookupHost(const char *name, - int (*result_callback) (void *id, - void *closure, - int status, - const char *result), - void *closure, - void **id_return) -{ - char buf[MAXHOSTNAMELEN + 100]; - queued_response *obj = 0; - int code = 0; - int i; - char *s; - - ASSERT(result_callback); - if (!result_callback) return -1; - ASSERT(id_return); - if (!id_return) return -1; - *id_return = 0; - - ASSERT(name); - if (!name || !*name) return -1; /* invalid host name: better error code? */ - if (strchr(name, '\n')) return -1; /* ditto */ - if (strchr(name, '\r')) return -1; - - if (strlen(name) > MAXHOSTNAMELEN) - return -1; /* host name too long: return better error code? */ - - obj = new_queued_response(result_callback, closure); - if (!obj) return -1; /* out of memory: return better error code? */ - - - LOG_PROC1("writing: lookup",name,"\n"); - fprintf(dns_out_fd, "lookup: %s\n", name); - fflush(dns_out_fd); - FLUSH(fileno(dns_out_fd)); - - /* We have just written a "lookup:" command to proc2. - As soon as this command is received, proc2 will write a 2xx response - back to us, ACKing it, and giving us an ID. We must wait for that - response in order to return the ID to our caller; we block waiting - for it, knowing that it won't be long in coming. - - However, there could be other data in the pipe already -- the final - results of previously launched commands (1xx responses or 5xx responses.) - So we read commands, and process them, until we find the one we're - looking for. - - Under no circumstances can there be more than one 2xx response in the - pipe at a time (since this is the only place a command is issued that - can cause a 2xx response to be generated, and each call waits for it.) - */ - -AGAIN: - - *buf = 0; - fgets(buf, sizeof(buf)-1, dns_in_fd); - LOG_PROC1("read (lookup)",buf,""); - - obj->id = 0; - - if (!*buf) /* EOF, perhaps? */ - { - code = DNS_STATUS_INTERNAL_ERROR; - } - else - { - i = sscanf(buf, "%d:", &code); - ASSERT(i == 1); - if (code <= 100) code = DNS_STATUS_INTERNAL_ERROR; - } - - switch (code) - { - case DNS_STATUS_LOOKUP_STARTED: /* 2xx: id\n" */ - i = sscanf(buf, "%d: %lu\n", &code, &obj->id); - ASSERT(i == 2); - *id_return = (void *) obj->id; - return 0; - break; - - case DNS_STATUS_LOOKUP_OK: /* 1xx or 5xx which is an */ - case DNS_STATUS_LOOKUP_FAILED: /* async response (not for us) */ - handle_async_response(buf); - goto AGAIN; - break; - - case DNS_STATUS_LOOKUP_NOT_STARTED: - default: /* 5xx: error msg\n" - Presumably this is for us. - (If not, there's a bug...) */ - ASSERT(code == DNS_STATUS_LOOKUP_NOT_STARTED); - s = strchr(buf, ':'); - if (s) s++; - code = (code > 100 ? -code : -DNS_STATUS_INTERNAL_ERROR); - code = free_queued_response(obj, code, (s ? string_trim(s) : "???")); - obj = 0; - return code; - break; - } - ASSERT(0); /* not reached */ - return -1; -} - - -/* Prematurely give up on the given host-lookup transaction. - The `token' is what was returned by DNS_AsyncLookupHost. - This causes the result_callback to be called with a negative - status. - */ -int -DNS_AbortHostLookup(void *token) -{ - char buf[MAXHOSTNAMELEN + 100]; - int code = 0; - int i; - long id = (int) token; - long id2 = 0; - queued_response *obj = 0; - char *s; - - for (obj = proc1_queue; obj; obj = obj->next) - if (obj->id == id) break; - - if (!obj) return -1; - -#ifdef PROC1_DEBUG_PRINT - fprintf(stderr, "\tproc1 (%lu): writing: kill: %lu (ql=%ld)\n", - (unsigned long) getpid(), id, proc1_queue_length()); -#endif /* PROC1_DEBUG_PRINT */ - - fprintf(dns_out_fd, "kill: %lu\n", id); - fflush(dns_out_fd); - FLUSH(fileno(dns_out_fd)); - - - /* We have just written a "kill:" command to proc2. - As soon as this command is received, proc2 will write a 1xx or 5xx - response back to us, ACKing it. We must wait for that response in - order to return an error code to our caller; we block waiting for it, - knowing that it won't be long in coming. - - However, there could be other data in the pipe already -- the final - results of previously launched commands (1xx responses or 5xx responses.) - So we read commands, and process them, until we find the one we're - looking for. - - Under no circumstances can there be more than one kill-response in the - pipe at a time (since this is the only place a command is issued that - can cause a kill-response response to be generated, and each call waits - for it.) - */ - -AGAIN: - - *buf = 0; - fgets(buf, sizeof(buf)-1, dns_in_fd); - LOG_PROC1("read (kill)",buf,""); - - i = sscanf(buf, "%d:", &code); - ASSERT(i == 1); - if (code <= 100) code = DNS_STATUS_INTERNAL_ERROR; - - switch (code) - { - case DNS_STATUS_KILLED_OK: - return free_queued_response(obj, -DNS_STATUS_KILLED_OK, "killed"); - break; - - case DNS_STATUS_LOOKUP_OK: /* 1xx or 5xx which is an */ - case DNS_STATUS_LOOKUP_FAILED: /* async response (not for us) */ - - /* Actually, it might be for us -- if we've issued a kill, but the - success/failure for this same code raced in before the response - to the kill (a kill-failure, presumably) then ignore this response - (wait for the kill-failure instead.) */ - id2 = 0; - i = sscanf(buf, "%d: %lu:", &code, &id2); - ASSERT(i == 2); - if (i == 2 && id2 == id) { - LOG_PROC1("Bug #87736 (1)",buf,""); - handle_async_response(buf); - goto AGAIN; - } - - /* Not for us -- let it through. */ - handle_async_response(buf); - goto AGAIN; - break; - - case DNS_STATUS_KILL_FAILED: - default: /* 5xx: error msg\n" - Presumably this is for us. - (If not, there's a bug...) */ - ASSERT(code == DNS_STATUS_KILL_FAILED); - s = strchr(buf, ':'); - if (s) - { - char *s2 = strchr(++s, ':'); - if (s2) s = s2+1; - } - code = (code > 100 ? -code : -DNS_STATUS_INTERNAL_ERROR); - free_queued_response(obj, code, (s ? string_trim(s) : "???")); - LOG_PROC1("Bug #87736 (2)",buf,""); - return code; - break; - } - ASSERT(0); /* not reached */ - return -1; -} - - - -/* The main select() loop of your program should call this when the fd - that was returned by DNS_SpawnProcess comes active. This may cause - some of the result_callback functions to run. - - If this returns negative, then a fatal error has happened, and you - should close `fd' and not select() for it again. Call gethostbyname() - in the foreground or something. - */ -int -DNS_ServiceProcess(int fd) -{ - char buf[MAXHOSTNAMELEN + 100]; - char *s = 0; - int status = 0; - int final_status = 0; - -AGAIN: - - ASSERT(fd == fileno(dns_in_fd)); - if (fd != fileno(dns_in_fd)) return -1; - - ASSERT(final_status <= 0); - - /* Poll to see if input is available on fd. - NOTE: This only works because we've marked the FILE* object wrapped - around this fd as being fully unbuffered!! - */ - { - fd_set fdset; - struct timeval t = { 0L, 0L, }; - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - status = select(fd+1, &fdset, 0, 0, &t); - if (status < 0 && final_status == 0) - final_status = status; - if (status <= 0) /* error, or no input ready */ - return final_status; - } - - *buf = 0; - s = fgets(buf, sizeof(buf)-1, dns_in_fd); - - if (s && *s) - { - LOG_PROC1("read (async)",buf,""); - } - else - { - /* #### If there's nothing to read, the socket must be closed? */ - LOG_PROC1("read (async)","nothing -- returning error\n",""); - return (final_status < 0 ? final_status : -1); - } - - /* call all pending procs, but remember the first error code that - one of them returned. - */ - status = handle_async_response(buf); - status = 0; /* #### */ - if (status < 0 && final_status == 0) - final_status = status; - - /* see if there is more to read. */ - goto AGAIN; -} - - - -#ifdef DEBUG -void -print_fdset(fd_set *fdset) -{ - int i; - int any = 0; - if (!fdset) return; - for (i = 0; i < getdtablesize(); i++) - { - if (FD_ISSET(i, fdset)) - { - if (any) fprintf(stderr, ", "); - any = 1; - fprintf(stderr, "%d", i); - } - } -} - -void -print_fd(int fd) -{ - int status; - fd_set fdset; - struct timeval t = { 0L, 0L, }; - - fprintf(stderr, " %d:\n", fd); - - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - status = select(fd+1, &fdset, 0, 0, &t); - if (status == 0) - fprintf(stderr, " readable (no input)\n"); - else if (status == 1) - fprintf(stderr, " readable (pending)\n"); - else - fprintf(stderr, " unreadable (error %d)\n", status); - - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - status = select(fd+1, 0, &fdset, 0, &t); - if (status == 0) - fprintf(stderr, " writeable (no input)\n"); - else if (status == 1) - fprintf(stderr, " writeable (pending)\n"); - else - fprintf(stderr, " unwriteable (error %d)\n", status); - - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - status = select(fd+1, 0, 0, &fdset, &t); - if (status == 0) - fprintf(stderr, " exceptionable (no input)\n"); - else if (status == 1) - fprintf(stderr, " exceptionable (pending)\n"); - else - fprintf(stderr, " unexceptionable (error %d)\n", status); -} - - -void -print_fdsets(fd_set *read, fd_set *write, fd_set *except) -{ - int i; - fd_set all; - FD_ZERO(&all); - - fprintf(stderr, "rd: "); print_fdset(read); - fprintf(stderr, "\nwr: "); print_fdset(write); - fprintf(stderr, "\nex: "); print_fdset(except); - fprintf(stderr, "\n"); - - if (read) - for (i = 0; i < getdtablesize(); i++) - if (FD_ISSET(i, read)) FD_SET(i, &all); - if (write) - for (i = 0; i < getdtablesize(); i++) - if (FD_ISSET(i, write)) FD_SET(i, &all); - if (except) - for (i = 0; i < getdtablesize(); i++) - if (FD_ISSET(i, except)) FD_SET(i, &all); - - for (i = 0; i < getdtablesize(); i++) - if (FD_ISSET(i, &all)) print_fd(i); -} - -#endif /* DEBUG */ - - - - -#ifdef STANDALONE - -typedef struct test_id_cons { - char *name; - void *id; - struct test_id_cons *next; -} test_id_cons; -static test_id_cons *test_list = 0; - -static int -test_cb (void *id, void *closure, int status, const char *result) -{ - const char *argv0 = (char *) closure; - test_id_cons *cons = test_list; - - while(cons) - { - if (cons->id == id) break; - cons = cons->next; - ASSERT(cons); - } - - if (status == 1) - { - unsigned char *ip = (unsigned char *) result; - fprintf(stderr, "%s: %s = %d.%d.%d.%d\n", - argv0, cons->name, ip[0], ip[1], ip[2], ip[3]); - } - else - { - fprintf(stderr, "%s: %s: error %d: %s\n", - argv0, cons->name, status, result); - } - return 0; -} - -int -main (int argc, char **argv) -{ - char buf[MAXHOSTNAMELEN + 100]; - int fd = DNS_SpawnProcess(argc, argv); - - if (fd <= 0) - { - fprintf(stderr, "%s: dns init failed\n", argv[0]); - exit(-1); - } - - fprintf(stderr, - "Type host names to spawn lookups.\n" - "Type `abort ID' to kill one off.\n" - "Type `quit' when done.\n\n"); - - while(1) - { - int status = 0; - fd_set fdset; - - FD_ZERO(&fdset); - FD_SET(fd, &fdset); - FD_SET(fileno(stdin), &fdset); - - status = select(getdtablehi(), &fdset, 0, 0, 0); - if (status <= 0) - { - fprintf(stderr, "%s: select() returned %d\n", argv[0], status); - exit(-1); - } - - if (!FD_ISSET(fd, &fdset) && - !FD_ISSET(fileno(stdin), &fdset)) - { - fprintf(stderr, "%s: neither fd is set?\n", argv[0]); - exit(-1); - } - - if (FD_ISSET(fd, &fdset)) - { - status = DNS_ServiceProcess(fd); - if (status < 0) - { - fprintf(stderr, "%s: DNS_ServiceProcess() returned %d\n", - argv[0], status); - exit(-1); - } - } - - if (FD_ISSET(fileno(stdin), &fdset)) - { - /* Read a line from the user. */ - char *line = fgets(buf, sizeof(buf)-1, stdin); - - line = string_trim(line); - - if (!strcmp(line, "quit") || !strcmp(line, "exit")) - { - fprintf(stderr, "buh bye now\n"); - exit(0); - } - else if (!strncmp(line, "abort ", 6)) - { - long id; - status = sscanf(line+6, "%lu\n", &id); - if (status != 1) - { - test_id_cons *cons = test_list; - while(cons) - { - if (!strcmp(cons->name, line+6)) break; - cons = cons->next; - } - if (cons) - id = (long) cons->id; - else - { - fprintf(stderr, "%s: %s is not a known host or id.\n", - argv[0], line+6); - continue; - } - } - - status = DNS_AbortHostLookup((void *)id); - if (status < 0) - fprintf(stderr, "%s: DNS_AbortHostLookup(%ld) returned %d\n", - argv[0], id, status); - } - else if (strchr(line, ' ') || strchr(line, '\t')) - { - fprintf(stderr, "%s: unrecognized command %s.\n", - argv[0], line); - } - else - { - void *id = 0; - test_id_cons *cons = 0; - - fprintf(stderr, "%s: looking up %s...", argv[0], line); - status = DNS_AsyncLookupHost(line, test_cb, argv[0], &id); - if (status == 0) - fprintf(stderr, " id = %lu.\n", (long)id); - else - fprintf(stderr, - "\n%s: DNS_AsyncLookupHost(%s) returned %d (id = %lu)\n", - argv[0], line, status, (long)id); - - cons = (test_id_cons *) malloc(sizeof(*cons)); - cons->name = strdup(line); - cons->id = id; - cons->next = test_list; - test_list = cons; - } - } - } -} - -#endif /* STANDALONE */ -#endif /* UNIX_ASYNC_DNS && XP_UNIX */ diff --git a/mozilla/network/main/win-dns.cpp b/mozilla/network/main/win-dns.cpp deleted file mode 100644 index 4809b3654e6..00000000000 --- a/mozilla/network/main/win-dns.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifdef XP_PC -#include <windows.h> -#ifdef WIN32_LEAN_AND_MEAN -#include <winsock2.h> -#endif -#include "net.h" -#include "nsISupports.h" -#include "merrors.h" -#include "prnetdb.h" -#include "plstr.h" -#include "prmem.h" -#include "prlog.h" -#include "nslocks.h" - -#ifdef DEBUG -static PRLogModuleInfo* gDNSLogModuleInfo; - -#define DNS_TRACE_LOOKUPS 0x1 -#define DNS_TRACE_SLOW 0x2 // XXX not yet implemented - -#define DNS_LOG_TEST(_lm,_bit) (PRIntn((_lm)->level) & (_bit)) - -#define DNS_TRACE(_bit,_args) \ - PR_BEGIN_MACRO \ - if (DNS_LOG_TEST(gDNSLogModuleInfo,_bit)) { \ - PR_LogPrint _args; \ - } \ - PR_END_MACRO - -#else -#define DNS_TRACE(_bit,_args) -#endif - -struct SocketWaiter { - void Init(PRFileDesc* fd) { - mSocket = fd; - mNext = NULL; - } - - PRFileDesc* mSocket; - SocketWaiter* mNext; -}; - -struct DNSCacheEntry { - nsresult Init(void* aContext, const char* aHost, PRFileDesc* fd); - - void Destroy(); - - static DNSCacheEntry** Lookup(const char* aHost); - - void* mContext; - char* mHost; - SocketWaiter* mSockets; - PRHostEnt* mHostEnt; - int mError; - PRBool mFinished; - HANDLE mHandle; - DNSCacheEntry* mNext; -}; - -extern "C" { -static UINT gMSGFoundDNS; -UINT gMSGAsyncSelect; -HWND gDNSWindow; -}; - -static DNSCacheEntry* gDNSCache; - -void -DNSCacheEntry::Destroy() -{ - PR_Free(mHost); - PR_Free(mHostEnt); - SocketWaiter* sw = mSockets; - while (NULL != sw) { - SocketWaiter* next = sw->mNext; - PR_Free(sw); - sw = next; - } -} - -nsresult -DNSCacheEntry::Init(void* aContext, const char* aHost, PRFileDesc* fd) -{ - mContext = aContext; - mError = 0; - mFinished = PR_FALSE; - mHandle = NULL; - mNext = NULL; - - mHost = PL_strdup(aHost); - mHostEnt = (PRHostEnt*) PR_Malloc(sizeof(char) * PR_NETDB_BUF_SIZE); - mSockets = (SocketWaiter*) PR_Malloc(sizeof(SocketWaiter)); - mSockets->Init(fd); - - if ((NULL == mHost) || (NULL == mHostEnt) || (NULL == mSockets)) { - return NS_ERROR_FAILURE; - } - mHostEnt->h_name = NULL; - mHostEnt->h_aliases = NULL; - mHostEnt->h_addr_list = NULL; - return NS_OK; -} - -DNSCacheEntry** -DNSCacheEntry::Lookup(const char* aHost) -{ - DNSCacheEntry** pentry = &gDNSCache; - DNSCacheEntry* entry = *pentry; - while (NULL != entry) { - if (PL_strcasecmp(aHost, entry->mHost) == 0) { - return pentry; - } - pentry = &entry->mNext; - entry = entry->mNext; - } - return pentry; -} - -#if defined(NO_NETWORK_POLLING) -extern "C" PRFileDesc* net_GetFileDescFromOSFD(PRInt32); -extern "C" void net_AsyncSelect(PRFileDesc* fd, long netMask); -#endif /* NO_NETWORK_POLLING */ - -static LRESULT CALLBACK -#if defined(WIN16) -__loadds -#endif -EventProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - if (gMSGFoundDNS == uMsg) { - // Get error code now - int error = WSAGETASYNCERROR(lParam); - - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: handle=%p error=%d", (HANDLE)wParam, error)); - - // Search cache for matching handle - LRESULT rv = 1; - DNSCacheEntry** pentry = &gDNSCache; - DNSCacheEntry* entry = gDNSCache; - while (NULL != entry) { - if (!entry->mFinished && ((HANDLE)wParam == entry->mHandle)) { - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: finished '%s'", entry->mHost)); - - // Found a match - entry->mFinished = PR_TRUE; - entry->mError = error; - if (0 != error) { - rv = 0; - } - SocketWaiter** psw = &entry->mSockets; - SocketWaiter* sw = entry->mSockets; - while (NULL != sw) { - // Poke netlib - int iWantMore = NET_ProcessNet(sw->mSocket, NET_SOCKET_FD); - *psw = sw->mNext; - PR_Free(sw); - sw = *psw; - } -#if XXX_DONT_CACHE_DNS_LOOKUPS - if (NULL == entry->mSockets) { - // Now that entry is complete, remove it - *pentry = entry->mNext; - entry->Destroy(); - PR_Free(entry); - } -#endif - return rv; - } - pentry = &entry->mNext; - entry = entry->mNext; - } - return rv; - } - -#if defined(NO_NETWORK_POLLING) - if (gMSGAsyncSelect == uMsg) { - PRFileDesc* fd; - - /* - * Enter the Libnet lock for the call to net_GetFileDescFromOSFD(...) - */ - LIBNET_LOCK(); - - fd = net_GetFileDescFromOSFD(wParam); - if (NULL != fd) { - /* - * Queue up another asynchronous notification before calling - * NET_ProcessNet(...). This way, we do not need to konw if the socket - * is still active after the call (or if it was closed...). If the - * connection is closed, the asynchronous request will be canceled... - */ - net_AsyncSelect(fd, - FD_READ | FD_WRITE | FD_ACCEPT | FD_CONNECT | FD_CLOSE | FD_OOB); - - /* Process the connection which has data... */ - NET_ProcessNet(fd, NET_SOCKET_FD); - } - - LIBNET_UNLOCK(); - } -#endif /* NO_NETWORK_POLLING */ - - return DefWindowProc(hwnd, uMsg, wParam, lParam); -} - -void net_InitAsyncDNS() -{ - static char *windowClass = "NETLIB:DNSWindow"; - -#ifdef DEBUG - gDNSLogModuleInfo = PR_NewLogModule("netlibdns"); -#endif - - // Allocate a message id for the event handler - gMSGFoundDNS = RegisterWindowMessage("Mozilla:DNSMessage"); - gMSGAsyncSelect = RegisterWindowMessage("Mozilla:AsyncSelectMessage"); - - // Register the class for the event receiver window - WNDCLASS wc; - wc.style = 0; - wc.lpfnWndProc = EventProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = NULL; - wc.hIcon = NULL; - wc.hCursor = NULL; - wc.hbrBackground = (HBRUSH) NULL; - wc.lpszMenuName = (LPCSTR) NULL; - wc.lpszClassName = windowClass; - RegisterClass(&wc); - - // Create the event receiver window - gDNSWindow = CreateWindow(windowClass, - "Mozilla:DNSEventHandler", - 0, 0, 0, 10, 10, - NULL, NULL, NULL, - NULL); - - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: hidden window=%p msg=%d", - gDNSWindow, gMSGFoundDNS)); -} - -extern "C" int -NET_AsyncDNSLookup(void* aContext, - const char* aHostPort, - PRHostEnt** aHoststructPtrPtr, - PRFileDesc* aSocket); - -int -NET_AsyncDNSLookup(void* aContext, - const char* aHostPort, - PRHostEnt** aHoststructPtrPtr, - PRFileDesc* aSocket) -{ - /* DNS initialization failed... */ - if (NULL == gDNSWindow) { - PR_ASSERT(0); - return -1; - } - - *aHoststructPtrPtr = NULL; - - // Look in cache first - DNSCacheEntry** pentry = DNSCacheEntry::Lookup(aHostPort); - DNSCacheEntry* entry = *pentry; - if (NULL != entry) { - // If lookup returned an error then indicate that to the caller... - if ((0 != entry->mError) && entry->mFinished) { - WSASetLastError(entry->mError); - if (NULL == entry->mSockets) { - // XXX can't get here, right? - // Delete entry when last socket is done with it... - *pentry = entry->mNext; - entry->Destroy(); - PR_Free(entry); - } - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: '%s' error=%d\n", entry->mHost, entry->mError)); - return -1; - } - - // If lookup finished then return the answer - if ((NULL != entry->mHostEnt->h_name) && entry->mFinished) { - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: '%s' finished\n", entry->mHost)); - *aHoststructPtrPtr = entry->mHostEnt; - return 0; - } - - // See if we are already waiting for the answer - SocketWaiter* sw = entry->mSockets; - while (NULL != sw) { - if (sw->mSocket == aSocket) { - return MK_WAITING_FOR_LOOKUP; - } - sw = sw->mNext; - } - - // Add this socket to the wait list - sw = (SocketWaiter*) PR_Malloc(sizeof(SocketWaiter)); - if (NULL == sw) { - return -1; - } - sw->Init(aSocket); - sw->mSocket = aSocket; - sw->mNext = entry->mSockets; - entry->mSockets = sw; - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: still waiting for host='%s'\n", entry->mHost)); - return MK_WAITING_FOR_LOOKUP; - } - - // Create a new cache entry for the host name - entry = (DNSCacheEntry*) PR_Malloc(sizeof(DNSCacheEntry)); - if (NULL == entry) { - return -1; - } - if (NS_OK != entry->Init(aContext, aHostPort, aSocket)) { - entry->Destroy(); - PR_Free(entry); - return -1; - } - - // Start async lookup on that host name - HANDLE h = WSAAsyncGetHostByName(gDNSWindow, - gMSGFoundDNS, - entry->mHost, - (char *)entry->mHostEnt, - PR_NETDB_BUF_SIZE); - DNS_TRACE(DNS_TRACE_LOOKUPS, - ("DNS lookup: begin waiting for host='%s' handle=%p\n", - entry->mHost, h)); - if (NULL == h) { - entry->Destroy(); - PR_Free(entry); - return -1; - } - entry->mHandle = h; - entry->mNext = *pentry; - *pentry = entry; - return MK_WAITING_FOR_LOOKUP; -} - -#endif diff --git a/mozilla/network/makefile.win b/mozilla/network/makefile.win deleted file mode 100644 index 09a9758cb24..00000000000 --- a/mozilla/network/makefile.win +++ /dev/null @@ -1,49 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the network stuff -# -#------------------------------------------------------------------------ - -DEPTH=.. - -DIRS= \ - main \ - mimetype \ -!ifdef NU_CACHE - cache\nu \ -!endif - cache \ - protocol \ - cnvts \ - client \ - public \ - module \ - $(NULL) - -include <$(DEPTH)\config\rules.mak> - - diff --git a/mozilla/network/mimetype/MANIFEST b/mozilla/network/mimetype/MANIFEST deleted file mode 100644 index bb41828b944..00000000000 --- a/mozilla/network/mimetype/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mkformat.h diff --git a/mozilla/network/mimetype/Makefile.in b/mozilla/network/mimetype/Makefile.in deleted file mode 100644 index a93925c852a..00000000000 --- a/mozilla/network/mimetype/Makefile.in +++ /dev/null @@ -1,90 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = mimetype -LIBRARY_NAME = mimetype - -REQUIRES = network img layer util - -CSRCS = mkformat.c - -EXPORTS = $(srcdir)/mkformat.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - -# -# This converts mime.types to C source code, -# and also to an HTML table that shows what's in it. -# -MIME_TYPES = $(srcdir)/mime.types -MIME_TYPES_UNIX = $(srcdir)/mime.types-unix -MIME_TYPES_NONUNIX = $(srcdir)/mime.types-nonunix -AD2C = sh $(topsrcdir)/cmd/xfe/ad2c - -mktypes.h: $(MIME_TYPES) $(MIME_TYPES_UNIX) $(MIME_TYPES_NONUNIX) - rm -f $@ - @echo "generating $@ from $<..." ; \ - (echo '/* Generated file - do not edit! */' ; \ - echo '' ; \ - cat $(MIME_TYPES) | grep -v '^#' | $(AD2C) ; \ - echo '' ; \ - echo '#ifdef XP_UNIX' ; \ - cat $(MIME_TYPES_UNIX) | grep -v '^#' | $(AD2C) ; \ - echo '#else /* !XP_UNIX */' ; \ - cat $(MIME_TYPES_NONUNIX) | grep -v '^#' | $(AD2C) ; \ - echo '#endif /* !XP_UNIX */' ; \ - ) > $@ - -mime-types.html: $(MIME_TYPES) $(MIME_TYPES_UNIX) - rm -f $@ - @echo "generating $@ from $<..." ; \ - (echo '<TITLE>Netscape MIME Types</TITLE>' ; \ - echo '<H1 ALIGN=CENTER>Netscape MIME Types</H1>' ; \ - echo '<CENTER>' ; \ - echo '<TABLE BORDER CELLSPACING=0 CELLPADDING=5>' ; \ - echo '<TR><TH></TH><TH>Content Type:</TH>' ; \ - echo '<TH>Extensions:</TH><TH>Description:</TH></TR>' ; \ - echo '<TR></TR><TR></TR><TR></TR>' ; \ - cat $(MIME_TYPES) $(MIME_TYPES_UNIX) | grep -v '^#' | \ - sed 's@exts="\([^"]*\)"[ ]*[\]*@<TR><TD><TT>\1</TT></TD>@; \ - s@desc="\([^"]*\)"[ ]*[\]*@<TD>\1</TD>@; \ - s@enc=\([^ ]*\)[ ]*[\]*$$@<TD>encoding/\1</TD>@; \ - s@type=\([^ ]*\)[ ]*[\]*$$@<TD>\1</TD>@; \ - s@icon=\([^ ]*\)[ ]*[\]*$$@<TD><IMG SRC=\1></TD></TR>@'\ - | sed 's/,/ /g' \ - | awk '{if ( $$0 ~ /^<TR/ ) {printf "%s" , $$0} \ - else {printf "%s\n" , $$0} }' \ - | sed 's@\(<TR>\)\(<TD>.*</TD>\)\(<TD>.*</TD>\)\(<TD>.*</TD>\)\(<TD>.*</TD>\)\(</TR>\)$$@\1\5!\3!\2!\4\6@' \ - | tr '!' '\012' \ - | sed 's@<TD></TD>@<TD>\&nbsp;</TD>@' ; \ - echo '</TABLE>' ; \ - echo '</CENTER>' ; \ - ) > $@ - diff --git a/mozilla/network/mimetype/makefile.win b/mozilla/network/mimetype/makefile.win deleted file mode 100644 index 6687e9bcd97..00000000000 --- a/mozilla/network/mimetype/makefile.win +++ /dev/null @@ -1,84 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkformat.obj \ - $(NULL) - - -CSRCS = \ - mkformat.c \ - $(NULL) - - -MODULE=mimetype -DEPTH=..\.. - -LIBRARY_NAME=mimetype - -EXTRA_LIBS= - -REQUIRES= foo parse jtools java zlib nspr dbm util network js security -EXPORTS= \ - mkformat.h \ - $(NULL) - -C_OBJS = \ - $(NULL) - - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\network \ - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/mimetype/mime.types b/mozilla/network/mimetype/mime.types deleted file mode 100644 index 0c2676b91bc..00000000000 --- a/mozilla/network/mimetype/mime.types +++ /dev/null @@ -1,304 +0,0 @@ -#--Netscape Communications Corporation MIME Information -# Do not delete the above line. It is used to identify the file type. - -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -# This file defines all of the default file extensions recognised by Netscape. -# See also mime.types-unix and mime.types-nonunix for some platform-specific -# stuff. - -# If you add a new non-"text/" type to this file, and it's primarily a -# line-based textual type, you may also want to update the list of -# application-types-that-are-really-textual in mime_type_requires_b64_p() -# in libmsg/compose.c, so that docs of that type don't always get base64 -# encoded when mailed. - -#################################################################### -# Text -#################################################################### - -exts="txt,text" type=text/plain \ -desc="Plain Text" icon=internal-gopher-text - -exts="html,htm" type=text/html \ -desc="Hypertext Markup Language" icon=internal-gopher-text - -exts="xml" type=text/xml \ -desc="Extensible Markup Language" icon=internal-gopher-text - -exts="rdf" type=text/rdf \ -desc="Resource Description Framework" icon=internal-gopher-text -# XXX should this be text/xml? - -exts="xul" type=text/xul \ -desc="XML-Based User Interface Language" icon=internal-gopher-text -# XXX should this be text/xml? - -exts="rtf" type=application/rtf \ -desc="Rich Text Format" icon=internal-gopher-text -# note: text/richtext is *not the same format* - -exts="pdf" type=application/pdf \ -desc="Portable Document Format" icon=internal-gopher-text - -exts="tex" type=application/x-tex \ -desc="TeX Document" icon=internal-gopher-text - -exts="latex" type=application/x-latex \ -desc="LaTeX Document" icon=internal-gopher-text - -exts="dvi" type=application/x-dvi \ -desc="TeX DVI Data" icon=internal-gopher-text - -exts="texi,texinfo" type=application/x-texinfo \ -desc="GNU TeXinfo Document" icon=internal-gopher-text - -exts="vcf" type=text/x-vcard \ -desc="VCard" icon=internal-gopher-unknown - - -#################################################################### -# Images -#################################################################### - -exts="gif" type=image/gif \ -desc="GIF Image" icon=internal-gopher-image - -exts="jpeg,jpg,jpe,jfif,pjpeg,pjp" type=image/jpeg \ -desc="JPEG Image" icon=internal-gopher-image - -exts="png" type=image/png \ -desc="PNG Image" icon=internal-gopher-image - -exts="tiff,tif" type=image/tiff \ -desc="TIFF Image" icon=internal-gopher-image - -exts="ras" type=image/x-cmu-raster \ -desc="CMU Raster Image" icon=internal-gopher-image - -exts="xbm" type=image/x-xbitmap \ -desc="X Bitmap" icon=internal-gopher-image -# note: have also seen "image/x-bitmap" - -exts="xpm" type=image/x-xpixmap \ -desc="X Pixmap" icon=internal-gopher-image -# note: have also seen "image/x-xpm" - -exts="xwd" type=image/x-xwindowdump \ -desc="X Window Dump Image" icon=internal-gopher-image -# note: have also seen "image/x-xwd" - -exts="pnm" type=image/x-portable-anymap \ -desc="PBM Image" icon=internal-gopher-image - -exts="pbm" type=image/x-portable-bitmap \ -desc="PBM Image" icon=internal-gopher-image - -exts="pgm" type=image/x-portable-graymap \ -desc="PGM Image" icon=internal-gopher-image - -exts="ppm" type=image/x-portable-pixmap \ -desc="PPM Image" icon=internal-gopher-image -# note: have also seen "image/x-pbm", "image/x-pgm", "image/x-ppm". - -exts="rgb" type=image/x-rgb \ -desc="RGB Image" icon=internal-gopher-image - -exts="bmp" type=image/x-MS-bmp \ -desc="Windows Bitmap" icon=internal-gopher-image - -exts="pcd" type=image/x-photo-cd \ -desc="PhotoCD Image" icon=internal-gopher-image - -exts="ief" type=image/ief \ -desc="" icon=internal-gopher-image -# What is "ief"? - -exts="fif" type=application/fractals \ -desc="Fractal Image Format" icon=internal-gopher-image - - -#################################################################### -# Audio -#################################################################### - -exts="au,snd" type=audio/basic \ -desc="ULAW Audio" icon=internal-gopher-sound - -exts="aif,aiff,aifc" type=audio/x-aiff \ -desc="AIFF Audio" icon=internal-gopher-sound - -exts="wav" type=audio/x-wav \ -desc="WAV Audio" icon=internal-gopher-sound - -exts="mp2,mpa,abs,mpega" type=audio/x-mpeg \ -desc="MPEG Audio" icon=internal-gopher-sound - -exts="ra,ram" type=audio/x-pn-realaudio \ -desc="RealAudio" icon=internal-gopher-sound - - -#################################################################### -# Video -#################################################################### - -exts="mpeg,mpg,mpe,mpv,vbs,mpegv" type=video/mpeg \ -desc="MPEG Video" icon=internal-gopher-movie - -exts="mpv2,mp2v" type=video/x-mpeg2 \ -desc="MPEG2 Video" icon=internal-gopher-movie - -exts="qt,mov,moov" type=video/quicktime \ -desc="Quicktime Video" icon=internal-gopher-movie - -exts="avi" type=video/x-msvideo \ -desc="Microsoft Video" icon=internal-gopher-movie - - -#################################################################### -# Archives -#################################################################### - -exts="hqx" type=application/mac-binhex40 \ -desc="Macintosh BinHex Archive" icon=internal-gopher-binary -# note: have also seen "application/x-macbinhex40" - -exts="sit" type=application/x-stuffit \ -desc="Macintosh StuffIt Archive" icon=internal-gopher-binary - -exts="zip" type=application/x-zip-compressed \ -desc="Zip Compressed Data" icon=internal-gopher-binary - -exts="shar" type=application/x-shar \ -desc="Unix Shell Archive" icon=internal-gopher-unknown - -exts="tar" type=application/x-tar \ -desc="Unix Tape Archive" icon=internal-gopher-binary - -exts="gtar" type=application/x-gtar \ -desc="GNU Tape Archive" icon=internal-gopher-binary - -exts="cpio" type=application/x-cpio \ -desc="Unix CPIO Archive" icon=internal-gopher-binary -# note: have also seen "application/x-sv4cpio" -# and "application/x-bcpio" for ".bcpio" files -- what's that? -# and "application/x-sv4crc" for ".sv4crc" -- what's that? - -exts="jar" type=application/java-archive \ -desc="Java Archive" icon=internal-gopher-binary - - -#################################################################### -# Programs -#################################################################### - -exts="exe,bin" type=application/octet-stream \ -desc="Binary Executable" icon=internal-gopher-binary - -exts="ai,eps,ps" type=application/postscript \ -desc="Postscript Document" icon=internal-gopher-text - -exts="csh" type=application/x-csh \ -desc="C Shell Program" icon=internal-gopher-unknown - -exts="sh" type=application/x-sh \ -desc="Bourne Shell Program" icon=internal-gopher-unknown - -exts="tcl" type=application/x-tcl \ -desc="TCL Program" icon=internal-gopher-unknown - -exts="pl" type=application/x-perl \ -desc="Perl Program" icon=internal-gopher-unknown - -exts="js,mocha" type=application/x-javascript \ -desc="JavaScript Program" icon=internal-gopher-unknown - -exts="pac" type=application/x-ns-proxy-autoconfig \ -desc="Proxy Auto-Config" icon=internal-gopher-unknown - -exts="jsc" type=application/x-javascript-config \ -desc="JavaScript Config" icon=internal-gopher-unknown - -exts="p7m,p7c" type=application/x-pkcs7-mime \ -desc="PKCS7 Encrypted Data" icon=internal-gopher-binary - -exts="p7s" type=application/x-pkcs7-signature \ -desc="PKCS7 Signature" icon=internal-gopher-binary - -exts="enc" type=application/pre-encrypted \ -desc="Pre-encrypted Data" icon=internal-gopher-binary - -exts="crl" type=application/x-pkcs7-crl \ -desc="Certificate Revocation List" icon=internal-gopher-binary - -exts="ckl" type=application/x-fortezza-ckl \ -desc="Compromised Key List" icon=internal-gopher-binary - -# This is too ambiguous an extension. Those losers. -#exts="src" type=application/x-wais-source \ -#desc="WAIS Source" icon=internal-gopher-unknown - -#################################################################### -# Encodings -#################################################################### - -exts="uu,uue" enc=x-uuencode \ -desc="UUEncoded Data" icon=internal-gopher-binary - -#################################################################### -# Documents -#################################################################### - -exts="doc,dot" type=application/msword \ -desc="Microsoft Word Document" icon=internal-gopher-text - -exts="xls,xlt,xlm,xld,xla,xlc,xlw,xll" type=application/vnd.ms-excel \ -desc="Microsoft Excel Worksheet" icon=internal-gopher-text - -exts="mdb,mda,mde" type=application/vnd.ms-access \ -desc="Microsoft Access Database" icon=internal-gopher-text - -exts="ppt,pot,ppa,pps,pwz" type=application/vnd.ms-powerpoint \ -desc="Microsoft PowerPoint Show" icon=internal-gopher-text - -exts="scd,sch,sc2" type=application/vnd.ms-schedule \ -desc="Microsoft Schedule+ Application" icon=internal-gopher-text - -exts="lwp,sam" type=application/vnd.lotus-wordpro \ -desc="Lotus WordPro Document" icon=internal-gopher-text - -exts="123,wk4,wk3,wk1" type=application/vnd.lotus-1-2-3 \ -desc="Lotus 123 Document" icon=internal-gopher-text - -exts="apr,vew" type=application/vnd.lotus-approach \ -desc="Lotus Approach Document" icon=internal-gopher-text - -exts="prz,pre" type=application/vnd.lotus-freelance \ -desc="Lotus Freelance Document" icon=internal-gopher-text - -exts="or3,or2,org" type=application/vnd.lotus-organizer \ -desc="Lotus Organizer Document" icon=internal-gopher-text - -exts="scm" type=application/vnd.lotus-screencam \ -desc="Lotus ScreenCam Movie" icon=internal-gopher-text - -exts="wpd,wp6" type=application/wordperfect5.1 \ -desc="WordPerfect Document" icon=internal-gopher-text - diff --git a/mozilla/network/mimetype/mime.types-nonunix b/mozilla/network/mimetype/mime.types-nonunix deleted file mode 100644 index 1fe4a200505..00000000000 --- a/mozilla/network/mimetype/mime.types-nonunix +++ /dev/null @@ -1,34 +0,0 @@ -#--Netscape Communications Corporation MIME Information -# Do not delete the above line. It is used to identify the file type. - -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -# This file defines all of the default file extensions recognised by Netscape -# on non-Unix platforms. See also mime.types and mime.types-unix. - -#################################################################### -# Archives -#################################################################### - -exts="Z" type=application/x-compress \ -desc="Compressed Data" icon=internal-gopher-binary - -exts="gz" enc=x-gzip \ -desc="GNU Zip Compressed Data" icon=internal-gopher-binary diff --git a/mozilla/network/mimetype/mime.types-unix b/mozilla/network/mimetype/mime.types-unix deleted file mode 100644 index aec12c281c5..00000000000 --- a/mozilla/network/mimetype/mime.types-unix +++ /dev/null @@ -1,60 +0,0 @@ -#--Netscape Communications Corporation MIME Information -# Do not delete the above line. It is used to identify the file type. - -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -# This file defines all of the default file extensions recognised by Netscape -# on Unix platforms. See also mime.types and mime.types-nonunix. - - -#################################################################### -# Text -#################################################################### - -exts="t,tr,roff" type=application/x-troff \ -desc="TROFF Document" icon=internal-gopher-text - -exts="me" type=application/x-troff-me \ -desc="TROFF Document" icon=internal-gopher-text - -exts="ms" type=application/x-troff-ms \ -desc="TROFF Document" icon=internal-gopher-text - -exts="man" type=application/x-troff-man \ -desc="Unix Manual Page" icon=internal-gopher-text - - -#################################################################### -# Video -#################################################################### - -exts="movie" type=video/x-sgi-movie \ -desc="SGI Video" icon=internal-gopher-movie - - -#################################################################### -# Encodings -#################################################################### - -exts="Z" enc=x-compress \ -desc="Compressed Data" icon=internal-gopher-binary - -exts="gz" enc=x-gzip \ -desc="GNU Zip Compressed Data" icon=internal-gopher-binary diff --git a/mozilla/network/mimetype/mkformat.c b/mozilla/network/mimetype/mkformat.c deleted file mode 100644 index f85a4c9df20..00000000000 --- a/mozilla/network/mimetype/mkformat.c +++ /dev/null @@ -1,1269 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * determine the format of a file - * - * Started with Rob's code and - * then hacked up by Lou. - */ - -#include "plstr.h" -#include "prmem.h" -#include "mkutils.h" -#include "mkformat.h" -#include "netutils.h" -#include "net_xp_file.h" - -static char *net_default_types [] = { -# include "ngtypes.h" - 0 }; - -/* func proto - */ -PRIVATE int cinfo_parse_mcc_line(char *line, Bool is_external, - Bool is_local, char **src_string); -PRIVATE int net_cinfo_merge(char *fn, Bool is_local); - -/* ----------------------------- Static data ------------------------------ */ - -/* The master database of content info (linked list) */ -PRIVATE XP_List * NET_ciMasterList=0; - -/* - * cinfo.c: Content Information for a file, i.e. its type, etc. - * - * See cinfo.h for full details. - * - * Rob McCool - */ - -/* init types loads standard types so that a config file - * is not required and can also read - * a mime types file if filename is passed in non empty and - * non null - * - * on each call to NET_InitFileFormatTypes the extension list - * will be completely free'd and rebuilt. - * - * if you pass in NULL filename pointers they will not be - * attempted to be read - */ -PUBLIC int -NET_InitFileFormatTypes(char * personal_file, char *global_file) -{ - /* init the data structures - */ - int i = 0; - -#ifdef XP_UNIX - NET_CleanupFileFormat(NULL); -#else /* !XP_UNIX */ - NET_CleanupFileFormat(); -#endif /* !XP_UNIX */ - NET_ciMasterList = XP_ListNew(); - - TRACEMSG((" Setting up File Format code")); - - while (net_default_types [i]) - { - char buf [256]; - char *src_string = 0; - PL_strcpy (buf, net_default_types [i]); - StrAllocCopy(src_string, buf); - cinfo_parse_mcc_line (buf, FALSE, FALSE, &src_string); /* destroys buf */ - i++; - if (src_string) PR_Free(src_string); - - } - - /* read the external mime types file and return */ - if(global_file) - { - net_cinfo_merge(global_file, FALSE); - } - if(personal_file) - { - net_cinfo_merge(personal_file, TRUE); - } - - return(0); -} - -/* -------------------------- Module structures --------------------------- */ - - - -static NET_cinfo default_cinfo_type = { -#ifdef MCC_PROXY - MAGNUS_INTERNAL_UNKNOWN, -#else - UNKNOWN_CONTENT_TYPE, -#endif - 0, - 0, - 0, - 0, - 0, - TRUE, - 0 -}; - -#ifdef NOT_USED -static NET_cinfo default_cinfo_enc = { - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0 -}; -#endif /* NOT_USED */ - -/* ------------------------------ _cinfo_free ------------------------------ */ - - -PRIVATE void -_cinfo_free(NET_cinfo *ci) -{ - - PR_FREEIF(ci->type); - PR_FREEIF(ci->encoding); - PR_FREEIF(ci->language); - PR_FREEIF(ci->desc); - PR_FREEIF(ci->icon); - PR_FREEIF(ci->alt_text); -} - - -/* ---------------------------- NET_cdataCreate ---------------------------- */ - - -PUBLIC NET_cdataStruct * -NET_cdataCreate(void) -{ - NET_cdataStruct *cd = PR_NEW(NET_cdataStruct); - - if(!cd) - return(NULL); - - memset(cd, 0, sizeof(NET_cdataStruct)); - - return cd; -} - - -/* ----------------------------- NET_cdataFree ---------------------------- */ - - -PUBLIC void -NET_cdataFree(NET_cdataStruct *cd) -{ - register int x; - - if(cd->exts) - { - for(x = 0; x < cd->num_exts; x++) - PR_Free(cd->exts[x]); - PR_Free(cd->exts); - } - if ( cd->src_string ) - PR_Free(cd->src_string); - - _cinfo_free(&cd->ci); - - PR_Free(cd); - cd = 0; -} - -/* ---------------------------- NET_cdataAdd ------------------------------- */ - -PUBLIC void -NET_cdataAdd(NET_cdataStruct *cd) -{ - XP_ListAddObject(NET_ciMasterList, cd); -} - -/* ---------------------------- NET_cdataRemove ---------------------------- */ - -PUBLIC void -NET_cdataRemove(NET_cdataStruct *cd) -{ - XP_ListRemoveObject(NET_ciMasterList, cd); - - NET_cdataFree(cd); -} - -PUBLIC NET_cdataStruct* -NET_cdataExist(NET_cdataStruct *old_cd ) -{ - NET_cdataStruct *found_cd = NULL; - NET_cdataStruct *cd = NULL; - XP_List *infoList; - - infoList = cinfo_MasterListPointer(); - - if ( !infoList ) - return found_cd; - - while ((cd= (NET_cdataStruct *)XP_ListNextObject(infoList)) != NULL) - { - if ( old_cd->ci.type && - cd->ci.type && - !PL_strcasecmp(old_cd->ci.type, cd->ci.type)) - { - /* found matching type */ - found_cd = cd; - break; - } - else if ( !old_cd->ci.type && - old_cd->ci.encoding && - cd->ci.encoding && - !PL_strcasecmp(old_cd->ci.encoding, cd->ci.encoding)) - { - /* found matching encoding */ - found_cd = cd; - break; - } - } - return found_cd; -} - -#if 0 -PRIVATE -Bool -net_cdata_exist_ext( char *ext, NET_cdataStruct *cd ) -{ - Bool not_found = FALSE; - int n; - - if (!cd->exts) return not_found; - - for ( n = 0; n < cd->num_exts; n++ ) - { - if (!PL_strcasecmp(cd->exts[n], ext) ) - { - not_found = TRUE; - break; - } - } - return not_found; -} -#endif - -/* ---------------------------- net_cdata_new_ext ----------------------------- */ - - -PRIVATE -void -net_cdata_new_ext(char *ext, NET_cdataStruct *cd) -{ - int n = cd->num_exts; - - cd->exts = (char **) (n ? PR_Realloc(cd->exts, (n+1)*sizeof(char *)) - : PR_Malloc(sizeof(char *))); - - if(!cd->exts) - return; - - cd->exts[n] = 0; - StrAllocCopy(cd->exts[n], ext); - cd->num_exts = ++n; -} - - -/* ----------------------------- cinfo_merge ------------------------------ */ - - -int _cinfo_parse_mimetypes(XP_File fp, char *t, Bool is_local); -int _cinfo_parse_mcc(XP_File fp, char *t, Bool is_local); - -PRIVATE int -net_cinfo_merge(char *fn, Bool is_local) -{ - XP_File fp; - char t[CINFO_MAX_LEN]; - int ret; - - TRACEMSG(("\n\nnet_cinfo_merge: called with %s\n\n\n", fn)); - if(!(fp = NET_XP_FileOpen(fn ? fn : "mime.types", xpMimeTypes, XP_FILE_READ))) { - TRACEMSG(("cinfo.c: File open failed")); - return -1; - } - - TRACEMSG(("Reading mime.types file")); - - if(!(NET_XP_FileReadLine(t, CINFO_MAX_LEN, fp))) { - TRACEMSG(("cinfo.c: Mime types file is empty")); - return -1; - - } else if(!strncmp(t, MCC_MT_MAGIC, MCC_MT_MAGIC_LEN) || - !strncmp(t, NCC_MT_MAGIC, NCC_MT_MAGIC_LEN)) { - /* Look for magic number */ - TRACEMSG(("Loading MCC mime types file")); - ret = _cinfo_parse_mcc(fp, t, is_local); - - } else { - TRACEMSG(("Loading old NCSA mime types file")); - ret = _cinfo_parse_mimetypes(fp, t, is_local); - } - - NET_XP_FileClose(fp); - return ret; -} - - -static NET_cinfo * -net_cinfo_find_type_or_encoding (char *uri, XP_Bool type_p) -{ - char *start = uri; - char *end, *c; - NET_cinfo *result = &default_cinfo_type; - XP_Bool saw_encoding = FALSE; - - c = PL_strrchr (uri, '/'); - if (c) start = c; - - end = start + PL_strlen (start); - c = PL_strrchr (start, '?'); - if (c) end = c; - c = PL_strrchr (start, '#'); - if (c && c < end) end = c; - -AGAIN: - for (c = end - 1; c >= uri; c--) - if (*c == '/' || *c == '.') - break; - - if (c >= uri && *c == '.') - { - int32 i; - XP_List *list_ptr = NET_ciMasterList; - NET_cdataStruct *cdata; - uint32 ext_len; - start = c + 1; - ext_len = end - start; - while ((cdata = (NET_cdataStruct *) XP_ListNextObject (list_ptr)) != NULL) - for (i = cdata->num_exts - 1; i >= 0; i--) - if (PL_strlen (cdata->exts[i]) == ext_len && - !PL_strncasecmp (start, cdata->exts [i], ext_len)) - { - if (type_p && cdata->ci.type) - { - /* We are looking for a type, and this extension represents - one. Since this is the last one in the path (since we - start from the end and go backwards) we're done now. - */ - return &cdata->ci; - } - else if (type_p && cdata->ci.encoding) - { - /* We are looking for a type, and this extension represents - an encoding. Skip over it and look for the next - extension earlier in the file name (as that may turn out - to be a type which we should take instead.) - - But, if this is the second encoding we've seen, then the - final content-type is irrelevant, because we have no - mechanism for decoding multiple encodings. So, while - "foo.gif.gz" gets type gif, encoding gz, "foo.tar.gz.uu" - gets type unknown, encoding uu. This is especially - important for the types that we put on outgoing MIME - attachments. - */ - if (saw_encoding) - return &default_cinfo_type; - saw_encoding = TRUE; - end = start - 1; - goto AGAIN; - } - else if (cdata->ci.type) - { - PR_ASSERT (!type_p); - /* We are looking for an encoding, and this extension - represents a content-type. That means that there are - no encodings after the type in this file name, and - therefore it has no encoding (an encoding which occurs - before a type doesn't count: "foo.uu.gif" should be of - type gif with no encoding, not encoding uu. Also, - "foo.uu.unknown" should be of an unknown type with no - encoding; and "foo.uu.gif.Z" should be type gif, - encoding compress.) - */ - return &default_cinfo_type; - } - else if (cdata->ci.encoding) - { - PR_ASSERT (!type_p); - /* We are looking for an encoding, and this extension - represents one. It is the last one in the file name, - so now we're done. ("foo.gz.uu" gets encoding "uu" - instead of "gz".) - */ - return &cdata->ci; - } - /* Else, this cdata is junk, or something... Skip it. */ - } - } - - return (result); -} - - -PUBLIC NET_cinfo * -NET_cinfo_find_type (char *uri) -{ - return net_cinfo_find_type_or_encoding (uri, TRUE); -} - -PUBLIC NET_cinfo * -NET_cinfo_find_enc (char *uri) -{ - return net_cinfo_find_type_or_encoding (uri, FALSE); -} - - -#if defined(DEBUG) && defined(XP_UNIX) -void -print_mime_types() -{ - int32 i; - XP_List *list_ptr = NET_ciMasterList; - NET_cdataStruct *cdata; - - fprintf(stderr, "\n---------\n"); - - while ((cdata = (NET_cdataStruct *) XP_ListNextObject (list_ptr))) - { - fprintf (stderr, "%s%s%s (%s; %s):", - (cdata->ci.type ? cdata->ci.type : ""), - (cdata->ci.type && *cdata->ci.type && - cdata->ci.encoding && *cdata->ci.encoding - ? "+" : ""), - (cdata->ci.encoding ? cdata->ci.encoding : ""), - (cdata->ci.desc ? cdata->ci.desc : "no desc"), - (cdata->ci.icon ? cdata->ci.icon : "no icon")); - - for (i = cdata->num_exts - 1; i >= 0; i--) - fprintf (stderr, " %s", cdata->exts[i]); - fprintf (stderr, "\n"); - } -} -#endif /* DEBUG && XP_UNIX */ - - -/* return a cdataStruct from a mime_type - */ -PRIVATE NET_cdataStruct * -NET_cinfo_find_cdata_by_type(char *mime_type) -{ - NET_cdataStruct *cdata; - XP_List * list_ptr; - - if(!mime_type) - return(NULL); - - list_ptr = NET_ciMasterList; - while((cdata = (NET_cdataStruct *) XP_ListNextObject(list_ptr)) != NULL) - { - if(cdata->ci.type && !PL_strcasecmp(mime_type, cdata->ci.type)) - return(cdata); - } - - return(NULL); -} - -/* return a cinfo from a mime_type - */ -PUBLIC NET_cinfo * -NET_cinfo_find_info_by_type(char *mime_type) -{ - NET_cdataStruct *cdata = NET_cinfo_find_cdata_by_type(mime_type); - - if(cdata) - return(&cdata->ci); - else - return(NULL); -} - - -/* --------------------------- cinfo_find_ext ------------------------------ */ - -/* returns an extension (without the ".") for - * a given mime type. - * - * If no match is found NULL is returned. - * - * Do not free the returned char * - */ -PUBLIC char * -NET_cinfo_find_ext(char *mime_type) -{ - NET_cdataStruct *cdata = NET_cinfo_find_cdata_by_type(mime_type); - - if(cdata) - return(cdata->exts[0]); - else - return(NULL); -} - - -/* ----------------------------- File parsers ----------------------------- */ - - -#if 0 -static void -net_build_string(char** curr_str, char *new_str) -{ - int len; - - if ( new_str && *new_str ) - { - if (!*curr_str ) - { - len = strlen(new_str); - *curr_str = (char *)PR_Malloc((len+1)*sizeof(char)); - sprintf(*curr_str, "%s", new_str); - } - else - { - len = strlen(new_str) + strlen(*curr_str); - *curr_str = (char *)PR_Malloc((len+1)*sizeof(char)); - sprintf(*curr_str, "%s%s", *curr_str, new_str); - } - } -} -#endif /* 0 */ - -/* Parse old NCSA mime.types files */ - -int -_cinfo_parse_mimetypes(XP_File fp, char *t, Bool is_local) -{ - char *ext, *end; - NET_cdataStruct *cd; - char *src_string = 0; - - /* t is already filled. */ - while(1) { - - if ( src_string ) - { - src_string = XP_AppendStr(src_string, t); - } - else - { - StrAllocCopy(src_string, t); - } - - while((*t) && (NET_IS_SPACE(*t))) - ++t; - - if(*t && (*t != '#')) { - ext = t; - while((*ext) && (!NET_IS_SPACE(*ext))) ++ext; - if((*ext)) - *ext++ = '\0'; - - cd = NULL; - - while((*ext)) { - while((*ext) && (NET_IS_SPACE(*ext))) ++ext; - - if((*ext)) { - if(!cd) { - cd = NET_cdataCreate(); - if(!cd) - return(-1); - } - - cd->is_local = is_local; - cd->is_external = FALSE; /* don't count these as external types */ - - cd->is_modified = FALSE; /* default is not modified in any way */ - end = ext+1; - while((*end) && (!NET_IS_SPACE(*end))) ++end; - if(*end) - *end++ = '\0'; - net_cdata_new_ext(ext, cd); - ext = end; - } - } - if(cd) { - NET_cdataStruct *old_cd = NULL; - PR_FREEIF(cd->ci.type); - cd->ci.type = 0; - StrAllocCopy(cd->ci.type, t); - PR_FREEIF(cd->src_string); - StrAllocCopy(cd->src_string, src_string); - - if ( (old_cd = NET_cdataExist(cd)) != NULL) - /* Found an old one, remove it first */ - { - /* Extra hack: if the old one defined an icon, or a desc, - and the new one does not, carry those over. */ - char *icon = (old_cd->ci.icon && !cd->ci.icon - ? PL_strdup(old_cd->ci.icon) - : 0); - char *desc = (old_cd->ci.desc && !cd->ci.desc - ? PL_strdup(old_cd->ci.desc) - : 0); - - NET_cdataRemove(old_cd); - old_cd = 0; - - if (icon) cd->ci.icon = icon; - if (desc) cd->ci.desc = desc; - } - /* Not an existing type, we add a new one */ - NET_cdataAdd(cd); - PR_Free(src_string); - src_string = 0; - } - } - if(!(NET_XP_FileReadLine(t, CINFO_MAX_LEN, fp))) - break; - } - return 0; -} - - -PUBLIC int -cinfo_parse_mcc_line(char *line, Bool is_external, Bool is_local, - char **src_string) -{ - int ln = 1; - char *t, *u, *v, *name, *value, c; - NET_cdataStruct *cd; - - if(line && *line) - { - cd = NULL; - - t = line; - - if((*t) && (*t != '#')) { - while(1) { - - while(*t && NET_IS_SPACE(*t)) ++t; - if(!(*t)) - break; - name = t; - - while(*t && (*t != '=')) ++t; - if(!(*t)) { - TRACEMSG(("line %d: name without =", ln)); - if(cd) - NET_cdataFree(cd); - return (-1); - } - for(u = t - 1; NET_IS_SPACE(*u); --u) - ; - *(u+1) = '\0'; /* terminate name */ - ++t; - while(*t && (*t != '\"') && (NET_IS_SPACE(*t))) ++t; - if(!(*t)) { - TRACEMSG(("line %d: empty value", ln)); - if(cd) - NET_cdataFree(cd); - return (-1); - } - if(*t == '\"') { - value = ++t; - while(*t && (*t != '\"')) ++t; - if(!(*t)) { - TRACEMSG(("line %d: missing closing quotes", ln)); - if(cd) - NET_cdataFree(cd); - return (-1); - } - } - else { - value = t; - while(*t && (!NET_IS_SPACE(*t))) ++t; - /* null t is okay */ - } - if(*t) *t++ = '\0'; - if(!cd) { - cd = NET_cdataCreate(); - if(!cd) - return(0); - - cd->is_external = is_external; - cd->is_modified = FALSE; /* default is "not modified yet!*/ - cd->is_local = is_local; - PR_FREEIF(cd->src_string); - cd->src_string = *src_string; - *src_string = 0; - } - - if(!PL_strcasecmp(name, "type")) { - PR_FREEIF(cd->ci.type); - cd->ci.type = 0; - StrAllocCopy(cd->ci.type, value); - - } else if(!PL_strcasecmp(name, "enc")) { - PR_FREEIF(cd->ci.encoding); - cd->ci.encoding = 0; - StrAllocCopy(cd->ci.encoding, value); - - } else if(!PL_strcasecmp(name, "lang")) { - PR_FREEIF(cd->ci.language); - cd->ci.language = 0; - StrAllocCopy(cd->ci.language, value); - - } else if(!PL_strcasecmp(name, "desc")) { - PR_FREEIF(cd->ci.desc); - cd->ci.desc = 0; - StrAllocCopy(cd->ci.desc, value); - - } else if(!PL_strcasecmp(name, "alt")) { - PR_FREEIF(cd->ci.alt_text); - cd->ci.alt_text = 0; - StrAllocCopy(cd->ci.alt_text, value); - - } else if(!PL_strcasecmp(name, "icon")) { - PR_FREEIF(cd->ci.icon); - cd->ci.icon = 0; - StrAllocCopy(cd->ci.icon, value); - - } else if(!PL_strcasecmp(name, "exts")) { - u = value; - while(1) { - v = u; - while(*u && (*u != ',')) ++u; - c = *u; - *u = '\0'; - net_cdata_new_ext(v, cd); - if(c) - ++u; - else - break; - } - } - } - - /* Some people like to be clever and use mime.types entries - like "type=application/x-tar enc=x-gzip exts=tgz", - but unfortunately, that doesn't even come close to working, - and will override (delete) the existing tar entry, causing - disaster of various forms. - - So, if this line defines *both* "type" and "enc", just throw - it away. - */ - if (cd && - cd->ci.type && *cd->ci.type && - cd->ci.encoding && *cd->ci.encoding) - { - NET_cdataFree(cd); - cd = 0; - } - - if(cd) - { - NET_cdataStruct *old_cd = NULL; - - if ((old_cd = NET_cdataExist(cd)) != NULL) - /* Found an old one, remove it first */ - { - /* Extra hack: if the old one defined an icon, or a desc, - and the new one does not, carry those over. */ - char *icon = (old_cd->ci.icon && !cd->ci.icon - ? PL_strdup(old_cd->ci.icon) - : 0); - char *desc = (old_cd->ci.desc && !cd->ci.desc - ? PL_strdup(old_cd->ci.desc) - : 0); - - NET_cdataRemove(old_cd); - old_cd = 0; - - if (icon) cd->ci.icon = icon; - if (desc) cd->ci.desc = desc; - } - NET_cdataAdd(cd); - } - } - - ln++; - } - return 0; /* #### what should return value be? */ -} - - -/* Parse sexy new MCC mime types files */ -int -_cinfo_parse_mcc(XP_File fp, char *line, Bool is_local) -{ - char *end; - char *src_string = 0; - - TRACEMSG(("mime.types file is MCC type")); - - /* t is already filled. */ - - if ( !src_string ) - StrAllocCopy(src_string, line); - else - { - src_string = XP_AppendStr(src_string, line); - } - while(1) { - cinfo_parse_mcc_line(line, TRUE, is_local, &src_string); - - if(!(NET_XP_FileReadLine(line, CINFO_MAX_LEN, fp))) - break; - - if ( !src_string ) - StrAllocCopy(src_string, line); - else - { - src_string = XP_AppendStr(src_string, line); - } - /* assemble extended lines - */ - end = &line[PL_strlen(line)-1]; - while (end > line && (*end == CR || *end == LF)) - end--; - while(*end == '\\') - { - *end = ' '; - end++; - - if(!(NET_XP_FileReadLine(end, CINFO_MAX_LEN-(end-line), fp))) - break; - - if ( !src_string ) - StrAllocCopy(src_string, end); - else - src_string = XP_AppendStr(src_string, end); - - - end = &end[PL_strlen(end)-1]; - while (end > line && (*end == CR || *end == LF)) - end--; - - if((end-line)+2 >= CINFO_MAX_LEN) - break; - } - } - - return 0; -} - -/* return the master cdata List pointer - */ -PUBLIC XP_List * -cinfo_MasterListPointer() -{ - return(NET_ciMasterList); -} - -/* fills in cdata structure - * - * if cdata for a given type do not exist, create a new one - */ -PUBLIC void -NET_cdataCommit(char * mimeType, char * cdataString) -{ - XP_List * extensionList; - NET_cdataStruct * matchInfo = NULL; - int listSize; - int i; - - extensionList = cinfo_MasterListPointer(); - if (!extensionList) - { - NET_ciMasterList = XP_ListNew(); - extensionList = cinfo_MasterListPointer(); /* Lou help me out here, - create the list and - matchInfo */ - } - if (!extensionList) - return; - - listSize = XP_ListCount(extensionList); - for (i = 1; i<=listSize; i++) - { - NET_cdataStruct * cinfo = - (NET_cdataStruct *)XP_ListGetObjectNum(extensionList, i); - if (cinfo && - cinfo->ci.type && - (PL_strcasecmp(mimeType, cinfo->ci.type) == 0)) - { - int j; - matchInfo = cinfo; - for ( j= 0; j< matchInfo->num_exts; j++) /* Free 'em all */ - PR_Free((char*)matchInfo->exts[j]); - PR_Free(matchInfo->exts); - matchInfo->exts = NULL; - break; - } - } - - if (matchInfo == NULL) - { - matchInfo = NET_cdataCreate(); - if (matchInfo == NULL) - { - return; - } - else - { - PR_FREEIF(matchInfo->ci.type); - matchInfo->ci.type = 0; - StrAllocCopy(matchInfo->ci.type, mimeType); - } - NET_cdataAdd(matchInfo); - - } - /* Found the right type */ - { - char newExtension[30]; /* extension limit is 30 chars */ - char * citer; - int newExIndex = 0; - memset(newExtension, 0, sizeof(newExtension)); - citer = cdataString; - - matchInfo->num_exts = 0; - matchInfo->exts = (char**)PR_Malloc(10); - - if (matchInfo->exts == NULL) - return; - while (*citer != 0) /* Parse the string. Skip all non-c*/ - { - if (isalnum(*citer) && (newExIndex < 29)) /* NET_IS_ALPHA(*citer) */ - newExtension[newExIndex++] = *citer; - else if (PL_strlen(newExtension) > 0) - { - char * newString = NULL; - newExtension[newExIndex] = 0; - StrAllocCopy(newString, newExtension); - matchInfo->num_exts++; - matchInfo->exts = - (char**)PR_Realloc(matchInfo->exts, - matchInfo->num_exts * sizeof(void*)); - matchInfo->exts[matchInfo->num_exts-1] = newString; - newExIndex = 0; - newExtension[0] = 0; - } - citer++; - } - /* commit the last extension, if there was one */ - if (PL_strlen(newExtension) > 0) - { - char * newString = NULL; - newExtension[newExIndex] = 0; - StrAllocCopy(newString, newExtension); - matchInfo->num_exts++; - matchInfo->exts = - (char**)PR_Realloc(matchInfo->exts, - matchInfo->num_exts * sizeof(void*)); - matchInfo->exts[matchInfo->num_exts-1] = newString; - } - } -} - - -PUBLIC XP_Bool -NET_IsOldMimeTypes (XP_List *masterList) -{ - NET_cdataStruct *cd; - - while((cd = XP_ListNextObject(masterList)) != NULL) - { - if ( cd->is_local && !cd->is_external ) - { /* This means that this is a old mime types */ - return TRUE; - } - } - return FALSE; -} - -#ifndef XP_UNIX -static void -net_Real_CleanupFileFormat(char *filename, Bool file_not_open) -{ - NET_cdataStruct * cdata; - XP_File fp = 0; - int len = 0; - XP_Bool failed = FALSE; - char buffer[512]; - int i; - - if(!NET_ciMasterList) - return; - - /* Need to remove from the end so that the next time - around, the file will be loaded up into a list in - the consistent way */ - while(!failed && ((cdata = (NET_cdataStruct *)XP_ListRemoveEndObject(NET_ciMasterList)) != NULL)) - { - - if(file_not_open && - (cdata->is_external|| cdata->is_modified)) - { - /* open file - * if it doesn't open we won't try again - */ - fp = NET_XP_FileOpen(filename? filename : "mime.types", - xpMimeTypes, XP_FILE_WRITE); - TRACEMSG(("Writing mime types file...")); - file_not_open = FALSE; - - if(fp) - { - PR_snprintf(buffer, sizeof(buffer), "#\ ---Netscape Communications Corporation MIME Information\n#\ -Do not delete the above line. It is used to identify the file type.\n#\n"); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - } - - /* Save out the modfied entries as well */ - /* cdata might be modified in FE */ - - if((cdata->is_external||cdata->is_modified) && fp) - { - if(!failed && cdata->ci.type) - { - PR_snprintf(buffer, sizeof(buffer), "type=%.500s ", - cdata->ci.type); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - if(!failed && cdata->ci.encoding) - { - PR_snprintf(buffer, sizeof(buffer), "enc=%.500s ", - cdata->ci.encoding); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - if(!failed && (cdata->num_exts > 0)) - { - PR_snprintf(buffer, sizeof(buffer), "exts=%.500s", - cdata->exts[0]); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - - for(i=1; !failed, i<cdata->num_exts; i++) - { - PR_snprintf(buffer, sizeof(buffer), ",%.500s", - cdata->exts[i]); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - PR_snprintf(buffer, sizeof(buffer), " "); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - if(!failed && cdata->ci.icon) - { - PR_snprintf(buffer, sizeof(buffer), "icon=\"%.500s\" ", - cdata->ci.icon); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - if(!failed && cdata->ci.desc) - { - PR_snprintf(buffer, sizeof(buffer), "desc=\"%.500s\" ", - cdata->ci.desc); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - if(!failed && cdata->ci.alt_text) - { - PR_snprintf(buffer, sizeof(buffer), "alt=\"%.500s\" ", - cdata->ci.alt_text); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - PR_snprintf(buffer, sizeof(buffer), "%c", LF); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - - /* free the data - */ - NET_cdataFree(cdata); - } - - XP_ListDestroy(NET_ciMasterList); - NET_ciMasterList = 0; - - if(!file_not_open && fp) - NET_XP_FileClose(fp); - /* This function should really return a return code, and handle any errors */ - -} -#endif /* XP_UNIX */ - -#ifdef XP_UNIX -PUBLIC void -NET_CleanupFileFormat(char *filename) -{ - NET_cdataStruct *cdata; - XP_File fp = 0; - int len = 0; - XP_Bool failed = FALSE; - Bool file_open = FALSE; - XP_List *modifiedList = NULL; - char buffer[512]; - Bool first = TRUE; - - if ( !NET_ciMasterList ) return; - - if ( filename ) - { - fp = NET_XP_FileOpen(filename, xpMimeTypes, XP_FILE_WRITE); - /* Need to remove from the end so that the next time - around, the file will be loaded up into a list in - the consistent way */ - - if ( fp ) - { - file_open = TRUE; - modifiedList = XP_ListNew(); - while((cdata = (NET_cdataStruct *) XP_ListRemoveEndObject(NET_ciMasterList))) - { - if ( cdata->is_local ) - { - if ( first && !NET_IsOldMimeTypes(NET_ciMasterList) ) - { - first = FALSE; - if (cdata->src_string && *cdata->src_string && - strncmp(cdata->src_string, MCC_MT_MAGIC, - MCC_MT_MAGIC_LEN) && - strncmp(cdata->src_string, NCC_MT_MAGIC, - NCC_MT_MAGIC_LEN)) - { - /* Write out standard new mime type header info */ - PR_snprintf(buffer, sizeof(buffer), - "#\ ---Netscape Communications Corporation MIME Information\n#\ -Do not delete the above line. It is used to identify the file type.\n#\n"); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - } - } - if (!failed && cdata->src_string && *cdata->src_string ) - { - len = NET_XP_FileWrite(cdata->src_string, - strlen(cdata->src_string), fp); - - if (cdata->src_string[strlen(cdata->src_string)-1] != '\n') - len = NET_XP_FileWrite("\n", strlen("\n"), fp); - } - NET_cdataFree(cdata); - - } - else if ( cdata->is_modified ) - XP_ListAddObject(modifiedList, cdata); - else - NET_cdataFree(cdata); - - } - - while (!failed && (cdata = (NET_cdataStruct *) XP_ListRemoveEndObject(modifiedList))) - { - - if ( first && !NET_IsOldMimeTypes(NET_ciMasterList) ) - { - first = FALSE; - if (cdata->src_string && *cdata->src_string && - strncmp(cdata->src_string, MCC_MT_MAGIC, - MCC_MT_MAGIC_LEN) && - strncmp(cdata->src_string, NCC_MT_MAGIC, - NCC_MT_MAGIC_LEN)) - { - /* Write out standard new mime type header info */ - PR_snprintf(buffer, sizeof(buffer), - "#\ ---Netscape Communications Corporation MIME Information\n#\ -Do not delete the above line. It is used to identify the file type.\n#\n"); - len = NET_XP_FileWrite(buffer, strlen(buffer), fp); - if (len != (int) strlen(buffer)) - failed = TRUE; - - } - } - - if (!failed && cdata->src_string && *cdata->src_string ) - { - len = NET_XP_FileWrite(cdata->src_string, - strlen(cdata->src_string), fp); - if (len != (int) strlen(cdata->src_string)) - failed = TRUE; - if ( cdata->src_string[strlen(cdata->src_string)-1] != '\n') - { - len = NET_XP_FileWrite("\n", strlen("\n"), fp); - if (len != (int) strlen("\n")) - failed = TRUE; - } - } - - NET_cdataFree(cdata); - } - NET_XP_FileClose(fp); - } - } - else /* Clean up each node before deleting the root node */ - { - while((cdata = (NET_cdataStruct *) XP_ListRemoveEndObject(NET_ciMasterList))) - NET_cdataFree(cdata); - } - XP_ListDestroy(NET_ciMasterList); - NET_ciMasterList = 0; - /* This function should really return an error code and deal with any errors when they happen */ -} - -#else /* !XP_UNIX */ - -PUBLIC void -NET_CleanupFileFormat() -{ - Bool file_not_open=TRUE; - net_Real_CleanupFileFormat(NULL, file_not_open); -} - -#endif /* !XP_UNIX */ diff --git a/mozilla/network/mimetype/mkformat.h b/mozilla/network/mimetype/mkformat.h deleted file mode 100644 index b542a3e038a..00000000000 --- a/mozilla/network/mimetype/mkformat.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * cinfo.h: Content Information for a file, i.e. its type, etc. - * - * See cinfo.c for dependency information. - * - * Rob McCool - */ - -#ifndef MKFORMAT_H -#define MKFORMAT_H - -/* ------------------------------ Constants ------------------------------- */ - - -/* - * This will be the first string in the file, followed by x.x version - * where x is an integer. - * - * If this magic string is not found, cinfo_merge will try to parse - * the file as a NCSA httpd mime.types file. - */ - -#define MCC_MT_MAGIC "#--MCOM MIME Information" -#define MCC_MT_MAGIC_LEN 24 - -#define NCC_MT_MAGIC "#--Netscape Communications Corporation MIME Information" -#define NCC_MT_MAGIC_LEN 40 /* Don't bother to check it all */ - -/* The character which separates extensions with cinfo_find */ - -#define CINFO_SEPARATOR '.' - -/* The maximum length of a line in this file */ - -#define CINFO_MAX_LEN 1024 - -/* The hash function for the database. Hashed on extension. */ -#include <ctype.h> -#define CINFO_HASH(s) (isalpha(s[0]) ? tolower(s[0]) - 'a' : 26) - -/* The hash table size for that function */ -#define CINFO_HASHSIZE 27 - - -/* ------------------------------ Structures ------------------------------ */ - -/* see ../include/net.h for the NET_cinfo struct */ - -/* ------------------------------ Prototypes ------------------------------ */ - -/* - * cinfo_find finds any content information for the given uri. The file name - * is the string following the last / in the uri. Multiple extensions are - * separated by CINFO_SEPARATOR. You may pass in a filename instead of uri. - * - * Returns a newly allocated cinfo structure with the information it - * finds. The elements of this structure are coming right out of the types - * database and so if you change it or want to keep it around for long you - * should strdup it. You should free only the structure itself when finished - * with it. - * - * If there is no information for any one of the extensions it - * finds, it will ignore that extension. If it cannot find information for - * any of the extensions, it will return NULL. - */ -extern NET_cinfo *NET_cinfo_find(char *uri); -extern NET_cinfo *NET_cinfo_find_type(char *uri); -extern NET_cinfo *NET_cinfo_find_enc (char *uri); - - -/* - * cinfo_lookup finds the information about the given content-type, and - * returns a cinfo structure so you can look up description and icon. - */ -NET_cinfo *NET_cinfo_lookup(char *type); - -#endif /* MKFORMAT_H */ diff --git a/mozilla/network/mimetype/mktypes.h b/mozilla/network/mimetype/mktypes.h deleted file mode 100644 index 4787d52320b..00000000000 --- a/mozilla/network/mimetype/mktypes.h +++ /dev/null @@ -1,166 +0,0 @@ -/* Generated file - do not edit! */ - -"exts=\"txt,text\" type=text/plain \ -desc=\"Plain Text\" icon=internal-gopher-text", -"exts=\"html,htm\" type=text/html \ -desc=\"Hypertext Markup Language\" icon=internal-gopher-text", -"exts=\"xml\" type=text/xml \ -desc=\"Extensible Markup Language\" icon=internal-gopher-text", -"exts=\"rtf\" type=application/rtf \ -desc=\"Rich Text Format\" icon=internal-gopher-text", -"exts=\"pdf\" type=application/pdf \ -desc=\"Portable Document Format\" icon=internal-gopher-text", -"exts=\"tex\" type=application/x-tex \ -desc=\"TeX Document\" icon=internal-gopher-text", -"exts=\"latex\" type=application/x-latex \ -desc=\"LaTeX Document\" icon=internal-gopher-text", -"exts=\"dvi\" type=application/x-dvi \ -desc=\"TeX DVI Data\" icon=internal-gopher-text", -"exts=\"texi,texinfo\" type=application/x-texinfo \ -desc=\"GNU TeXinfo Document\" icon=internal-gopher-text", -"exts=\"vcf\" type=text/x-vcard \ -desc=\"VCard\" icon=internal-gopher-unknown", -"exts=\"gif\" type=image/gif \ -desc=\"GIF Image\" icon=internal-gopher-image", -"exts=\"jpeg,jpg,jpe,jfif,pjpeg,pjp\" type=image/jpeg \ -desc=\"JPEG Image\" icon=internal-gopher-image", -"exts=\"png\" type=image/png \ -desc=\"PNG Image\" icon=internal-gopher-image", -"exts=\"tiff,tif\" type=image/tiff \ -desc=\"TIFF Image\" icon=internal-gopher-image", -"exts=\"ras\" type=image/x-cmu-raster \ -desc=\"CMU Raster Image\" icon=internal-gopher-image", -"exts=\"xbm\" type=image/x-xbitmap \ -desc=\"X Bitmap\" icon=internal-gopher-image", -"exts=\"xpm\" type=image/x-xpixmap \ -desc=\"X Pixmap\" icon=internal-gopher-image", -"exts=\"xwd\" type=image/x-xwindowdump \ -desc=\"X Window Dump Image\" icon=internal-gopher-image", -"exts=\"pnm\" type=image/x-portable-anymap \ -desc=\"PBM Image\" icon=internal-gopher-image", -"exts=\"pbm\" type=image/x-portable-bitmap \ -desc=\"PBM Image\" icon=internal-gopher-image", -"exts=\"pgm\" type=image/x-portable-graymap \ -desc=\"PGM Image\" icon=internal-gopher-image", -"exts=\"ppm\" type=image/x-portable-pixmap \ -desc=\"PPM Image\" icon=internal-gopher-image", -"exts=\"rgb\" type=image/x-rgb \ -desc=\"RGB Image\" icon=internal-gopher-image", -"exts=\"bmp\" type=image/x-MS-bmp \ -desc=\"Windows Bitmap\" icon=internal-gopher-image", -"exts=\"pcd\" type=image/x-photo-cd \ -desc=\"PhotoCD Image\" icon=internal-gopher-image", -"exts=\"ief\" type=image/ief \ -desc=\"\" icon=internal-gopher-image", -"exts=\"fif\" type=application/fractals \ -desc=\"Fractal Image Format\" icon=internal-gopher-image", -"exts=\"au,snd\" type=audio/basic \ -desc=\"ULAW Audio\" icon=internal-gopher-sound", -"exts=\"aif,aiff,aifc\" type=audio/x-aiff \ -desc=\"AIFF Audio\" icon=internal-gopher-sound", -"exts=\"wav\" type=audio/x-wav \ -desc=\"WAV Audio\" icon=internal-gopher-sound", -"exts=\"mp2,mpa,abs,mpega\" type=audio/x-mpeg \ -desc=\"MPEG Audio\" icon=internal-gopher-sound", -"exts=\"ra,ram\" type=audio/x-pn-realaudio \ -desc=\"RealAudio\" icon=internal-gopher-sound", -"exts=\"mpeg,mpg,mpe,mpv,vbs,mpegv\" type=video/mpeg \ -desc=\"MPEG Video\" icon=internal-gopher-movie", -"exts=\"mpv2,mp2v\" type=video/x-mpeg2 \ -desc=\"MPEG2 Video\" icon=internal-gopher-movie", -"exts=\"qt,mov,moov\" type=video/quicktime \ -desc=\"Quicktime Video\" icon=internal-gopher-movie", -"exts=\"avi\" type=video/x-msvideo \ -desc=\"Microsoft Video\" icon=internal-gopher-movie", -"exts=\"hqx\" type=application/mac-binhex40 \ -desc=\"Macintosh BinHex Archive\" icon=internal-gopher-binary", -"exts=\"sit\" type=application/x-stuffit \ -desc=\"Macintosh StuffIt Archive\" icon=internal-gopher-binary", -"exts=\"zip\" type=application/x-zip-compressed \ -desc=\"Zip Compressed Data\" icon=internal-gopher-binary", -"exts=\"shar\" type=application/x-shar \ -desc=\"Unix Shell Archive\" icon=internal-gopher-unknown", -"exts=\"tar\" type=application/x-tar \ -desc=\"Unix Tape Archive\" icon=internal-gopher-binary", -"exts=\"gtar\" type=application/x-gtar \ -desc=\"GNU Tape Archive\" icon=internal-gopher-binary", -"exts=\"cpio\" type=application/x-cpio \ -desc=\"Unix CPIO Archive\" icon=internal-gopher-binary", -"exts=\"jar\" type=application/java-archive \ -desc=\"Java Archive\" icon=internal-gopher-binary", -"exts=\"exe,bin\" type=application/octet-stream \ -desc=\"Binary Executable\" icon=internal-gopher-binary", -"exts=\"ai,eps,ps\" type=application/postscript \ -desc=\"Postscript Document\" icon=internal-gopher-text", -"exts=\"csh\" type=application/x-csh \ -desc=\"C Shell Program\" icon=internal-gopher-unknown", -"exts=\"sh\" type=application/x-sh \ -desc=\"Bourne Shell Program\" icon=internal-gopher-unknown", -"exts=\"tcl\" type=application/x-tcl \ -desc=\"TCL Program\" icon=internal-gopher-unknown", -"exts=\"pl\" type=application/x-perl \ -desc=\"Perl Program\" icon=internal-gopher-unknown", -"exts=\"js,mocha\" type=application/x-javascript \ -desc=\"JavaScript Program\" icon=internal-gopher-unknown", -"exts=\"pac\" type=application/x-ns-proxy-autoconfig \ -desc=\"Proxy Auto-Config\" icon=internal-gopher-unknown", -"exts=\"jsc\" type=application/x-javascript-config \ -desc=\"JavaScript Config\" icon=internal-gopher-unknown", -"exts=\"p7m,p7c\" type=application/x-pkcs7-mime \ -desc=\"PKCS7 Encrypted Data\" icon=internal-gopher-binary", -"exts=\"p7s\" type=application/x-pkcs7-signature \ -desc=\"PKCS7 Signature\" icon=internal-gopher-binary", -"exts=\"enc\" type=application/pre-encrypted \ -desc=\"Pre-encrypted Data\" icon=internal-gopher-binary", -"exts=\"crl\" type=application/x-pkcs7-crl \ -desc=\"Certificate Revocation List\" icon=internal-gopher-binary", -"exts=\"ckl\" type=application/x-fortezza-ckl \ -desc=\"Compromised Key List\" icon=internal-gopher-binary", -"exts=\"uu,uue\" enc=x-uuencode \ -desc=\"UUEncoded Data\" icon=internal-gopher-binary", -"exts=\"doc,dot\" type=application/msword \ -desc=\"Microsoft Word Document\" icon=internal-gopher-text", -"exts=\"xls,xlt,xlm,xld,xla,xlc,xlw,xll\" type=application/vnd.ms-excel \ -desc=\"Microsoft Excel Worksheet\" icon=internal-gopher-text", -"exts=\"mdb,mda,mde\" type=application/vnd.ms-access \ -desc=\"Microsoft Access Database\" icon=internal-gopher-text", -"exts=\"ppt,pot,ppa,pps,pwz\" type=application/vnd.ms-powerpoint \ -desc=\"Microsoft PowerPoint Show\" icon=internal-gopher-text", -"exts=\"scd,sch,sc2\" type=application/vnd.ms-schedule \ -desc=\"Microsoft Schedule+ Application\" icon=internal-gopher-text", -"exts=\"lwp,sam\" type=application/vnd.lotus-wordpro \ -desc=\"Lotus WordPro Document\" icon=internal-gopher-text", -"exts=\"123,wk4,wk3,wk1\" type=application/vnd.lotus-1-2-3 \ -desc=\"Lotus 123 Document\" icon=internal-gopher-text", -"exts=\"apr,vew\" type=application/vnd.lotus-approach \ -desc=\"Lotus Approach Document\" icon=internal-gopher-text", -"exts=\"prz,pre\" type=application/vnd.lotus-freelance \ -desc=\"Lotus Freelance Document\" icon=internal-gopher-text", -"exts=\"or3,or2,org\" type=application/vnd.lotus-organizer \ -desc=\"Lotus Organizer Document\" icon=internal-gopher-text", -"exts=\"scm\" type=application/vnd.lotus-screencam \ -desc=\"Lotus ScreenCam Movie\" icon=internal-gopher-text", -"exts=\"wpd,wp6\" type=application/wordperfect5.1 \ -desc=\"WordPerfect Document\" icon=internal-gopher-text", - -#ifdef XP_UNIX -"exts=\"t,tr,roff\" type=application/x-troff \ -desc=\"TROFF Document\" icon=internal-gopher-text", -"exts=\"me\" type=application/x-troff-me \ -desc=\"TROFF Document\" icon=internal-gopher-text", -"exts=\"ms\" type=application/x-troff-ms \ -desc=\"TROFF Document\" icon=internal-gopher-text", -"exts=\"man\" type=application/x-troff-man \ -desc=\"Unix Manual Page\" icon=internal-gopher-text", -"exts=\"movie\" type=video/x-sgi-movie \ -desc=\"SGI Video\" icon=internal-gopher-movie", -"exts=\"Z\" enc=x-compress \ -desc=\"Compressed Data\" icon=internal-gopher-binary", -"exts=\"gz\" enc=x-gzip \ -desc=\"GNU Zip Compressed Data\" icon=internal-gopher-binary", -#else /* !XP_UNIX */ -"exts=\"Z\" type=application/x-compress \ -desc=\"Compressed Data\" icon=internal-gopher-binary", -"exts=\"gz\" enc=x-gzip \ -desc=\"GNU Zip Compressed Data\" icon=internal-gopher-binary", -#endif /* !XP_UNIX */ diff --git a/mozilla/network/mimetype/ngtypes.h b/mozilla/network/mimetype/ngtypes.h deleted file mode 100644 index 77b7239a4b4..00000000000 --- a/mozilla/network/mimetype/ngtypes.h +++ /dev/null @@ -1,173 +0,0 @@ -/* Generated file - do not edit! */ - -"exts=\"txt,text\" type=text/plain \ -desc=\"Plain Text\" icon=resource:/res/network/gopher-text.gif", -"exts=\"html,htm\" type=text/html \ -desc=\"Hypertext Markup Language\" icon=resource:/res/network/gopher-text.gif", -"exts=\"xml\" type=text/xml \ -desc=\"Extensible Markup Language\" icon=resource:/res/network/gopher-text.gif", -"exts=\"rdf\" type=text/rdf \ -desc=\"Resource Description Framework\" icon=resource:/res/network/gopher-text.gif", -"exts=\"xul\" type=text/xul \ -desc=\"XML-Based User Interface Language\" icon=resource:/res/network/gopher-text.gif", -"exts=\"rtf\" type=application/rtf \ -desc=\"Rich Text Format\" icon=resource:/res/network/gopher-text.gif", -"exts=\"pdf\" type=application/pdf \ -desc=\"Portable Document Format\" icon=resource:/res/network/gopher-text.gif", -"exts=\"tex\" type=application/x-tex \ -desc=\"TeX Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"latex\" type=application/x-latex \ -desc=\"LaTeX Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"dvi\" type=application/x-dvi \ -desc=\"TeX DVI Data\" icon=resource:/res/network/gopher-text.gif", -"exts=\"texi,texinfo\" type=application/x-texinfo \ -desc=\"GNU TeXinfo Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"vcf\" type=text/x-vcard \ -desc=\"VCard\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"gif\" type=image/gif \ -desc=\"GIF Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"jpeg,jpg,jpe,jfif,pjpeg,pjp\" type=image/jpeg \ -desc=\"JPEG Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"png\" type=image/png \ -desc=\"PNG Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"tiff,tif\" type=image/tiff \ -desc=\"TIFF Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"ras\" type=image/x-cmu-raster \ -desc=\"CMU Raster Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"xbm\" type=image/x-xbitmap \ -desc=\"X Bitmap\" icon=resource:/res/network/gopher-image.gif", -"exts=\"xpm\" type=image/x-xpixmap \ -desc=\"X Pixmap\" icon=resource:/res/network/gopher-image.gif", -"exts=\"xwd\" type=image/x-xwindowdump \ -desc=\"X Window Dump Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"pnm\" type=image/x-portable-anymap \ -desc=\"PBM Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"pbm\" type=image/x-portable-bitmap \ -desc=\"PBM Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"pgm\" type=image/x-portable-graymap \ -desc=\"PGM Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"ppm\" type=image/x-portable-pixmap \ -desc=\"PPM Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"rgb\" type=image/x-rgb \ -desc=\"RGB Image\" icon=resource:/res/network/gopher-image.gif", -"exts=\"bmp\" type=image/x-MS-bmp \ -desc=\"Windows Bitmap\" icon=resource:/res/network/gopher-image.gif", -"exts=\"pcd\" type=image/x-photo-cd \ -desc=\"PhotoCD Image\" icon=resource:/res/network/gopher-image.gif", - -"exts=\"ief\" type=image/ief \ -desc=\"\" icon=resource:/res/network/gopher-image.gif", -"exts=\"fif\" type=application/fractals \ -desc=\"Fractal Image Format\" icon=resource:/res/network/gopher-image.gif", -"exts=\"au,snd\" type=audio/basic \ -desc=\"ULAW Audio\" icon=resource:/res/network/gopher-sound.gif", -"exts=\"aif,aiff,aifc\" type=audio/x-aiff \ -desc=\"AIFF Audio\" icon=resource:/res/network/gopher-sound.gif", -"exts=\"wav\" type=audio/x-wav \ -desc=\"WAV Audio\" icon=resource:/res/network/gopher-sound.gif", -"exts=\"mp2,mpa,abs,mpega\" type=audio/x-mpeg \ -desc=\"MPEG Audio\" icon=resource:/res/network/gopher-sound.gif", -"exts=\"ra,ram\" type=audio/x-pn-realaudio \ -desc=\"RealAudio\" icon=resource:/res/network/gopher-sound.gif", -"exts=\"mpeg,mpg,mpe,mpv,vbs,mpegv\" type=video/mpeg \ -desc=\"MPEG Video\" icon=resource:/res/network/gopher-movie.gif", -"exts=\"mpv2,mp2v\" type=video/x-mpeg2 \ -desc=\"MPEG2 Video\" icon=resource:/res/network/gopher-movie.gif", -"exts=\"qt,mov,moov\" type=video/quicktime \ -desc=\"Quicktime Video\" icon=resource:/res/network/gopher-movie.gif", -"exts=\"avi\" type=video/x-msvideo \ -desc=\"Microsoft Video\" icon=resource:/res/network/gopher-movie.gif", -"exts=\"hqx\" type=application/mac-binhex40 \ -desc=\"Macintosh BinHex Archive\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"sit\" type=application/x-stuffit \ -desc=\"Macintosh StuffIt Archive\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"zip\" type=application/x-zip-compressed \ -desc=\"Zip Compressed Data\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"shar\" type=application/x-shar \ -desc=\"Unix Shell Archive\" icon=resource:/res/network/gopher-unknown", -"exts=\"tar\" type=application/x-tar \ -desc=\"Unix Tape Archive\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"gtar\" type=application/x-gtar \ -desc=\"GNU Tape Archive\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"cpio\" type=application/x-cpio \ -desc=\"Unix CPIO Archive\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"jar\" type=application/java-archive \ -desc=\"Java Archive\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"exe,bin\" type=application/octet-stream \ -desc=\"Binary Executable\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"ai,eps,ps\" type=application/postscript \ -desc=\"Postscript Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"csh\" type=application/x-csh \ -desc=\"C Shell Program\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"sh\" type=application/x-sh \ -desc=\"Bourne Shell Program\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"tcl\" type=application/x-tcl \ -desc=\"TCL Program\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"pl\" type=application/x-perl \ -desc=\"Perl Program\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"js,mocha\" type=application/x-javascript \ -desc=\"JavaScript Program\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"pac\" type=application/x-ns-proxy-autoconfig \ -desc=\"Proxy Auto-Config\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"jsc\" type=application/x-javascript-config \ -desc=\"JavaScript Config\" icon=resource:/res/network/gopher-unknown.gif", -"exts=\"p7m,p7c\" type=application/x-pkcs7-mime \ -desc=\"PKCS7 Encrypted Data\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"p7s\" type=application/x-pkcs7-signature \ -desc=\"PKCS7 Signature\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"enc\" type=application/pre-encrypted \ -desc=\"Pre-encrypted Data\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"crl\" type=application/x-pkcs7-crl \ -desc=\"Certificate Revocation List\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"ckl\" type=application/x-fortezza-ckl \ -desc=\"Compromised Key List\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"uu,uue\" enc=x-uuencode \ -desc=\"UUEncoded Data\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"doc,dot\" type=application/msword \ -desc=\"Microsoft Word Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"xls,xlt,xlm,xld,xla,xlc,xlw,xll\" type=application/vnd.ms-excel \ -desc=\"Microsoft Excel Worksheet\" icon=resource:/res/network/gopher-text.gif", -"exts=\"mdb,mda,mde\" type=application/vnd.ms-access \ -desc=\"Microsoft Access Database\" icon=resource:/res/network/gopher-text.gif", -"exts=\"ppt,pot,ppa,pps,pwz\" type=application/vnd.ms-powerpoint \ -desc=\"Microsoft PowerPoint Show\" icon=resource:/res/network/gopher-text.gif", -"exts=\"scd,sch,sc2\" type=application/vnd.ms-schedule \ -desc=\"Microsoft Schedule+ Application\" icon=resource:/res/network/gopher-text.gif", -"exts=\"lwp,sam\" type=application/vnd.lotus-wordpro \ -desc=\"Lotus WordPro Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"123,wk4,wk3,wk1\" type=application/vnd.lotus-1-2-3 \ -desc=\"Lotus 123 Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"apr,vew\" type=application/vnd.lotus-approach \ -desc=\"Lotus Approach Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"prz,pre\" type=application/vnd.lotus-freelance \ -desc=\"Lotus Freelance Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"or3,or2,org\" type=application/vnd.lotus-organizer \ -desc=\"Lotus Organizer Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"scm\" type=application/vnd.lotus-screencam \ -desc=\"Lotus ScreenCam Movie\" icon=resource:/res/network/gopher-text.gif", -"exts=\"wpd,wp6\" type=application/wordperfect5.1 \ -desc=\"WordPerfect Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"eml\" type=message/rfc822 \ -desc=\"RFC822 Messages\" icon=resource:/res/network/gopher-text.gif", - -#ifdef XP_UNIX -"exts=\"t,tr,roff\" type=application/x-troff \ -desc=\"TROFF Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"me\" type=application/x-troff-me \ -desc=\"TROFF Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"ms\" type=application/x-troff-ms \ -desc=\"TROFF Document\" icon=resource:/res/network/gopher-text.gif", -"exts=\"man\" type=application/x-troff-man \ -desc=\"Unix Manual Page\" icon=resource:/res/network/gopher-text.gif", -"exts=\"movie\" type=video/x-sgi-movie \ -desc=\"SGI Video\" icon=resource:/res/network/gopher-movie.gif", -"exts=\"Z\" enc=x-compress \ -desc=\"Compressed Data\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"gz\" enc=x-gzip \ -desc=\"GNU Zip Compressed Data\" icon=resource:/res/network/gopher-binary.gif", -#else /* !XP_UNIX */ -"exts=\"Z\" type=application/x-compress \ -desc=\"Compressed Data\" icon=resource:/res/network/gopher-binary.gif", -"exts=\"gz\" enc=x-gzip \ -desc=\"GNU Zip Compressed Data\" icon=resource:/res/network/gopher-binary.gif", -#endif /* !XP_UNIX */ diff --git a/mozilla/network/module/MANIFEST b/mozilla/network/module/MANIFEST deleted file mode 100644 index bf1a28b8a2b..00000000000 --- a/mozilla/network/module/MANIFEST +++ /dev/null @@ -1,15 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist:network:module directory -# - -nsINetService.h -nsINetSupport.h -nsIRelatedLinks.h -nsIRefreshUrl.h -nsIConnectionInfo.h -nsIURLGroup.h -nsINetlibURL.h -nsIProtocol.h -nsIProtocolURLFactory.h -nsIUnicharStreamLoader.h -nsSocketTransport.h diff --git a/mozilla/network/module/Makefile.in b/mozilla/network/module/Makefile.in deleted file mode 100644 index 09f3fb0e522..00000000000 --- a/mozilla/network/module/Makefile.in +++ /dev/null @@ -1,90 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = netlib -LIBRARY_NAME = netlib - -INHIBIT_STRIP_NOT_EXPORTED = 1 - -ifdef ENABLE_TESTS -DIRS += tests -endif - -CPPSRCS = \ - nsNetService.cpp \ - nsNetThread.cpp \ - nsNetStream.cpp \ - nsNetStreamLoader.cpp \ - nsHttpUrl.cpp \ - nsStubContext.cpp \ - nsNetStubs.cpp \ - nsNetFile.cpp \ - nsNetIDs.cpp \ - nsLoadAttribs.cpp \ - nsNetFactory.cpp \ - nsHttpURLFactory.cpp \ - nsSocketTransport.cpp \ - $(NULL) - -EXPORTS = \ - nsINetService.h \ - nsINetSupport.h \ - nsIRelatedLinks.h \ - nsIRefreshUrl.h \ - nsIConnectionInfo.h \ - nsIURLGroup.h \ - nsINetlibURL.h \ - nsIProtocol.h \ - nsIProtocolURLFactory.h \ - nsIUnicharStreamLoader.h \ - nsSocketTransport.h \ - $(NULL) - -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -IMAGES = \ - $(srcdir)/res/gopher-audio.gif \ - $(srcdir)/res/gopher-binary.gif \ - $(srcdir)/res/gopher-find.gif \ - $(srcdir)/res/gopher-image.gif \ - $(srcdir)/res/gopher-menu.gif \ - $(srcdir)/res/gopher-movie.gif \ - $(srcdir)/res/gopher-telnet.gif \ - $(srcdir)/res/gopher-text.gif \ - $(srcdir)/res/gopher-unknown.gif \ - $(NULL) - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - -GARBAGE += $(wildcard $(DIST)/bin/res/network/gopher-*.gif) - -install:: - $(INSTALL) $(IMAGES) $(DIST)/bin/res/network - diff --git a/mozilla/network/module/makefile.win b/mozilla/network/module/makefile.win deleted file mode 100644 index 3e31844390f..00000000000 --- a/mozilla/network/module/makefile.win +++ /dev/null @@ -1,180 +0,0 @@ -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -IGNORE_MANIFEST = 1 - -#//------------------------------------------------------------------------ -#// -# New build system where zip dll is build indepenant of java stubs. -#// -#//------------------------------------------------------------------------ -MODULE = netlib -EXPORTS = nsINetService.h \ - nsINetSupport.h \ - nsIRelatedLinks.h \ - nsINetlibURL.h \ - nsIURLGroup.h \ - nsIUnicharStreamLoader.h \ - nsIConnectionInfo.h \ - nsIRefreshUrl.h \ - nsIProtocol.h \ - nsIProtocolURLFactory.h \ - nsSocketTransport.h \ - $(NULL) - -DIRS = tests -#//------------------------------------------------------------------------ -#// -#// Specify the depth of the current directory relative to the -#// root of NS -#// -#//------------------------------------------------------------------------ -DEPTH= ..\.. -include <$(DEPTH)/config/config.mak> - -MAKE_OBJ_TYPE=DLL -#//------------------------------------------------------------------------ -#// -#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...) -#// -#//------------------------------------------------------------------------ -DLLNAME=netlib -MAPFILE=netlib.map -DEFFILE=net.def - -#//------------------------------------------------------------------------ -#// -#// Define the files necessary to build the target (ie. OBJS) -#// -#//------------------------------------------------------------------------ -OBJS= \ - .\$(OBJDIR)\nsNetService.obj \ - .\$(OBJDIR)\nsNetThread.obj \ - .\$(OBJDIR)\nsNetStream.obj \ - .\$(OBJDIR)\nsNetStreamLoader.obj \ - .\$(OBJDIR)\nsHttpUrl.obj \ - .\$(OBJDIR)\nsStubContext.obj \ - .\$(OBJDIR)\nsNetStubs.obj \ - .\$(OBJDIR)\nsNetIDs.obj \ - .\$(OBJDIR)\nsNetFile.obj \ - .\$(OBJDIR)\nsLoadAttribs.obj \ - .\$(OBJDIR)\nsNetFactory.obj \ - .\$(OBJDIR)\nsHttpURLFactory.obj \ - .\$(OBJDIR)\nsSocketTransport.obj \ - $(NULL) - -#//------------------------------------------------------------------------ -#// -#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...) -#// (these must be defined before the common makefiles are included) -#// -#//------------------------------------------------------------------------ - -DLL=.\$(OBJDIR)\$(DLLNAME).dll - -#//------------------------------------------------------------------------ -#// -#// Define any local options for the make tools -#// (ie. LCFLAGS, LLFLAGS, LLIBS, LINCS) -#// -#//------------------------------------------------------------------------ -#LCFLAGS=-DNETSCAPE -D_IMPL_NS_NET -DNO_NETWORK_POLLING -LCFLAGS=-DNETSCAPE -D_IMPL_NS_NET - - -NETLIBS=\ - $(DIST)\lib\abouturl.lib \ - $(DIST)\lib\fileurl.lib \ - $(DIST)\lib\ftpurl.lib \ - $(DIST)\lib\gophurl.lib \ - $(DIST)\lib\httpurl.lib \ - $(DIST)\lib\sockstub.lib \ - $(DIST)\lib\remoturl.lib \ -!ifdef NU_CACHE - $(DIST)\lib\cache.lib \ -!endif - $(DIST)\lib\netcache.lib \ - $(DIST)\lib\netcnvts.lib \ - $(DIST)\lib\mimetype.lib \ - $(DIST)\lib\network.lib \ - $(NULL) - -LLIBS=$(LLIBS) $(LIBNSPR) \ - $(DIST)\lib\secfreenav32.lib \ - $(DIST)\lib\libpwcac.lib \ - $(DIST)\lib\js32$(VERSION_NUMBER).lib \ - $(DIST)\lib\xppref32.lib \ - $(DIST)\lib\xpcom.lib \ - $(DIST)\lib\xplib.lib \ - $(DIST)\lib\zlib.lib \ - $(DIST)\lib\dbm32.lib \ - $(NETLIBS) \ - $(NULL) - -LINCS=$(LINCS) -I. \ - -I..\public \ - -I$(PUBLIC)\raptor \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\xpcom \ - -I$(PUBLIC)\httpurl \ -!ifdef NU_CACHE - -I$(PUBLIC)\cache \ -!endif - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\netcnvts \ - -I$(PUBLIC)\abouturl \ - -I$(PUBLIC)\fileurl \ - -I$(PUBLIC)\ftpurl \ - -I$(PUBLIC)\gophurl \ - -I$(PUBLIC)\httpurl \ - -I$(PUBLIC)\sockstub \ - -I$(PUBLIC)\remoturl \ - -I$(PUBLIC)\netlib \ - -I$(PUBLIC)\chrome \ - $(NULL) - -# clobber and clobber_all will remove the following garbage: -GARBAGE = $(GARBAGE) _gen - - -#//------------------------------------------------------------------------ -#// -#// Include the common makefile rules -#// -#//------------------------------------------------------------------------ -include <$(DEPTH)/config/rules.mak> - -$(DLL): $(NETLIBS) - -install:: $(DLL) - $(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).dll $(DIST)\bin - $(MAKE_INSTALL) .\$(OBJDIR)\netlib.lib $(DIST)\lib - $(MAKE_INSTALL) .\res\gopher-audio.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-binary.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-find.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-image.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-menu.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-movie.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-telnet.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-text.gif $(DIST)\bin\res\network - $(MAKE_INSTALL) .\res\gopher-unknown.gif $(DIST)\bin\res\network - diff --git a/mozilla/network/module/net.def b/mozilla/network/module/net.def deleted file mode 100644 index dff5349c19e..00000000000 --- a/mozilla/network/module/net.def +++ /dev/null @@ -1,26 +0,0 @@ -; The contents of this file are subject to the Netscape Public -; License Version 1.1 (the "License"); you may not use this file -; except in compliance with the License. You may obtain a copy of -; the License at http://www.mozilla.org/NPL/ -; -; Software distributed under the License is distributed on an "AS -; IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -; implied. See the License for the specific language governing -; rights and limitations under the License. -; -; The Original Code is mozilla.org code. -; -; The Initial Developer of the Original Code is Netscape -; Communications Corporation. Portions created by Netscape are -; Copyright (C) 1998 Netscape Communications Corporation. All -; Rights Reserved. -; -; Contributor(s): - -LIBRARY netlib.dll - -EXPORTS - NS_NewINetService - NET_ToggleTrace - NET_PollSockets - NET_RegisterContentTypeConverter diff --git a/mozilla/network/module/nsHttpURLFactory.cpp b/mozilla/network/module/nsHttpURLFactory.cpp deleted file mode 100644 index 691ba7ed2fe..00000000000 --- a/mozilla/network/module/nsHttpURLFactory.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsIProtocolURLFactory.h" -#include "nsHttpUrl.h" -#include "nsINetService.h" -#include "nsNetThread.h" -#include "nsIServiceManager.h" -#include "nsString.h" - -class nsHttpURLFactory : public nsIProtocolURLFactory -{ -public: - - NS_DECL_ISUPPORTS - - //////////////////////////////////////////////////////////////////////////// - // nsIProtocolURLFactory: - - NS_IMETHOD CreateURL(nsIURI* *aResult, - const nsString& aSpec, - const nsIURI* aContextURL = nsnull, - nsISupports* aContainer = nsnull, - nsILoadGroup* aGroup = nsnull); - - //////////////////////////////////////////////////////////////////////////// - // nsHttpURLFactory: - - nsHttpURLFactory(void); - virtual ~nsHttpURLFactory(void); - -protected: - -}; - -nsHttpURLFactory::nsHttpURLFactory(void) -{ - NS_INIT_REFCNT(); -} - -nsHttpURLFactory::~nsHttpURLFactory(void) -{ -} - -static NS_DEFINE_IID(kIProtocolURLFactoryIID, NS_IPROTOCOLURLFACTORY_IID); -NS_IMPL_ISUPPORTS(nsHttpURLFactory, kIProtocolURLFactoryIID); - -NS_IMETHODIMP -nsHttpURLFactory::CreateURL(nsIURI* *aResult, - const nsString& aSpec, - const nsIURI* aContextURL, - nsISupports* aContainer, - nsILoadGroup* aGroup) -{ - nsHttpUrlImpl* url = new nsHttpUrlImpl(aContainer, aGroup); - if (url == NULL) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(url); - nsresult err = url->ParseURL(aSpec, aContextURL); - if (err != NS_OK) { - NS_RELEASE(url); - return err; - } - *aResult = url; - return NS_OK; -} - -static NS_DEFINE_IID(kINetServiceIID, NS_INETSERVICE_IID); -static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID); - -// XXX temporarily, until we have pluggable protocols... -extern "C" NS_NET nsresult -NS_InitializeHttpURLFactory(nsINetService* inet) -{ - nsresult rv; - nsHttpURLFactory* urlf = new nsHttpURLFactory(); - if (urlf == NULL) - return NS_ERROR_OUT_OF_MEMORY; -#if 0 - nsINetService *inet = nsnull; - rv = nsServiceManager::GetService(kNetServiceCID, - kINetServiceIID, - (nsISupports **)&inet); - if (rv != NS_OK) return rv; -#endif - rv = inet->RegisterProtocol(*new nsString("http"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("https"), urlf, NULL); - if (rv != NS_OK) goto done; - - // XXX Hacks until we have real urlf objects for these... - inet->RegisterProtocol(*new nsString("ftp"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("resource"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("chrome"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("file"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("javascript"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("sockstub"), urlf, NULL); - if (rv != NS_OK) goto done; - inet->RegisterProtocol(*new nsString("about"), urlf, NULL); - if (rv != NS_OK) goto done; - - done: -#if 0 - nsServiceManager::ReleaseService(kNetServiceCID, inet); -#endif - return rv; -} - -//////////////////////////////////////////////////////////////////////////////// diff --git a/mozilla/network/module/nsHttpUrl.cpp b/mozilla/network/module/nsHttpUrl.cpp deleted file mode 100644 index 591db1cf37a..00000000000 --- a/mozilla/network/module/nsHttpUrl.cpp +++ /dev/null @@ -1,954 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifdef XP_PC -#include <windows.h> // for InterlockedIncrement -#endif -#include "nsHttpUrl.h" -#include "nsIProtocolConnection.h" -#include "nsIURLGroup.h" -#include "nsString.h" - -#include "nsINetService.h" /* XXX: NS_FALSE */ - -#include "prmem.h" -#include "plstr.h" -#include "nsCRT.h" -#include "nsStubContext.h" - -static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID); -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static NS_DEFINE_IID(kIHttpURLIID, NS_IHTTPURL_IID); -static NS_DEFINE_IID(kIURLIID, NS_IURL_IID); -static NS_DEFINE_IID(kIPostToServerIID, NS_IPOSTTOSERVER_IID); -static NS_DEFINE_IID(kIProtocolConnectionIID, NS_IPROTOCOLCONNECTION_IID); - -nsHttpUrlImpl::nsHttpUrlImpl(nsISupports* aContainer, nsILoadGroup* aGroup) -{ - NS_INIT_REFCNT(); - - m_PostType = Send_None; - m_PostBuffer = nsnull; - m_PostBufferLength = 0; - m_URL_s = nsnull; - - mProtocol = nsnull; - mHost = nsnull; - mFile = nsnull; - mRef = nsnull; - mPort = -1; - mSpec = nsnull; - mSearch = nsnull; - mContainer = nsnull; - mLoadGroup = aGroup; - - NS_NewLoadAttribs( getter_AddRefs(mLoadAttribs) ); - - // NS_IF_ADDREF(mLoadGroup); --- a url should not own its group, its group already owns it - - mContainer = aContainer; - // NS_IF_ADDREF(mContainer); --- a url should not own its container, its container already owns it - // ParseURL(aSpec, aURL); // XXX whh -} - -nsHttpUrlImpl::~nsHttpUrlImpl() -{ - // NS_IF_RELEASE(mContainer); - // NS_IF_RELEASE(mLoadGroup); - - PR_FREEIF(mSpec); - PR_FREEIF(mProtocol); - PR_FREEIF(mHost); - PR_FREEIF(mFile); - PR_FREEIF(mRef); - PR_FREEIF(mSearch); - PR_FREEIF(m_PostBuffer); - if (nsnull != m_URL_s) { - NET_DropURLStruct(m_URL_s); - } -} - -NS_IMPL_THREADSAFE_ADDREF(nsHttpUrlImpl); -NS_IMPL_THREADSAFE_RELEASE(nsHttpUrlImpl); - -nsresult nsHttpUrlImpl::QueryInterface(const nsIID &aIID, void** aInstancePtr) -{ - if (NULL == aInstancePtr) { - return NS_ERROR_NULL_POINTER; - } - - static NS_DEFINE_IID(kINetlibURLIID, NS_INETLIBURL_IID); - static NS_DEFINE_IID(kIPostToServerIID, NS_IPOSTTOSERVER_IID); - if (aIID.Equals(kIHttpURLIID) || aIID.Equals(kISupportsIID)) { - *aInstancePtr = (void*) ((nsIHttpURL*)this); - AddRef(); - return NS_OK; - } - if (aIID.Equals(kIURLIID)) { - *aInstancePtr = (void*) ((nsIURI*)this); - AddRef(); - return NS_OK; - } - if (aIID.Equals(kINetlibURLIID)) { - *aInstancePtr = (void*) ((nsINetlibURL*)this); - AddRef(); - return NS_OK; - } - if (aIID.Equals(kIPostToServerIID)) { - *aInstancePtr = (void*) ((nsIPostToServer*)this); - AddRef(); - return NS_OK; - } - -#if defined(NS_DEBUG) - /* - * Check for the debug-only interface indicating thread-safety - */ - static NS_DEFINE_IID(kIsThreadsafeIID, NS_ISTHREADSAFE_IID); - if (aIID.Equals(kIsThreadsafeIID)) { - return NS_OK; - } -#endif - - return NS_NOINTERFACE; -} - - -NS_METHOD nsHttpUrlImpl::SetURLInfo(URL_Struct *URL_s) -{ - nsresult result = NS_OK; - - /* Hook us up with the world. */ - m_URL_s = URL_s; - NET_HoldURLStruct(URL_s); - - if (Send_None != m_PostType) { - /* Free any existing POST data hanging off the URL_Struct */ - if (nsnull != URL_s->post_data) { - PR_Free(URL_s->post_data); - } - - /* - * Store the new POST data into the URL_Struct - */ - URL_s->post_data = m_PostBuffer; - URL_s->post_data_size = m_PostBufferLength; - URL_s->post_data_is_file = (Send_Data == m_PostType) ? FALSE : TRUE; - /* - * Is the request a POST or PUT - */ - URL_s->method = (Send_File == m_PostType) ? URL_PUT_METHOD : URL_POST_METHOD; - - /* Reset the local post state... */ - m_PostType = Send_None; - m_PostBuffer = nsnull; /* The URL_Struct owns the memory now... */ - m_PostBufferLength = 0; - } - - return result; -} - -NS_METHOD nsHttpUrlImpl::GetURLInfo(URL_Struct_** aResult) const -{ - nsresult rv; - - if (nsnull == aResult) { - rv = NS_ERROR_NULL_POINTER; - } else { - /* XXX: Should the URL be reference counted here?? */ - *aResult = m_URL_s; - rv = NS_OK; - } - - return rv; -} - -NS_METHOD nsHttpUrlImpl::SendFile(const char *aFile) -{ - nsresult result; - - result = PostFile(aFile); - if (NS_OK == result) { - m_PostType = Send_File; - } - return result; -} - - -NS_METHOD nsHttpUrlImpl::SendDataFromFile(const char *aFile) -{ - nsresult result; - - result = PostFile(aFile); - if (NS_OK == result) { - m_PostType = Send_DataFromFile; - } - return result; -} - - -NS_METHOD nsHttpUrlImpl::SendData(const char *aBuffer, PRUint32 aLength) -{ - nsresult result = NS_OK; - - /* Deal with error conditions... */ - if (nsnull == aBuffer) { - result = NS_ERROR_ILLEGAL_VALUE; - goto done; - } - else if (Send_None != m_PostType) { - result = NS_IPOSTTOSERVER_ALREADY_POSTING; - goto done; - } - - /* Copy the post data... */ - m_PostBuffer = (char *)PR_Malloc(aLength+1); - if (nsnull == m_PostBuffer) { - result = NS_ERROR_OUT_OF_MEMORY; - goto done; - } - memcpy(m_PostBuffer, aBuffer, aLength); - m_PostBuffer[aLength] = '\0'; - m_PostBufferLength = aLength; - m_PostType = Send_Data; - -done: - return result; -} - -NS_METHOD nsHttpUrlImpl::AddMimeHeader(const char *name, const char *value) -{ - MWContext *stubContext=NULL; - char *aName=NULL; - char *aVal=NULL; - PRBool addColon=TRUE; - PRInt32 len=0; - - NS_PRECONDITION((name != nsnull) && ((*name) != nsnull), "Bad name"); - NS_PRECONDITION((value != nsnull) && ((*value) != nsnull), "Bad value"); - - if(!name - || !*name - || !value - || !*value) - return NS_FALSE; - - // Make sure we've got a colon on the end of the header name - if(PL_strchr(name, ':')) - addColon=FALSE; - - /* Bring in our own copies of the data. */ - if(addColon) - aName = (char*)PR_Malloc(PL_strlen(name)+2); // add extra byte for colon - else - aName = (char*)PR_Malloc(PL_strlen(name)+1); - if(!aName) - return NS_ERROR_OUT_OF_MEMORY; - aVal = (char*)PR_Malloc(PL_strlen(value)+1); - if(!aVal) - return NS_ERROR_OUT_OF_MEMORY; - - PL_strcpy(aName, name); - if(addColon) { - PL_strcat(aName, ":"); - } - - PL_strcpy(aVal, value); - - stubContext = new_stub_context(m_URL_s); - - /* Make the real call to NET_ParseMimeHeader, passing in the dummy bam context. */ - - - NET_ParseMimeHeader(FO_CACHE_AND_NGLAYOUT, - stubContext, - m_URL_s, - aName, - aVal, - TRUE); - PR_Free(aName); - PR_Free(aVal); - return NS_OK; -} - -nsresult nsHttpUrlImpl::PostFile(const char *aFile) -{ - nsresult result = NS_OK; - - /* Deal with error conditions... */ - if (nsnull == aFile) { - result = NS_ERROR_ILLEGAL_VALUE; - goto done; - } - else if (Send_None != m_PostType) { - result = NS_IPOSTTOSERVER_ALREADY_POSTING; - goto done; - } - - /* Copy the post data... */ - m_PostBuffer = PL_strdup(aFile); - - if (nsnull == m_PostBuffer) { - result = NS_ERROR_OUT_OF_MEMORY; - goto done; - } - m_PostBufferLength = PL_strlen(aFile); - -done: - return result; -} - -//////////////////////////////////////////////////////////////////////////////// - -// XXX recode to use nsString api's - -// XXX don't bother with port numbers -// XXX don't bother with ref's -// XXX null pointer checks are incomplete -nsresult nsHttpUrlImpl::ParseURL(const nsString& aSpec, const nsIURI* aURL) -{ - // XXX hack! - char* cSpec = aSpec.ToNewCString(); - - const char* uProtocol = nsnull; - const char* uHost = nsnull; - const char* uFile = nsnull; - PRUint32 uPort; - if (nsnull != aURL) { - nsresult rslt = aURL->GetProtocol(&uProtocol); - if (rslt != NS_OK) return rslt; - rslt = aURL->GetHost(&uHost); - if (rslt != NS_OK) return rslt; - rslt = aURL->GetFile(&uFile); - if (rslt != NS_OK) return rslt; - rslt = aURL->GetHostPort(&uPort); - if (rslt != NS_OK) return rslt; - } - - NS_LOCK_INSTANCE(); - - PR_FREEIF(mProtocol); - PR_FREEIF(mHost); - PR_FREEIF(mFile); - PR_FREEIF(mRef); - PR_FREEIF(mSearch); - mPort = -1; - - if (nsnull == cSpec) { - if (nsnull == aURL) { - NS_UNLOCK_INSTANCE(); - return NS_ERROR_ILLEGAL_VALUE; - } - mProtocol = (nsnull != uProtocol) ? PL_strdup(uProtocol) : nsnull; - mHost = (nsnull != uHost) ? PL_strdup(uHost) : nsnull; - mPort = uPort; - mFile = (nsnull != uFile) ? PL_strdup(uFile) : nsnull; - - NS_UNLOCK_INSTANCE(); - return NS_OK; - } - - // Strip out reference and search info - char* ref = strpbrk(cSpec, "#?"); - if (nsnull != ref) { - char* search = nsnull; - if ('#' == *ref) { - search = PL_strchr(ref + 1, '?'); - if (nsnull != search) { - *search++ = '\0'; - } - - PRIntn hashLen = PL_strlen(ref + 1); - if (0 != hashLen) { - mRef = (char*) PR_Malloc(hashLen + 1); - PL_strcpy(mRef, ref + 1); - } - } - else { - search = ref + 1; - } - - if (nsnull != search) { - // The rest is the search - PRIntn searchLen = PL_strlen(search); - if (0 != searchLen) { - mSearch = (char*) PR_Malloc(searchLen + 1); - PL_strcpy(mSearch, search); - } - } - - // XXX Terminate string at start of reference or search - *ref = '\0'; - } - - // The URL is considered absolute if and only if it begins with a - // protocol spec. A protocol spec is an alphanumeric string of 1 or - // more characters that is terminated with a colon. - PRBool isAbsolute = PR_FALSE; - char* cp; - char* ap = cSpec; - char ch; - while (0 != (ch = *ap)) { - if (((ch >= 'a') && (ch <= 'z')) || - ((ch >= 'A') && (ch <= 'Z')) || - ((ch >= '0') && (ch <= '9'))) { - ap++; - continue; - } - if ((ch == ':') && (ap - cSpec >= 2)) { - isAbsolute = PR_TRUE; - cp = ap; - break; - } - break; - } - - if (!isAbsolute) { - // relative spec - if (nsnull == aURL) { - delete[] cSpec; - - NS_UNLOCK_INSTANCE(); - return NS_ERROR_ILLEGAL_VALUE; - } - - // keep protocol and host - mProtocol = (nsnull != uProtocol) ? PL_strdup(uProtocol) : nsnull; - mHost = (nsnull != uHost) ? PL_strdup(uHost) : nsnull; - mPort = uPort; - - // figure out file name - PRInt32 len = PL_strlen(cSpec) + 1; - if ((len > 1) && (cSpec[0] == '/')) { - // Relative spec is absolute to the server - mFile = PL_strdup(cSpec); - } else { - if (cSpec[0] != '\0') { - // Strip out old tail component and put in the new one - char* dp = PL_strrchr(uFile, '/'); - if (!dp) { - delete[] cSpec; - NS_UNLOCK_INSTANCE(); - return NS_ERROR_ILLEGAL_VALUE; - } - PRInt32 dirlen = (dp + 1) - uFile; - mFile = (char*) PR_Malloc(dirlen + len); - PL_strncpy(mFile, uFile, dirlen); - PL_strcpy(mFile + dirlen, cSpec); - } - else { - mFile = PL_strdup(uFile); - } - } - - /* Stolen from netlib's mkparse.c. - * - * modifies a url of the form /foo/../foo1 -> /foo1 - * and /foo/./foo1 -> /foo/foo1 - */ - char *fwdPtr = mFile; - char *urlPtr = mFile; - - for(; *fwdPtr != '\0'; fwdPtr++) - { - - if(*fwdPtr == '/' && *(fwdPtr+1) == '.' && *(fwdPtr+2) == '/') - { - /* remove ./ - */ - fwdPtr += 1; - } - else if(*fwdPtr == '/' && *(fwdPtr+1) == '.' && *(fwdPtr+2) == '.' && - (*(fwdPtr+3) == '/' || *(fwdPtr+3) == '\0')) - { - /* remove foo/.. - */ - /* reverse the urlPtr to the previous slash - */ - if(urlPtr != mFile) - urlPtr--; /* we must be going back at least one */ - for(;*urlPtr != '/' && urlPtr != mFile; urlPtr--) - ; /* null body */ - - /* forward the fwd_prt past the ../ - */ - fwdPtr += 2; - } - else - { - /* copy the url incrementaly - */ - *urlPtr++ = *fwdPtr; - } - } - - *urlPtr = '\0'; /* terminate the url */ - - // Now that we've resolved the relative URL, we need to reconstruct - // a URL spec from the components. - ReconstructSpec(); - } else { - // absolute spec - - PR_FREEIF(mSpec); - PRInt32 slen = aSpec.Length(); - mSpec = (char *) PR_Malloc(slen + 1); - aSpec.ToCString(mSpec, slen+1); - - // get protocol first - PRInt32 plen = cp - cSpec; - mProtocol = (char*) PR_Malloc(plen + 1); - PL_strncpy(mProtocol, cSpec, plen); - mProtocol[plen] = 0; - cp++; // eat : in protocol - - // skip over one, two or three slashes if it isn't about: - if (PL_strcmp(mProtocol, "about") != 0) { - if (*cp == '/') { - cp++; - if (*cp == '/') { - cp++; - if (*cp == '/') { - cp++; - } - } - } else { - delete[] cSpec; - - NS_UNLOCK_INSTANCE(); - return NS_ERROR_ILLEGAL_VALUE; - } - } - - -#if defined(XP_UNIX) || defined (XP_MAC) || defined (XP_BEOS) - // Always leave the top level slash for absolute file paths under Mac and UNIX. - // The code above sometimes results in stripping all of slashes - // off. This only happens when a previously stripped url is asked to be - // parsed again. Under Win32 this is not a problem since file urls begin - // with a drive letter not a slash. This problem show's itself when - // nested documents such as iframes within iframes are parsed. - - if (PL_strcmp(mProtocol, "file") == 0) { - if (*cp != '/') { - cp--; - } - } -#endif /* XP_UNIX */ - - const char* cp0 = cp; - if ((PL_strcmp(mProtocol, "resource") == 0) || - (PL_strcmp(mProtocol, "file") == 0) || - (PL_strcmp(mProtocol, "about") == 0)) { - // resource/file url's do not have host names. - // The remainder of the string is the file name - PRInt32 flen = PL_strlen(cp); - mFile = (char*) PR_Malloc(flen + 1); - PL_strcpy(mFile, cp); - -#ifdef NS_WIN32 - if (PL_strcmp(mProtocol, "file") == 0) { - // If the filename starts with a "x|" where is an single - // character then we assume it's a drive name and change the - // vertical bar back to a ":" - if ((flen >= 2) && (mFile[1] == '|')) { - mFile[1] = ':'; - } - } -#endif /* NS_WIN32 */ - } else { - // Host name follows protocol for http style urls - cp = PL_strpbrk(cp, "/:"); - - if (nsnull == cp) { - // There is only a host name - PRInt32 hlen = PL_strlen(cp0); - mHost = (char*) PR_Malloc(hlen + 1); - PL_strcpy(mHost, cp0); - } - else { - PRInt32 hlen = cp - cp0; - mHost = (char*) PR_Malloc(hlen + 1); - PL_strncpy(mHost, cp0, hlen); - mHost[hlen] = 0; - - if (':' == *cp) { - // We have a port number - cp0 = cp+1; - cp = PL_strchr(cp, '/'); - mPort = strtol(cp0, (char **)nsnull, 10); - } - } - - if (nsnull == cp) { - // There is no file name - // Set filename to "/" - mFile = (char*) PR_Malloc(2); - mFile[0] = '/'; - mFile[1] = 0; - } - else { - // The rest is the file name - PRInt32 flen = PL_strlen(cp); - mFile = (char*) PR_Malloc(flen + 1); - PL_strcpy(mFile, cp); - } - } - } - -//printf("protocol='%s' host='%s' file='%s'\n", mProtocol, mHost, mFile); - delete[] cSpec; - - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -void -nsHttpUrlImpl::ReconstructSpec(void) -{ - PR_FREEIF(mSpec); - - char portBuffer[10]; - if (-1 != mPort) { - PR_snprintf(portBuffer, 10, ":%d", mPort); - } - else { - portBuffer[0] = '\0'; - } - - PRInt32 plen = PL_strlen(mProtocol) + PL_strlen(mHost) + - PL_strlen(portBuffer) + PL_strlen(mFile) + 4; - if (mRef) { - plen += 1 + PL_strlen(mRef); - } - if (mSearch) { - plen += 1 + PL_strlen(mSearch); - } - - mSpec = (char *) PR_Malloc(plen + 1); - if (PL_strcmp(mProtocol, "about") == 0) { - PR_snprintf(mSpec, plen, "%s:%s", mProtocol, mFile); - } else { - PR_snprintf(mSpec, plen, "%s://%s%s%s", - mProtocol, ((nsnull != mHost) ? mHost : ""), portBuffer, - mFile); - } - - if (mRef) { - PL_strcat(mSpec, "#"); - PL_strcat(mSpec, mRef); - } - if (mSearch) { - PL_strcat(mSpec, "?"); - PL_strcat(mSpec, mSearch); - } -} - -//////////////////////////////////////////////////////////////////////////////// - -PRBool nsHttpUrlImpl::Equals(const nsIURI* aURL) const -{ - PRBool bIsEqual(PR_FALSE); - if (aURL) - { - NS_LOCK_INSTANCE(); - nsIHttpURL* otherURL; - if (NS_SUCCEEDED(((nsIURI*)aURL)->QueryInterface(kIHttpURLIID, (void**)&otherURL))) { - nsHttpUrlImpl* other = (nsHttpUrlImpl*)otherURL; - bIsEqual = PRBool((0 == PL_strcmp(mProtocol, other->mProtocol)) && - (0 == PL_strcasecmp(mHost, other->mHost)) && - (0 == PL_strcmp(mFile, other->mFile)) && - (0 == PL_strcmp(mRef, other->mRef)) && - (0 == PL_strcmp(mSearch, other->mSearch))); - NS_RELEASE(otherURL); - } - NS_UNLOCK_INSTANCE(); - } - return bIsEqual; -} - -nsresult nsHttpUrlImpl::GetProtocol(const char* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mProtocol; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetProtocol(const char *aNewProtocol) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mProtocol = nsCRT::strdup(aNewProtocol); - ReconstructSpec(); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetHost(const char* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mHost; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetHost(const char *aNewHost) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mHost = nsCRT::strdup(aNewHost); - ReconstructSpec(); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetFile(const char* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mFile; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetFile(const char *aNewFile) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mFile = nsCRT::strdup(aNewFile); - ReconstructSpec(); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetSpec(const char* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mSpec; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetSpec(const char *aNewSpec) -{ - // XXX is this right, or should we call ParseURL? - nsresult rv = NS_OK; -// NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - rv = ParseURL(aNewSpec); - PR_FREEIF(mSpec); - mSpec = nsCRT::strdup(aNewSpec); - NS_UNLOCK_INSTANCE(); - return rv; -} - -nsresult nsHttpUrlImpl::GetRef(const char* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mRef; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetRef(const char *aNewRef) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mRef = nsCRT::strdup(aNewRef); - ReconstructSpec(); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetHostPort(PRUint32 *result) const -{ - NS_LOCK_INSTANCE(); - *result = mPort; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetHostPort(PRUint32 aNewPort) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mPort = aNewPort; - ReconstructSpec(); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetSearch(const char* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mSearch; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetSearch(const char *aNewSearch) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mSearch = nsCRT::strdup(aNewSearch); - ReconstructSpec(); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetContainer(nsISupports* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mContainer; - NS_IF_ADDREF(mContainer); // getters must |AddRef| their result, even if they _didn't_ already own it - NS_UNLOCK_INSTANCE(); - if (mContainer) - return NS_OK; - else - return NS_ERROR_UNEXPECTED; // Indicate an error if no container -} - -nsresult nsHttpUrlImpl::SetContainer(nsISupports* container) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - // NS_IF_RELEASE(mContainer); - mContainer = container; - // NS_IF_ADDREF(mContainer); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetLoadAttribs(nsILoadAttribs* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mLoadAttribs; - NS_IF_ADDREF(*result); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetLoadAttribs(nsILoadAttribs* aLoadAttribs) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - mLoadAttribs = dont_QueryInterface(aLoadAttribs); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetLoadGroup(nsILoadGroup* *result) const -{ - NS_LOCK_INSTANCE(); - *result = mLoadGroup; - NS_IF_ADDREF(mLoadGroup); // getters must |AddRef| their result, even if they didn'st already own it - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetLoadGroup(nsILoadGroup* group) -{ - NS_ASSERTION(m_URL_s == nsnull, "URL has already been opened"); - NS_LOCK_INSTANCE(); - // NS_IF_RELEASE(mLoadGroup); - mLoadGroup = group; - // NS_IF_ADDREF(mLoadGroup); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetPostHeader(const char* name, const char* value) -{ - NS_LOCK_INSTANCE(); - // XXX - PR_ASSERT(0); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::SetPostData(nsIInputStream* input) -{ - NS_LOCK_INSTANCE(); - mPostData = dont_QueryInterface(input); - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -nsresult nsHttpUrlImpl::GetContentLength(PRInt32 *len) -{ - NS_LOCK_INSTANCE(); - *len = m_URL_s->content_length; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - - - -nsresult nsHttpUrlImpl::GetServerStatus(PRInt32 *status) -{ - NS_LOCK_INSTANCE(); - *status = m_URL_s->server_status; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - - -nsresult nsHttpUrlImpl::ToString(PRUnichar* *unichars) const -{ - nsAutoString string; - NS_LOCK_INSTANCE(); - - // XXX Special-case javascript: URLs for the moment. - // This code will go away when we actually start doing - // protocol-specific parsing. - if (PL_strcmp(mProtocol, "javascript") == 0) { - string.SetString(mSpec); - } else if (PL_strcmp(mProtocol, "about") == 0) { - string.SetString(mProtocol); - string.Append(':'); - string.Append(mFile); - } else { - string.SetLength(0); - string.Append(mProtocol); - string.Append("://"); - if (nsnull != mHost) { - string.Append(mHost); - if (0 < mPort) { - string.Append(':'); - string.Append(mPort, 10); - } - } - string.Append(mFile); - if (nsnull != mRef) { - string.Append('#'); - string.Append(mRef); - } - if (nsnull != mSearch) { - string.Append('?'); - string.Append(mSearch); - } - } - NS_UNLOCK_INSTANCE(); - *unichars = string.ToNewUnicode(); - return NS_OK; -} - diff --git a/mozilla/network/module/nsHttpUrl.h b/mozilla/network/module/nsHttpUrl.h deleted file mode 100644 index 22bd135fc4c..00000000000 --- a/mozilla/network/module/nsHttpUrl.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsHttpUrl_h__ -#define nsHttpUrl_h__ - -#include "nsNetStream.h" -#include "nsIURL.h" -#include "nsINetlibURL.h" -#include "nsIHttpURL.h" -#include "nsIPostToServer.h" -#include "nsCOMPtr.h" - -class nsHttpUrlImpl : public nsIURI, public nsINetlibURL, public nsIHttpURL, - public nsIPostToServer // XXX for now -{ -public: - // from nsIURI: - - NS_IMETHOD_(PRBool) Equals(const nsIURI *aURL) const; - NS_IMETHOD GetSpec(const char* *result) const; - NS_IMETHOD SetSpec(const char* spec); - NS_IMETHOD GetProtocol(const char* *result) const; - NS_IMETHOD SetProtocol(const char* protocol); - NS_IMETHOD GetHost(const char* *result) const; - NS_IMETHOD SetHost(const char* host); - NS_IMETHOD GetHostPort(PRUint32 *result) const; - NS_IMETHOD SetHostPort(PRUint32 port); - NS_IMETHOD GetFile(const char* *result) const; - NS_IMETHOD SetFile(const char* file); - NS_IMETHOD GetRef(const char* *result) const; - NS_IMETHOD SetRef(const char* ref); - NS_IMETHOD GetSearch(const char* *result) const; - NS_IMETHOD SetSearch(const char* search); - NS_IMETHOD GetContainer(nsISupports* *result) const; - NS_IMETHOD SetContainer(nsISupports* container); - NS_IMETHOD GetLoadAttribs(nsILoadAttribs* *result) const; - NS_IMETHOD SetLoadAttribs(nsILoadAttribs* loadAttribs); - NS_IMETHOD GetLoadGroup(nsILoadGroup* *result) const; - NS_IMETHOD SetLoadGroup(nsILoadGroup* group); - NS_IMETHOD SetPostHeader(const char* name, const char* value); - NS_IMETHOD SetPostData(nsIInputStream* input); - NS_IMETHOD GetContentLength(PRInt32 *len); - NS_IMETHOD GetServerStatus(PRInt32 *status); - NS_IMETHOD ToString(PRUnichar* *aString) const; - - // from nsINetlibURL: - - NS_IMETHOD GetURLInfo(URL_Struct_ **aResult) const; - NS_IMETHOD SetURLInfo(URL_Struct_ *URL_s); - - // nsHttpUrlImpl: - - typedef enum { - Send_None, - Send_File, - Send_Data, - Send_DataFromFile - } SendType; - - nsHttpUrlImpl(nsISupports* aContainer, nsILoadGroup* aGroup); - - NS_DECL_ISUPPORTS - - /* nsIPostToServer interface... */ - NS_IMETHOD SendFile(const char *aFile); - NS_IMETHOD SendData(const char *aBuffer, PRUint32 aLength); - NS_IMETHOD SendDataFromFile(const char *aFile); - - /* nsIHttpUrl interface... */ - - /* Handle http-equiv meta tags. */ - NS_IMETHOD AddMimeHeader(const char *name, const char *value); - - nsresult ParseURL(const nsString& aSpec, const nsIURI* aURL = nsnull); - -protected: - virtual ~nsHttpUrlImpl(); - - nsresult PostFile(const char *aFile); - void ReconstructSpec(void); - - /* Here's our link to the netlib world.... */ - URL_Struct *m_URL_s; - - SendType m_PostType; - char *m_PostBuffer; - PRInt32 m_PostBufferLength; - - char* mSpec; - char* mProtocol; - char* mHost; - char* mFile; - char* mRef; - char* mSearch; - PRInt32 mPort; - - nsCOMPtr<nsIInputStream> mPostData; - nsISupports* mContainer; // explicitly changed to no longer own its container - nsCOMPtr<nsILoadAttribs> mLoadAttribs; - nsILoadGroup* mLoadGroup; // explicitly changed to no longer own its group -}; - -#endif // nsHttpUrl_h__ diff --git a/mozilla/network/module/nsIConnectionInfo.h b/mozilla/network/module/nsIConnectionInfo.h deleted file mode 100644 index f339a03ca25..00000000000 --- a/mozilla/network/module/nsIConnectionInfo.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIConnectionInfo_h__ -#define nsIConnectionInfo_h__ - -#include "nsISupports.h" - -#define NS_ICONNECTIONINFO_IID \ -{ 0xa6cf9062, 0x15b3, 0x11d2, \ - { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 } } - -class nsIURI; -class nsIInputStream; -class nsIOutputStream; -class nsIStreamListener; - -class nsIConnectionInfo : public nsISupports { -public: - - static const nsIID& GetIID() { static nsIID iid = NS_ICONNECTIONINFO_IID; return iid; } - - /** - * Get the URL associated with this connection. - * - * @param aURL Out parameter - * @result NS_OK if successful - */ - NS_IMETHOD GetURL(nsIURI **aURL)=0; - - /** - * Set the URL associated with this connection. I added this because it is possible - * to keep a connection open and run different urls on the connection. (i.e. - * for mail protocols or other consumers of the pluggable protocol interface). - * - * @param aURL In parameter - * @result NS_OK if successful - */ - NS_IMETHOD SetURL(nsIURI *aURL) = 0; - - /** - * Get the input stream associated with this connection - * - * @param aStream Out parameter - * @result NS_OK if successful - */ - NS_IMETHOD GetInputStream(nsIInputStream **aStream)=0; - - /** - * Get the output stream associated with this connection - * - * @param aStream Out parameter - * @result NS_OK if successful - */ - NS_IMETHOD GetOutputStream(nsIOutputStream **aStream)=0; - - /** - * Get the stream listener associated with this connection - * - * @param aConsumer Out parameter - * @result NS_OK if successful - */ - NS_IMETHOD GetConsumer(nsIStreamListener **aConsumer)=0; -}; - -#endif // nsIConnectionInfo_h__ diff --git a/mozilla/network/module/nsINetFile.h b/mozilla/network/module/nsINetFile.h deleted file mode 100644 index 11c648fbb64..00000000000 --- a/mozilla/network/module/nsINetFile.h +++ /dev/null @@ -1,165 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef __nsINetFile_h -#define __nsINetFile_h -#include "nsISupports.h" -#include "nsString.h" -#include "prio.h" - -// These defines are for temporary use until we get a real dir manager. -#define USER_DIR_TOK "%USER%" -#define CACHE_DIR_TOK "%CACHE_D%" -#define DEF_DIR_TOK "%DEF_D%" - -#define COOKIE_FILE_TOK "%COOKIE_F%" -#ifdef XP_PC -#define COOKIE_FILE "cookies.txt" -#else -#define COOKIE_FILE "cookies" -#endif - -#ifdef CookieManagement -#define COOKIE_PERMISSION_FILE_TOK "%COOKIE_PERMISSION_F%" -#ifdef XP_PC -#define COOKIE_PERMISSION_FILE "cookperm.txt" -#else -#define COOKIE_PERMISSION_FILE "cookperm" -#endif -#endif - -#ifdef SingleSignon -#define SIGNON_FILE_TOK "%SIGNON_F%" -#ifdef XP_PC -#define SIGNON_FILE "signons.txt" -#else -#define SIGNON_FILE "signons" -#endif -#endif - -#define CACHE_DB_F_TOK "%CACHE_DB_F%" -#define CACHE_DB_FILE "fat.db" - -// {9E04ADC2-2B1D-11d2-B6EB-00805F8A2676} -#define NS_INETFILE_IID \ -{ 0x9e04adc2, 0x2b1d, 0x11d2, \ - {0xb6, 0xeb, 0x00, 0x80, 0x5f, 0x8a, 0x26, 0x76} } - -// Represents a file for use with nsINetFile routines. -typedef struct _nsFile { - PRFileDesc *fd; -} nsFile; - -// Represents a directory for use with nsINetFile routines. -typedef struct _nsDir { - PRDir *dir; -} nsDir; - -// Open flags. Used with nsINetFile::OpenFile. -typedef enum { - nsRead = 1, - nsWrite = 2, - nsReadWrite = 3, - nsReadBinary = 5, - nsWriteBinary = 6, - nsReadWriteBinary = 7, - nsOverWrite = 8 -} nsFileMode; - -class nsINetFile: public nsISupports { -public: - /* - * File methods - */ - - // Convert a generic file names into a platform file path - // Currently generic file location information is prepended to the - // begining of aName. For example, if I wanted to open the cookie file, - // I'd pass in "%USER%\cookies.txt . aName is platform specific. - NS_IMETHOD GetFilePath(const char *aName, char **aRes) = 0; - NS_IMETHOD GetTemporaryFilePath(const char *aName, char **aRes) = 0; - NS_IMETHOD GetUniqueFilePath(const char *aName, char **aRes) = 0; - NS_IMETHOD GetCacheFileName(char *aDirTok, char **aRes) = 0; - - // Open a file - NS_IMETHOD OpenFile(const char *aPath, nsFileMode aMode, - nsFile** aRes) = 0; - - // Close a file - NS_IMETHOD CloseFile(nsFile* aFile) = 0; - - // Read a file - NS_IMETHOD FileRead(nsFile *aFile, char **aBuf, - PRInt32 *aBuflen, - PRInt32 *aBytesRead) = 0; - - NS_IMETHOD FileReadLine(nsFile *aFile, char **aBuf, - PRInt32 *aBuflen, - PRInt32 *aBytesRead) = 0; - - // Write a file - NS_IMETHOD FileWrite(nsFile *aFile, const char *aBuf, - PRInt32 *aLen, - PRInt32 *aBytesWritten) = 0; - - // Sync a file with disk - NS_IMETHOD FileSync(nsFile *aFile) = 0; - - // Remove a file - NS_IMETHOD FileRemove(const char *aPath) = 0; - - // Rename a file - NS_IMETHOD FileRename(const char *aPathOld, const char *aPathNew) = 0; - - /* - * Directory Methods - */ - - // Open a directory - NS_IMETHOD OpenDir(const char *aPath, nsDir** aRes) = 0; - - // Close a directory - NS_IMETHOD CloseDir(nsDir *aDir) = 0; - - // Create a directory - NS_IMETHOD CreateDir(const char *aPath, PRBool aRecurse) = 0; - - // Assocaite a token with a directory. - NS_IMETHOD SetDirectory(const char *aToken, const char *aDir) = 0; - - // Associate a filename with a token, and optionally a dir token. - NS_IMETHOD SetFileAssoc(const char *aToken, const char *aFile, const char *aDirToken) = 0; - -}; - -/** - * Create an instance of the INetFile - * - */ -extern "C" NS_NET nsresult NS_NewINetFile(nsINetFile** aInstancePtrResult, - nsISupports* aOuter); - - -extern "C" NS_NET nsresult NS_InitINetFile(void); - -extern "C" NS_NET nsresult NS_ShutdownINetFile(); - -#endif //__nsINetFile_h diff --git a/mozilla/network/module/nsINetService.h b/mozilla/network/module/nsINetService.h deleted file mode 100644 index c1d594776cc..00000000000 --- a/mozilla/network/module/nsINetService.h +++ /dev/null @@ -1,267 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsINetService_h___ -#define nsINetService_h___ - -#include "nsString.h" -#include "nscore.h" -#include "nsISupports.h" -#include "nsIURL.h" -#include "nsIStreamListener.h" -#include "nsITransport.h" -#ifdef SingleSignon -#include "lo_ele.h" -#endif - -class nsIProtocolURLFactory; -class nsIProtocol; - - /* XXX: This should be moved to ns/xpcom/src/nserror.h */ -// #define NS_OK 0 -#define NS_FALSE NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 20) - - -/* cfb1a480-c78f-11d1-bea2-00805f8a66dc */ -#define NS_INETSERVICE_IID \ -{ 0xcfb1a480, 0xc78f, 0x11d1, \ - {0xbe, 0xa2, 0x00, 0x80, 0x5f, 0x8a, 0x66, 0xdc} } - -/* {3F1BFE70-4D9C-11d2-9E7E-006008BF092E} */ -#define NS_NETSERVICE_CID \ -{ 0x3f1bfe70, 0x4d9c, 0x11d2, \ - {0x9e, 0x7e, 0x00, 0x60, 0x08, 0xbf, 0x09, 0x2e} } - - -/** - * The nsINetService interface provides an API to the networking service. - * This is a preliminary interface which <B>will</B> change over time! - * - */ -struct nsINetService : public nsISupports -{ - static const nsIID& GetIID() { static nsIID iid = NS_INETSERVICE_IID; return iid; } - /** - * Initiate an asynchronous URL load.<BR><BR> - * - * @param aUrl The URL to load. - * @param aConsumer An object that will receive notifications during the - * URL loading. This parameter cannot be NULL. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD OpenStream(nsIURI *aUrl, - nsIStreamListener *aConsumer) = 0; - - /** - * Initiate a synchronous URL load.<BR><BR> - * - * @param aUrl The URL to load. - * @param aConsumer An object that will receive notifications during the - * URL loading. This parameter can be NULL if - * notifications are not required. - * @param aNewStream An output parameter to recieve the blocking stream - * created for this URL load. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD OpenBlockingStream(nsIURI *aUrl, - nsIStreamListener *aConsumer, - nsIInputStream **aNewStream) = 0; - - /** - * Interrupt an asynchronous URL load.<BR><BR> - * - * @param aUrl The URL to stop loading. - * @return Returns NS_OK if successful, or NS_ERROR_FAILURE if an error occurred. - */ - NS_IMETHOD InterruptStream(nsIURI* aURL) = 0; - - /** - * Get the complete cookie string associated with the URL - * - * @param aURL The URL for which to get the cookie string - * @param aCookie The string object which will hold the result - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetCookieString(nsIURI *aURL, nsString& aCookie)=0; - - /** - * Set the cookie string associated with the URL - * - * @param aURL The URL for which to set the cookie string - * @param aCookie The string to set - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD SetCookieString(nsIURI *aURL, const nsString& aCookie)=0; - - NS_IMETHOD Cookie_DisplayCookieInfoAsHTML()=0; - NS_IMETHOD Cookie_CookieViewerReturn(nsAutoString results)=0; - NS_IMETHOD Cookie_GetCookieListForViewer(nsString& aCookieList)=0; - NS_IMETHOD Cookie_GetPermissionListForViewer(nsString& aPermissionList)=0; - - /** - * Get the http proxy used for http transactions. - * - * @param aProxyHTTP The url used as a proxy. The url is of the form - * "host.server:port". - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetProxyHTTP(nsString& aProxyHTTP)=0; - - /** - * Set the http proxy to be used for http transactions. - * - * @param aProxyHTTP The url to use as a proxy. The url is of the form - * "host.server:port". - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD SetProxyHTTP(nsString& aProxyHTTP)=0; - - /** - * Get the http version number setting. - * - * @param aOneOne If true, the client is sending HTTP/1.1, if false HTTP/1.0 - * is being sent. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetHTTPOneOne(PRBool& aOneOne)=0; - - /** - * Set the http version number setting. - * - * @param aSendOneOne True if you want the http version number sent out - * to be 1.1, false if you want it to be 1.0. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD SetHTTPOneOne(PRBool aSendOneOne)=0; - - /** - * Get the application name string that will be used as part - * of a HTTP request. - * - * @param aAppCodeName The application name string. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetAppCodeName(nsString& aAppCodeName)=0; - - /** - * Get the application version string that will be used as part - * of a HTTP request. - * - * @param aAppVersion The application version string. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetAppVersion(nsString& aAppVersion)=0; - - /** - * Get the application name. - * - * @param aAppName The application name. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetAppName(nsString& aAppName)=0; - - /** - * Get the translation of the application. The value for language - * is usually a 2-letter code such as "en" and occasionally a - * five-character code to indicate a language subtype, such as "zh_CN". - * - * @param aLanguage The application language. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetLanguage(nsString& aLanguage)=0; - - /** - * Get the current platform (machine type). - * - * @param aPlatform The current platform. - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetPlatform(nsString& aPlatform)=0; - - /** - * Get the HTTP advertised user agent string. - * - * @param aUA The current user agent string being sent out in HTTP requests. - * @retrun Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD GetUserAgent(nsString& aUA)=0; - - /** - * Add a string to the user agent AppVersion. - * - * @param aCustom The string to be inserted into the AppVersion portion - * of the user agent string. A user-agent of the form: - * Mozilla/x.x [en] (OS; I) becomes Mozilla/x.x [en]C-aCustom (OS; I) - * @return Returns NS_OK if successful, or NS_FALSE if an error occurred. - */ - NS_IMETHOD SetCustomUserAgent(nsString aCustom)=0; - - // Managing pluggable protocols: - - NS_IMETHOD RegisterProtocol(const nsString& aName, - nsIProtocolURLFactory* aProtocolURLFactory, - nsIProtocol* aProtocol) = 0; - - NS_IMETHOD UnregisterProtocol(const nsString& aName) = 0; - - NS_IMETHOD GetProtocol(const nsString& aName, - nsIProtocolURLFactory* *aProtocolURLFactory, - nsIProtocol* *aProtocol) = 0; - - NS_IMETHOD CreateURL(nsIURI* *aURLResult, - const nsString& aSpec, - const nsIURI* aContextURL = nsnull, - nsISupports* aContainer = nsnull, - nsILoadGroup* aGroup = nsnull) = 0; - - /** - * Protocol connection pools should use this call into the service manager to - * produce a transport interface on a socket. You need to pass in a port and a host - * name to associate with the socket. - */ - - NS_IMETHOD CreateSocketTransport(nsITransport **aTransport, PRUint32 aPortToUse, const char * aHostName) = 0; - - /** - * Protocol connection pools should use this call into the service manager to produce - * a transport interface to a file based socket. You need to pass in the name of the file - * you want to associate with the socket transport - */ - - NS_IMETHOD CreateFileSocketTransport(nsITransport **aTransport, const char * aFileName) = 0; - - NS_IMETHOD AreThereActiveConnections(void) = 0; -}; - - -/** - * Create an instance of the INetService - * - */ -extern "C" NS_NET nsresult NS_NewINetService(nsINetService** aInstancePtrResult, - nsISupports* aOuter); - -extern "C" NS_NET nsresult NS_InitINetService(); - -extern "C" NS_NET nsresult NS_ShutdownINetService(); - -#endif /* nsINetService_h___ */ diff --git a/mozilla/network/module/nsINetSupport.h b/mozilla/network/module/nsINetSupport.h deleted file mode 100644 index c0b76430e72..00000000000 --- a/mozilla/network/module/nsINetSupport.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef __nsINetSupport_h -#define __nsINetSupport_h -#include "nsString.h" - -// {4F065980-015B-11d2-AA0C-00805F8A7AC4} -#define NS_INETSUPPORT_IID \ -{ 0x4f065980, 0x15b, 0x11d2, \ - {0xaa, 0xc, 0x0, 0x80, 0x5f, 0x8a, 0x7a, 0xc4} } - -class nsINetSupport: public nsISupports { -public: - NS_IMETHOD_(void) Alert(const nsString &aText) = 0; - - NS_IMETHOD_(PRBool) Confirm(const nsString &aText) = 0; - - NS_IMETHOD_(PRBool) Prompt(const nsString &aText, - const nsString &aDefault, - nsString &aResult) = 0; - - NS_IMETHOD_(PRBool) PromptUserAndPassword(const nsString &aText, - nsString &aUser, - nsString &aPassword) = 0; - - NS_IMETHOD_(PRBool) PromptPassword(const nsString &aText, - nsString &aPassword) = 0; -}; - -#endif diff --git a/mozilla/network/module/nsINetlibURL.h b/mozilla/network/module/nsINetlibURL.h deleted file mode 100644 index e1b94dab3a4..00000000000 --- a/mozilla/network/module/nsINetlibURL.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsINetlibURL_h___ -#define nsINetlibURL_h___ - -#include "nsIURL.h" -#include "net.h" - -/* forward declaration */ -struct URL_Struct_; - -#define NS_INETLIBURL_IID \ -{ /* bcf62ef0-3267-11d2-8163-006008119d7a */ \ - 0xbcf62ef0, \ - 0x3267, \ - 0x11d2, \ - {0x81, 0x63, 0x00, 0x60, 0x08, 0x11, 0x9d, 0x7a} \ -} - -/** - * The nsINetlibURL interface provides browser-private access to URL - * internals and integration with netlib without exposing the - * implementation. - */ -class nsINetlibURL : public nsISupports { -public: - static const nsIID& GetIID() { static nsIID iid = NS_INETLIBURL_IID; return iid; } - - NS_IMETHOD GetURLInfo(URL_Struct_ **aResult) const = 0; - NS_IMETHOD SetURLInfo(URL_Struct_ *URL_s) = 0; - -}; - -#endif /* nsINetlibURL_h___ */ diff --git a/mozilla/network/module/nsIProtocol.h b/mozilla/network/module/nsIProtocol.h deleted file mode 100644 index ec210e6c515..00000000000 --- a/mozilla/network/module/nsIProtocol.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIProtocol_h___ -#define nsIProtocol_h___ - -#include "nsISupports.h" -#include "nscore.h" - -#define NS_IPROTOCOL_IID \ -{ /* 677d9a90-93ee-11d2-816a-006008119d7a */ \ - 0x677d9a90, \ - 0x93ee, \ - 0x11d2, \ - {0x81, 0x6a, 0x00, 0x60, 0x08, 0x11, 0x9d, 0x7a} \ -} - -class nsIProtocol : public nsISupports -{ -public: - - // XXX Other methods will follow when we work out pluggable protocols, - // but for now, this is just a means to parse and construct URL objects. - -}; - -#endif /* nsIIProtocol_h___ */ diff --git a/mozilla/network/module/nsIProtocolConnection.h b/mozilla/network/module/nsIProtocolConnection.h deleted file mode 100644 index aad1a890b61..00000000000 --- a/mozilla/network/module/nsIProtocolConnection.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIProtocolConnection_h___ -#define nsIProtocolConnection_h___ - -#include "nscore.h" -#include "nsISupports.h" - - -/* forward declaration */ -struct URL_Struct_; - -/* 121CC0F1-EA26-11d1-BEAE-00805F8A66DC */ -#define NS_IPROTOCOLCONNECTION_IID \ -{ 0x121cc0f1, 0xea26, 0x11d1, \ - { 0xbe, 0xae, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0xdc } } - - - -class nsIProtocolConnection : public nsISupports -{ -public: - NS_IMETHOD InitializeURLInfo(URL_Struct_ *URL_s) = 0; - NS_IMETHOD GetURLInfo(URL_Struct_ **aResult) = 0; -}; - -#endif /* nsIIProtocolConnection_h___ */ diff --git a/mozilla/network/module/nsIProtocolURLFactory.h b/mozilla/network/module/nsIProtocolURLFactory.h deleted file mode 100644 index 0a6654fd3c5..00000000000 --- a/mozilla/network/module/nsIProtocolURLFactory.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIProtocolURLFactory_h___ -#define nsIProtocolURLFactory_h___ - -#include "nsISupports.h" -#include "nscore.h" - -class nsString; -class nsIURI; -class nsILoadGroup; - -#define NS_IPROTOCOLURLFACTORY_IID \ -{ /* aed57ad0-705e-11d2-8166-006008119d7a */ \ - 0xaed57ad0, \ - 0x705e, \ - 0x11d2, \ - {0x81, 0x66, 0x00, 0x60, 0x08, 0x11, 0x9d, 0x7a} \ -} - -/** - * nsIProtocolURLFactory deals with protocol-specific URL parsing. It - * constructs a URL that implements the nsIURI interface and that gets - * loaded by a corresponding protocol handler. - * - * Note that one nsIProtocolURLFactory implementation might handle the - * URL syntax for several different protocols, e.g. http, https, file -- - * all of these protocol's URL syntax looks the same. - */ -class nsIProtocolURLFactory : public nsISupports -{ -public: - - NS_IMETHOD CreateURL(nsIURI* *aResult, - const nsString& aSpec, - const nsIURI* aContextURL = nsnull, - nsISupports* aContainer = nsnull, - nsILoadGroup* aGroup = nsnull) = 0; -}; - -#endif /* nsIIProtocolURLFactory_h___ */ diff --git a/mozilla/network/module/nsIRefreshUrl.h b/mozilla/network/module/nsIRefreshUrl.h deleted file mode 100644 index b34e8a13cef..00000000000 --- a/mozilla/network/module/nsIRefreshUrl.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIRefreshUrl_h___ -#define nsIRefreshUrl_h___ - -#include "nscore.h" -#include "nsISupports.h" -#include "nsIURL.h" - -#include "nspr.h" - -/* 69EFC430-2EFE-11d2-9E5D-006008BF092E */ -#define NS_IREFRESHURL_IID \ -{ 0x69efc430, 0x2efe, 0x11d2, \ - { 0x9e, 0x5d, 0x0, 0x60, 0x8, 0xbf, 0x9, 0x2e } } - -struct nsIRefreshUrl : public nsISupports -{ - /** - * Reloads a url after waiting millis milliseconds. - * - * @param url The url to refresh. - * @param millis The number of milliseconds to wait. - * @param repeat Do you want the url to be repeatedly refreshed every millis milliseconds. - */ - NS_IMETHOD RefreshURL(nsIURI *url, PRInt32 millis, PRBool repeat) = 0; - - /** - * Cancels all timer loads. - */ - NS_IMETHOD CancelRefreshURLTimers(void) = 0; -}; - -#endif /* nsIRefreshUrl_h___ */ diff --git a/mozilla/network/module/nsIRelatedLinks.h b/mozilla/network/module/nsIRelatedLinks.h deleted file mode 100644 index 6d359a831d8..00000000000 --- a/mozilla/network/module/nsIRelatedLinks.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef __nsIRelatedLinks_h -#define __nsIRelatedLinks_h - -#include "nscore.h" -#include "nsISupports.h" - -#include "nspr.h" - -typedef struct _RL_Window* RL_Window; -typedef struct _RL_Item* RL_Item; -typedef uint8 RL_ItemType; - -#define RL_CONTAINER 1 -#define RL_SEPARATOR 2 -#define RL_LINK 3 -#define RL_LINK_NEW_WINDOW 4 - -typedef void (*RLCallBackProc)(void* pdata, RL_Window win); - -/* 1A0B6FA1-EA25-11d1-BEAE-00805F8A66DC */ - -#define NS_IRELATEDLINKS_IID \ -{ 0x2ae42530, 0x1b90, 0x11d2, \ - { 0x84, 0xb6, 0x00, 0x80, 0x5f, 0x8a, 0x1d, 0xb7 } } - -class nsIRelatedLinks : public nsISupports -{ -public: - - virtual void DestroyRLWindow(RL_Window win) = 0; - - virtual void SetRLWindowURL(RL_Window win, char* url) = 0; - - virtual RL_Item WindowItems (RL_Window win) = 0; - - virtual RL_Item NextItem(RL_Item item) = 0; - - virtual RL_Item ItemChild(RL_Item item) = 0; - - virtual uint8 ItemCount(RL_Window win) = 0; - - virtual RL_ItemType GetItemType(RL_Item item) = 0; - - virtual char* ItemName(RL_Item item) = 0; - - virtual char* ItemUrl(RL_Item item) = 0; - - virtual RL_Window MakeRLWindowWithCallback(RLCallBackProc callBack, void*fedata) = 0; - -}; - -extern "C" void RL_Init(); -extern "C" nsIRelatedLinks * NS_NewRelatedLinks(); - -#endif - - diff --git a/mozilla/network/module/nsIURLGroup.h b/mozilla/network/module/nsIURLGroup.h deleted file mode 100644 index 6f3c3c1220b..00000000000 --- a/mozilla/network/module/nsIURLGroup.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIURLGroup_h__ -#define nsIURLGroup_h__ - -#include "nsISupports.h" - -class nsString; -class nsIURI; -class nsIInputStream; -class nsIStreamListener; -class nsILoadAttribs; - -/* {a4071430-5263-11d2-929b-00105a1b0d64} */ -#define NS_ILOADGROUP_IID \ -{ 0xa4071430, 0x5263, 0x11d2, \ - {0x92, 0x9b, 0x00, 0x10, 0x5a, 0x1b, 0x0d, 0x64} } - -class nsILoadGroup : public nsISupports -{ -public: - - static const nsIID& GetIID() { static nsIID iid = NS_ILOADGROUP_IID; return iid; } - - /** - * Create a new URL, setting its LoadAttributes to the default - * LoadAttributes for the group. - * - * If aBaseURL is non-null then aSpec is interpreted as relative to - * aBaseURL. - * - * @param aInstancePtrResult Newly created URL. - * @param aBaseURL An existing URL to be treated as a base - * @param aSpec String specification of the URL - * @param aContainer An ISupports interface associated with the - * URL. - * @return Returns NS_OK if successful, otherwise NS_ERROR_FAILURE... - */ - NS_IMETHOD CreateURL(nsIURI** aInstancePtrResult, - nsIURI* aBaseURL, - const nsString& aSpec, - nsISupports* aContainer) = 0; - - /** - * Initiate an asynchronous URL load... - * - * @param aUrl The URL to be loaded. - * @param aConsumer The nsIStreamListener where the data and loading - * notifications will be sent. - * - * @return Returns NS_OK if successful, otherwise NS_ERROR_FAILURE. - */ - NS_IMETHOD OpenStream(nsIURI *aUrl, - nsIStreamListener *aConsumer) = 0; - - /** - * Get the nsILoadAttributes for this nsILoadGroup and its children... - * - * @param aLoadAttribs Result parameter containing the nsILoadAttributes - * instance. - * - * @return Returns NS_OK if successful, otherwise NS_ERROR_FAILURE. - */ - NS_IMETHOD GetDefaultLoadAttributes(nsILoadAttribs*& aLoadAttribs) = 0; - - /** - * Set the nsILoadAttributes for this nsILoadGroup and its children... - * - * @param aLoadAttribs nsILoadAttributes instance to be used by this - * nsILoadGroup and its children. - * - * @return Returns NS_OK if successful, otherwise NS_ERROR_FAILURE. - */ - NS_IMETHOD SetDefaultLoadAttributes(nsILoadAttribs* aLoadAttribs) = 0; - - /** - * Add a child to an nsILoadGroup. - * - * @param aGroup The nsILoadGroup to be added as a child. When the - * child is added it will receive the nsILoadAttribs - * of its parent... - * - * @return Returns NS_OK if successful, otherwise NS_ERROR_FAILURE. - */ - NS_IMETHOD AddChildGroup(nsILoadGroup* aGroup) = 0; - - /** - * Remove a child from an nsILoadGroup. - * - * @param aGroup The nsILoadGroup to be removed. - * - * @return Returns NS_OK if successful, otherwise NS_ERROR_FAILURE. - */ - NS_IMETHOD RemoveChildGroup(nsILoadGroup* aGroup) = 0; -}; - -#endif /* nsIURLGroup_h__ */ diff --git a/mozilla/network/module/nsIUnicharStreamLoader.h b/mozilla/network/module/nsIUnicharStreamLoader.h deleted file mode 100644 index 862fec45c90..00000000000 --- a/mozilla/network/module/nsIUnicharStreamLoader.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef nsIUnicharStreamLoader_h___ -#define nsIUnicharStreamLoader_h___ - -#include "nsISupports.h" -#include "nsString.h" - -#define NS_IUNICHARSTREAMLOADER_IID \ - {0xa6cf90d8, 0x15b3, 0x11d2, \ - {0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32}} - -class nsIUnicharStreamLoader; -class nsIURI; - -/** - * Funtion registered with the stream loader. This function is called - * when the stream is done loading (or has aborted). - * - * @param aLoader the loader - * @param aData the result of the load as a unicode character string - * @param aRef the opaque data passed to the loader - * @param aStatus the completion status of the stream - */ -typedef void (*nsStreamCompleteFunc)(nsIUnicharStreamLoader* aLoader, - nsString& aData, - void* aRef, - nsresult aStatus); - -/** - * The purpose of this interface is to provide a mechanism for a - * byte stream to be loaded asynchronously from a URL, the stream - * data to be accumulated, and the result to be returned as a - * unicode character string. - */ -class nsIUnicharStreamLoader : public nsISupports { -public: - /** - * Get the number of bytes read so far. - * - * @param aNumBytes out parameter to get number of unicode - * characters read. - */ - NS_IMETHOD GetNumCharsRead(PRInt32* aNumChars) = 0; -}; - -/** - * Start loading the specified URL and accumulating the stream data. - * When the stream is completed, the result is sent to the complete - * function as a unicode character string. - * - * @param aInstancePtrResult new stream loader - * @param aURL the URL to load - * @param aFunc the function to call on termination of stream loading - * @param aRef an opaque value that will later be sent to the termination - * function - */ -extern NS_NET nsresult NS_NewUnicharStreamLoader(nsIUnicharStreamLoader** aInstancePtrResult, - nsIURI* aURL, - nsStreamCompleteFunc aFunc, - void* aRef); - -#endif /* nsIUnicharStreamLoader_h___ */ diff --git a/mozilla/network/module/nsLoadAttribs.cpp b/mozilla/network/module/nsLoadAttribs.cpp deleted file mode 100644 index aff24f5565c..00000000000 --- a/mozilla/network/module/nsLoadAttribs.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsString.h" -#include "nsILoadAttribs.h" -#include "prtypes.h" -#include "prmem.h" -#include "plstr.h" - -#if defined(XP_PC) -#include <windows.h> // Needed for Interlocked APIs defined in nsISupports.h -#endif /* XP_PC */ - - -// nsLoadAttribs definition. -class nsLoadAttribs : public nsILoadAttribs { -public: - nsLoadAttribs(); - - // nsISupports - NS_DECL_ISUPPORTS - - // nsILoadAttribs - NS_IMETHOD Clone(nsILoadAttribs* aLoadAttribs); - - NS_IMETHOD SetBypassProxy(PRBool aBypass); - NS_IMETHOD GetBypassProxy(PRBool *aBypass); - - NS_IMETHOD SetLocalIP(const PRUint32 aIP); - NS_IMETHOD GetLocalIP(PRUint32 *aIP); - - NS_IMETHOD SetReloadType(nsURLReloadType aType); - NS_IMETHOD GetReloadType(nsURLReloadType* aResult); - - NS_IMETHOD SetLoadType(nsURLLoadType aType); - NS_IMETHOD GetLoadType(nsURLLoadType* aResult); - - // Byte Range Support - NS_IMETHOD SetByteRangeHeader(const char *aByteRangeHeader); - NS_IMETHOD GetByteRangeHeader(char** aByteRangeHeader); - -protected: - virtual ~nsLoadAttribs(); - -private: - PRBool mBypass; - PRUint32 mLocalIP; - nsURLLoadType mLoadType; - nsURLReloadType mReloadType; - char* mByteRangeHeader; -}; - -// nsLoadAttribs Implementation - -static NS_DEFINE_IID(kILoadAttribsIID, NS_ILOAD_ATTRIBS_IID); -NS_IMPL_THREADSAFE_ISUPPORTS(nsLoadAttribs, kILoadAttribsIID); - -nsLoadAttribs::nsLoadAttribs() -{ - NS_INIT_REFCNT(); - - mBypass = PR_FALSE; - mLocalIP = 0; - mLoadType = nsURLLoadNormal; - mReloadType = nsURLReload; - mByteRangeHeader = nsnull; -} - -nsLoadAttribs::~nsLoadAttribs() -{ - PR_FREEIF(mByteRangeHeader); -} - -NS_IMETHODIMP -nsLoadAttribs::Clone(nsILoadAttribs* aLoadAttribs) -{ - nsresult rv = NS_OK; - - if (nsnull == aLoadAttribs) { - rv = NS_ERROR_NULL_POINTER; - } else { - NS_LOCK_INSTANCE(); - - aLoadAttribs->GetBypassProxy(&mBypass); - aLoadAttribs->GetLocalIP(&mLocalIP); - aLoadAttribs->GetReloadType(&mReloadType); - - NS_UNLOCK_INSTANCE(); - } - return rv; - -} - -NS_IMETHODIMP -nsLoadAttribs::SetBypassProxy(PRBool aBypass) -{ - NS_LOCK_INSTANCE(); - mBypass = aBypass; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -NS_IMETHODIMP -nsLoadAttribs::GetBypassProxy(PRBool *aBypass) -{ - nsresult rv = NS_OK; - - if (nsnull == aBypass) { - rv = NS_ERROR_NULL_POINTER; - } else { - NS_LOCK_INSTANCE(); - *aBypass = mBypass; - NS_UNLOCK_INSTANCE(); - } - return rv; -} - -NS_IMETHODIMP -nsLoadAttribs::SetLocalIP(const PRUint32 aLocalIP) -{ - NS_LOCK_INSTANCE(); - mLocalIP = aLocalIP; - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -NS_IMETHODIMP -nsLoadAttribs::GetLocalIP(PRUint32 *aLocalIP) -{ - nsresult rv = NS_OK; - - if (nsnull == aLocalIP) { - rv = NS_ERROR_NULL_POINTER; - } else { - NS_LOCK_INSTANCE(); - *aLocalIP = mLocalIP; - NS_UNLOCK_INSTANCE(); - } - return rv; -} - -NS_IMETHODIMP -nsLoadAttribs::SetReloadType(nsURLReloadType aType) -{ - nsresult rv = NS_OK; - - if ((aType < nsURLReload) || (aType >= nsURLReloadMax)) { - rv = NS_ERROR_ILLEGAL_VALUE; - } else { - NS_LOCK_INSTANCE(); - mReloadType = aType; - NS_UNLOCK_INSTANCE(); - } - return rv; -} - -NS_IMETHODIMP -nsLoadAttribs::GetReloadType(nsURLReloadType* aResult) -{ - nsresult rv = NS_OK; - - if (nsnull == aResult) { - rv = NS_ERROR_NULL_POINTER; - } else { - NS_LOCK_INSTANCE(); - *aResult = mReloadType; - NS_UNLOCK_INSTANCE(); - } - return rv; -} - -NS_IMETHODIMP -nsLoadAttribs::SetLoadType(nsURLLoadType aType) -{ - nsresult rv = NS_OK; - - if ((aType < nsURLLoadNormal) || (aType >= nsURLLoadMax)) { - rv = NS_ERROR_ILLEGAL_VALUE; - } else { - NS_LOCK_INSTANCE(); - mLoadType = aType; - NS_UNLOCK_INSTANCE(); - } - return rv; -} - -NS_IMETHODIMP -nsLoadAttribs::GetLoadType(nsURLLoadType* aResult) -{ - nsresult rv = NS_OK; - - if (nsnull == aResult) { - rv = NS_ERROR_NULL_POINTER; - } else { - NS_LOCK_INSTANCE(); - *aResult = mLoadType; - NS_UNLOCK_INSTANCE(); - } - return rv; -} - -NS_IMETHODIMP -nsLoadAttribs::SetByteRangeHeader(const char* aByteRangeHeader) -{ - NS_LOCK_INSTANCE(); - - // Free the old range header if any... - PR_FREEIF(mByteRangeHeader); - mByteRangeHeader = nsnull; - - if (nsnull != aByteRangeHeader) { - mByteRangeHeader = PL_strdup(aByteRangeHeader); - } - - NS_UNLOCK_INSTANCE(); - return NS_OK; -} - -NS_IMETHODIMP -nsLoadAttribs::GetByteRangeHeader(char **aByteRangeHeader) -{ - nsresult rv = NS_OK; - - NS_LOCK_INSTANCE(); - - if (nsnull == aByteRangeHeader) { - rv = NS_ERROR_NULL_POINTER; - } else if (nsnull != mByteRangeHeader) { - *aByteRangeHeader = PL_strdup(mByteRangeHeader); - } else { - *aByteRangeHeader = nsnull; - } - - NS_UNLOCK_INSTANCE(); - return rv; -} - -// Creation routines -NS_NET nsresult NS_NewLoadAttribs(nsILoadAttribs** aInstancePtrResult) { - nsILoadAttribs* it; - - NS_NEWXPCOM(it, nsLoadAttribs); - if (nsnull == it) { - return NS_ERROR_OUT_OF_MEMORY; - } - return it->QueryInterface(kILoadAttribsIID, (void **) aInstancePtrResult); -} diff --git a/mozilla/network/module/nsNetFactory.cpp b/mozilla/network/module/nsNetFactory.cpp deleted file mode 100644 index e2b1bcc2c5b..00000000000 --- a/mozilla/network/module/nsNetFactory.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nscore.h" -#include "nsIFactory.h" -#include "nsISupports.h" -#include "nsINetService.h" -#include "nsNetService.h" -#include "nsIServiceManager.h" -#include "nsIComponentManager.h" - -/* This implementation of the network service factory is presently - * only taking advantage of the service retrieval benefit that the - * nsINetService interface provides. The module initialization and - * unloading is still bound to main program execution and closing. - * Once we break this dependence, the - * nsNetFactory will also appropriately handle loading/initializing/ - * unloading of the library. - */ - -static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID); -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static NS_DEFINE_IID(kIFactoryIID, NS_IFACTORY_IID); - -extern nsNetlibService *gNetlibService; // See nsNetService.cpp - -class nsNetFactory : public nsIFactory -{ - public: - // nsISupports methods - NS_IMETHOD QueryInterface(const nsIID &aIID, - void **aResult); - NS_IMETHOD_(nsrefcnt) AddRef(void); - NS_IMETHOD_(nsrefcnt) Release(void); - - // nsIFactory methods - NS_IMETHOD CreateInstance(nsISupports *aOuter, - const nsIID &aIID, - void **aResult); - - NS_IMETHOD LockFactory(PRBool aLock); - - nsNetFactory(const nsCID &aClass); - - protected: - virtual ~nsNetFactory(); - - private: - nsrefcnt mRefCnt; - nsCID mClassID; -}; - -nsNetFactory::nsNetFactory(const nsCID &aClass) -{ - mRefCnt = 0; - mClassID = aClass; -} - -nsNetFactory::~nsNetFactory() -{ -} - -nsresult nsNetFactory::QueryInterface(const nsIID &aIID, - void **aResult) -{ - if (aResult == NULL) { - return NS_ERROR_NULL_POINTER; - } - - // Always NULL result, in case of failure - *aResult = NULL; - - if (aIID.Equals(kISupportsIID)) { - *aResult = (void *)(nsISupports*)this; - } else if (aIID.Equals(kIFactoryIID)) { - *aResult = (void *)(nsIFactory*)this; - } - - if (*aResult == NULL) { - return NS_NOINTERFACE; - } - - AddRef(); // Increase reference count for caller - return NS_OK; -} - -NS_IMPL_ADDREF(nsNetFactory); -NS_IMPL_RELEASE(nsNetFactory); - -nsresult nsNetFactory::CreateInstance(nsISupports *aOuter, - const nsIID &aIID, - void **aResult) -{ - nsresult res; - if (aResult == NULL) { - return NS_ERROR_NULL_POINTER; - } - - *aResult = NULL; - - if (mClassID.Equals(kNetServiceCID)) { -#ifdef XP_PC - /* This ifdef fixes bug 2414. Unix and mac initialize NS_InitINetService in - NS_NewINetService so this initialization was being done twice. Therefore - to fix the bug we are ifdef-ing this section to be done for windows only */ - - // No need create a new one if we've already got one. - if (!gNetlibService) { - res = NS_InitINetService(); - if (res != NS_OK) - return NS_ERROR_FAILURE; - } -#endif - - // Hook the caller up. - res = NS_NewINetService((nsINetService**)aResult, aOuter); - } - return res; -} - -nsresult nsNetFactory::LockFactory(PRBool aLock) -{ - // Not implemented in simplest case. - return NS_OK; -} - -// return the proper factory to the caller -#if defined(XP_MAC) && defined(MAC_STATIC) -extern "C" NS_NET nsresult -NSGetFactory_NETLIB_DLL(nsISupports* serviceMgr, - const nsCID &aClass, - const char *aClassName, - const char *aProgID, - nsIFactory **aFactory) -#else -extern "C" NS_NET nsresult -NSGetFactory(nsISupports* serviceMgr, - const nsCID &aClass, - const char *aClassName, - const char *aProgID, - nsIFactory **aFactory) -#endif -{ - if (nsnull == aFactory) { - return NS_ERROR_NULL_POINTER; - } - - *aFactory = new nsNetFactory(aClass); - - if (nsnull == aFactory) { - return NS_ERROR_OUT_OF_MEMORY; - } - - return (*aFactory)->QueryInterface(kIFactoryIID, (void**)aFactory); -} diff --git a/mozilla/network/module/nsNetFile.cpp b/mozilla/network/module/nsNetFile.cpp deleted file mode 100644 index 8c4e758a1c9..00000000000 --- a/mozilla/network/module/nsNetFile.cpp +++ /dev/null @@ -1,962 +0,0 @@ -#include "nsNetFile.h" -#include "prmem.h" -#include "nsString.h" -#include "plstr.h" -#include "prerror.h" - -#if !defined(XP_UNIX) && !defined(XP_BEOS) -#include "direct.h" -#endif - -#include <time.h> - -#ifndef _MAX_PATH -#define _MAX_PATH 1024 -#endif - -char USER_DIR[_MAX_PATH]; -char CACHE_DIR[_MAX_PATH]; -char DEF_DIR[_MAX_PATH]; - -static NS_DEFINE_IID(kINetFileIID, NS_INETFILE_IID); - -NS_IMPL_ISUPPORTS(nsNetFile, kINetFileIID); - -typedef struct _nsFileAssoc { - nsString name; - nsString dirTok; -} nsFileAssoc; - -// Comparison routine for the fileAssoc objects. -PR_IMPLEMENT(int) -PL_CompareFileAssoc(const void *v1, const void *v2) -{ - nsFileAssoc *a = (nsFileAssoc*)v1; - nsFileAssoc *b = (nsFileAssoc*)v2; - - return *a->name.GetUnicode() == *b->name.GetUnicode(); -} - -nsNetFile::nsNetFile() { - NS_INIT_REFCNT(); -#ifdef XP_PC - mDirDel = '\\'; -#elif XP_MAC - mDirDel = ':'; -#else - mDirDel = '/'; -#endif - - mTokDel = '%'; - - mHTDirs = PL_NewHashTable(5, PL_HashString, PL_CompareStrings, - PL_CompareStrings, nsnull, nsnull); - - mHTFiles = PL_NewHashTable(10, PL_HashString, PL_CompareStrings, - PL_CompareFileAssoc, nsnull, nsnull); -} - -PR_CALLBACK PRIntn -NS_RemoveStringEntries(PLHashEntry* he, PRIntn i, void* arg) -{ - char *entry = (char*)he->value; - - NS_ASSERTION(entry != nsnull, "null entry"); - PR_Free(entry); - return HT_ENUMERATE_REMOVE; -} - -nsNetFile::~nsNetFile() { - // Clear the hash table. - PL_HashTableEnumerateEntries(mHTDirs, NS_RemoveStringEntries, 0); - PL_HashTableDestroy(mHTDirs); - - PL_HashTableEnumerateEntries(mHTFiles, NS_RemoveStringEntries, 0); - PL_HashTableDestroy(mHTFiles); -} - -nsresult nsNetFile::GetFilePath(const char *aName, char **aRes) { - nsString newPath, fileName; - char *tmpString; - char *path = nsnull, *locName = nsnull; - char *tokBegin, *dirTok, *fileTok, *nextTok; - nsFileAssoc *faFile = nsnull; - - - NS_PRECONDITION( (aName != nsnull), "Null pointer."); - - locName = URLSyntaxToLocal(aName); - if (!locName) - return NS_ERROR_OUT_OF_MEMORY; - - // If we were handed an absolute path, spit it back. - if ( (*locName == mDirDel) // mac and unix - || - (*locName && (*(locName + 1) == ':') ) ) // pc - { - newPath = locName; - PR_Free(locName); - locName = nsnull; - tmpString = newPath.ToNewCString(); - if (!tmpString) - return NS_ERROR_OUT_OF_MEMORY; - path = PL_strdup(tmpString); - delete[] tmpString; - tmpString = nsnull; - - *aRes = path; - return NS_OK; - } - - // First see if this has been explicitly registered - faFile = (nsFileAssoc*)PL_HashTableLookup(mHTFiles, locName); - if (faFile) { - char *dir = nsnull; - if (faFile->dirTok.Length()) { - char *csDT; - tmpString = faFile->dirTok.ToNewCString(); - if (!tmpString) { - return NS_ERROR_OUT_OF_MEMORY; - } - csDT = PL_strdup(tmpString); - delete[] tmpString; - tmpString = nsnull; - - dir = (char*)PL_HashTableLookup(mHTDirs, csDT); - PR_Free(csDT); - } - // If it wasn't in the table give the file a default dir. - if (!dir) { - dir = (char*)PL_HashTableLookup(mHTDirs, DEF_DIR_TOK); - NS_PRECONDITION( (dir != nsnull), "No default dir registered."); - return NS_ERROR_FAILURE; - } - newPath = dir; - if (dir[PL_strlen(path)-1] != mDirDel) { - newPath.Append(mDirDel); - } - newPath.Append(faFile->name); - tmpString = newPath.ToNewCString(); - *aRes = PL_strdup(tmpString); - delete[] tmpString; - return NS_OK; - } - - // If we've gotten this far, this file wasn't registered, or the user wants - // to use a different directory with the file. - - // Lookup the token(s) in our hash table(s). - dirTok = nsnull; - fileTok = nsnull; - - tokBegin = PL_strchr(locName, mTokDel); - if (tokBegin) { - nextTok = PL_strchr(tokBegin+1, mTokDel); - if (nextTok) { - // Check for more (could be another token or a filename). - if (*(nextTok+1)) { - // Set the first one as the dir. - char tmp = *(nextTok+1); - *(nextTok+1) = '\0'; - dirTok = PL_strdup(tokBegin); - *(nextTok+1) = tmp; - tokBegin = nextTok+1; - nextTok = PL_strchr(tokBegin+1, mTokDel); - } - if (nextTok) { - *(nextTok+1) = '\0'; - fileTok = PL_strdup(tokBegin); - *(nextTok+1) = mTokDel; - } else { - // no file token - fileTok = PL_strdup(tokBegin); - } - } - } - - // If the user passed in a dir token, use it. - if (dirTok) { - char *path = (char*)PL_HashTableLookup(mHTDirs, dirTok); - PR_Free(dirTok); - // If it wasn't in the table, fail. - if (!path) { - PR_Free(fileTok); - return NS_ERROR_FAILURE; - } - newPath = path; - if (path[PL_strlen(path)-1] != mDirDel) { - newPath.Append(mDirDel); - } - } - - if (fileTok) { - faFile = (nsFileAssoc*)PL_HashTableLookup(mHTFiles, fileTok); - if (faFile) - fileName = faFile->name; - else - fileName = fileTok; // It wasn't a token after all; - } else { - fileName = (char *)aName; - } - - newPath.Append(fileName); - PR_Free(fileTok); - tmpString = newPath.ToNewCString(); - *aRes = PL_strdup(tmpString); - delete[] tmpString; - PR_FREEIF(locName); - return NS_OK; -} - -nsresult nsNetFile::GetTemporaryFilePath(const char *aName, char **aRes) { - - return NS_OK; -} - -nsresult nsNetFile::GetUniqueFilePath(const char *aName, char **aRes) { - - return NS_OK; -} - -void nsNetFile::GenerateGlobalRandomBytes(void *aDest, size_t aLen) { - /* This is a temporary implementation to avoid */ - /* the cache filename horkage. This needs to have a more */ - /* secure/free implementation here - Gagan */ - - char* output=(char*)aDest; - size_t i; - srand((unsigned int) PR_IntervalToMilliseconds(PR_IntervalNow())); - for (i=0;i<aLen; i++) - { - int t = rand(); - *output = (char) (t % 256); - output++; - } -} - -#define MAX_PATH_LEN 512 - -#if defined(XP_UNIX) || defined(XP_BEOS) - -// Checked this in to fix the build. I have no idea where this lives -// on Unix. I have no idea if this implementation does the right thing -// or even works. -static void -_strrev(char* s) -{ - // Find the end of the string. - char* p = s; - while (*p) - ++p; - - --p; // back to the last character - - // Now reverse the string: s and p will eventually meet in the middle. - while (s < p) { - char c = *p; - *p = *s; - *s = c; - - ++s; - --p; - } -} -#endif - -nsresult nsNetFile::GetCacheFileName(char *aDirTok, char **aRes) { - char *file_buf = nsnull; - char *ext = ".MOZ"; - char *prefix = "M"; - PRStatus status; - PRFileInfo statinfo; - char *dir = (char*)PL_HashTableLookup(mHTDirs, aDirTok); - - file_buf = (char*)PR_Calloc(1, MAX_PATH_LEN); - if (!dir) - return NS_ERROR_FAILURE; - - - // We need to base our temporary file names on time, and not on sequential - // addition because of the cache not being updated when the user - // crashes and files that have been deleted are over written with - // other files; bad data. - // The 52 valid DOS file name characters are - // 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_^$~!#%&-{}@`'() - // We will only be using the first 32 of the choices. - // - // Time name format will be M+++++++.MOZ - // Where M is the single letter prefix (can be longer....) - // Where +++++++ is the 7 character time representation (a full 8.3 - // file name will be made). - // Where .MOZ is the file extension to be used. - // - // In the event that the time requested is the same time as the last call - // to this function, then the current time is incremented by one, - // as is the last time called to facilitate unique file names. - // In the event that the invented file name already exists (can't - // really happen statistically unless the clock is messed up or we - // manually incremented the time), then the times are incremented - // until an open name can be found. - // - // time_t (the time) has 32 bits, or 4,294,967,296 combinations. - // We will map the 32 bits into the 7 possible characters as follows: - // Starting with the lsb, sets of 5 bits (32 values) will be mapped - // over to the appropriate file name character, and then - // incremented to an approprate file name character. - // The left over 2 bits will be mapped into the seventh file name - // character. - // - - int i_letter, i_timechars, i_numtries = 0; - char ca_time[8]; - time_t this_call = (time_t)0; - - // We have to base the length of our time string on the length - // of the incoming prefix.... - // - i_timechars = 8 - PL_strlen(prefix); - - // Infinite loop until the conditions are satisfied. - // There is no danger, unless every possible file name is used. - // - while(1) { - // We used to use the time to generate this. - // Now, we use some crypto to avoid bug #47027 - GenerateGlobalRandomBytes((void *)&this_call, sizeof(this_call)); - - // Convert the time into a 7 character string. - // Strip only the signifigant 5 bits. - // We'll want to reverse the string to make it look coherent - // in a directory of file names. - // - for(i_letter = 0; i_letter < i_timechars; i_letter++) { - ca_time[i_letter] = (char)((this_call >> (i_letter * 5)) & 0x1F); - - // Convert any numbers to their equivalent ascii code - // - if(ca_time[i_letter] <= 9) { - ca_time[i_letter] += '0'; - // Convert the character to it's equivalent ascii code - // - } else { - ca_time[i_letter] += 'A' - 10; - } - } - - // End the created time string. - // - ca_time[i_letter] = '\0'; - - // Reverse the time string. - // - _strrev(ca_time); - - // Create the fully qualified path and file name. - // - sprintf(file_buf, "%s\\%s%s%s", dir, prefix, ca_time, ext); - - // Determine if the file exists, and mark that we've tried yet - // another file name (mark to be used later). - // - // Use the system call instead of XP_Stat since we already - // know the name and we don't want recursion - // - status = PR_GetFileInfo(file_buf, &statinfo); - i_numtries++; - - // If it does not exists, we are successful, return the name. - // - if(status == PR_FAILURE) { - /* don't generate a directory as part of the - * cache temp names. When the cache file name - * is passed into the other XP_File functions - * we will append the cache directory to the name - * to get the complete path. - * This will allow the cache to be moved around - * and for netscape to be used to generate external - * cache FAT's. :lou - */ - sprintf(file_buf, "%s%s%s", prefix, ca_time, ext); - - *aRes = file_buf; - break; - } - } // End while - - return NS_OK; -} - -#if 0 - -// Here for reference. -PUBLIC char * -xp_TempFileName(int type, const char * request_prefix, const char * extension, - char* file_buf) -{ - const char * directory = NULL; - char * ext = NULL; // file extension if any - char * prefix = NULL; // file prefix if any - XP_Bool bDirSlash = FALSE; - - XP_StatStruct statinfo; - int status; - - // - // based on the type of request determine what directory we should be - // looking into - // - switch(type) { - case xpCache: - directory = theApp.m_pCacheDir; - ext = ".MOZ"; - prefix = CACHE_PREFIX; - break; -#ifdef OLD_MOZ_MAIL_NEWS - case xpSNewsRC: - case xpNewsRC: - case xpNewsgroups: - case xpSNewsgroups: - case xpTemporaryNewsRC: - directory = g_MsgPrefs.m_csNewsDir; - ext = (char *)extension; - prefix = (char *)request_prefix; - break; - case xpMailFolderSummary: - case xpMailFolder: - directory = g_MsgPrefs.m_csMailDir; - ext = (char *)extension; - prefix = (char *)request_prefix; - break; - case xpAddrBook: - //changed jonm-- to support multi-profile - //directory = theApp.m_pInstallDir->GetCharValue(); - directory = (const char *)theApp.m_UserDirectory; - if ((request_prefix == 0) || (XP_STRLEN (request_prefix) == 0)) - prefix = "abook"; - ext = ".nab"; - break; -#endif // OLD_MOZ_MAIL_NEWS - case xpCacheFAT: - directory = theApp.m_pCacheDir; - prefix = "fat"; - ext = "db"; - break; - case xpJPEGFile: - directory = theApp.m_pTempDir; - ext = ".jpg"; - prefix = (char *)request_prefix; - break; - case xpPKCS12File: - directory = theApp.m_pTempDir; - ext = ".p12"; - prefix = (char *)request_prefix; - break; - case xpURL: - { - if (request_prefix) - { - if ( XP_STRRCHR(request_prefix, '/') ) - { - const char *end; - XP_StatStruct st; - - directory = (char *)request_prefix; - end = directory + XP_STRLEN(directory) - 1; - if ( *end == '/' || *end == '\\' ) { - bDirSlash = TRUE; - } - if (XP_Stat (directory, &st, xpURL)) - XP_MakeDirectoryR (directory, xpURL); - ext = (char *)extension; - prefix = (char *)"su"; - break; - } - } - // otherwise, fall through - } - case xpTemporary: - default: - directory = theApp.m_pTempDir; - ext = (char *)extension; - prefix = (char *)request_prefix; - break; - } - - if(!directory) - return(NULL); - - if(!prefix) - prefix = "X"; - - if(!ext) - ext = ".TMP"; - - // We need to base our temporary file names on time, and not on sequential - // addition because of the cache not being updated when the user - // crashes and files that have been deleted are over written with - // other files; bad data. - // The 52 valid DOS file name characters are - // 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_^$~!#%&-{}@`'() - // We will only be using the first 32 of the choices. - // - // Time name format will be M+++++++.MOZ - // Where M is the single letter prefix (can be longer....) - // Where +++++++ is the 7 character time representation (a full 8.3 - // file name will be made). - // Where .MOZ is the file extension to be used. - // - // In the event that the time requested is the same time as the last call - // to this function, then the current time is incremented by one, - // as is the last time called to facilitate unique file names. - // In the event that the invented file name already exists (can't - // really happen statistically unless the clock is messed up or we - // manually incremented the time), then the times are incremented - // until an open name can be found. - // - // time_t (the time) has 32 bits, or 4,294,967,296 combinations. - // We will map the 32 bits into the 7 possible characters as follows: - // Starting with the lsb, sets of 5 bits (32 values) will be mapped - // over to the appropriate file name character, and then - // incremented to an approprate file name character. - // The left over 2 bits will be mapped into the seventh file name - // character. - // - - int i_letter, i_timechars, i_numtries = 0; - char ca_time[8]; - time_t this_call = (time_t)0; - - // We have to base the length of our time string on the length - // of the incoming prefix.... - // - i_timechars = 8 - strlen(prefix); - - // Infinite loop until the conditions are satisfied. - // There is no danger, unless every possible file name is used. - // - while(1) { - // We used to use the time to generate this. - // Now, we use some crypto to avoid bug #47027 - RNG_GenerateGlobalRandomBytes((void *)&this_call, sizeof(this_call)); - - // Convert the time into a 7 character string. - // Strip only the signifigant 5 bits. - // We'll want to reverse the string to make it look coherent - // in a directory of file names. - // - for(i_letter = 0; i_letter < i_timechars; i_letter++) { - ca_time[i_letter] = (char)((this_call >> (i_letter * 5)) & 0x1F); - - // Convert any numbers to their equivalent ascii code - // - if(ca_time[i_letter] <= 9) { - ca_time[i_letter] += '0'; - } - // Convert the character to it's equivalent ascii code - // - else { - ca_time[i_letter] += 'A' - 10; - } - } - - // End the created time string. - // - ca_time[i_letter] = '\0'; - - // Reverse the time string. - // - _strrev(ca_time); - - // Create the fully qualified path and file name. - // - if (bDirSlash) - sprintf(file_buf, "%s%s%s%s", directory, prefix, ca_time, ext); - else - sprintf(file_buf, "%s\\%s%s%s", directory, prefix, ca_time, ext); - - // Determine if the file exists, and mark that we've tried yet - // another file name (mark to be used later). - // - // Use the system call instead of XP_Stat since we already - // know the name and we don't want recursion - // - status = _stat(file_buf, &statinfo); - i_numtries++; - - // If it does not exists, we are successful, return the name. - // - if(status == -1) { - /* don't generate a directory as part of the - * cache temp names. When the cache file name - * is passed into the other XP_File functions - * we will append the cache directory to the name - * to get the complete path. - * This will allow the cache to be moved around - * and for netscape to be used to generate external - * cache FAT's. :lou - */ - if(type == xpCache ) - sprintf(file_buf, "%s%s%s", prefix, ca_time, ext); - -// TRACE("Temp file name is %s\n", file_buf); - return(file_buf); - } - - // If there is no room for additional characters in the time, - // we'll have to return NULL here, or we go infinite. - // This is a one case scenario where the requested prefix is - // actually 8 letters long. - // Infinite loops could occur with a 7, 6, 5, etc character prefixes - // if available files are all eaten up (rare to impossible), in - // which case, we should check at some arbitrary frequency of - // tries before we give up instead of attempting to Vulcanize - // this code. Live long and prosper. - // - if(i_timechars == 0) { - break; - } - else if(i_numtries == 0x00FF) { - break; - } - } - - // Requested name is thought to be impossible to generate. - // - TRACE("No more temp file names....\n"); - return(NULL); - -} -#endif // 0 - - -nsresult nsNetFile::OpenFile(const char *aPath, nsFileMode aMode, nsFile** aRes) { - nsFile *file = nsnull; - char *path = nsnull; - NS_PRECONDITION( (aPath != nsnull), "Null pointer."); - - if (!aPath) - return NS_ERROR_NULL_POINTER; - if (!*aPath) - return NS_ERROR_FAILURE; - - file = (nsFile*) PR_Malloc(sizeof(nsFile)); - if (!file) - return NS_ERROR_OUT_OF_MEMORY; - - // Get the correct path. - if (GetFilePath(aPath, &path) == NS_ERROR_OUT_OF_MEMORY) - return NS_ERROR_OUT_OF_MEMORY; - - // We should never be opening a relative file. - NS_PRECONDITION( ( (*path != mDirDel) && (*path && (*path+1 != ':'))), "Opening a relative path."); - - file->fd = PR_Open(path, (convertToPRFlag(aMode)), 0600); - - PR_Free(path); - path = nsnull; - - if (!file->fd) { - PR_Free(file); - return NS_ERROR_NULL_POINTER; - } - - *aRes = file; - - return NS_OK; -} - -nsresult nsNetFile::CloseFile(nsFile* aFile) { - - PRStatus rv; - NS_PRECONDITION( (aFile != nsnull), "Null pointer."); - - if (!aFile->fd) - return NS_ERROR_NULL_POINTER; - - rv = PR_Close(aFile->fd); - - if (rv == PR_FAILURE) - return NS_ERROR_FAILURE; - - PR_Free(aFile); - aFile = nsnull; - - return NS_OK; -} - -nsresult nsNetFile::FileRead(nsFile *aFile, char **aBuf, - PRInt32 *aBuflen, - PRInt32 *aBytesRead) { - NS_PRECONDITION( (aFile != nsnull), "Null pointer."); - - if (*aBuflen < 1) - return NS_OK; - - *aBytesRead = PR_Read(aFile->fd, *aBuf, *aBuflen); - - if (*aBytesRead == -1) { - return NS_ERROR_FAILURE; - } - return NS_OK; -} - -nsresult nsNetFile::FileReadLine(nsFile *aFile, char **aBuf, - PRInt32 *aBuflen, - PRInt32 *aBytesRead) { - PRInt32 readBytes; - PRInt32 idx = 0; - char *tmpBuf = nsnull; - - NS_PRECONDITION( (aFile != nsnull), "Null pointer."); - - if (*aBuflen < 1) { - *aBytesRead = 0; - return NS_OK; - } - - readBytes = PR_Read(aFile->fd, *aBuf, *aBuflen); - tmpBuf = *aBuf; - - if (readBytes > 0) { - while (idx < readBytes) { - if (tmpBuf[idx] == 10) { // LF - if (tmpBuf[idx+1]) - tmpBuf[idx+1] = '\0'; - // Back the file pointer up. - PR_Seek(aFile->fd, ((idx+1) - readBytes), PR_SEEK_CUR); - *aBytesRead = idx+1; - return NS_OK; - } - idx++; - } - } - - if (readBytes == *aBuflen) - return NS_ERROR_FAILURE; - - return NS_ERROR_FAILURE; -} - -nsresult nsNetFile::FileWrite(nsFile *aFile, const char *aBuf, - PRInt32 *aLen, - PRInt32 *aBytesWritten) { - PRErrorCode error; // for testing, not propogated. - NS_PRECONDITION( (aFile != nsnull), "Null pointer."); - - if (*aLen < 1) - return NS_OK; - - *aBytesWritten = PR_Write(aFile->fd, aBuf, *aLen); - - if (*aBytesWritten == -1) { - error = PR_GetError(); - return NS_ERROR_FAILURE; - } - return NS_OK; -} - -nsresult nsNetFile::FileSync(nsFile *aFile) { - NS_PRECONDITION( (aFile != nsnull), "Null pointer."); - - if (PR_Sync(aFile->fd) == PR_FAILURE) - return NS_ERROR_FAILURE; - - return NS_OK; -} - -nsresult nsNetFile::FileRemove(const char *aPath) { - char *path = nsnull; - NS_PRECONDITION( (aPath != nsnull), "Null pointer."); - - // Only remove absolute paths. - if (GetFilePath(aPath, &path) == NS_ERROR_OUT_OF_MEMORY) - return NS_ERROR_OUT_OF_MEMORY; - - // We should never be deleting a relative file. - NS_PRECONDITION( ( (*path != mDirDel) && (*path && (*path+1 != ':'))), "Deleting a relative path."); - - PR_Free(path); - - return NS_OK; -} - -nsresult nsNetFile::FileRename(const char *aPathOld, const char *aPathNew) { - - return NS_OK; -} - -nsresult nsNetFile::OpenDir(const char *aPath, nsDir** aRes) { - - return NS_OK; -} - -nsresult nsNetFile::CloseDir(nsDir *aDir) { - - return NS_OK; -} - -nsresult nsNetFile::CreateDir(const char *aPath, PRBool aRecurse) { - - return NS_OK; -} - -nsresult nsNetFile::SetDirectory(const char *aToken, const char *aDir) { - nsresult rv = NS_OK; - - if (!PL_HashTableAdd(mHTDirs, PL_strdup(aToken), PL_strdup(aDir))) { - rv = NS_ERROR_FAILURE; - } - return rv; -} - - // Associate a filename with a token, and optionally a dir token. -nsresult nsNetFile::SetFileAssoc(const char *aToken, - const char *aFile, - const char *aDirToken) { - nsString val(aFile); - nsFileAssoc *theFile = new nsFileAssoc; - - if (aDirToken) { - // Check for existence. - char *dir = (char*)PL_HashTableLookup(mHTDirs, aDirToken); - if (!dir) - return NS_ERROR_FAILURE; - theFile->dirTok = aDirToken; - } - - theFile->name = aFile; - - if (!PL_HashTableAdd(mHTFiles, aToken, theFile)) { - return NS_ERROR_FAILURE; - } - return NS_OK; -} - -PRIntn nsNetFile::convertToPRFlag(nsFileMode aMode) { - - switch (aMode) { - case nsRead: - return PR_RDONLY; - case nsWrite: - return PR_WRONLY; - case nsReadWrite: - return PR_RDWR; - case nsReadBinary: - return PR_RDONLY; - case nsWriteBinary: - return PR_WRONLY; - case nsReadWriteBinary: - return PR_RDWR; - case nsOverWrite: - return (PR_TRUNCATE | PR_WRONLY | PR_CREATE_FILE); - default: - return PR_RDONLY; - } -} - -char *nsNetFile::URLSyntaxToLocal(const char *aPath) - -#ifdef XP_PC -{ - char *p, *newName; - - if(!aPath) - return nsnull; - - // If the name is only '/' or begins '//' keep the - // whole name else strip the leading '/' - PRBool bChopSlash = PR_FALSE; - - if(aPath[0] == '/') - bChopSlash = PR_TRUE; - - // save just / as a path - if(aPath[0] == '/' && aPath[1] == '\0') - bChopSlash = PR_FALSE; - - // spanky Win9X path name - if(aPath[0] == '/' && aPath[1] == '/') - bChopSlash = PR_FALSE; - - if(bChopSlash) - newName = PL_strdup(&(aPath[1])); - else - newName = PL_strdup(aPath); - - if(!newName) - return nsnull; - - if( newName[1] == '|' ) - newName[1] = ':'; - - for(p = newName; *p; p++){ - if( *p == '/' ) - *p = '\\'; - } - - return(newName); -} -#elif XP_MAC -{ - return nsnull; -} -#else // UNIX -{ - return nsnull; -} -#endif - - -extern "C" { -/* - * Factory for creating instance of the NetFile... - */ -NS_NET nsresult NS_NewINetFile(nsINetFile** aInstancePtrResult, - nsISupports* aOuter) -{ - if (nsnull != aOuter) { - return NS_ERROR_NO_AGGREGATION; - } - -#ifdef XP_MAC - // Perform static initialization... - if (nsnull == netFileInit) { - netFileInit = new nsNetFileInit; - } -#endif /* XP_MAC */ // XXX on the mac this never gets shutdown - - // The Netlib Service is created by the nsNetFileInit class... - if (nsnull == gNetFile) { - return NS_ERROR_OUT_OF_MEMORY; - } - - return gNetFile->QueryInterface(kINetFileIID, (void**)aInstancePtrResult); -} - - -NS_NET nsresult NS_InitINetFile(void) -{ - /* XXX: For now only allow a single instance of the Netlib Service */ - if (nsnull == gNetFile) { - gNetFile = new nsNetFile(); - if (nsnull == gNetFile) { - return NS_ERROR_OUT_OF_MEMORY; - } - } - - NS_ADDREF(gNetFile); - return NS_OK; -} - -NS_NET nsresult NS_ShutdownINetFile() -{ - nsNetFile *service = gNetFile; - - // Release the container... - if (nsnull != service) { - NS_RELEASE(service); - } - return NS_OK; -} - -}; /* extern "C" */ diff --git a/mozilla/network/module/nsNetFile.h b/mozilla/network/module/nsNetFile.h deleted file mode 100644 index 7be9b097071..00000000000 --- a/mozilla/network/module/nsNetFile.h +++ /dev/null @@ -1,104 +0,0 @@ -#include "prio.h" -#include "nsINetFile.h" -#include "plhash.h" - - -#ifndef ns_net_file_h_ -#define ns_net_file_h_ - -/* This is a singleton implementation. */ - -class nsNetFile : public nsINetFile { -public: - NS_DECL_ISUPPORTS - - nsNetFile(); - - // Convert a generic file names into a platform file path - NS_IMETHOD GetFilePath(const char *aName, char **aRes); - NS_IMETHOD GetTemporaryFilePath(const char *aName, char **aRes); - NS_IMETHOD GetUniqueFilePath(const char *aName, char **aRes); - NS_IMETHOD GetCacheFileName(char *aDirTok, char **aRes); - - // Open a file - NS_IMETHOD OpenFile(const char *aPath, nsFileMode aMode, - nsFile** aRes); - - // Close a file - NS_IMETHOD CloseFile(nsFile* aFile); - - // Read a file - NS_IMETHOD FileRead(nsFile *aFile, char **aBuf, - PRInt32 *aBuflen, - PRInt32 *aBytesRead); - - // Read a line from a file - NS_IMETHOD FileReadLine(nsFile *aFile, char **aBuf, - PRInt32 *aBuflen, - PRInt32 *aBytesRead); - - // Write a file - NS_IMETHOD FileWrite(nsFile *aFile, const char *aBuf, - PRInt32 *aLen, - PRInt32 *aBytesWritten); - - // Sync a file with disk - NS_IMETHOD FileSync(nsFile *aFile); - - // Remove a file - NS_IMETHOD FileRemove(const char *aPath); - - // Rename a file - NS_IMETHOD FileRename(const char *aPathOld, const char *aPathNew); - - /* - * Directory Methods - */ - - // Open a directory - NS_IMETHOD OpenDir(const char *aPath, nsDir** aRes); - - // Close a directory - NS_IMETHOD CloseDir(nsDir *aDir); - - // Create a directory - NS_IMETHOD CreateDir(const char *aPath, PRBool aRecurse); - - // Set the internal directories - NS_IMETHOD SetDirectory(const char *aToken, const char *aDir); - - // Associate a filename with a token, and optionally a dir token. - NS_IMETHOD SetFileAssoc(const char *aToken, const char *aFile, const char *aDirToken); - -protected: - virtual ~nsNetFile(); - -private: - void GenerateGlobalRandomBytes(void *aDest, size_t aLen); - PRIntn convertToPRFlag(nsFileMode aMode); - char * URLSyntaxToLocal(const char * aPath); - char mTokDel; // token delimiter - char mDirDel; // directory delimiter - PLHashTable *mHTDirs; // directory registry - PLHashTable *mHTFiles; // file registry -}; - -// The one and only singleton pointer to an nsNetFile. -static nsNetFile *gNetFile = nsnull; - -// -// Class to manage static initialization -// -struct nsNetFileInit { - nsNetFileInit() { - gNetFile = nsnull; - (void) NS_InitINetFile(); - } - - ~nsNetFileInit() { - NS_ShutdownINetFile(); - gNetFile = nsnull; - } -}; - -#endif // ns_net_file_h_ diff --git a/mozilla/network/module/nsNetIDs.cpp b/mozilla/network/module/nsNetIDs.cpp deleted file mode 100644 index 0bab65e23d1..00000000000 --- a/mozilla/network/module/nsNetIDs.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#define NS_IMPL_IDS -#include "nsINetSupport.h" -#include "nsIStreamListener.h" -#include "nsIPref.h" diff --git a/mozilla/network/module/nsNetService.cpp b/mozilla/network/module/nsNetService.cpp deleted file mode 100644 index 1ec2e54bdac..00000000000 --- a/mozilla/network/module/nsNetService.cpp +++ /dev/null @@ -1,1666 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsIComponentManager.h" -#include "nsITimer.h" -#include "nsNetService.h" -#include "nsNetStream.h" -#include "nsNetFile.h" -#include "nsStubContext.h" -#include "prefapi.h" -#include "mkprefs.h" -extern "C" { -#include "mkutils.h" -#include "mkgeturl.h" -#include "mktrace.h" -#include "mkstream.h" -#include "cvchunk.h" -#include "httpurl.h" -} /* end of extern "C" */ - -#include "netcache.h" -#include "cookies.h" -#include "plstr.h" - -#include "nsString.h" -#include "nsINetlibURL.h" -#include "nsIProtocolConnection.h" -#include "nsINetlibURL.h" -#include "nsIProtocolURLFactory.h" -#include "nsIProtocol.h" -#include "nsIURLGroup.h" -#include "nsIServiceManager.h" -#include "nsIEventQueueService.h" -#include "nsCRT.h" -#include "nsSocketTransport.h" - -#include "nsIChromeRegistry.h" - -#ifdef XP_PC -#include <windows.h> -static HINSTANCE g_hInst = NULL; -#endif - -#ifdef XP_BEOS -#include <OS.h> -#include <image.h> -#endif - -#ifdef XP_UNIX -#include <sys/utsname.h> -#endif /* XP_UNIX */ - - -/* -** Define TIMEBOMB_ON for beta builds. -** Undef TIMEBOMB_ON for release builds. -*/ -/*#define TIMEBOMB_ON*/ -#undef TIMEBOMB_ON - -/* -** After this date all hell breaks loose -*/ -#ifdef TIMEBOMB_ON -#define TIME_BOMB_TIME 917856001 /* 2/01/98 + 1 secs */ -#define TIME_BOMB_WARNING_TIME 915955201 /* 1/10/98 + 1 secs */ -#else -#define TIME_BOMB_TIME -1 -#define TIME_BOMB_WARNING_TIME -1 -#endif - - -// Declare the nsFile struct here so it's state is initialized before -// we initialize netlib. -#ifdef NS_NET_FILE - -#include "nsNetFile.h" -#if defined(XP_MAC) || defined(XP_UNIX) -static nsNetFileInit* netFileInit = nsnull; -#else -static nsNetFileInit netFileInit; -#endif - -#endif // NS_NET_FILE -// End nsFile specific - -/* XXX: Legacy definitions... */ -// Global count of active urls from mkgeturl.c -extern "C" int NET_TotalNumberOfProcessingURLs; - -extern "C" HTTP_Version DEFAULT_VERSION; - -extern "C" void net_AddrefContext(MWContext* window_id); -static void bam_exit_routine(URL_Struct *URL_s, int status, MWContext *window_id); - -#if defined(XP_WIN) && !defined(NETLIB_THREAD) -nsresult PerformNastyWindowsAsyncDNSHack(URL_Struct* URL_s, nsIURI* aURL); -#endif /* XP_WIN && !NETLIB_THREAD */ - -char *mangleResourceIntoFileURL(const char* aResourceFileName); - -extern nsIStreamListener* ns_NewStreamListenerProxy(nsIStreamListener* aListener, nsIEventQueue* aEventQ); - -extern "C" { -#if defined(XP_WIN) || defined(XP_OS2) -extern char *XP_AppCodeName; -extern char *XP_AppVersion; -extern char *XP_AppName; -extern char *XP_AppLanguage; -extern char *XP_AppPlatform; -#else -extern const char *XP_AppCodeName; -extern const char *XP_AppVersion; -extern const char *XP_AppName; -extern const char *XP_AppLanguage; -extern const char *XP_AppPlatform; -#endif - -} /* end of extern "C" */ - -static NS_DEFINE_IID(kINetlibURLIID, NS_INETLIBURL_IID); -static NS_DEFINE_IID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID); -static NS_DEFINE_IID(kIEventQueueServiceIID, NS_IEVENTQUEUESERVICE_IID); - -// Chrome registry service for handling of chrome URLs -static NS_DEFINE_IID(kChromeRegistryCID, NS_CHROMEREGISTRY_CID); -static NS_DEFINE_IID(kIChromeRegistryIID, NS_ICHROMEREGISTRY_IID); -nsIChromeRegistry* nsNetlibService::gChromeRegistry = nsnull; -int nsNetlibService::gRefCnt = 0; - -nsNetlibService::nsNetlibService() -{ - nsresult rv; - - NS_INIT_REFCNT(); - - /* - * Cache the EventQueueService... - */ - // XXX: What if this fails? - mEventQService = nsnull; - rv = nsServiceManager::GetService(kEventQueueServiceCID, - kIEventQueueServiceIID, - (nsISupports **)&mEventQService); - - /* - m_stubContext = new_stub_context(); - */ - mPollingTimer = nsnull; - - mNetlibThread = new nsNetlibThread(); - if (nsnull != mNetlibThread) { - mNetlibThread->Start(); - } - - /* Setup our default prefs. Eventually these will come out of a default - * all.js file, but, for now each module needs to address their own - * default settings. */ - - PREF_SetDefaultIntPref(pref_proxyType, 3); - PREF_SetDefaultCharPref(pref_proxyACUrl, ""); - PREF_SetDefaultCharPref(pref_socksServer, ""); - PREF_SetDefaultIntPref(pref_socksPort, 0); - PREF_SetDefaultCharPref(pref_proxyFtpServer, ""); - PREF_SetDefaultIntPref(pref_proxyFtpPort, 0); - PREF_SetDefaultCharPref(pref_proxyGopherServer, ""); - PREF_SetDefaultIntPref(pref_proxyGopherPort, 0); - PREF_SetDefaultCharPref(pref_proxyHttpServer, ""); - PREF_SetDefaultIntPref(pref_proxyHttpPort, 0); - PREF_SetDefaultCharPref(pref_proxyNewsServer, ""); - PREF_SetDefaultIntPref(pref_proxyNewsPort, 0); - PREF_SetDefaultCharPref(pref_proxyWaisServer, ""); - PREF_SetDefaultIntPref(pref_proxyWaisPort, 0); - PREF_SetDefaultCharPref(pref_proxyNoProxiesOn, ""); - PREF_SetDefaultCharPref(pref_padPacURL, ""); - PREF_SetDefaultCharPref(pref_scriptName, ""); - - PREF_SetDefaultIntPref("timebomb.expiration_time",TIME_BOMB_TIME); - PREF_SetDefaultIntPref("timebomb.warning_time", TIME_BOMB_WARNING_TIME); - - // XXX: Where should the defaults really come from - XP_AppCodeName = PL_strdup("Mozilla"); - XP_AppName = PL_strdup("Netscape"); - - /* - * XXX: Some of these should come from resources and/or - * platform-specific code. - */ - XP_AppLanguage = PL_strdup("en"); -#ifdef XP_WIN - { - OSVERSIONINFO info = { sizeof OSVERSIONINFO }; - GetVersionEx( &info ); - if ( info.dwPlatformId == VER_PLATFORM_WIN32_NT ) { - XP_AppPlatform = PL_strdup("WinNT"); - } else if ( info.dwMinorVersion > 0 ) { - XP_AppPlatform = PL_strdup("Win98"); - } else { - XP_AppPlatform = PL_strdup("Win95"); - } - } -#elif defined(XP_MAC) - XP_AppPlatform = PL_strdup("MacPPC"); -#elif defined(XP_BEOS) - XP_AppPlatform = PL_strdup("BeOS"); -#elif defined(XP_UNIX) - /* XXX: Need to differentiate between various Unisys */ - struct utsname name; - int ret = uname(&name); - if (ret >= 0) { - XP_AppPlatform = PL_strdup((char *) name.sysname); - } - -#endif - - /* XXXXX TEMPORARY TESTING HACK XXXXX */ - char buf[64]; - char *ver = PR_GetEnv("NG_REQUEST_VER"); - /* Build up the appversion. */ - sprintf(buf, "%s [%s] (%s; I)", - (ver ? ver : "5.0"), - XP_AppLanguage, - XP_AppPlatform); - if (XP_AppVersion) - PR_Free((char *)XP_AppVersion); - XP_AppVersion = PL_strdup(buf); - - mProtocols = new nsHashtable(); - PR_ASSERT(mProtocols); - - // Create the chrome registry. If it fails, that's ok. - gRefCnt++; - - if (gRefCnt == 1) - { - gChromeRegistry = nsnull; - if (NS_FAILED(nsServiceManager::GetService(kChromeRegistryCID, - kIChromeRegistryIID, - (nsISupports **)&gChromeRegistry))) { - gChromeRegistry = nsnull; - } - } -} - - -static NS_DEFINE_IID(kINetServiceIID, NS_INETSERVICE_IID); -NS_IMPL_THREADSAFE_ISUPPORTS(nsNetlibService,kINetServiceIID); - - -nsNetlibService::~nsNetlibService() -{ - TRACEMSG(("nsNetlibService is being destroyed...\n")); - - gRefCnt--; - if (gRefCnt == 0) - { - NS_IF_RELEASE(gChromeRegistry); - gChromeRegistry = nsnull; - } - - /* - if (NULL != m_stubContext) { - free_stub_context((MWContext *)m_stubContext); - m_stubContext = NULL; - } - */ - - NS_IF_RELEASE(mPollingTimer); - - if (nsnull != mNetlibThread) { - mNetlibThread->Stop(); - delete mNetlibThread; - } - - if (nsnull != mEventQService) { - nsServiceManager::ReleaseService(kEventQueueServiceCID, mEventQService); - mEventQService = nsnull; - } - - delete mProtocols; -} - - - -void nsNetlibService::SetupURLStruct(nsIURI *aUrl, URL_Struct *aURL_s) -{ - nsresult rv; - nsILoadAttribs* loadAttribs; - rv = aUrl->GetLoadAttribs(&loadAttribs); - - - /* If this url has load attributes, setup the underlying url struct - * accordingly. */ - if (loadAttribs) { - nsURLLoadType loadType; - nsURLReloadType reloadType; - PRUint32 localIP; - char* byteRangeHeader=NULL; - - NS_VERIFY_THREADSAFE_INTERFACE(loadAttribs); - - rv = loadAttribs->GetReloadType(&reloadType); - if (NS_FAILED(rv)) { - reloadType = nsURLReload; - } - if ((reloadType == nsURLReloadBypassProxy) || - (reloadType == nsURLReloadBypassCacheAndProxy)) { - PRBool bBypassProxy; - - rv = loadAttribs->GetBypassProxy(&bBypassProxy); - if (NS_FAILED(rv)) { - bBypassProxy = PR_FALSE; - } - aURL_s->bypassProxy = bBypassProxy; - } - /* Set the NET_ReloadMethod to correspond with what we've - * been asked to do. - * - * 0 = nsURLReload (normal) - * 1 = nsURLReloadBypassCache - * 2 = nsURLReloadBypassProxy - * 3 = nsURLReloadBypassCacheAndProxy - */ - if ((reloadType == nsURLReloadBypassCache) || - (reloadType == nsURLReloadBypassCacheAndProxy)) { - aURL_s->force_reload = NET_SUPER_RELOAD; - } else { - aURL_s->force_reload = NET_NORMAL_RELOAD; - } - - rv = loadAttribs->GetLoadType(&loadType); - if (NS_FAILED(rv)) { - loadType = nsURLLoadNormal; - } - if (loadType == nsURLLoadBackground) { - aURL_s->load_background = PR_TRUE; - } else { - aURL_s->load_background = PR_FALSE; - } - - rv = loadAttribs->GetLocalIP(&localIP); - if (NS_FAILED(rv)) { - localIP = 0; - } - aURL_s->localIP = localIP; - - rv = loadAttribs->GetByteRangeHeader(&byteRangeHeader); - if (NS_FAILED(rv)) - { - byteRangeHeader = NULL; - } - else - { - aURL_s->range_header = byteRangeHeader; - } - - NS_RELEASE(loadAttribs); - } -} - -nsresult nsNetlibService::OpenStream(nsIURI *aUrl, - nsIStreamListener *aConsumer) -{ - URL_Struct *URL_s; - nsConnectionInfo *pConn; - nsINetlibURL *netlibURL; - nsresult result; - nsIStreamListener* consumer; - nsIEventQueue* evQueue = nsnull; - - if ((NULL == aConsumer) || (NULL == aUrl)) { - return NS_FALSE; - } - -#if defined(NETLIB_THREAD) - if (nsnull != mEventQService) { - mEventQService->GetThreadEventQueue(NS_CURRENT_THREAD, &evQueue); - } - if (nsnull == evQueue) { - return NS_FALSE; - } - - consumer = ns_NewStreamListenerProxy(aConsumer, evQueue); - if (nsnull == consumer) { - return NS_FALSE; - } -#else - consumer = aConsumer; -#endif - - /* Create the nsConnectionInfo object... */ - pConn = new nsConnectionInfo(aUrl, NULL, consumer); - if (NULL == pConn) { - return NS_FALSE; - } - NS_ADDREF(pConn); - - /* - * XXX: Rewrite the resource: URL into a file: URL - */ - const char* protocol; - result = aUrl->GetProtocol(&protocol); - NS_ASSERTION(result == NS_OK, "deal with this"); - - // Deal with chrome URLS - if ((PL_strcmp(protocol, "chrome") == 0) && - gChromeRegistry != nsnull) { - - if (NS_FAILED(result = gChromeRegistry->InitRegistry()) || - NS_FAILED(result = gChromeRegistry->ConvertChromeURL(aUrl))) { - NS_ERROR("Unable to convert chrome URL."); - return result; - } - - result = aUrl->GetProtocol(&protocol); - NS_ASSERTION(result == NS_OK, "deal with this"); - } - - if (PL_strcmp(protocol, "resource") == 0) { - char* fileName; - char* search = NULL; - const char* file; - aUrl->GetSearch(&file); - if (file) search = XP_STRDUP(file); - result = aUrl->GetFile(&file); - NS_ASSERTION(result == NS_OK, "deal with this"); - fileName = mangleResourceIntoFileURL(file); - aUrl->SetSpec(fileName); - if (search) { - aUrl->SetSearch(search); - PR_Free(search); - } - PR_Free(fileName); - } - - /* Create the URLStruct... */ - - const char* spec = NULL; - result = aUrl->GetSpec(&spec); - NS_ASSERTION(result == NS_OK, "deal with this"); - URL_s = NET_CreateURLStruct(spec, NET_NORMAL_RELOAD); - if (NULL == URL_s) { - NS_RELEASE(pConn); - return NS_FALSE; - } - - SetupURLStruct(aUrl, URL_s); - - /* - * Attach the Data Consumer to the URL_Struct. - * - * Both the Data Consumer and the URL_Struct are freed in the - * bam_exit_routine(...) - * - * The Reference count on pConn is already 1 so no AddRef() is necessary. - */ - URL_s->fe_data = pConn; - - /* - * Attach the Event Queue to use when proxying data back to the thread - * which initiated the URL load... - * - * Currently, this information is needed to marshall the call to the URL - * exit_routine(...) on the correct thread... - */ - - URL_s->owner_data = evQueue; - - /* Done with the event queue pointer at this point. Release it. */ - NS_IF_RELEASE(evQueue); - - /* - * Give the protocol a chance to initialize any URL_Struct fields... - * - * XXX: Currently the return value form InitializeURLInfo(...) is - * ignored... Should the connection abort if it fails? - */ - result = aUrl->QueryInterface(kINetlibURLIID, (void**)&netlibURL); - if (NS_OK == result) { - netlibURL->SetURLInfo(URL_s); - NS_RELEASE(netlibURL); - } - - /* Create a new Context and set its reference count to one.. */ - MWContext *stubContext = new_stub_context(URL_s); - net_AddrefContext(stubContext); - - /* Check for timebomb...*/ -#ifdef TIMEBOMB_ON - NET_CheckForTimeBomb(stubContext); -#endif /* TIMEBOMB_ON */ - - /* Start the URL load... */ - NET_GetURL (URL_s, /* URL_Struct */ - FO_CACHE_AND_NGLAYOUT, /* FO_Present_type */ - (MWContext *)stubContext, /* MWContext */ - bam_exit_routine); /* Exit routine... */ - - /* Remember, the URL_s may have been freed ! */ - - /* - * Start the network timer to call NET_PollSockets(...) until the - * URL has been completely loaded... - */ - SchedulePollingTimer(); - return NS_OK; -} - - -nsresult nsNetlibService::OpenBlockingStream(nsIURI *aUrl, - nsIStreamListener *aConsumer, - nsIInputStream **aNewStream) -{ - URL_Struct *URL_s; - nsConnectionInfo *pConn; - nsNetlibStream *pBlockingStream; - nsINetlibURL *netlibURL; - nsIStreamListener* consumer = nsnull; - nsIEventQueue* evQueue = nsnull; - nsresult result; - - if (NULL == aNewStream) { - return NS_FALSE; - } - - if (NULL != aUrl) { -#if defined(NETLIB_THREAD) - if (nsnull != mEventQService) { - mEventQService->GetThreadEventQueue(NS_CURRENT_THREAD, &evQueue); - } - if (nsnull == evQueue) { - goto loser; - } - - if (nsnull != aConsumer) { - consumer = ns_NewStreamListenerProxy(aConsumer, evQueue); - if (nsnull == consumer) { - goto loser; - } - } -#else - consumer = aConsumer; -#endif - - /* Create the blocking stream... */ - pBlockingStream = new nsBlockingStream(); - - if (NULL == pBlockingStream) { - goto loser; - } - /* - * AddRef the new stream in anticipation of returning it... This will - * keep it alive :-) - */ - NS_ADDREF(pBlockingStream); - - /* Create the nsConnectionInfo object... */ - pConn = new nsConnectionInfo(aUrl, pBlockingStream, consumer); - if (NULL == pConn) { - NS_RELEASE(pBlockingStream); - goto loser; - } - NS_ADDREF(pConn); - - /* - * XXX: Rewrite the resource: URL into a file: URL - */ - const char* protocol; - result = aUrl->GetProtocol(&protocol); - NS_ASSERTION(result == NS_OK, "deal with this"); - - // Deal with chrome URLS - if ((PL_strcmp(protocol, "chrome") == 0) && - gChromeRegistry != nsnull) { - - if (NS_FAILED(result = gChromeRegistry->InitRegistry()) || - NS_FAILED(result = gChromeRegistry->ConvertChromeURL(aUrl))) { - NS_ERROR("Unable to convert chrome URL."); - return result; - } - - result = aUrl->GetProtocol(&protocol); - NS_ASSERTION(result == NS_OK, "deal with this"); - } - - if (PL_strcmp(protocol, "resource") == 0) { - char* fileName; - const char* file; - result = aUrl->GetFile(&file); - NS_ASSERTION(result == NS_OK, "deal with this"); - fileName = mangleResourceIntoFileURL(file); - aUrl->SetSpec(fileName); - PR_Free(fileName); - } - - /* Create the URLStruct... */ - - const char* spec = NULL; - result = aUrl->GetSpec(&spec); - NS_ASSERTION(result == NS_OK, "deal with this"); - URL_s = NET_CreateURLStruct(spec, NET_NORMAL_RELOAD); - if (NULL == URL_s) { - NS_RELEASE(pBlockingStream); - NS_RELEASE(pConn); - goto loser; - } - - SetupURLStruct(aUrl, URL_s); - -#if defined(XP_WIN) && !defined(NETLIB_THREAD) - /* - * When opening a blocking HTTP stream, perform a synchronous DNS - * lookup now, to avoid netlib from doing an async lookup later - * and causing a deadlock! - */ - result = PerformNastyWindowsAsyncDNSHack(URL_s, aUrl); - if (NS_OK != result) { - NET_FreeURLStruct(URL_s); - NS_RELEASE(pBlockingStream); - NS_RELEASE(pConn); - goto loser; - } -#endif /* XP_WIN && !NETLIB_THREAD */ - - /* - * Attach the ConnectionInfo object to the URL_Struct. - * - * Both the ConnectionInfo and the URL_Struct are freed in the - * bam_exit_routine(...) - * The Reference count on pConn is already 1 so no AddRef() is - * necessary. - */ - URL_s->fe_data = pConn; - - /* - * Attach the Event Queue to use when proxying data back to the thread - * which initiated the URL load... - * - * Currently, this information is needed to marshall the call to the URL - * exit_routine(...) on the correct thread... - */ - URL_s->owner_data = evQueue; - - /* Done with the event queue pointer at this point. Release it. */ - NS_IF_RELEASE(evQueue); - - /* - * Give the protocol a chance to initialize any URL_Struct fields... - * - * XXX: Currently the return value form InitializeURLInfo(...) is - * ignored... Should the connection abort if it fails? - */ - result = aUrl->QueryInterface(kINetlibURLIID, (void**)&netlibURL); - if (NS_OK == result) { - netlibURL->SetURLInfo(URL_s); - NS_RELEASE(netlibURL); - } - -/* printf("+++ Loading %s\n", aUrl); */ - - /* Create a new Context and set its reference count to one.. */ - MWContext *stubContext = new_stub_context(URL_s); - net_AddrefContext(stubContext); - - /* Check for timebomb...*/ -#ifdef TIMEBOMB_ON - NET_CheckForTimeBomb(stubContext); -#endif /* TIMEBOMB_ON */ - - /* Start the URL load... */ - if (0 > NET_GetURL (URL_s, /* URL_Struct */ - FO_CACHE_AND_NGLAYOUT, /* FO_Present_type */ - (MWContext *) stubContext, /* MWContext */ - bam_exit_routine)) /* Exit routine... */ - { - //Not releasing anything since bam_exit_routine will still be called. - goto loser; - } - /* Remember, the URL_s may have been freed ! */ - - /* - * Start the network timer to call NET_PollSockets(...) until the - * URL has been completely loaded... - */ - SchedulePollingTimer(); - - *aNewStream = pBlockingStream; - return NS_OK; - } - -loser: - *aNewStream = NULL; - return NS_FALSE; -} - -static NS_DEFINE_IID(kIProtocolConnectionIID, NS_IPROTOCOLCONNECTION_IID); -static NS_DEFINE_IID(kINetLibUrlIID, NS_INETLIBURL_IID); - -NS_IMETHODIMP -nsNetlibService::InterruptStream(nsIURI* aURL) -{ - nsINetlibURL * pNetUrl = nsnull; - - nsresult rv = NS_OK; - - if (nsnull == aURL) { - rv = NS_ERROR_NULL_POINTER; - goto done; - } - - rv = aURL->QueryInterface(kINetLibUrlIID, (void**)&pNetUrl); - if (NS_SUCCEEDED(rv)) { - URL_Struct* URL_s; - int status = -1; - - pNetUrl->GetURLInfo(&URL_s); - if (nsnull != URL_s) { - status = NET_InterruptStream(URL_s); - } - NS_RELEASE(pNetUrl); - - if (status != 0) { - rv = NS_ERROR_FAILURE; - } - } - -done: - return rv; -} - - -NS_IMETHODIMP -nsNetlibService::GetCookieString(nsIURI *aURL, nsString& aCookie) -{ - // XXX How safe is it to create a stub context without a URL_Struct? - MWContext *stubContext = new_stub_context(nsnull); - - const char *spec = NULL; - nsresult result = aURL->GetSpec(&spec); - NS_ASSERTION(result == NS_OK, "deal with this"); - char *cookie = NET_GetCookie(stubContext, (char *)spec); - - if (nsnull != cookie) { - aCookie.SetString(cookie); - PR_FREEIF(cookie); - } - else { - aCookie.SetString(""); - } - - free_stub_context(stubContext); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::SetCookieString(nsIURI *aURL, const nsString& aCookie) -{ - // XXX How safe is it to create a stub context without a URL_Struct? - MWContext *stubContext = new_stub_context(nsnull); - - const char *spec = NULL; - nsresult result = aURL->GetSpec(&spec); - NS_ASSERTION(result == NS_OK, "deal with this"); - char *cookie = aCookie.ToNewCString(); - - NET_SetCookieString(stubContext, (char *)spec, cookie); - - delete []cookie; - free_stub_context(stubContext); - return NS_OK; -} - -extern void -COOKIE_DisplayCookieInfoAsHTML(); - -extern void -COOKIE_GetCookieListForViewer (nsString& aCookieList); - -extern void -COOKIE_GetPermissionListForViewer (nsString& aPermissionList); - -extern void -COOKIE_CookieViewerReturn(nsAutoString results); - -NS_IMETHODIMP -nsNetlibService::Cookie_DisplayCookieInfoAsHTML(){ - ::COOKIE_DisplayCookieInfoAsHTML(); - return NS_OK; -} - -NS_IMETHODIMP nsNetlibService::Cookie_CookieViewerReturn(nsAutoString results){ - ::COOKIE_CookieViewerReturn(results); - return NS_OK; -} - -NS_IMETHODIMP nsNetlibService::Cookie_GetCookieListForViewer(nsString& aCookieList){ - ::COOKIE_GetCookieListForViewer(aCookieList); - return NS_OK; -} - -NS_IMETHODIMP nsNetlibService::Cookie_GetPermissionListForViewer(nsString& aPermissionList){ - ::COOKIE_GetPermissionListForViewer(aPermissionList); - return NS_OK; -} - - - -NS_IMETHODIMP -nsNetlibService::GetProxyHTTP(nsString& aProxyHTTP) { - char *proxy = nsnull; - PRInt32 port; - char outBuf[MAXHOSTNAMELEN + 8]; - *outBuf = '\0'; - - if ( PREF_OK != PREF_CopyCharPref(pref_proxyHttpServer,&proxy) ) { - return NS_FALSE; - } - - if ( PREF_OK != PREF_GetIntPref(pref_proxyHttpPort,&port) ) { - PR_FREEIF(proxy); - return NS_FALSE; - } - - sprintf(outBuf,"%s:%d", proxy, port); - PR_FREEIF(proxy); - aProxyHTTP.SetString(outBuf); - - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::SetProxyHTTP(nsString& aProxyHTTP) { - nsresult rv = NS_OK; - PRInt32 port; - nsString nsSPort; - char *csPort = nsnull; - char *proxy = nsnull; - nsString nsSProxy; - PRInt32 colonIdx; - PRUnichar colon = ':'; - - if (aProxyHTTP.Length() < 1) { - NET_SelectProxyStyle(PROXY_STYLE_NONE); - return NS_OK; - } - - if ( (colonIdx = aProxyHTTP.FindChar(colon)) < 0 ) - return NS_FALSE; - - aProxyHTTP.Left(nsSProxy, colonIdx); - aProxyHTTP.Mid(nsSPort, colonIdx+1, aProxyHTTP.Length() - colonIdx); - - proxy = nsSProxy.ToNewCString(); - if (!proxy) - return NS_FALSE; - csPort = nsSPort.ToNewCString(); - if (!csPort) { - delete[] proxy; - return NS_FALSE; - } - - port = atoi(csPort); - - if ( PREF_OK != PREF_SetCharPref(pref_proxyHttpServer, proxy) ) { - rv = NS_FALSE; - } - if ( PREF_OK != PREF_SetIntPref(pref_proxyHttpPort, port) ) { - rv = NS_FALSE; - } - delete[] proxy; - delete[] csPort; - - NET_SelectProxyStyle(PROXY_STYLE_MANUAL); - - return rv; -} - -NS_IMETHODIMP -nsNetlibService::GetHTTPOneOne(PRBool& aOneOne) { - aOneOne = (ONE_POINT_ONE == DEFAULT_VERSION); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::SetHTTPOneOne(PRBool aSendOneOne) { - if (aSendOneOne) - DEFAULT_VERSION = ONE_POINT_ONE; - else - DEFAULT_VERSION = ONE_POINT_O; - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetAppCodeName(nsString& aAppCodeName) -{ - aAppCodeName.SetString(XP_AppCodeName); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetAppVersion(nsString& aAppVersion) -{ - aAppVersion.SetString(XP_AppVersion); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetAppName(nsString& aAppName) -{ - aAppName.SetString(XP_AppName); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetLanguage(nsString& aLanguage) -{ - aLanguage.SetString(XP_AppLanguage); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetPlatform(nsString& aPlatform) -{ - aPlatform.SetString(XP_AppPlatform); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetUserAgent(nsString& aUA) -{ - char buf[64]; - PR_snprintf(buf, 64, "%.100s/%.90s", XP_AppCodeName, XP_AppVersion); - aUA.SetString(buf); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::SetCustomUserAgent(nsString aCustom) -{ - PRInt32 inIdx; -#ifdef emacs_knew_how_to_pattern_match_better_oh_well - PRUnichar junkChar = '['; -#endif - PRUnichar inChar = ']'; - - if (!XP_AppVersion || (0 >= aCustom.Length()) ) - return NS_FALSE; - - nsString newAppVersion = XP_AppVersion; - - inIdx = newAppVersion.FindChar(inChar); - if (0 > inIdx) { - newAppVersion.Insert(aCustom, inIdx + 1); - } - - PR_Free((char *)XP_AppVersion); - XP_AppVersion = newAppVersion.ToNewCString(); - return NS_OK; - -} - -//////////////////////////////////////////////////////////////////////////////// - -class nsStringHashKey : public nsHashKey -{ -public: - nsStringHashKey(const nsString& aName) - : mName(aName) - { - } - - virtual ~nsStringHashKey(void) - { - } - - virtual PRUint32 HashValue(void) const; - virtual PRBool Equals(const nsHashKey *aKey) const; - virtual nsHashKey *Clone(void) const; - -protected: - const nsString& mName; -}; - -PRUint32 nsStringHashKey::HashValue(void) const -{ - return nsCRT::HashValue(mName.GetUnicode()); -} - -PRBool nsStringHashKey::Equals(const nsHashKey *aKey) const -{ - const nsStringHashKey* other = (const nsStringHashKey*)aKey; - return mName.EqualsIgnoreCase(other->mName); -} - -nsHashKey *nsStringHashKey::Clone(void) const -{ - return new nsStringHashKey(mName); -} - -struct nsProtocolPair { - nsIProtocolURLFactory* mProtocolURLFactory; - nsIProtocol* mProtocol; -}; - -NS_IMETHODIMP -nsNetlibService::RegisterProtocol(const nsString& aName, - nsIProtocolURLFactory* aProtocolURLFactory, - nsIProtocol* aProtocol) -{ - nsStringHashKey* key = new nsStringHashKey(aName); - if (key == NULL) - return NS_ERROR_OUT_OF_MEMORY; - NS_ADDREF(aProtocolURLFactory); - NS_IF_ADDREF(aProtocol); // XXX remove IF - nsProtocolPair* pair = new nsProtocolPair; - if (pair == NULL) { - delete key; - return NS_ERROR_OUT_OF_MEMORY; - } - pair->mProtocolURLFactory = aProtocolURLFactory; - pair->mProtocol = aProtocol; - mProtocols->Put(key, pair); - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::UnregisterProtocol(const nsString& aName) -{ - nsStringHashKey key(aName); - nsProtocolPair* pair = (nsProtocolPair*)mProtocols->Remove(&key); - NS_RELEASE(pair->mProtocolURLFactory); - NS_IF_RELEASE(pair->mProtocol); // XXX remove IF - delete pair; - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::GetProtocol(const nsString& aName, - nsIProtocolURLFactory* *aProtocolURLFactory, - nsIProtocol* *aProtocol) -{ - nsStringHashKey key(aName); - nsProtocolPair* pair = (nsProtocolPair*)mProtocols->Get(&key); - if (pair == NULL) - return NS_ERROR_FAILURE; - if (aProtocolURLFactory) - *aProtocolURLFactory = pair->mProtocolURLFactory; - if (aProtocol) - *aProtocol = pair->mProtocol; - return NS_OK; -} - -NS_IMETHODIMP -nsNetlibService::CreateURL(nsIURI* *aURL, - const nsString& aSpec, - const nsIURI* aContextURL, - nsISupports* aContainer, - nsILoadGroup* aGroup) -{ - nsAutoString protoName; - PRInt32 pos = aSpec.FindChar(':'); - if (pos >= 0) { - aSpec.Left(protoName, pos); - } - else if (aContextURL) { - const char* str; - aContextURL->GetProtocol(&str); - protoName = str; - } - else { - protoName = "http"; - } - nsIProtocolURLFactory* protocolURLFactory; - nsresult err = GetProtocol(protoName, &protocolURLFactory, NULL); - if (err != NS_OK) return err; - - return protocolURLFactory->CreateURL(aURL, aSpec, aContextURL, aContainer, aGroup); -} - -NS_IMETHODIMP nsNetlibService::CreateSocketTransport(nsITransport **aTransport, PRUint32 aPortToUse, const char * aHostName) -{ - nsSocketTransport *pNSSocketTransport = NULL; - - NS_DEFINE_IID(kITransportIID, NS_ITRANSPORT_IID); - - pNSSocketTransport = new nsSocketTransport(aPortToUse, aHostName); - if (pNSSocketTransport->QueryInterface(kITransportIID, (void**)aTransport) != NS_OK) { - // then we're trying get a interface other than nsISupports and - // nsITransport - return NS_ERROR_FAILURE; - } - - return NS_OK; -} - -NS_IMETHODIMP nsNetlibService::CreateFileSocketTransport(nsITransport **aTransport, const char * aFileName) -{ - NS_PRECONDITION(aFileName, "You need to specify the file name of the file you wish to create a socket for"); - - nsSocketTransport *pNSSocketTransport = NULL; - - NS_DEFINE_IID(kITransportIID, NS_ITRANSPORT_IID); - - pNSSocketTransport = new nsSocketTransport(aFileName); - if (pNSSocketTransport->QueryInterface(kITransportIID, (void**)aTransport) != NS_OK) { - // then we're trying get a interface other than nsISupports and - // nsITransport - return NS_ERROR_FAILURE; - } - - return NS_OK; -} - - -NS_IMETHODIMP -nsNetlibService::AreThereActiveConnections() -{ - if (NET_AreThereActiveConnections() == PR_TRUE) - return 1; - else - return 0; -} - - -static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID); - -NS_NET nsresult NS_NewURL(nsIURI** aInstancePtrResult, - const nsString& aSpec, - const nsIURI* aURL, - nsISupports* aContainer, - nsILoadGroup* aGroup) -{ - NS_PRECONDITION(nsnull != aInstancePtrResult, "null ptr"); - if (nsnull == aInstancePtrResult) { - return NS_ERROR_NULL_POINTER; - } - - nsINetService *inet = nsnull; - nsresult rv = nsServiceManager::GetService(kNetServiceCID, - kINetServiceIID, - (nsISupports **)&inet); - if (rv != NS_OK) return rv; - - rv = inet->CreateURL(aInstancePtrResult, aSpec, aURL, aContainer, aGroup); - - nsServiceManager::ReleaseService(kNetServiceCID, inet); - return rv; -} - -NS_NET nsresult NS_MakeAbsoluteURL(nsIURI* aURL, - const nsString& aBaseURL, - const nsString& aSpec, - nsString& aResult) -{ - nsIURI* base = nsnull; - if (0 < aBaseURL.Length()) { - nsresult err = NS_NewURL(&base, aBaseURL); - if (err != NS_OK) return err; - } - else { - const char* str; - NS_ASSERTION(nsnull != aURL, "url is null"); - aURL->GetSpec(&str); - nsresult err = NS_NewURL(&base, str); - if (err != NS_OK) return err; - } - nsIURI* url = nsnull; - nsresult err = NS_NewURL(&url, aSpec, base); - if (err != NS_OK) goto done; - - PRUnichar* str; - err = url->ToString(&str); - if (err) goto done; - aResult = str; - delete []str; - - done: - NS_IF_RELEASE(url); - NS_IF_RELEASE(base); - return err; -} - -NS_NET nsresult NS_OpenURL(nsIURI* aURL, nsIStreamListener* aConsumer) -{ - nsresult rv; - nsILoadGroup* group = nsnull; - - rv = aURL->GetLoadGroup(&group); - if (NS_SUCCEEDED(rv)) { - if (nsnull != group) { - rv = group->OpenStream(aURL, aConsumer); - NS_RELEASE(group); - } else { - nsINetService *inet = nsnull; - - rv = nsServiceManager::GetService(kNetServiceCID, - kINetServiceIID, - (nsISupports **)&inet); - if (NS_SUCCEEDED(rv)) { - rv = inet->OpenStream(aURL, aConsumer); - nsServiceManager::ReleaseService(kNetServiceCID, inet); - } - } - } - return rv; -} - -NS_NET nsresult NS_OpenURL(nsIURI* aURL, nsIInputStream* *aNewStream, - nsIStreamListener* aConsumer) -{ - nsINetService *inet = nsnull; - nsresult rv = nsServiceManager::GetService(kNetServiceCID, - kINetServiceIID, - (nsISupports **)&inet); - if (rv != NS_OK) return rv; - - rv = inet->OpenBlockingStream(aURL, aConsumer, aNewStream); - - nsServiceManager::ReleaseService(kNetServiceCID, inet); - return rv; -} - -//////////////////////////////////////////////////////////////////////////////// - -void nsNetlibService::SchedulePollingTimer() -{ -#if !defined(NETLIB_THREAD) - // If a timer is already active, then do not create another... - if (nsnull == mPollingTimer) { - if (NS_OK == NS_NewTimer(&mPollingTimer)) { - mPollingTimer->Init(nsNetlibService::NetPollSocketsCallback, this, 1000 / 50); - } - } -#endif /* ! NETLIB_THREAD */ -} - - -void nsNetlibService::CleanupPollingTimer(nsITimer* aTimer) -{ -#if !defined(NETLIB_THREAD) - NS_PRECONDITION((aTimer == mPollingTimer), "Unknown Timer..."); - - NS_RELEASE(mPollingTimer); -#endif /* ! NETLIB_THREAD */ -} - - -#if !defined(NETLIB_THREAD) -void nsNetlibService::NetPollSocketsCallback(nsITimer* aTimer, void* aClosure) -{ - nsNetlibService* inet = (nsNetlibService*)aClosure; - - NS_PRECONDITION((nsnull != inet), "Null pointer"); - if (nsnull != inet) { - (void) NET_PollSockets(); - - inet->CleanupPollingTimer(aTimer); - // Keep scheduling callbacks as long as there are URLs to process... -/// if (0 < NET_TotalNumberOfProcessingURLs) { - inet->SchedulePollingTimer(); -/// } - } -} - -#if defined(XP_WIN) -/* - * This routine is used to avoid a (hopefully temporary) problem which netlib - * has when processing blocking HTTP streams. - * - * When ASYNC_DNS is enabled, all DNS lookups go through the main message pump, - * unfortunately, this is not possible when processing a blocking stream, so - * we deadlock :-( - * - * To avoid this deadlock, we synchronously resolve the hostname and store it - * in the little known IPAddressString field of the URL_Struct. This prevents - * netlib from doing an Async DNS lookup later... - */ -nsresult PerformNastyWindowsAsyncDNSHack(URL_Struct *URL_s, nsIURI* aURL) -{ - PRHostEnt hpbuf; - char dbbuf[PR_NETDB_BUF_SIZE]; - PRStatus err; - nsresult rv = NS_OK; - - /* Only attempt to resolve the hostname for HTTP URLs... */ - if (0 == PL_strcasecmp("http", aURL->GetProtocol())) { - /* Perform a synchronous DNS lookup... */ - err = PR_GetHostByName(aURL->GetHost(), dbbuf, sizeof(dbbuf), &hpbuf); - if (PR_SUCCESS == err) { - int a,b,c,d; - unsigned char *pc; - - pc = (unsigned char *) hpbuf.h_addr_list[0]; - - a = (int) *pc; - b = (int) *(++pc); - c = (int) *(++pc); - d = (int) *(++pc); - URL_s->IPAddressString = PR_smprintf("%d.%d.%d.%d", a,b,c,d); - } else { - /* - * If we fail to resolve a host on a HTTP connection, then - * abort the connection to prevent a deadlock... - */ - rv = NS_ERROR_FAILURE; - } - } - return rv; -} -#endif /* XP_WIN */ -#endif /* !NETLIB_THREAD */ - - -// This is global so it can be accessed by the NetFactory (nsNetFactory.cpp) -nsNetlibService *gNetlibService = nsnull; - -// -// Class to manage static initialization of the Netlib DLL... -// -struct nsNetlibInit { - nsNetlibInit() { - gNetlibService = nsnull; -#if !defined(NETLIB_THREAD) - /* - * The netlib thread cannot be created within a static constructor - * since a runtime library lock is being held by the mozilla thread - * which results in a deadlock when the netlib thread is started... - */ - (void) NS_InitINetService(); -#endif /* !NETLIB_THREAD */ - } - - ~nsNetlibInit() { -#if !defined(NETLIB_THREAD) - NS_ShutdownINetService(); -#endif /* !NETLIB_THREAD */ - gNetlibService = nsnull; - } -}; - -#if defined(XP_MAC) || defined(XP_UNIX) -static nsNetlibInit* netlibInit = nsnull; -#else -static nsNetlibInit netlibInit; -#endif - -extern "C" { -/* - * Factory for creating instance of the NetlibService... - */ -NS_NET nsresult NS_NewINetService(nsINetService** aInstancePtrResult, - nsISupports* aOuter) -{ - if (nsnull != aOuter) { - return NS_ERROR_NO_AGGREGATION; - } - -#if defined(XP_MAC) || defined(XP_UNIX) - // Perform static initialization... - if (nsnull == netlibInit) { - netlibInit = new nsNetlibInit; - } -#endif /* XP_MAC */ // XXX on the mac this never gets shutdown - - // The Netlib Service is created by the nsNetlibInit class... - if (nsnull == gNetlibService) { - (void) NS_InitINetService(); -/// return NS_ERROR_OUT_OF_MEMORY; - } - - return gNetlibService->QueryInterface(kINetServiceIID, (void**)aInstancePtrResult); -} - -extern "C" NS_NET nsresult -NS_InitializeHttpURLFactory(nsINetService* inet); - -NS_NET nsresult NS_InitINetService() -{ - /* XXX: For now only allow a single instance of the Netlib Service */ - if (nsnull == gNetlibService) { - gNetlibService = new nsNetlibService(); - if (nsnull == gNetlibService) { - return NS_ERROR_OUT_OF_MEMORY; - } - // XXX temporarily, until we have pluggable protocols... - NS_InitializeHttpURLFactory(gNetlibService); - } - - NS_ADDREF(gNetlibService); - return NS_OK; -} - - -NS_NET nsresult NS_ShutdownINetService() -{ - return NS_OK; -} - -} /* extern "C" */ - -/* - * This is the generic exit routine for all URLs loaded via the new - * BAM APIs... - */ -static void bam_exit_routine(URL_Struct *URL_s, int status, MWContext *window_id) -{ - TRACEMSG(("bam_exit_routine was called...\n")); - - if (NULL != URL_s) { - nsConnectionInfo *pConn = (nsConnectionInfo *)URL_s->fe_data; - -#ifdef NOISY - printf("+++ Finished loading %s\n", URL_s->address); -#endif - PR_ASSERT(pConn); - - /* Release the ConnectionInfo object held in the URL_Struct. */ - if (nsnull != pConn) { - /* - * Normally, the stream is closed when the connection has been - * completed. However, if the URL exit proc was called directly - * by NET_GetURL(...), then the stream may still be around... - */ - if (nsnull != pConn->pNetStream) { - pConn->pNetStream->Close(); - NS_RELEASE(pConn->pNetStream); - } - - /* - * If the connection is still marked as active, then - * notify the Data Consumer that the Binding has completed... - * Since the connection is still active, the stream was never - * closed (or possibly created). So, the binding has failed... - */ - if ((nsConnectionActive == pConn->mStatus) && - (nsnull != pConn->pConsumer)) { - nsAutoString status; - pConn->pConsumer->OnStopRequest(pConn->pURL, NS_BINDING_FAILED, status.GetUnicode()); - NS_RELEASE(pConn->pConsumer); - } - - /* Release the nsConnectionInfo object hanging off of the fe_data */ - URL_s->fe_data = NULL; - NS_RELEASE(pConn); - } - - /* Delete the URL_Struct... */ - NET_FreeURLStruct(URL_s); - } -} - -/* - * Ugly hack to free contexts - */ - -extern "C" void net_AddrefContext(MWContext *context) -{ - if (nsnull != context) { - context->ref_count++; - } -} - -extern "C" void net_ReleaseContext(MWContext *context) -{ - if (context) { - NS_PRECONDITION((0 < context->ref_count), "Context reference count is bad."); - if ((0 == --context->ref_count) && (context->modular_data)) { - free_stub_context(context); - } else { - TRACEMSG(("net_ReleaseContext: not releasing non-modular context")); - } - } -} - - -/* - * Rewrite "resource:/" URLs into file: URLs with the path of the - * executable prepended to the file path... - */ -char *mangleResourceIntoFileURL(const char* aResourceFileName) -{ - // XXX For now, resources are not in jar files - // Find base path name to the resource file - char* resourceBase; - -#ifdef XP_PC - // XXX For now, all resources are relative to the .exe file - resourceBase = (char *)PR_Malloc(_MAX_PATH);; - DWORD mfnLen = GetModuleFileName(g_hInst, resourceBase, _MAX_PATH); - // Truncate the executable name from the rest of the path... - char* cp = strrchr(resourceBase, '\\'); - if (nsnull != cp) { - *cp = '\0'; - } - // Change the first ':' into a '|' - cp = PL_strchr(resourceBase, ':'); - if (nsnull != cp) { - *cp = '|'; - } -#endif /* XP_PC */ - -#ifdef XP_UNIX - -// -// Obtain the resource: url base from the environment variable -// -// MOZILLA_FIVE_HOME -// -// Which is the standard place where mozilla stores global (ie, not -// user specific) data -// - -#ifndef MAXPATHLEN -#define MAXPATHLEN 1024 // A good guess, i suppose -#endif - -#define MOZILLA_FIVE_HOME "MOZILLA_FIVE_HOME" - - static char * nsUnixMozillaHomePath = nsnull; - - if (nsnull == nsUnixMozillaHomePath) - { - nsUnixMozillaHomePath = PR_GetEnv(MOZILLA_FIVE_HOME); - } - if (nsnull == nsUnixMozillaHomePath) - { - static char homepath[MAXPATHLEN]; - FILE* pp; - if (!(pp = popen("pwd", "r"))) { -#ifdef DEBUG - printf("RESOURCE protocol error in nsURL::mangeResourceIntoFileURL 1\n"); -#endif - return(nsnull); - } - if (fgets(homepath, MAXPATHLEN, pp)) { - homepath[PL_strlen(homepath)-1] = 0; - } - else { -#ifdef DEBUG - printf("RESOURCE protocol error in nsURL::mangeResourceIntoFileURL 2\n"); -#endif - pclose(pp); - return(nsnull); - } - pclose(pp); - nsUnixMozillaHomePath = homepath; - } - - resourceBase = XP_STRDUP(nsUnixMozillaHomePath); -#ifdef DEBUG - { - static PRBool firstTime = PR_TRUE; - if (firstTime) { - firstTime = PR_FALSE; - printf("Using '%s' as the resource: base\n", resourceBase); - } - } -#endif - -#endif /* XP_UNIX */ - -#ifdef XP_BEOS - { - static char buf[MAXPATHLEN]; - int32 cookie = 0; - image_info info; - char *p; - if(get_next_image_info(0, &cookie, &info) == B_OK) - { - strcpy(buf, info.name); - if((p = strrchr(buf, '/')) != 0) - *p = 0; - else - return nsnull; - - resourceBase = XP_STRDUP(buf); - } - else - return nsnull; - } -#endif /* XP_BEOS */ - -#ifdef XP_MAC - resourceBase = XP_STRDUP("usr/local/netscape/bin"); -#endif /* XP_MAC */ - - // Join base path to resource name - if (aResourceFileName[0] == '/') { - aResourceFileName++; - } - PRInt32 baseLen = PL_strlen(resourceBase); - PRInt32 resLen = PL_strlen(aResourceFileName); - PRInt32 totalLen = 8 + baseLen + 1 + resLen + 1; - char* fileName = (char *)PR_Malloc(totalLen); - PR_snprintf(fileName, totalLen, "file:///%s/%s", resourceBase, aResourceFileName); - -#ifdef XP_PC - // Change any backslashes into foreward slashes... - while ((cp = PL_strchr(fileName, '\\')) != 0) { - *cp = '/'; - cp++; - } -#endif /* XP_PC */ - - PR_Free(resourceBase); - - return fileName; -} - - - - -#ifdef XP_PC - -BOOL WINAPI DllMain(HINSTANCE hDllInst, - DWORD fdwReason, - LPVOID lpvReserved) -{ - BOOL bResult = TRUE; - - switch (fdwReason) - { - case DLL_PROCESS_ATTACH: - { - // save our instance - g_hInst = hDllInst; - } - break; - - case DLL_PROCESS_DETACH: - break; - - case DLL_THREAD_ATTACH: - break; - - case DLL_THREAD_DETACH: - break; - - default: - break; - } - - return (bResult); -} - - -#endif /* XP_PC */ diff --git a/mozilla/network/module/nsNetService.h b/mozilla/network/module/nsNetService.h deleted file mode 100644 index 715112484dc..00000000000 --- a/mozilla/network/module/nsNetService.h +++ /dev/null @@ -1,130 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsNetService_h___ -#define nsNetService_h___ - -#include "nsString.h" -#include "nspr.h" -#include "nsIPref.h" -#include "nsITransport.h" -#include "nsIEventQueueService.h" -#include "nsINetService.h" -#include "nsNetThread.h" -#include "nsHashtable.h" -#include "net.h" - -class nsITimer; - -// The chrome registry interface -class nsIChromeRegistry; - -class nsNetlibService : public nsINetService { - -public: - NS_DECL_ISUPPORTS - - nsNetlibService(); - - /* Implementation of the nsINetService interface */ - NS_IMETHOD OpenStream(nsIURI *aUrl, - nsIStreamListener *aConsumer); - NS_IMETHOD OpenBlockingStream(nsIURI *aUrl, - nsIStreamListener *aConsumer, - nsIInputStream **aNewStream); - - NS_IMETHOD InterruptStream(nsIURI* aURL); - - NS_IMETHOD GetCookieString(nsIURI *aURL, nsString& aCookie); - NS_IMETHOD SetCookieString(nsIURI *aURL, const nsString& aCookie); - - NS_IMETHOD Cookie_DisplayCookieInfoAsHTML(); - NS_IMETHOD Cookie_CookieViewerReturn(nsAutoString results); - NS_IMETHOD Cookie_GetCookieListForViewer(nsString& aCookieList); - NS_IMETHOD Cookie_GetPermissionListForViewer(nsString& aPermissionList); - - NS_IMETHOD GetProxyHTTP(nsString& aProxyHTTP); - NS_IMETHOD SetProxyHTTP(nsString& aProxyHTTP); - NS_IMETHOD GetHTTPOneOne(PRBool& aOneOne); - NS_IMETHOD SetHTTPOneOne(PRBool aSendOneOne); - - NS_IMETHOD GetAppCodeName(nsString& aAppCodeName); - NS_IMETHOD GetAppVersion(nsString& aAppVersion); - NS_IMETHOD GetAppName(nsString& aAppName); - NS_IMETHOD GetLanguage(nsString& aLanguage); - NS_IMETHOD GetPlatform(nsString& aPlatform); - NS_IMETHOD GetUserAgent(nsString& aUA); - NS_IMETHOD SetCustomUserAgent(nsString aCustom); - NS_IMETHOD RegisterProtocol(const nsString& aName, - nsIProtocolURLFactory* aProtocolURLFactory, - nsIProtocol* aProtocol); - NS_IMETHOD UnregisterProtocol(const nsString& aName); - NS_IMETHOD GetProtocol(const nsString& aName, - nsIProtocolURLFactory* *aProtocolURLFactory, - nsIProtocol* *aProtocol); - NS_IMETHOD CreateURL(nsIURI* *aURL, - const nsString& aSpec, - const nsIURI* aContextURL = nsnull, - nsISupports* aContainer = nsnull, - nsILoadGroup* aGroup = nsnull); - NS_IMETHOD AreThereActiveConnections(void); - - NS_IMETHOD CreateSocketTransport(nsITransport **aTransport, PRUint32 aPortToUse, const char * aHostName); - - NS_IMETHOD CreateFileSocketTransport(nsITransport **aTransport, const char * aFileName); - -protected: - virtual ~nsNetlibService(); - - nsresult StartNetlibThread(void); - nsresult StopNetlibThread(void); - - void SchedulePollingTimer(); - void CleanupPollingTimer(nsITimer* aTimer); - static void NetPollSocketsCallback(nsITimer* aTimer, void* aClosure); - -#if defined(NETLIB_THREAD) - static void NetlibThreadMain(void *aParam); -#endif /* NETLIB_THREAD */ - - // Chrome Registry static variables - static nsIChromeRegistry* gChromeRegistry; - static int gRefCnt; - -private: - void SetupURLStruct(nsIURI *aURL, URL_Struct *aURL_s); - /* XXX: This is temporary until bamwrap.cpp is removed... */ - void *m_stubContext; - nsIPref *mPref; - - nsITimer* mPollingTimer; - - nsNetlibThread* mNetlibThread; - nsIEventQueueService* mEventQService; - - nsHashtable* mProtocols; -}; - -extern "C" void net_ReleaseContext(MWContext *context); - - -#endif /* nsNetService_h___ */ diff --git a/mozilla/network/module/nsNetStream.cpp b/mozilla/network/module/nsNetStream.cpp deleted file mode 100644 index aa817c111d8..00000000000 --- a/mozilla/network/module/nsNetStream.cpp +++ /dev/null @@ -1,778 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsNetStream.h" -#include "net.h" -#include "mktrace.h" - -#if defined(XP_PC) -#include <windows.h> // Needed for Interlocked APIs defined in nsISupports.h -#endif /* XP_PC */ - -/* XXX: Declare NET_PollSockets(...) for the blocking stream hack... */ -extern "C" { - XP_Bool NET_PollSockets(void); -} - - -static NS_DEFINE_IID(kIInputStreamIID, NS_IINPUTSTREAM_IID); -static NS_DEFINE_IID(kIConnectionInfoIID, NS_ICONNECTIONINFO_IID); - -#define BUFFER_BLOCK_SIZE 8192 - - - - -nsConnectionInfo::nsConnectionInfo(nsIURI *aURL, - nsNetlibStream *aStream, - nsIStreamListener *aNotify) -{ - NS_INIT_REFCNT(); - - /* - * Cache the thread which is making the network request. Any cross-thread - * marshalling events will be sent to its event queue... - * - * XXX: Currently, this assumes that the nsConnectionInfo is *always* - * created on the requesting thread... The requesting thread - * should really be passed in via the public APIs... - */ - mRequestingThread = PR_GetCurrentThread(); - - mStatus = nsConnectionActive; - pURL = aURL; - pNetStream = aStream; - pConsumer = aNotify; - - NS_IF_ADDREF(pURL); - NS_IF_ADDREF(pNetStream); - NS_IF_ADDREF(pConsumer); - - NS_VERIFY_THREADSAFE_INTERFACE(pURL); - NS_VERIFY_THREADSAFE_INTERFACE(pNetStream); - NS_VERIFY_THREADSAFE_INTERFACE(pConsumer); -} - - -NS_IMPL_THREADSAFE_ISUPPORTS(nsConnectionInfo, kIConnectionInfoIID); - - -nsConnectionInfo::~nsConnectionInfo() -{ - TRACEMSG(("nsConnectionInfo is being destroyed...\n")); - - NS_IF_RELEASE(pURL); - NS_IF_RELEASE(pNetStream); - NS_IF_RELEASE(pConsumer); -} - -NS_IMETHODIMP -nsConnectionInfo::GetURL(nsIURI **aURL) -{ - *aURL = pURL; - NS_IF_ADDREF(pURL); - - return NS_OK; -} - -NS_IMETHODIMP -nsConnectionInfo::SetURL(nsIURI *aURL) -{ - NS_IF_RELEASE(pURL); // release old one - pURL = aURL; - NS_IF_ADDREF(pURL); // now addref new one - - return NS_OK; -} - - -NS_IMETHODIMP -nsConnectionInfo::GetInputStream(nsIInputStream **aStream) -{ - *aStream = (nsIInputStream *)pNetStream; - NS_IF_ADDREF(pNetStream); - - return NS_OK; -} - -NS_IMETHODIMP -nsConnectionInfo::GetOutputStream(nsIOutputStream **aStream) -{ - *aStream = (nsIOutputStream *)pNetStream; - NS_IF_ADDREF(pNetStream); - - return NS_OK; -} - -NS_IMETHODIMP -nsConnectionInfo::GetConsumer(nsIStreamListener **aConsumer) -{ - *aConsumer = pConsumer; - NS_IF_ADDREF(pConsumer); - - return NS_OK; -} - -nsNetlibStream::nsNetlibStream(void) -{ - NS_INIT_REFCNT(); - - m_Lock = PR_NewMonitor(); - m_bIsClosed = PR_FALSE; -} - - -NS_IMPL_THREADSAFE_ADDREF(nsNetlibStream) -NS_IMPL_THREADSAFE_RELEASE(nsNetlibStream) - -nsresult nsNetlibStream::QueryInterface(const nsIID &aIID, void** aInstancePtr) -{ - if (NULL == aInstancePtr) { - return NS_ERROR_NULL_POINTER; - } - static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); - static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID); - if (aIID.Equals(kIInputStreamIID)) { - *aInstancePtr = (void*) ((nsIInputStream*)this); - AddRef(); - return NS_OK; - } - if (aIID.Equals(kIOutputStreamIID)) { - *aInstancePtr = (void*) ((nsIOutputStream*)this); - AddRef(); - return NS_OK; - } - if (aIID.Equals(kISupportsIID)) { - *aInstancePtr = ((nsISupports *)(nsIInputStream *)this); - AddRef(); - return NS_OK; - } - -#if defined(NS_DEBUG) - /* - * Check for the debug-only interface indicating thread-safety - */ - static NS_DEFINE_IID(kIsThreadsafeIID, NS_ISTHREADSAFE_IID); - if (aIID.Equals(kIsThreadsafeIID)) { - return NS_OK; - } -#endif /* NS_DEBUG */ - - return NS_NOINTERFACE; -} - - - -nsNetlibStream::~nsNetlibStream() -{ - if (m_Lock) { - PR_DestroyMonitor(m_Lock); - m_Lock = NULL; - } -} - - -nsresult nsNetlibStream::Close() -{ - LockStream(); - m_bIsClosed = PR_TRUE; - UnlockStream(); - - return NS_OK; -} - - - - -nsBufferedStream::nsBufferedStream(void) -{ - m_BufferLength = BUFFER_BLOCK_SIZE; - - m_Buffer = new char[m_BufferLength]; - /* If the allocation failed, mark the stream as closed... */ - if (NULL == m_Buffer) { - m_bIsClosed = PR_TRUE; - m_BufferLength = 0; - } - - m_DataLength = 0; - m_ReadOffset = m_WriteOffset = 0; -} - - - - -nsBufferedStream::~nsBufferedStream() -{ - TRACEMSG(("nsBufferedStream is being destroyed...\n")); - - if (m_Buffer) { - delete[] m_Buffer; - m_Buffer = NULL; - } -} - - -nsresult nsBufferedStream::GetAvailableSpace(PRUint32 *aCount) -{ - nsresult err; - PRUint32 size = 0; - - if (m_bIsClosed) { - err = NS_BASE_STREAM_EOF; - } else { - err = NS_OK; - - LockStream(); - NS_ASSERTION(m_BufferLength >= m_WriteOffset, "unsigned madness"); - size = m_BufferLength - m_WriteOffset; - UnlockStream(); - } - *aCount = size; - return err; -} - - -nsresult nsBufferedStream::GetLength(PRUint32 *aLength) -{ - LockStream(); - *aLength = m_DataLength; - UnlockStream(); - - return NS_OK; -} - - -nsresult nsBufferedStream::Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteCount) -{ - PRUint32 bytesFree; - nsresult rv = NS_OK; - - LockStream(); - - NS_PRECONDITION((m_Buffer || m_bIsClosed), "m_Buffer is NULL!"); - NS_PRECONDITION((m_WriteOffset >= m_ReadOffset), "Read past the end of buffer."); - - /* Check for initial error conditions... */ - if (NULL == aBuf) { - rv = NS_BASE_STREAM_ILLEGAL_ARGS; - goto done; - } else if (m_bIsClosed) { - rv = NS_BASE_STREAM_EOF; - goto done; - } - - if (!m_bIsClosed && aBuf) { - /* Grow the buffer if necessary */ - NS_ASSERTION(m_BufferLength >= m_WriteOffset, "unsigned madness"); - bytesFree = m_BufferLength - m_WriteOffset; - if (aLen > bytesFree) { - char *newBuffer; - - m_BufferLength += (((aLen - bytesFree) / BUFFER_BLOCK_SIZE)+1) * BUFFER_BLOCK_SIZE; - newBuffer = (char *)realloc(m_Buffer, m_BufferLength); - /* If the allocation failed, close the stream and free the buffer... */ - if (NULL == newBuffer) { - m_bIsClosed = PR_TRUE; - free(m_Buffer); - m_Buffer = NULL; - m_BufferLength = 0; - - goto done; - } else { - m_Buffer = newBuffer; - } - } - - memcpy(&m_Buffer[m_WriteOffset], aBuf, aLen); - m_WriteOffset += aLen; - - *aWriteCount = aLen; - m_DataLength += aLen; - } - else if (m_bIsClosed) - { - rv = NS_BASE_STREAM_CLOSED; - } - -done: - UnlockStream(); - - return rv; -} - - -nsresult nsBufferedStream::Read(char *aBuf, - PRUint32 aCount, - PRUint32 *aReadCount) -{ - nsresult rv = NS_OK; - - LockStream(); - - NS_PRECONDITION((m_Buffer || m_bIsClosed), "m_Buffer is NULL!"); - NS_PRECONDITION((m_WriteOffset >= m_ReadOffset), "Read past the end of buffer."); - - /* Check for initial error conditions... */ - if (NULL == aBuf) { - rv = NS_BASE_STREAM_ILLEGAL_ARGS; - *aReadCount = 0; - goto done; - } else if (m_bIsClosed && (0 == m_DataLength)) { - rv = NS_BASE_STREAM_EOF; - *aReadCount = 0; - goto done; - } - - if (m_Buffer && m_DataLength) { - - /* Do not read more data than there is available... */ - if (aCount > m_DataLength) { - aCount = m_DataLength; - } - - memcpy(aBuf, &m_Buffer[m_ReadOffset], aCount); - m_ReadOffset += aCount; - - *aReadCount = aCount; - m_DataLength -= aCount; - } - else - *aReadCount = 0; - -done: - UnlockStream(); - - return rv; -} - -nsAsyncStream::nsAsyncStream(PRUint32 buffer_size) -{ - m_BufferLength = buffer_size; - - m_Buffer = (char *)malloc(m_BufferLength); - /* If the allocation failed, mark the stream as closed... */ - if (NULL == m_Buffer) { - m_bIsClosed = PR_TRUE; - m_BufferLength = 0; - } - - m_DataLength = 0; - m_ReadOffset = m_WriteOffset = 0; -} - - -nsAsyncStream::~nsAsyncStream() -{ - TRACEMSG(("nsAsyncStream is being destroyed...\n")); - - if (m_Buffer) { - free(m_Buffer); - m_Buffer = NULL; - } -} - - -nsresult nsAsyncStream::GetAvailableSpace(PRUint32 *aCount) -{ - nsresult err; - PRInt32 size = 0; - - if (m_bIsClosed) { - err = NS_BASE_STREAM_EOF; - } else { - err = NS_OK; - - LockStream(); - size = m_BufferLength - m_DataLength; - UnlockStream(); - } - *aCount = size; - return err; -} - - -nsresult nsAsyncStream::GetLength(PRUint32 *aLength) -{ - LockStream(); - *aLength = m_DataLength; - UnlockStream(); - - return NS_OK; -} - - -nsresult nsAsyncStream::Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteCount) -{ - PRUint32 bytesFree; - nsresult rv = NS_OK; - - LockStream(); - - NS_PRECONDITION((m_Buffer || m_bIsClosed), "m_Buffer is NULL!"); - - /* Check for initial error conditions... */ - if (NULL == aBuf) { - rv = NS_BASE_STREAM_ILLEGAL_ARGS; - goto done; - } else if (m_bIsClosed) { - rv = NS_BASE_STREAM_EOF; - goto done; - } - - if (!m_bIsClosed && aBuf) { - - /* Do not store more data than there is space for... */ - NS_ASSERTION(m_BufferLength >= m_DataLength, "unsigned madness"); - bytesFree = m_BufferLength - m_DataLength; - if (aLen > bytesFree) { - aLen = bytesFree; - } - - /* Storing the data will cause m_WriteOffset to wrap */ - if (m_WriteOffset + aLen > m_BufferLength) { - PRInt32 delta; - - /* Store the first chunk through the end of the buffer */ - delta = m_BufferLength - m_WriteOffset; - memcpy(&m_Buffer[m_WriteOffset], aBuf, delta); - - /* Store the second chunk from the beginning of the buffer */ - m_WriteOffset = aLen-delta; - memcpy(m_Buffer, &aBuf[delta], m_WriteOffset); - } else { - memcpy(&m_Buffer[m_WriteOffset], aBuf, aLen); - m_WriteOffset += aLen; - } - - *aWriteCount = aLen; - m_DataLength += aLen; - } - -done: - UnlockStream(); - - return rv; -} - - -nsresult nsAsyncStream::Read(char *aBuf, - PRUint32 aCount, - PRUint32 *aReadCount) -{ - nsresult rv = NS_OK; - - LockStream(); - - NS_PRECONDITION((m_Buffer || m_bIsClosed), "m_Buffer is NULL!"); - - /* Check for initial error conditions... */ - if (NULL == aBuf) { - rv = NS_BASE_STREAM_ILLEGAL_ARGS; - *aReadCount = 0; - goto done; - } else if (m_bIsClosed && (0 == m_DataLength)) { - rv = NS_BASE_STREAM_EOF; - *aReadCount = 0; - goto done; - } - - if (m_Buffer && m_DataLength) { - - /* Do not read more data than there is available... */ - if (aCount > m_DataLength) { - aCount = m_DataLength; - } - - /* Reading the data will cause m_ReadOffset to wrap */ - if (m_ReadOffset + aCount > m_BufferLength) { - PRInt32 delta; - - /* Read the first chunk through the end of the buffer */ - delta = m_BufferLength - m_ReadOffset; - memcpy(aBuf, &m_Buffer[m_ReadOffset], delta); - - /* Read the second chunk from the beginning of the buffer */ - m_ReadOffset = aCount-delta; - memcpy(&aBuf[delta], m_Buffer, m_ReadOffset); - } else { - memcpy(aBuf, &m_Buffer[m_ReadOffset], aCount); - m_ReadOffset += aCount; - } - - *aReadCount = aCount; - m_DataLength -= aCount; - } - else - *aReadCount = 0; - -done: - UnlockStream(); - - return rv; -} - - - - - - - - - -nsBlockingStream::nsBlockingStream() -{ - m_BufferLength = BUFFER_BLOCK_SIZE; - - m_Buffer = (char *)malloc(m_BufferLength); - /* If the allocation failed, mark the stream as closed... */ - if (NULL == m_Buffer) { - m_bIsClosed = PR_TRUE; - m_BufferLength = 0; - } - - m_DataLength = 0; - m_ReadOffset = m_WriteOffset = 0; -} - - -nsBlockingStream::~nsBlockingStream() -{ - TRACEMSG(("nsBlockingStream is being destroyed...\n")); - - if (m_Buffer) { - free(m_Buffer); - m_Buffer = NULL; - } -} - - -nsresult nsBlockingStream::Close() -{ - LockStream(); - m_bIsClosed = PR_TRUE; - -#if defined(NETLIB_THREAD) - /* Wake up any waiting threads... */ - PR_Notify(m_Lock); -#endif /* NETLIB_THREAD */ - - UnlockStream(); - - return NS_OK; -} - -nsresult nsBlockingStream::GetAvailableSpace(PRUint32 *aCount) -{ - nsresult err; - PRInt32 size = 0; - - if (m_bIsClosed) { - err = NS_BASE_STREAM_EOF; - } else { - err = NS_OK; - - LockStream(); - size = m_BufferLength - m_DataLength; - UnlockStream(); - } - *aCount = size; - return err; -} - - -nsresult nsBlockingStream::GetLength(PRUint32 *aLength) -{ - LockStream(); - *aLength = m_DataLength; - UnlockStream(); - - return NS_OK; -} - - -nsresult nsBlockingStream::Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteCount) -{ - PRUint32 bytesFree; - nsresult rv = NS_OK; - - LockStream(); - - NS_PRECONDITION((m_Buffer || m_bIsClosed), "m_Buffer is NULL!"); - - /* Check for initial error conditions... */ - if (NULL == aBuf) { - rv = NS_BASE_STREAM_ILLEGAL_ARGS; - goto done; - } else if (m_bIsClosed) { - rv = NS_BASE_STREAM_EOF; - goto done; - } - - if (!m_bIsClosed && aBuf) { - - /* Do not store more data than there is space for... */ - NS_ASSERTION(m_BufferLength >= m_DataLength, "unsigned madness"); - bytesFree = m_BufferLength - m_DataLength; - if (aLen > bytesFree) { - aLen = bytesFree; - } - - /* Storing the data will cause m_WriteOffset to wrap */ - if (m_WriteOffset + aLen > m_BufferLength) { - PRUint32 delta; - - /* Store the first chunk through the end of the buffer */ - NS_ASSERTION(m_BufferLength >= m_WriteOffset, "unsigned madness"); - delta = m_BufferLength - m_WriteOffset; - memcpy(&m_Buffer[m_WriteOffset], aBuf, delta); - - /* Store the second chunk from the beginning of the buffer */ - m_WriteOffset = aLen-delta; - memcpy(m_Buffer, &aBuf[delta], m_WriteOffset); - } else { - memcpy(&m_Buffer[m_WriteOffset], aBuf, aLen); - m_WriteOffset += aLen; - } - - *aWriteCount = aLen; - m_DataLength += aLen; - -#if defined(NETLIB_THREAD) - /* Wake up any waiting threads... */ - PR_Notify(m_Lock); -#endif /* NETLIB_THREAD */ - } - -done: - UnlockStream(); - - return rv; -} - - -nsresult nsBlockingStream::Read(char *aBuf, - PRUint32 aCount, - PRUint32 *aReadCount) -{ - nsresult rv = NS_OK; - - LockStream(); - - *aReadCount = 0; - - NS_PRECONDITION((m_Buffer || m_bIsClosed), "m_Buffer is NULL!"); - - /* Check for initial error conditions... */ - if (NULL == aBuf) { - rv = NS_BASE_STREAM_ILLEGAL_ARGS; - goto done; - } else if (m_bIsClosed && (0 == m_DataLength)) { - rv = NS_BASE_STREAM_EOF; - goto done; - } - - if (m_Buffer) { - - /* - * There is either enough data, or some data left in the stream - * after it has been closed... So, read it and return. - */ - if ((aCount <= m_DataLength) || m_bIsClosed) { - *aReadCount = ReadBuffer(aBuf, aCount); - } - /* Not enough data is available... Must block. */ - else { -#if !defined(NETLIB_THREAD) - UnlockStream(); - do { - NET_PollSockets(); - *aReadCount += ReadBuffer(aBuf + *aReadCount, aCount - *aReadCount); - /* XXX m_bIsClosed is checked outside of the lock! */ - } while ((aCount > *aReadCount) && !m_bIsClosed); - LockStream(); -#else - do { - PR_Wait(m_Lock, PR_INTERVAL_NO_TIMEOUT); - *aReadCount += ReadBuffer(aBuf + *aReadCount, aCount - *aReadCount); - } while ((aCount > *aReadCount) && !m_bIsClosed); -#endif /* NETLIB_THREAD */ - /* - * It is possible that the stream was closed during - * NET_PollSockets(...)... In this case, return EOF if no data - * is available... - */ - if ((0 == *aReadCount) && m_bIsClosed) { - rv = NS_BASE_STREAM_EOF; - } - } - } - -done: - UnlockStream(); - - return rv; -} - - -PRInt32 nsBlockingStream::ReadBuffer(char *aBuf, PRUint32 aCount) -{ - if (aCount == 0) return 0; /* avoid calling LockStream, memcpy, etc. */ - - PRUint32 bytesRead = 0; - - LockStream(); - - /* Do not read more data than there is available... */ - if (aCount > m_DataLength) { - aCount = m_DataLength; - } - - /* Reading the data will cause m_ReadOffset to wrap */ - if (m_ReadOffset + aCount > m_BufferLength) { - PRInt32 delta; - - /* Read the first chunk through the end of the buffer */ - delta = m_BufferLength - m_ReadOffset; - memcpy(aBuf, &m_Buffer[m_ReadOffset], delta); - - /* Read the second chunk from the beginning of the buffer */ - m_ReadOffset = aCount-delta; - memcpy(&aBuf[delta], m_Buffer, m_ReadOffset); - } else { - memcpy(aBuf, &m_Buffer[m_ReadOffset], aCount); - m_ReadOffset += aCount; - } - - bytesRead = aCount; - m_DataLength -= aCount; - - UnlockStream(); - - return bytesRead; -} diff --git a/mozilla/network/module/nsNetStream.h b/mozilla/network/module/nsNetStream.h deleted file mode 100644 index 945cb42d4f1..00000000000 --- a/mozilla/network/module/nsNetStream.h +++ /dev/null @@ -1,220 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef net_strm_h___ -#define net_strm_h___ - -#include "nspr.h" -#include "nsIURL.h" -#include "nsIInputStream.h" -#include "nsIOutputStream.h" -#include "nsIStreamListener.h" -#include "nsIConnectionInfo.h" - -/* Forward declaration... */ -class nsNetlibStream; - -/* Enumeration of the various connection states... */ -typedef enum { - nsConnectionActive = 0, - nsConnectionSucceeded, - nsConnectionAborted, - nsConnectionFailed, - nsConnectionMax -} nsConnectionStatus; - - -class nsConnectionInfo : public nsIConnectionInfo -{ -public: - NS_DECL_ISUPPORTS - - nsConnectionInfo(nsIURI *aURL, - nsNetlibStream *aStream, - nsIStreamListener *aNotify); - - NS_IMETHOD GetURL(nsIURI **aURL); - NS_IMETHOD SetURL(nsIURI *aURL); - NS_IMETHOD GetInputStream(nsIInputStream **aStream); - NS_IMETHOD GetOutputStream(nsIOutputStream **aStream); - NS_IMETHOD GetConsumer(nsIStreamListener **aConsumer); - -protected: - virtual ~nsConnectionInfo(); - -public: - nsIURI *pURL; - nsNetlibStream *pNetStream; - nsIStreamListener *pConsumer; - nsConnectionStatus mStatus; - PRThread* mRequestingThread; -}; - - -class nsNetlibStream : public nsIInputStream, - public nsIOutputStream -{ -public: - NS_DECL_ISUPPORTS - - nsNetlibStream(void); - - NS_IMETHOD GetAvailableSpace(PRUint32 *aCount) = 0; - - /* From nsIBaseStream interface */ - NS_IMETHOD Close(void); - -protected: - virtual ~nsNetlibStream(); - - inline void LockStream (void) { if (m_Lock) PR_EnterMonitor(m_Lock); } - inline void UnlockStream(void) { if (m_Lock) PR_ExitMonitor (m_Lock); } - -protected: - PRBool m_bIsClosed; - PRMonitor* m_Lock; - -}; - -/* - * Variable size, buffered stream... - */ -class nsBufferedStream : public nsNetlibStream { - -public: - nsBufferedStream(void); - - NS_IMETHOD GetAvailableSpace(PRUint32 *aCount); - - /* nsIInputStream interface */ - NS_IMETHOD GetLength(PRUint32 *aLength); - - NS_IMETHOD Read(char *aBuf, - PRUint32 aCount, - PRUint32 *aReadCount); - - /* nsIOutputStream interface */ - NS_IMETHOD Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteCount); - - NS_IMETHOD Flush(void) { - return NS_OK; - } - -protected: - virtual ~nsBufferedStream(); - -private: - char *m_Buffer; - PRUint32 m_BufferLength; - - PRUint32 m_DataLength; - PRUint32 m_ReadOffset; - PRUint32 m_WriteOffset; -}; - - -/* - * Fixed size stream... - */ - -class nsAsyncStream : public nsNetlibStream { - -public: - nsAsyncStream(PRUint32 buffer_size); - - NS_IMETHOD GetAvailableSpace(PRUint32 *aCount); - - /* nsIInputStream interface */ - NS_IMETHOD GetLength(PRUint32 *aLength); - - NS_IMETHOD Read(char *aBuf, - PRUint32 aCount, - PRUint32 *aReadLength); - - /* nsIOutputStream interface */ - NS_IMETHOD Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteLength); - - NS_IMETHOD Flush(void) { - return NS_OK; - } - -protected: - virtual ~nsAsyncStream(); - -private: - char *m_Buffer; - PRUint32 m_BufferLength; - - PRUint32 m_DataLength; - PRUint32 m_ReadOffset; - PRUint32 m_WriteOffset; -}; - - -/* - * Fixed size, blocking stream... - */ -class nsBlockingStream : public nsNetlibStream { - -public: - nsBlockingStream(void); - - NS_IMETHOD GetAvailableSpace(PRUint32 *aCount); - - /* nsIBaseStream interface */ - NS_IMETHOD Close(void); - - /* nsIInputStream interface */ - NS_IMETHOD GetLength(PRUint32 *aLength); - - NS_IMETHOD Read(char *aBuf, - PRUint32 aCount, - PRUint32 *aReadLength); - - /* nsIOutputStream interface */ - NS_IMETHOD Write(const char *aBuf, - PRUint32 aLen, - PRUint32 *aWriteLength); - - NS_IMETHOD Flush(void) { - return NS_OK; - } - -protected: - virtual ~nsBlockingStream(); - - PRInt32 ReadBuffer(char *aBuf, PRUint32 aCount); - -private: - char *m_Buffer; - PRUint32 m_BufferLength; - - PRUint32 m_DataLength; - PRUint32 m_ReadOffset; - PRUint32 m_WriteOffset; -}; - -#endif /* net_strm_h___ */ diff --git a/mozilla/network/module/nsNetStreamLoader.cpp b/mozilla/network/module/nsNetStreamLoader.cpp deleted file mode 100644 index 6beaca2be84..00000000000 --- a/mozilla/network/module/nsNetStreamLoader.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsIUnicharStreamLoader.h" -#include "nsIStreamListener.h" -#include "nsIInputStream.h" -#include "nsIURL.h" - -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static NS_DEFINE_IID(kIStreamListenerIID, NS_ISTREAMLISTENER_IID); -static NS_DEFINE_IID(kIUnicharStreamLoaderIID, NS_IUNICHARSTREAMLOADER_IID); - -class nsUnicharStreamLoader : public nsIUnicharStreamLoader, - public nsIStreamListener -{ -public: - nsUnicharStreamLoader(nsIURI* aURL, - nsStreamCompleteFunc aFunc, - void* aRef); - virtual ~nsUnicharStreamLoader(); - - NS_DECL_ISUPPORTS - - NS_IMETHOD GetNumCharsRead(PRInt32* aNumBytes); - - NS_IMETHOD OnStartRequest(nsIURI* aURL, const char *aContentType); - NS_IMETHOD OnProgress(nsIURI* aURL, PRUint32 aProgress, PRUint32 aProgressMax); - NS_IMETHOD OnStatus(nsIURI* aURL, const PRUnichar* aMsg); - NS_IMETHOD OnStopRequest(nsIURI* aURL, nsresult aStatus, const PRUnichar* aMsg); - NS_IMETHOD GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* aInfo); - NS_IMETHOD OnDataAvailable(nsIURI* aURL, nsIInputStream *aIStream, - PRUint32 aLength); - -protected: - nsStreamCompleteFunc mFunc; - void* mRef; - nsString* mData; -}; - - -nsUnicharStreamLoader::nsUnicharStreamLoader(nsIURI* aURL, - nsStreamCompleteFunc aFunc, - void* aRef) -{ - NS_INIT_REFCNT(); - mFunc = aFunc; - mRef = aRef; - mData = new nsString(); - - // XXX This is vile vile vile!!! - nsresult rv; - if (aURL) { - rv = NS_OpenURL(aURL, this); - if ((NS_OK != rv) && (nsnull != mFunc)) { - // Thou shalt not call out of scope whilst ones refcnt is zero - mRefCnt = 999; - (*mFunc)(this, *mData, mRef, rv); - mRefCnt = 0; - } - } -} - -nsUnicharStreamLoader::~nsUnicharStreamLoader() -{ - if (nsnull != mData) { - delete mData; - } -} - -NS_IMPL_ADDREF(nsUnicharStreamLoader) -NS_IMPL_RELEASE(nsUnicharStreamLoader) - -nsresult -nsUnicharStreamLoader::QueryInterface(const nsIID &aIID, void** aInstancePtr) -{ - if (NULL == aInstancePtr) { - return NS_ERROR_NULL_POINTER; - } - if (aIID.Equals(kIStreamListenerIID)) { - nsIStreamListener* tmp = this; - *aInstancePtr = (void*) tmp; - AddRef(); - return NS_OK; - } - if (aIID.Equals(kIUnicharStreamLoaderIID)) { - nsIUnicharStreamLoader* tmp = this; - *aInstancePtr = (void*) tmp; - AddRef(); - return NS_OK; - } - if (aIID.Equals(kISupportsIID)) { - nsIUnicharStreamLoader* tmp = this; - nsISupports* tmp2 = tmp; - *aInstancePtr = (void*) tmp2; - AddRef(); - return NS_OK; - } - - return NS_NOINTERFACE; -} - -NS_IMETHODIMP -nsUnicharStreamLoader::GetNumCharsRead(PRInt32* aNumBytes) -{ - if (nsnull != mData) { - *aNumBytes = mData->Length(); - } - else { - *aNumBytes = 0; - } - - return NS_OK; -} - -NS_IMETHODIMP -nsUnicharStreamLoader::OnStartRequest(nsIURI* aURL, - const char *aContentType) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsUnicharStreamLoader::OnProgress(nsIURI* aURL, - PRUint32 aProgress, - PRUint32 aProgressMax) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsUnicharStreamLoader::OnStatus(nsIURI* aURL, const PRUnichar* aMsg) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsUnicharStreamLoader::OnStopRequest(nsIURI* aURL, - nsresult aStatus, - const PRUnichar* aMsg) -{ - (*mFunc)(this, *mData, mRef, aStatus); - - return NS_OK; -} - -NS_IMETHODIMP -nsUnicharStreamLoader::GetBindInfo(nsIURI* aURL, - nsStreamBindingInfo* aInfo) -{ - return NS_OK; -} - -#define BUF_SIZE 1024 - -NS_IMETHODIMP -nsUnicharStreamLoader::OnDataAvailable(nsIURI* aURL, - nsIInputStream *aIStream, - PRUint32 aLength) -{ - nsresult rv = NS_OK; - char buffer[BUF_SIZE]; - PRUint32 len, lenRead; - - aIStream->GetLength(&len); - - while (len > 0) { - if (len < BUF_SIZE) { - lenRead = len; - } - else { - lenRead = BUF_SIZE; - } - - rv = aIStream->Read(buffer, lenRead, &lenRead); - if (NS_OK != rv) { - return rv; - } - - mData->Append(buffer, lenRead); - len -= lenRead; - } - - return rv; -} - -extern NS_NET nsresult -NS_NewUnicharStreamLoader(nsIUnicharStreamLoader** aInstancePtrResult, - nsIURI* aURL, - nsStreamCompleteFunc aFunc, - void* aRef) -{ - NS_PRECONDITION(nsnull != aInstancePtrResult, "null ptr"); - if (nsnull == aInstancePtrResult) { - return NS_ERROR_NULL_POINTER; - } - - nsUnicharStreamLoader* it = new nsUnicharStreamLoader(aURL, - aFunc, - aRef); - if (nsnull == it) { - return NS_ERROR_OUT_OF_MEMORY; - } - return it->QueryInterface(kIUnicharStreamLoaderIID, - (void **) aInstancePtrResult); -} diff --git a/mozilla/network/module/nsNetStubs.cpp b/mozilla/network/module/nsNetStubs.cpp deleted file mode 100644 index ad451eb405a..00000000000 --- a/mozilla/network/module/nsNetStubs.cpp +++ /dev/null @@ -1,2180 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "nsNetStubs.h" - -#include "nspr.h" -#include "xp_hash.h" -#include "xp_file.h" -#include "libi18n.h" -#include "libevent.h" -#include "mkgeturl.h" -#include "net.h" -#include "nsIRefreshUrl.h" -#include "nsString.h" -#include "nsNetStream.h" -#include "intl_csi.h" - -#ifdef NS_NET_FILE - -extern char *USER_DIR; -extern char *CACHE_DIR; -extern char *DEF_DIR; - -// For xp to ns file translation -#include "nsINetFile.h" -#include "nsVoidArray.h" -#include "direct.h" - -// The nsINetfile -static nsINetFile *fileMgr = nsnull; - -typedef struct _xp_to_nsFile { - nsFile *nsFp; - XP_File xpFp; -} xpNSFile; - -// Array of translation structs from xp to ns file. -static nsVoidArray switchBack; - -// end xp to ns file translation - -#endif // NS_NET_FILE - -extern "C" { -#include "secnav.h" -#include "preenc.h" -} - -/* From libimg */ -#define OPAQUE_CONTEXT void - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/intl_csi.c - *--------------------------------------------------------------------------- - */ - -extern "C" { - -#if defined(XP_UNIX) || defined(XP_MAC) -DB * -dbopen(const char */*fname*/, int /*flags*/,int /*mode*/, DBTYPE /*type*/, - const void */*openinfo*/) -{ -#if defined(XP_MAC) - PR_ASSERT(FALSE); -#endif - - return NULL; -} -#endif - -/* Meta charset is weakest. Only set doc_csid if no http or override */ -void -INTL_SetCSIDocCSID (INTL_CharSetInfo /*c*/, int16 /*doc_csid*/) -{ - MOZ_FUNCTION_STUB; -} - - -int16 -INTL_GetCSIDocCSID(INTL_CharSetInfo /*c*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -void -INTL_SetCSIWinCSID(INTL_CharSetInfo /*c*/, int16 /*win_csid*/) -{ - MOZ_FUNCTION_STUB; -} - - -int16 -INTL_GetCSIWinCSID(INTL_CharSetInfo /*c*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -INTL_CharSetInfo -LO_GetDocumentCharacterSetInfo(MWContext */*context*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/acptlang.c - *--------------------------------------------------------------------------- - */ - -/* INTL_GetAcceptCharset() */ -/* return the AcceptCharset from XP Preference */ -/* this should be a C style NULL terminated string */ -char* INTL_GetAcceptCharset() -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -/* INTL_GetAcceptLanguage() */ -/* return the AcceptLanguage from XP Preference */ -/* this should be a C style NULL terminated string */ -char* INTL_GetAcceptLanguage() -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/net_junk.c - *--------------------------------------------------------------------------- - */ -PUBLIC Stream * -INTL_ConvCharCode (int /*format_out*/, - void */*data_obj*/, - URL_Struct */*URL_s*/, - MWContext */*mwcontext*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/cvchcode.c - *--------------------------------------------------------------------------- - */ - -/* INTL_GetCharCodeConverter: - * RETURN: 1 if converter found, else 0 - * Also, sets: - * obj->cvtfunc: function handle for chararcter - * code set streams converter - * obj->cvtflag: (Optional) flag to converter - * function - * obj->from_csid: Code set converting from - * obj->to_csid: Code set converting to - * If the arg to_csid==0, then use the the conversion for the - * first conversion entry that matches the from_csid. - */ -int -INTL_GetCharCodeConverter(register int16 /*from_csid*/, - register int16 /*to_csid*/, - CCCDataObject /*obj*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -CCCDataObject -INTL_CreateCharCodeConverter() -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -unsigned char * -INTL_CallCharCodeConverter(CCCDataObject /*obj*/, const unsigned char */*buf*/, - int32 /*bufsz*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -void -INTL_DestroyCharCodeConverter(CCCDataObject /*obj*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/csnamefn.c - *--------------------------------------------------------------------------- - */ -int16 -INTL_CharSetNameToID(char */*charset*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/ucs2.c - *--------------------------------------------------------------------------- - */ -uint32 INTL_TextToUnicode( - INTL_Encoding_ID /*encoding*/, - unsigned char* /*src*/, - uint32 /*srclen*/, - INTL_Unicode* /*ustr*/, - uint32 /*ubuflen*/ -) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -uint32 INTL_TextToUnicodeLen( - INTL_Encoding_ID /*encoding*/, - unsigned char* /*src*/, - uint32 /*srclen*/ -) -{ - MOZ_FUNCTION_STUB; - return 0; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/fe_ccc.c - *--------------------------------------------------------------------------- - */ -/* - INTL_DocToWinCharSetID, - Based on DefaultDocCSID, it determines which Win CSID to use for Display -*/ -/* - - To Do: (ftang) - - We should seperate the DocToWinCharSetID logic from the cscvt_t table - for Cyrillic users. - -*/ -int16 INTL_DocToWinCharSetID(int16 /*csid*/) -{ - MOZ_FUNCTION_STUB; - return CS_FE_ASCII; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libi18n/doc_ccc.c - *--------------------------------------------------------------------------- - */ - -PUBLIC void INTL_CCCReportMetaCharsetTag(MWContext */*context*/, char */*charset_tag*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/authdll.cpp - *--------------------------------------------------------------------------- - */ -char * WFE_BuildCompuserveAuthString(URL_Struct */*URL_s*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -int -WFE_DoCompuserveAuthenticate(MWContext */*context*/, - URL_Struct */*URL_s*/, - char */*authenticate_header_value*/) -{ - MOZ_FUNCTION_STUB; - return NET_AUTH_FAILED_DONT_DISPLAY; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/regproto.cpp - *--------------------------------------------------------------------------- - */ - -// Purpose: See if we're supposed to handle a specific protocol differently. -// Arguments: pContext The context. -// iFormatOut The format out (possibly saving). -// pURL The URL to load. -// pExitFunc The URL exit routine. If we handle the protocol, we use the function. -//Returns: BOOL TRUE We want to handle the protocol here. -// FALSE Netlib continues to handle the protocol. -//Comments: To work with certain DDE topics which can cause URLs of a specific protocol type to be handled by another -// application. -//Revision History: -// 01-17-95 created GAB -// - -XP_Bool FE_UseExternalProtocolModule(MWContext */*pContext*/, FO_Present_Types /*iFormatOut*/, - URL_Struct */*pURL*/, - Net_GetUrlExitFunc */*pExitFunc*/) -{ - MOZ_FUNCTION_STUB; - return FALSE; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/femess.cpp - *--------------------------------------------------------------------------- - */ -// -// Prompt the user for a local file name -// -int FE_PromptForFileName(MWContext */*context*/, - const char */*prompt_string*/, - const char */*default_path*/, - XP_Bool /*file_must_exist_p*/, - XP_Bool /*directories_allowed_p*/, - ReadFileNameCallbackFunction /*fn*/, - void */*closure*/) -{ - MOZ_FUNCTION_STUB; - return -1; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/fegui.cpp - *--------------------------------------------------------------------------- - */ -// Return some spanked out full path on the mac. -// For windows, we just return what was passed in. -// We must provide it in a seperate buffer, otherwise they might change -// the original and change also what they believe to be saved. -char *WH_FilePlatformName(const char */*pName*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -// Purpose: Set a delayed load timer for a window for a particular URL. -// Arguments: pContext The context that we're in. We are only interested on wether or not there appears to be a Frame/hence document. -// ulSeconds The number of seconds that will pass before we attempt the reload. -// Returns: void -// Comments: -// Revision History: -// 02-17-95 created GAB -// 07-22-95 modified to use new context. -// 05-03-96 modified to use new API outside of idle loop. -// - -NS_DEFINE_IID(kRefreshURLIID, NS_IREFRESHURL_IID); - -void FE_SetRefreshURLTimer(MWContext *pContext, URL_Struct *URL_s) -{ - nsresult rv; - nsIRefreshUrl* IRefreshURL=nsnull; - nsString refreshURL(URL_s->refresh_url); - nsConnectionInfo* pConn; - - NS_PRECONDITION((URL_s != nsnull), "Null pointer..."); - NS_PRECONDITION((pContext != nsnull), "Null pointer..."); - NS_PRECONDITION((pContext->modular_data != nsnull), "Null pointer..."); - NS_PRECONDITION((pContext->modular_data->fe_data != nsnull), "Null pointer..."); - - // Get the nsConnectionInfo out of the context. - // modular_data points to a URL_Struct. - pConn = (nsConnectionInfo*) pContext->modular_data->fe_data; - - NS_PRECONDITION((pConn != nsnull), "Null pointer..."); - - if (nsnull != pConn) { - /* Get the pointer to the nsIRefreshURL from the nsISupports - * of the nsIContentViewerContainer the nsConnnectionInfo holds. - */ - if (nsnull != pConn->pURL) { - nsISupports* container; - - rv = pConn->pURL->GetContainer(&container); - if (container && (rv == NS_OK)) { - rv = container->QueryInterface(kRefreshURLIID, (void**)&IRefreshURL); - if(NS_SUCCEEDED(rv)) { - nsIURI* newURL; - - rv = NS_NewURL(&newURL, refreshURL); - if (NS_SUCCEEDED(rv)) { - rv = IRefreshURL->RefreshURL(newURL, URL_s->refresh*1000, FALSE); - NS_RELEASE(newURL); - } - NS_RELEASE(IRefreshURL); - } - NS_RELEASE(container); - } - } - } - MOZ_FUNCTION_STUB; -} - - -PUBLIC void -FE_ConnectToRemoteHost(MWContext * /*context*/, int /*url_type*/, - char * /*hostname*/, char * /*port*/, char * /*username*/) -{ - MOZ_FUNCTION_STUB; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/feutil.cpp - *--------------------------------------------------------------------------- - */ - -// The purpose of FEU_AhAhAhAhStayingAlive is to house the one and only -// saturday night fever function; named after Chouck's idol. -// This function will attempt to do all that is necessary in order -// to keep the application's messages flowing and idle loops -// going when we need to finish an asynchronous operation -// synchronously. -// The current cases that cause this are RPC calls into the -// application where we need to return a value or produce output -// from only one entry point before returning to the caller. -// -// If and when you modify this function, get your changes reviewed. -// It is too vital that this work, always. -// -// The function only attempts to look at one message at a time, or -// propigate one idle call at a time, keeping it's own idle count. -// This is not a loop. YOU must provide the loop which calls this function. -// -// Due to the nature and order of which we process windows messages, this -// can seriously mess with the flow of control through the client. -// If there is any chance at all that you can ensure that you are at the -// bottom of the message queue before doing this, then please take those -// measures. -void FEU_StayingAlive() -{ - MOZ_FUNCTION_STUB; -} - - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/cfe.cpp - *--------------------------------------------------------------------------- - */ -void FE_RunNetcaster(MWContext */*context*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/xp/xp_cntxt.c - *--------------------------------------------------------------------------- - */ - -/* - * if the passed context is in the global context list - * TRUE is returned. Otherwise false - */ -Bool XP_IsContextInList(MWContext */*context*/) -{ - MOZ_FUNCTION_STUB; - return FALSE; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/xp/xplocale.c - *--------------------------------------------------------------------------- - */ - -size_t XP_StrfTime(MWContext* /*context*/, char */*result*/, size_t /*maxsize*/, int /*format*/, - const struct tm */*timeptr*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/layout/edtutil.cpp - *--------------------------------------------------------------------------- - */ - -void EDT_SavePublishUsername(MWContext */*pContext*/, char */*pAddress*/, char */*pUsername*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/layout/layutil.c - *--------------------------------------------------------------------------- - */ - - /* - * Return the width of the window for this context in chars in the default - * fixed width font. Return -1 on error. - */ -int16 -LO_WindowWidthInFixedChars(MWContext */*context*/) -{ - MOZ_FUNCTION_STUB; - return 80; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/layout/layinfo.c - *--------------------------------------------------------------------------- - */ - -/* - * Prepare a bunch of information about the content of this - * document and prints the information as HTML down - * the passed in stream. - * - * Returns: - * -1 If the context passed does not correspond to any currently - * laid out document. - * 0 If the context passed corresponds to a document that is - * in the process of being laid out. - * 1 If the context passed corresponds to a document that is - * completly laid out and info can be found. - */ -PUBLIC intn -LO_DocumentInfo(MWContext */*context*/, NET_StreamClass */*stream*/) -{ - MOZ_FUNCTION_STUB; - return -1; -} - -#if 1 - -/* - *--------------------------------------------------------------------------- - * From ns/modules/libimg/src/if.c - *--------------------------------------------------------------------------- - */ - -/* - * determine what kind of image data we are dealing with - */ -#ifndef XP_MAC -int -IL_Type(const char */*buf*/, int32 /*len*/) -{ - MOZ_FUNCTION_STUB; - return 0; /* IL_NOTFOUND */ -} -#endif /* XP_MAC */ - -/* - *--------------------------------------------------------------------------- - * From ns/modules/libimg/src/ilclient.c - *--------------------------------------------------------------------------- - */ - -/* - * Create an HTML stream and generate HTML describing - * the image cache. Use "about:memory-cache" URL to acess. - */ -static int -IL_DisplayMemCacheInfoAsHTML(FO_Present_Types /*format_out*/, URL_Struct */*urls*/, - OPAQUE_CONTEXT */*cx*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -#ifndef XP_MAC -char * -IL_HTMLImageInfo(char */*url_address*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} -#endif /* XP_MAC */ - - -/* Set limit on approximate size, in bytes, of all pixmap storage used - by the imagelib. */ -#ifndef XP_MAC -void -IL_SetCacheSize(uint32 /*new_size*/) -{ - MOZ_FUNCTION_STUB; -} -#endif /* XP_MAC */ - - - -/* - *--------------------------------------------------------------------------- - * From ns/modules/libimg/src/external.c - *--------------------------------------------------------------------------- - */ -static NET_StreamClass * -IL_ViewStream(FO_Present_Types /*format_out*/, void */*newshack*/, URL_Struct */*urls*/, - OPAQUE_CONTEXT */*cx*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -#endif - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmisc/glhist.c - *--------------------------------------------------------------------------- - */ - -PUBLIC void -NET_RegisterEnableUrlMatchCallback(void) -{ - MOZ_FUNCTION_STUB; -} - - -/* start global history tracking - */ -PUBLIC void -GH_InitGlobalHistory(void) -{ - MOZ_FUNCTION_STUB; -} - - -/* save the global history to a file while leaving the object in memory - */ -PUBLIC void -GH_SaveGlobalHistory(void) -{ - MOZ_FUNCTION_STUB; -} - - - -/* create an HTML stream and push a bunch of HTML about - * the global history - */ -MODULE_PRIVATE int -NET_DisplayGlobalHistoryInfoAsHTML(MWContext */*context*/, - URL_Struct */*URL_s*/, - int /*format_out*/) -{ - MOZ_FUNCTION_STUB; - return MK_UNABLE_TO_CONVERT; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmisc/shist.c - *--------------------------------------------------------------------------- - */ -PUBLIC int -SHIST_GetIndex(History * /*hist*/, History_entry * /*entry*/) -{ - MOZ_FUNCTION_STUB; - return -1; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/plugin/npglue.c - *--------------------------------------------------------------------------- - */ - -XP_Bool -NPL_HandleURL(MWContext */*cx*/, - FO_Present_Types /*iFormatOut*/, URL_Struct */*pURL*/, Net_GetUrlExitFunc */*pExitFunc*/) -{ - MOZ_FUNCTION_STUB; - return FALSE; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmocha/lm_taint.c - *--------------------------------------------------------------------------- - */ - -const char * -LM_SkipWysiwygURLPrefix(const char */*url_string*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/htmldlgs/htmldlgs.c - *--------------------------------------------------------------------------- - */ - -void -XP_HandleHTMLPanel(URL_Struct */*url*/) -{ - MOZ_FUNCTION_STUB; -} - - -void -XP_HandleHTMLDialog(URL_Struct */*url*/) -{ - MOZ_FUNCTION_STUB; -} - - -/* - *--------------------------------------------------------------------------- - * Needed by mkcache.c (at least) - *--------------------------------------------------------------------------- - */ - -char ** fe_encoding_extensions = NULL; -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmisc/glhist.c - *--------------------------------------------------------------------------- - */ - -PUBLIC void -GH_UpdateGlobalHistory(URL_Struct * /*URL_s*/) -{ - MOZ_FUNCTION_STUB; -} - - -/* clear the global history list - */ -PUBLIC void -GH_ClearGlobalHistory(void) -{ - MOZ_FUNCTION_STUB; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmisc/shist.c - *--------------------------------------------------------------------------- - */ - - -PUBLIC History_entry * -SHIST_GetCurrent(History * /*hist*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -#ifdef NS_NET_FILE -// XXXXXXXXXXXXXXXXXXXXXXXXX NS_NET_FILE BEGIN XXXXXXXXXXXXXXXXXXXXXXXXX - -// Begin nsNetFile versions of xp_file routines. These stubs utilize the new -// nsINetFile interface to do file i/o type things. - - -// Utility routine to remove a transator object from the array and free it. -nsresult deleteTrans(nsFile *nsFp) { - xpNSFile *trans = nsnull; - - if (!nsFp) - return NS_OK; - - for (PRInt32 i = switchBack.Count(); i > 0; i--) { - trans = (xpNSFile*)switchBack.ElementAt(i-1); - if (trans && trans->nsFp == nsFp) { - switchBack.RemoveElement(trans); - if (trans->xpFp) { - PR_Free(trans->xpFp); - trans->xpFp = nsnull; - } - PR_Free(trans); - return NS_OK; - } - } - return NS_ERROR_FAILURE; - -} - -// Utility routine to convert an xpFile pointer to a ns file pointer. -nsFile * XpToNsFp(XP_File xpFp) { - nsFile *nsFp = nsnull; - xpNSFile *trans = nsnull; - - if (!xpFp) - return nsnull; - for (PRInt32 i = switchBack.Count(); i > 0; i--) { - trans = (xpNSFile*)switchBack.ElementAt(i-1); - if (trans && trans->xpFp == xpFp) { - nsFp = trans->nsFp; - break; - } - } - return nsFp; -} - -/* -// -// Open a file with the given name -// If a special file type is provided we might need to get the name -// out of the preferences list -// -*/ - -/* List of old xpFile enums we need to support - * Don't need cache stuff as new cache module will do it's own disk i/o -xpCacheFAT -xpCache -xpSARCache -xpExtCacheIndex - -xpProxyConfig -xpURL -xpJSConfig -xpTemporary -xpJSCookieFilters -xpFileToPost -xpMimeTypes -xpHTTPCookie -xpHTTPCookiePermission -xpHTTPSingleSignon*/ - -// Caller is repsonsible for freeing string. - -PRIVATE -char *xpFileTypeToName(XP_FileType type) { - char *name = nsnull; - switch (type) { - case (xpCache): - return PL_strdup(CACHE_DIR_TOK); - break; - case (xpCacheFAT): - return PL_strdup(CACHE_DIR_TOK CACHE_DB_F_TOK); - break; - case (xpProxyConfig): - break; - case (xpURL): - break; - case (xpJSConfig): - break; - case (xpTemporary): - break; - case (xpJSCookieFilters): - break; - case (xpFileToPost): - break; - case (xpMimeTypes): - break; - case (xpHTTPCookie): - return PL_strdup("%USER%%COOKIE_F%"); - case (xpHTTPCookiePermission): - return PL_strdup("%USER%%COOKIE_PERMISSION_F%"); -#ifdef SingleSignon - case (xpHTTPSingleSignon): - return PL_strdup("%USER%%SIGNON_F%"); -#endif - - default: - break; - } - return nsnull; -} - -/* -// The caller is responsible for XP_FREE()ing the return string -*/ -PUBLIC char * -WH_FileName (const char *NetName, XP_FileType type) -{ - char *path = nsnull, *aName = nsnull; - nsresult rv; - - if (!NetName || !*NetName) { - aName = xpFileTypeToName(type); - if (!aName) { - return NULL; - } - } - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - return NULL; - } - } - - rv = fileMgr->GetFilePath( (aName ? aName : NetName), &path); - PR_FREEIF(aName); - if (rv != NS_OK) - return NULL; - - return path; -} - -char * -WH_TempName(XP_FileType type, const char * prefix) -{ - char *path = nsnull, *aName = nsnull; - nsresult rv; - - aName = xpFileTypeToName(type); - if (!aName) { - return NULL; - } - - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - return NULL; - } - } - - rv = fileMgr->GetCacheFileName(aName, &path); - PR_FREEIF(aName); - if (rv != NS_OK) - return NULL; - - return path; -} - -PUBLIC int -NET_I_XP_Fileno(XP_File fp) { - nsFile *nsFp = XpToNsFp(fp); // nsnull ok. - - NS_PRECONDITION( (nsFp != nsnull), "Null pointer."); - - return (int) nsFp->fd; -} - -PUBLIC int -NET_I_XP_FileSeek(XP_File fp, long offset, int origin) { - nsFile *nsFp = XpToNsFp(fp); // nsnull ok. - PRSeekWhence sw; - - NS_PRECONDITION( (nsFp != nsnull), "Null pointer."); - - /* Need to confirm the origin to PRSeekWhence mapping */ - - switch (origin) { - case (0): - sw = PR_SEEK_SET; - break; - case (1): - sw = PR_SEEK_CUR; - break; - case (2): - sw = PR_SEEK_END; - break; - default: - sw = PR_SEEK_SET; - } - - return PR_Seek(nsFp->fd, offset, sw); -} - -// Initialization routine for nsNetFile. This registers all the directories -// and files in the nsNetFile instance. Use the form: -// token = %token% -// value = opaque string -// -// Directories and files are platform specific. -PUBLIC PRBool -NET_InitFilesAndDirs(void) { - PRFileInfo dir; - PRStatus status; - char tmpBuf[_MAX_PATH]; -#ifdef XP_PC - char *mDirDel = "\\"; -#elif XP_MAC - char *mDirDel = ":"; -#else - char *mDirDel = "/"; -#endif - - // Setup directories, step 1. - USER_DIR = _getcwd(USER_DIR, _MAX_PATH); - CACHE_DIR = _getcwd(CACHE_DIR, _MAX_PATH); - DEF_DIR = _getcwd(DEF_DIR, _MAX_PATH); - - // setup the cache dir. - PL_strcpy(tmpBuf, CACHE_DIR); - sprintf(CACHE_DIR,"%s%s%s%s", tmpBuf, mDirDel, "cache", mDirDel); - status = PR_GetFileInfo(CACHE_DIR, &dir); - if (status == PR_FAILURE) { - // Create the dir. - status = PR_MkDir(CACHE_DIR, 0600); - if (status != PR_SUCCESS) { - ; // bummer! - } - } - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - return FALSE; - } - } - - // Setup directories. - fileMgr->SetDirectory(USER_DIR_TOK, USER_DIR); - fileMgr->SetDirectory(CACHE_DIR_TOK, CACHE_DIR); - fileMgr->SetDirectory(DEF_DIR_TOK, DEF_DIR); - - // Setup files. - fileMgr->SetFileAssoc(COOKIE_FILE_TOK, COOKIE_FILE, USER_DIR_TOK); - fileMgr->SetFileAssoc(COOKIE_PERMISSION_FILE_TOK, COOKIE_PERMISSION_FILE, USER_DIR_TOK); -#ifdef SingleSignon - fileMgr->SetFileAssoc(SIGNON_FILE_TOK, SIGNON_FILE, USER_DIR_TOK); -#endif - fileMgr->SetFileAssoc(CACHE_DB_F_TOK, CACHE_DB_FILE, CACHE_DIR_TOK); - return TRUE; -} - -PUBLIC XP_File -NET_I_XP_FileOpen(const char * name, XP_FileType type, const XP_FilePerm perm) -{ - XP_File xpFp; - xpNSFile *trans = (xpNSFile*)PR_Malloc(sizeof(xpNSFile)); - nsFile *nsFp = nsnull; - nsresult rv; - nsFileMode mode; - char *aName = nsnull; - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - return NULL; - } - } - - // Just get some random address. - xpFp = (XP_File) PR_Malloc(1); - - trans->xpFp= xpFp; - - if ((!PL_strcasecmp(perm,XP_FILE_READ)) || - (!PL_strcasecmp(perm,XP_FILE_READ_BIN))) { - mode = nsRead; - } else if (!PL_strcasecmp(perm,XP_FILE_WRITE)) { - mode = nsOverWrite; - } else if (!PL_strcasecmp(perm,XP_FILE_WRITE_BIN)) { - mode = nsOverWrite; - } else { - mode = nsReadWrite; - } - - /* call OpenFile with nsNetFile syntax if necesary. */ - if ( (!name || !*name) - || type == xpCache ) { - char *tmpName = xpFileTypeToName(type); - nsString newName = tmpName; - PR_FREEIF(tmpName) - if (newName.Length() < 1) { - PR_Free(trans); - PR_Free(xpFp); - return NULL; - } - newName.Append(name); - aName = newName.ToNewCString(); - } - - rv = fileMgr->OpenFile( (aName ? aName : name), mode, &nsFp); - if (aName) - delete[] aName; - if (NS_OK != rv) { - return NULL; - } - - trans->nsFp = nsFp; - - switchBack.AppendElement(trans); - - return xpFp; -} - -PUBLIC char * -NET_I_XP_FileReadLine(char *outBuf, int outBufLen, XP_File fp) { - nsFile *nsFp = XpToNsFp(fp); // nsnull ok. - PRInt32 readBytes; - nsresult rv; - - NS_PRECONDITION( (nsFp != nsnull), "Null pointer"); - - if (!nsFp) - return NULL; - - if (!fileMgr) - return NULL; - - rv = fileMgr->FileReadLine( nsFp, &outBuf, &outBufLen, &readBytes); - if (NS_OK != rv) { - return NULL; - } - - return outBuf; -} - -PUBLIC int -NET_I_XP_FileRead(char *outBuf, int outBufLen, XP_File fp) { - nsFile *nsFp = XpToNsFp(fp); // nsnull ok. - PRInt32 readBytes; - nsresult rv; - - NS_PRECONDITION( (nsFp != nsnull), "Null pointer"); - - if (!nsFp) - return -1; - - if (!fileMgr) - return -1; - - rv = fileMgr->FileRead( nsFp, &outBuf, &outBufLen, &readBytes); - if (NS_OK != rv) { - return -1; - } - - return (int) readBytes; -} - -PUBLIC int -NET_I_XP_FileWrite(const char *buf, int bufLen, XP_File fp) { - nsFile *nsFp = XpToNsFp(fp); // nsnull ok. - PRInt32 wroteBytes; - PRInt32 len; - nsresult rv; - - if (bufLen < 0) - len = PL_strlen(buf); - else - len = bufLen; - - if (!nsFp) - return -1; - - if (!fileMgr) - return NULL; - - rv = fileMgr->FileWrite(nsFp, buf, &len, &wroteBytes);; - if (rv != NS_OK) - return NULL; - - return (int) wroteBytes; -} - -PUBLIC int -NET_I_XP_FileClose(XP_File fp) { - nsFile *nsFp = XpToNsFp(fp); // nsnull ok. - nsresult rv; - - NS_PRECONDITION( (nsFp != nsnull), "Null pointer"); - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - return 0; - } - } - - rv = fileMgr->CloseFile(nsFp); - if (rv != NS_OK) - return 0; - - deleteTrans(nsFp); - fp = nsnull; - - return 1; -} - - -/* -// -// Return 0 on success, -1 on failure. -// -*/ -PUBLIC int -NET_I_XP_FileRemove(const char * name, XP_FileType type) -{ - char *path = nsnull, *aName = nsnull; - nsresult rv; - - if ( (!name || !*name) - || type == xpCache ) { - char *tmpName = xpFileTypeToName(type); - nsString newName = tmpName; - PR_FREEIF(tmpName); - if (newName.Length() < 1) { - return NULL; - } - newName.Append(name); - aName = newName.ToNewCString(); - } - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - return NULL; - } - } - - rv = fileMgr->FileRemove((aName ? aName : name)); - if (aName) - delete[] aName; - if (rv != NS_OK) - return -1; - - return 0; -} - -PUBLIC int -NET_I_XP_Stat(const char * name, XP_StatStruct * info, XP_FileType type) -{ - int result = -1; - PRFileInfo fileInfo; - PRStatus status; - char *newName, *tmpName; - nsString ourName; - char *path; - nsresult rv; - - switch (type) { - case xpCache: - tmpName = xpFileTypeToName(type); - if (!tmpName) - return NULL; - ourName = tmpName; - PR_FREEIF(tmpName); - ourName.Append(name); - newName = ourName.ToNewCString(); - - if (!fileMgr) { - if (NS_NewINetFile(&fileMgr, nsnull) != NS_OK) { - delete[] newName; - return NULL; - } - } - - rv = fileMgr->GetFilePath(newName, &path); - if (rv != NS_OK) { - delete[] newName; - return -1; - } - status = PR_GetFileInfo(path, &fileInfo); - PR_Free(path); - delete[] newName; - if (status == PR_SUCCESS) { - // transfer the pr stat info over to the xp stat object. - // right now just moving over the size. - info->st_size = fileInfo.size; - return 0; - } - break; - case xpURL: - case xpFileToPost: { - newName = WH_FileName(name, type); - - if (!newName) return -1; - result = _stat( newName, info ); - PR_Free(newName); - break; - } - default: - break; - } - return result; -} - -PUBLIC XP_Dir -NET_I_XP_OpenDir(const char * name, XP_FileType type) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -PUBLIC void -NET_I_XP_CloseDir(XP_Dir dir) -{ - MOZ_FUNCTION_STUB; -} -/* -// -// Close the directory -// -*/ - -PUBLIC XP_DirEntryStruct * -NET_I_XP_ReadDir(XP_Dir dir) -{ - MOZ_FUNCTION_STUB; - return NULL; -} -// XXXXXXXXXXXXXXXXXXXXXXXXX NS_NET_FILE END XXXXXXXXXXXXXXXXXXXXXXXXX -#endif /* NS_NET_FILE */ - -#ifdef XP_MAC -char * -WH_TempName(XP_FileType type, const char * prefix) -{ - MOZ_FUNCTION_STUB; - return NULL; -} -#endif - -// Begin vanilla versions of xp_file routines. These are simply stubs. -#ifdef XP_PC - -#ifndef NS_NET_FILE - -char * -WH_TempName(XP_FileType type, const char * prefix) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -/* -// The caller is responsible for XP_FREE()ing the return string -*/ -PUBLIC char * -WH_FileName (const char *NetName, XP_FileType type) -{ - MOZ_FUNCTION_STUB; - - if (type == xpHTTPCookie) { -#ifdef XP_PC - return PL_strdup("cookies.txt"); -#else - return PL_strdup("cookies"); -#endif - } else if (type == xpHTTPCookiePermission) { -#ifdef XP_PC - return PL_strdup("cookperm.txt"); -#else - return PL_strdup("cookperm"); -#endif - } else if (type == xpHTTPSingleSignon) { -#ifdef XP_PC - return PL_strdup("signons.txt"); -#else - return PL_strdup("signons"); -#endif - } else if (type == xpCacheFAT) { -;// sprintf(newName, "%s\\fat.db", (const char *)theApp.m_pCacheDir); - - } else if ((type == xpURL) || (type == xpFileToPost)) { - /* - * This is the body of XP_NetToDosFileName(...) which is implemented - * for Windows only in fegui.cpp - */ - XP_Bool bChopSlash = FALSE; - char *p, *newName; - - if(!NetName) - return NULL; - - // If the name is only '/' or begins '//' keep the - // whole name else strip the leading '/' - - if(NetName[0] == '/') - bChopSlash = TRUE; - - // save just / as a path - if(NetName[0] == '/' && NetName[1] == '\0') - bChopSlash = FALSE; - - // spanky Win9X path name - if(NetName[0] == '/' && NetName[1] == '/') - bChopSlash = FALSE; - - if(bChopSlash) - newName = PL_strdup(&(NetName[1])); - else - newName = PL_strdup(NetName); - - if(!newName) - return NULL; - - if( newName[1] == '|' ) - newName[1] = ':'; - - for(p = newName; *p; p++){ - if( *p == '/' ) - *p = '\\'; - } - return(newName); - } - - return NULL; -} -#endif // !NS_NET_FILE - -PUBLIC XP_File -XP_FileOpen(const char * name, XP_FileType type, const XP_FilePerm perm) -{ - MOZ_FUNCTION_STUB; - switch (type) { - case xpURL: - case xpFileToPost: - case xpHTTPCookie: - case xpHTTPCookiePermission: -#ifdef SingleSignon - case xpHTTPSingleSignon: -#endif - { - XP_File fp; - char* newName = WH_FileName(name, type); - - if (!newName) return NULL; - - fp = fopen(newName, (char *) perm); - XP_FREE(newName); - return fp; - - } - default: - break; - } - - return NULL; -} - -PUBLIC XP_Dir -XP_OpenDir(const char * name, XP_FileType type) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -PUBLIC void -XP_CloseDir(XP_Dir dir) -{ - MOZ_FUNCTION_STUB; -} - -PUBLIC XP_DirEntryStruct * -XP_ReadDir(XP_Dir dir) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -PUBLIC int -XP_FileRemove(const char * name, XP_FileType type) -{ - if (PR_Delete(name) == PR_SUCCESS) - return 0; - return -1; -} - -/* -// -// Mimic unix stat call -// Return -1 on error -// -*/ -PUBLIC int -XP_Stat(const char * name, XP_StatStruct * info, XP_FileType type) -{ - int result = -1; - MOZ_FUNCTION_STUB; - - switch (type) { - case xpURL: - case xpFileToPost: { - char *newName = WH_FileName(name, type); - - if (!newName) return -1; - result = _stat( newName, info ); - XP_FREE(newName); - break; - } - default: - break; - } - return result; -} -#endif /* XP_PC */ - -PUBLIC void * -FE_AboutData (const char */*which*/, - char **data_ret, int32 *length_ret, char **content_type_ret) -{ - MOZ_FUNCTION_STUB; - - *data_ret = NULL; - *length_ret = 0; - *content_type_ret = NULL; - - return NULL; -} - - -PUBLIC void -FE_FreeAboutData (void * /*data*/, const char* /*which2*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/fenet.cpp - *--------------------------------------------------------------------------- - */ - -int FE_AsyncDNSLookup(MWContext */*context*/, char * /*host_port*/, - PRHostEnt ** /*hoststruct_ptr_ptr*/, PRFileDesc */*socket*/) -{ - MOZ_FUNCTION_STUB; - return -1; -} - -/* -// INTL_ResourceCharSet(void) -// -*/ -char *INTL_ResourceCharSet(void) -{ - MOZ_FUNCTION_STUB; - - return NULL; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/cfe.cpp - *--------------------------------------------------------------------------- - */ - -int32 FE_GetContextID(MWContext */*pContext*/) -{ - MOZ_FUNCTION_STUB; - return 0; -} - - -XP_Bool FE_IsNetcasterInstalled(void) -{ - MOZ_FUNCTION_STUB; - return FALSE; -} - -/* -// A Url has changed context. -// We need to mark it in the new context if it has ncapi_data (which we use -// to track such things under windows). -*/ -void FE_UrlChangedContext(URL_Struct */*pUrl*/, MWContext */*pOldContext*/, MWContext */*pNewContext*/) -{ - MOZ_FUNCTION_STUB; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/urlecho.cpp - *--------------------------------------------------------------------------- - */ -void FE_URLEcho(URL_Struct */*pURL*/, int /*iStatus*/, MWContext */*pContext*/) { -/* -// Purpose: Echo the URL to all appropriately registered applications that are monitoring such URL traffic. -// Arguments: pURL The URL which is being loaded. -// iStatus The status of the load. -// pContext The context in which the load occurred. -// Returns: void -// Comments: Well, sometimes there isn't a window in which the load occurred, what to do then? -// Just don't report. -// Revision History: -// 01-18-95 created GAB -// -*/ - MOZ_FUNCTION_STUB; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/edview2.cpp - *--------------------------------------------------------------------------- - */ -/* -// Note: This is used by Navigator's HTP UPLOAD as well as Composer's file saving -// DON'T ASSUME ANY EDITOR FUNCTIONALITY! -// Dialog to give feedback and allow canceling, overwrite protection -// when downloading remote files -// -*/ -void FE_SaveDialogCreate( MWContext */*pMWContext*/, int /*iFileCount*/, ED_SaveDialogType /*saveType*/ ) -{ - MOZ_FUNCTION_STUB; -} - - -void FE_SaveDialogSetFilename( MWContext */*pMWContext*/, char */*pFilename*/ ) -{ - MOZ_FUNCTION_STUB; -} - - -void FE_SaveDialogDestroy( MWContext */*pMWContext*/, int /*status*/, char */*pFileURL*/ ) -{ - MOZ_FUNCTION_STUB; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/compmapi.cpp - *--------------------------------------------------------------------------- - */ -void FE_AlternateCompose( - char * /*from*/, char * /*reply_to*/, char * /*to*/, char * /*cc*/, char * /*bcc*/, - char * /*fcc*/, char * /*newsgroups*/, char * /*followup_to*/, - char * /*organization*/, char * /*subject*/, char * /*references*/, - char * /*other_random_headers*/, char * /*priority*/, - char * /*attachment*/, char * /*newspost_url*/, char * /*body*/) -{ - MOZ_FUNCTION_STUB; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/nethelp.cpp - *--------------------------------------------------------------------------- - */ -MWContext *FE_GetNetHelpContext() -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -/* -// Called from mkhelp.c to get the standard location of the NetHelp folder as a URL -*/ -char * FE_GetNetHelpDir() -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/femess.cpp - *--------------------------------------------------------------------------- - */ -int FE_GetURL(MWContext */*pContext*/, URL_Struct */*pUrl*/) -{ - MOZ_FUNCTION_STUB; - - return -1; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/fmabstra.cpp - *--------------------------------------------------------------------------- - */ -void FE_RaiseWindow(MWContext */*pContext*/) -{ - MOZ_FUNCTION_STUB; -} - - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/fegrid.cpp - *--------------------------------------------------------------------------- - */ -/* -// Create a new window. -// If pChrome is NULL, do a FE_MakeBlankWindow.... -// pChrome specifies the attributes of a window. -// If you use this call, Toolbar information will not be saved in the preferences. -*/ -MWContext *FE_MakeNewWindow(MWContext */*pOldContext*/, URL_Struct */*pUrl*/, - char */*pContextName*/, Chrome */*pChrome*/) -{ - MOZ_FUNCTION_STUB; - - return NULL; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/cmd/winfe/timer.cpp - *--------------------------------------------------------------------------- - */ -/* this function should register a function that will - * be called after the specified interval of time has - * elapsed. This function should return an id - * that can be passed to FE_ClearTimeout to cancel - * the Timeout request. - * - * A) Timeouts never fail to trigger, and - * B) Timeouts don't trigger *before* their nominal timestamp expires, and - * C) Timeouts trigger in the same ordering as their timestamps - * - * After the function has been called it is unregistered - * and will not be called again unless re-registered. - * - * func: The function to be invoked upon expiration of - * the Timeout interval - * closure: Data to be passed as the only argument to "func" - * msecs: The number of milli-seconds in the interval - */ -PUBLIC void * -FE_SetTimeout(TimeoutCallbackFunction /*func*/, void * /*closure*/, uint32 /*msecs*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmocha/et_moz.c - *--------------------------------------------------------------------------- - */ - -JSBool -ET_PostMessageBox(MWContext* /*context*/, char* szMessage, JSBool /*bConfirm*/) -{ - MOZ_FUNCTION_STUB; - fprintf(stdout, "%c%s (y/n)? ", '\007', szMessage); /* \007 is BELL */ - char c; - for (;;) { - c = getchar(); - if (tolower(c) == 'y') { - return JS_TRUE; - } - if (tolower(c) == 'n') { - return JS_FALSE; - } - } - return JS_FALSE; -} - -JSBool -ET_PostCheckConfirmBox(MWContext* /*context*/, - char* szMainMessage, char* szCheckMessage, - char* /*szOKMessage*/, char* /*szCancelMessage*/, - XP_Bool *bChecked) -{ - MOZ_FUNCTION_STUB; - fprintf(stdout, "%c%s (y/n)? ", '\007', szMainMessage); /* \007 is BELL */ - char c; - XP_Bool result; - for (;;) { - c = getchar(); - if (tolower(c) == 'y') { - result = JS_TRUE; - break; - } - if (tolower(c) == 'n') { - result = JS_FALSE; - break; - } - } - fprintf(stdout, "%c%s y/n? ", '\007', szCheckMessage); /* \007 is BELL */ - for (;;) { - c = getchar(); - if (tolower(c) == 'y') { - *bChecked = TRUE; - break; - } - if (tolower(c) == 'n') { - *bChecked = FALSE; - break; - } - } - return result; -} - - -/* - * Tell the backend about a new load event. - */ -void -ET_SendLoadEvent(MWContext * /*pContext*/, int32 /*type*/, ETVoidPtrFunc /*fnClosure*/, - NET_StreamClass */*stream*/, int32 /*layer_id*/, Bool /*resize_reload*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmocha/lm_doc.c - *--------------------------------------------------------------------------- - */ - -NET_StreamClass * -LM_WysiwygCacheConverter(MWContext */*context*/, URL_Struct */*url_struct*/, - const char * /*wysiwyg_url*/, const char * /*base_href*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/libmocha/lm_win.c - *--------------------------------------------------------------------------- - */ -/* - * Entry point for front-ends to notify JS code of help events. - */ -void -LM_SendOnHelp(MWContext */*context*/) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/xp/xplocale.c - *--------------------------------------------------------------------------- - */ - -const char* INTL_ctime(MWContext* /*context*/, time_t */*date*/) -{ - static char result[40]; - - MOZ_FUNCTION_STUB; - *result = '\0'; - return result; -} - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/xp/xp_cntxt.c - *--------------------------------------------------------------------------- - */ - -/* - * Finds a context that should be loaded with the URL, given - * a name and current (refering) context. - * - * If the context returned is not NULL, name is already assigned to context - * structure. You should load the URL into this context. - * - * If you get back a NULL, you should create a new window - * - * Both context and current context can be null. - * Once the grids are in, there should be some kind of a logic that searches - * siblings first. - */ - -MWContext * XP_FindNamedContextInList(MWContext * /*context*/, char */*name*/) -{ - MOZ_FUNCTION_STUB; - return NULL; -} - - -MWContext* -XP_FindSomeContext() -{ - MOZ_FUNCTION_STUB; - return NULL; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/plugin/npglue.c - *--------------------------------------------------------------------------- - */ - -/* - * This exit routine is used for all streams requested by the - * plug-in: byterange request streams, NPN_GetURL streams, and - * NPN_PostURL streams. NOTE: If the exit routine gets called - * in the course of a context switch, we must NOT delete the - * URL_Struct. Example: FTP post with result from server - * displayed in new window -- the exit routine will be called - * when the upload completes, but before the new context to - * display the result is created, since the display of the - * results in the new context gets its own completion routine. - */ -void -NPL_URLExit(URL_Struct */*urls*/, int /*status*/, MWContext */*cx*/) -{ - MOZ_FUNCTION_STUB; -} - - - -/* - *--------------------------------------------------------------------------- - * From ns/lib/layout/layedit.c - *--------------------------------------------------------------------------- - */ - -void LO_SetBaseURL( MWContext */*context*/, char */*pURL*/ ) -{ - MOZ_FUNCTION_STUB; -} - -/* - *--------------------------------------------------------------------------- - * From ns/lib/layout/laysel.c - *--------------------------------------------------------------------------- - */ -/* - get first(last) if current element is NULL. -*/ -Bool -LO_getNextTabableElement( MWContext */*context*/, LO_TabFocusData */*pCurrentFocus*/, int /*forward*/ ) -{ - MOZ_FUNCTION_STUB; - return FALSE; -} - -PUBLIC int -NET_ParseNetHelpURL(URL_Struct */*URL_s*/) -{ - MOZ_FUNCTION_STUB; -/* return MK_OUT_OF_MEMORY; */ - return -207; -} - -#ifdef XP_UNIX -PUBLIC NET_StreamClass* NET_ExtViewerConverter ( FO_Present_Types /*format_out*/, - void */*data_obj*/, - URL_Struct */*URL_s*/, - MWContext */*window_id*/) -{ - return NULL; -} -#endif - -/* - * From xp_str.c - */ - -/* Allocate a new copy of a block of binary data, and returns it - */ -PUBLIC char * -NET_BACopy (char **destination, const char *source, size_t length) -{ - if(*destination) - { - XP_FREE(*destination); - *destination = 0; - } - - if (! source) - { - *destination = NULL; - } - else - { - *destination = (char *) PR_Malloc (length); - if (*destination == NULL) - return(NULL); - memcpy(*destination, source, length); - } - return *destination; -} - -/* binary block Allocate and Concatenate - * - * destination_length is the length of the existing block - * source_length is the length of the block being added to the - * destination block - */ -PUBLIC char * -NET_BACat (char **destination, - size_t destination_length, - const char *source, - size_t source_length) -{ - if (source) - { - if (*destination) - { - *destination = (char *) PR_Realloc (*destination, destination_length + source_length); - if (*destination == NULL) - return(NULL); - - memmove (*destination + destination_length, source, source_length); - - } - else - { - *destination = (char *) PR_Malloc (source_length); - if (*destination == NULL) - return(NULL); - - memcpy(*destination, source, source_length); - } - } - - return *destination; -} - -/* Very similar to strdup except it free's too - */ -PUBLIC char * -NET_SACopy (char **destination, const char *source) -{ - if(*destination) - { - XP_FREE(*destination); - *destination = 0; - } - if (! source) - { - *destination = NULL; - } - else - { - *destination = (char *) PR_Malloc (PL_strlen(source) + 1); - if (*destination == NULL) - return(NULL); - - PL_strcpy (*destination, source); - } - return *destination; -} - -/* Again like strdup but it concatinates and free's and uses Realloc -*/ -PUBLIC char * -NET_SACat (char **destination, const char *source) -{ - if (source && *source) - { - if (*destination) - { - int length = PL_strlen (*destination); - *destination = (char *) PR_Realloc (*destination, length + PL_strlen(source) + 1); - if (*destination == NULL) - return(NULL); - - PL_strcpy (*destination + length, source); - } - else - { - *destination = (char *) PR_Malloc (PL_strlen(source) + 1); - if (*destination == NULL) - return(NULL); - - PL_strcpy (*destination, source); - } - } - return *destination; -} - -/* remove front and back white space - * modifies the original string - */ -PUBLIC char * -XP_StripLine (char *string) -{ - char * ptr; - - /* remove leading blanks */ - while(*string=='\t' || *string==' ' || *string=='\r' || *string=='\n') - string++; - - for(ptr=string; *ptr; ptr++) - ; /* NULL BODY; Find end of string */ - - /* remove trailing blanks */ - for(ptr--; ptr >= string; ptr--) - { - if(*ptr=='\t' || *ptr==' ' || *ptr=='\r' || *ptr=='\n') - *ptr = '\0'; - else - break; - } - - return string; -} - -/************************************************************************/ - -char *XP_AppendStr(char *in, const char *append) -{ - int alen, inlen; - - alen = PL_strlen(append); - if (in) { - inlen = PL_strlen(in); - in = (char*) PR_Realloc(in,inlen+alen+1); - if (in) { - memcpy(in+inlen, append, alen+1); - } - } else { - in = (char*) PR_Malloc(alen+1); - if (in) { - memcpy(in, append, alen+1); - } - } - return in; -} - -void RDF_AddCookieResource(char* /*name*/, char* /*path*/, char* /*host*/, char* /*expires*/) -{ - MOZ_FUNCTION_STUB; -} - - -} /* end of extern "C" */ diff --git a/mozilla/network/module/nsNetStubs.h b/mozilla/network/module/nsNetStubs.h deleted file mode 100644 index dda49299876..00000000000 --- a/mozilla/network/module/nsNetStubs.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#if 0 -#define MOZ_FUNCTION_STUB \ - DebugBreak(); -#else -#define MOZ_FUNCTION_STUB -#endif diff --git a/mozilla/network/module/nsNetThread.cpp b/mozilla/network/module/nsNetThread.cpp deleted file mode 100644 index aef65811d7a..00000000000 --- a/mozilla/network/module/nsNetThread.cpp +++ /dev/null @@ -1,930 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "nscore.h" -#include "nsIComponentManager.h" - -#include "nspr.h" -#include "plevent.h" -#include "plstr.h" - -#include "nsNetThread.h" - -#include "nsIEventQueueService.h" -#include "nsIStreamListener.h" -#include "nsIInputStream.h" -#include "nsIURL.h" -#include "nsString.h" -#include "nsIRelatedLinks.h" - -extern "C" { -#include "sockstub.h" -#include "mkutils.h" -#include "mkgeturl.h" -#include "mktrace.h" -#include "mkstream.h" -#include "cvchunk.h" -#include "cvunzip.h" -#include "cvplugin.h" - -#include "fileurl.h" -#include "httpurl.h" -#include "ftpurl.h" -#include "abouturl.h" -#include "gophurl.h" -#include "fileurl.h" -#include "remoturl.h" -#include "netcache.h" - -#include "cvactive.h" -#include "nsCRT.h" - -PUBLIC NET_StreamClass * -NET_NGLayoutConverter(FO_Present_Types format_out, - void *converter_obj, - URL_Struct *URL_s, - MWContext *context); - -void net_AddrefContext(MWContext *context); -void net_ReleaseContext(MWContext *context); -} /* end of extern "C" */ - -#if defined(XP_PC) -void net_InitAsyncDNS(); -#endif /* XP_PC */ - - -PRThread* gNetlibThread = nsnull; - -/* - * Initialize our protocols - */ - -extern "C" void NET_ClientProtocolInitialize() -{ - NET_InitSockStubProtocol(); - NET_InitFileProtocol(); - NET_InitHTTPProtocol(); -#ifdef NU_CACHE - NET_InitNuCacheProtocol(); -#else - NET_InitMemCacProtocol(); -#endif - NET_InitFTPProtocol(); - NET_InitAboutProtocol(); - NET_InitGopherProtocol(); - NET_InitRemoteProtocol(); -} - -nsresult NS_InitNetlib(void) -{ - /* Initialize netlib with 32 sockets... */ - NET_InitNetLib(0, 32); - - /* Initialize the file extension -> content-type mappings */ - NET_InitFileFormatTypes(nsnull, nsnull); - - NET_FinishInitNetLib(); - - NET_RegisterContentTypeConverter("*", FO_CACHE_AND_NGLAYOUT, NULL, - NET_CacheConverter); - NET_RegisterContentTypeConverter("*", FO_NGLAYOUT, NULL, - NET_NGLayoutConverter); - NET_RegisterContentTypeConverter(APPLICATION_HTTP_INDEX, FO_NGLAYOUT, - NULL, NET_HTTPIndexFormatToHTMLConverter); - - NET_RegisterContentTypeConverter("text/*", FO_NGLAYOUT, NULL, - NET_PluginStream); - NET_RegisterContentTypeConverter("image/*", FO_NGLAYOUT, NULL, - NET_PluginStream); - NET_RegisterContentTypeConverter("application/*", FO_NGLAYOUT, NULL, - NET_PluginStream); - NET_RegisterContentTypeConverter(MESSAGE_RFC822, FO_NGLAYOUT, NULL, - NET_PluginStream); - - NET_RegisterEncodingConverter(ENCODING_GZIP, - (void *) ENCODING_GZIP, - NET_UnZipConverter); - NET_RegisterEncodingConverter(ENCODING_GZIP2, - (void *) ENCODING_GZIP2, - NET_UnZipConverter); - - NET_RegisterAllEncodingConverters("*", FO_NGLAYOUT); - - NET_RegisterUniversalEncodingConverter("chunked", - NULL, - NET_ChunkedDecoderStream); - - NET_RegisterContentTypeConverter("multipart/x-mixed-replace", FO_NGLAYOUT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - - NET_RegisterContentTypeConverter("multipart/mixed", FO_NGLAYOUT, - (void *) CVACTIVE_SIGNAL_AT_END_OF_MULTIPART, - CV_MakeMultipleDocumentStream); - - -#if defined(XP_PC) - net_InitAsyncDNS(); -#endif /* XP_PC */ - - return NS_OK; -} - - -nsNetlibThread::nsNetlibThread() -{ - mIsNetlibThreadRunning = PR_FALSE; - mNetlibEventQueue = nsnull; -} - - -nsNetlibThread::~nsNetlibThread() -{ - Stop(); -} - - -nsresult nsNetlibThread::Start(void) -{ - nsresult rv = NS_OK; - -#if defined(NETLIB_THREAD) -#if defined(NSPR20) && defined(DEBUG) - if (NETLIB==NULL) { - NETLIB = PR_NewLogModule("NETLIB"); - } -#endif - /* - * Create the netlib thread and wait for it to initialize Netlib... - */ - PR_CEnterMonitor(this); - - mThread = PR_CreateThread(PR_USER_THREAD, - nsNetlibThread::NetlibThreadMain, - this, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, - 4096); - - /* - * The netlib thread will call PR_Notify on the monitor when Netlib has - * been initialized... - */ - PR_CWait(this, PR_INTERVAL_NO_TIMEOUT); - PR_CExitMonitor(this); - NET_ReadCookies(""); -#else - /* - * Initialize Netlib... - */ - NS_InitNetlib(); -#endif /* !NETLIB_THREAD */ - - return rv; -} - - -nsresult nsNetlibThread::Stop(void) -{ -#if defined(NETLIB_THREAD) - PR_CEnterMonitor(this); - - if (PR_TRUE == mIsNetlibThreadRunning) { - mIsNetlibThreadRunning = PR_FALSE; - - PR_CWait(this, PR_INTERVAL_NO_TIMEOUT); - } - PR_CExitMonitor(this); - -#else - NET_ShutdownNetLib(); -#endif /* !NETLIB_THREAD */ - - return NS_OK; -} - - -void nsNetlibThread::NetlibThreadMain(void *aParam) -{ - nsNetlibThread* me = (nsNetlibThread*)aParam; - - PR_CEnterMonitor(me); - - me->mNetlibEventQueue = PL_CreateEventQueue("Netlib Event Queue", PR_GetCurrentThread()); - if (nsnull == me->mNetlibEventQueue) { - PR_CNotify(me); - PR_CExitMonitor(me); - - /* XXX: return error status... */ - return; - } - - /* - * Initialize netlib on the netlib thread... - */ - NS_InitNetlib(); - gNetlibThread = PR_GetCurrentThread(); - - me->mIsNetlibThreadRunning = PR_TRUE; - - /* - * Notify the caller thread that Netlib is now initialized... - */ - PR_CNotify(me); - PR_CExitMonitor(me); - - /* - * Call the platform specific main loop... - */ - me->NetlibMainLoop(); - - /* - * Netlib is being shutdown... Clean up and exit. - */ - PR_CEnterMonitor(me); - me->mIsNetlibThreadRunning = PR_FALSE; - - /* Notify the main thread that the Netlib thread is no longer running...*/ - PR_CNotify(me); - PR_CExitMonitor(me); - - PL_DestroyEventQueue(me->mNetlibEventQueue); - me->mNetlibEventQueue = nsnull; - - NET_ShutdownNetLib(); -} - -/* - * Platform specific main loop... - */ -#if defined(XP_PC) -void CALLBACK NetlibTimerProc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) -{ - (void) NET_PollSockets(); -} - -void nsNetlibThread::NetlibMainLoop(void) -{ - UINT timerId; - - /* - * Create a timer to periodically call NET_PollSockets(...) - */ -#if !defined(NO_NETWORK_POLLING) - timerId = SetTimer(NULL, 0, 10, (TIMERPROC)NetlibTimerProc); -#endif /* NO_NETWORK_POLLING */ - - while (PR_TRUE == mIsNetlibThreadRunning) { - MSG msg; - BOOL bIsMsg; - - /* - * Block for network activity... - * - * If NET_CallingNetlibAllTheTime(...) is set, then do not block - * because a non-socket based protocol is being serviced (ie. file) - */ - if (NET_IsCallNetlibAllTheTimeSet(NULL, NULL)) { - NET_ProcessNet(NULL, NET_EVERYTIME_TYPE); - bIsMsg = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); - } else { - bIsMsg = GetMessage(&msg, NULL, 0, 0); - } - - if (FALSE != bIsMsg) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - -#if !defined(NO_NETWORK_POLLING) - KillTimer(NULL, timerId); -#endif /* NO_NETWORK_POLLING */ -} - -#else -void nsNetlibThread::NetlibMainLoop() -{ - while (mIsNetlibThreadRunning) { - if (NET_IsCallNetlibAllTheTimeSet(NULL, NULL)) - NET_ProcessNet(NULL, NET_EVERYTIME_TYPE); - else - NET_PollSockets(); - } -} -#endif /* ! XP_PC */ - - -/* - * Proxy implementation for the nsIStreamListener interface... - */ - -class nsStreamListenerProxy : public nsIStreamListener -{ -public: - nsStreamListenerProxy(nsIStreamListener* aListener, nsIEventQueue* aEventQ); - - NS_DECL_ISUPPORTS - - NS_IMETHOD OnStartRequest(nsIURI* aURL, const char *aContentType); - NS_IMETHOD OnProgress(nsIURI* aURL, PRUint32 aProgress, PRUint32 aProgressMax); - NS_IMETHOD OnStatus(nsIURI* aURL, const PRUnichar* aMsg); - NS_IMETHOD OnStopRequest(nsIURI* aURL, nsresult aStatus, const PRUnichar* aMsg); - NS_IMETHOD GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* info); - NS_IMETHOD OnDataAvailable(nsIURI* aURL, nsIInputStream *aIStream, - PRUint32 aLength); - - void SetStatus(nsresult aStatus); - nsresult GetStatus(); - - nsIStreamListener* mRealListener; - -protected: - virtual ~nsStreamListenerProxy(); - -private: - nsresult mStatus; - nsIEventQueue* mEventQ; -}; - - -/*-------------------- Base Proxy Class ------------------------------------*/ - -struct ProxyEvent : public PLEvent -{ - virtual ~ProxyEvent(); - virtual void InitEvent(); - NS_IMETHOD HandleEvent() = 0; - void Fire(nsIEventQueue* aEventQ); - - static void PR_CALLBACK HandlePLEvent(PLEvent* aEvent); - static void PR_CALLBACK DestroyPLEvent(PLEvent* aEvent); -}; - -ProxyEvent::~ProxyEvent() -{ -} - -void ProxyEvent::InitEvent() -{ - PL_InitEvent(this, nsnull, - (PLHandleEventProc) ProxyEvent::HandlePLEvent, - (PLDestroyEventProc) ProxyEvent::DestroyPLEvent); -} - -void PR_CALLBACK ProxyEvent::HandlePLEvent(PLEvent* aEvent) -{ - /* - * XXX: This is a dangerous cast since it must adjust the pointer - * to compensate for the vtable... - */ - ProxyEvent *ev = (ProxyEvent*)aEvent; - - ev->HandleEvent(); -} - -void PR_CALLBACK ProxyEvent::DestroyPLEvent(PLEvent* aEvent) -{ - /* - * XXX: This is a dangerous cast since it must adjust the pointer - * to compensate for the vtable... - */ - ProxyEvent *ev = (ProxyEvent*)aEvent; - - delete ev; -} - - -void ProxyEvent::Fire(nsIEventQueue* aEventQ) -{ - InitEvent(); - - NS_PRECONDITION(nsnull != aEventQ, "nsIEventQueue for thread is null"); - - aEventQ->PostEvent(this); -} - - -/*--------- Base Class for the nsIStreamListenerProxy Class ----------------*/ - - -struct StreamListenerProxyEvent : public ProxyEvent -{ - StreamListenerProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL); - virtual ~StreamListenerProxyEvent(); - - virtual void InitEvent(); - static void PR_CALLBACK HandlePLEvent(PLEvent* aEvent); - - nsStreamListenerProxy* mProxy; - nsIURI* mURL; -}; - - -StreamListenerProxyEvent::StreamListenerProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL) -{ - mProxy = aProxy; - mURL = aURL; - - NS_IF_ADDREF(mProxy); - NS_IF_ADDREF(mURL); - -} - -StreamListenerProxyEvent::~StreamListenerProxyEvent() -{ - NS_IF_RELEASE(mProxy); - NS_IF_RELEASE(mURL); -} - -void StreamListenerProxyEvent::InitEvent() -{ - PL_InitEvent(this, nsnull, - (PLHandleEventProc) StreamListenerProxyEvent::HandlePLEvent, - (PLDestroyEventProc) ProxyEvent::DestroyPLEvent); -} - -void PR_CALLBACK StreamListenerProxyEvent::HandlePLEvent(PLEvent* aEvent) -{ - /* - * XXX: This is a dangerous cast since it must adjust the pointer - * to compensate for the vtable... - */ - nsresult rv; - StreamListenerProxyEvent *ev = (StreamListenerProxyEvent*)aEvent; - - rv = ev->HandleEvent(); - if (NS_FAILED(rv)) { - ev->mProxy->SetStatus(rv); - } -} - -/*-------------- OnStartRequest Proxy --------------------------------------*/ - -struct OnStartRequestProxyEvent : public StreamListenerProxyEvent -{ - OnStartRequestProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL, - const char *aContentType); - virtual ~OnStartRequestProxyEvent(); - NS_IMETHOD HandleEvent(); - - char *mContentType; -}; - -OnStartRequestProxyEvent::OnStartRequestProxyEvent(nsStreamListenerProxy* aProxy, - nsIURI* aURL, - const char *aContentType) - : StreamListenerProxyEvent(aProxy, aURL) -{ - mContentType = PL_strdup(aContentType); -} - -OnStartRequestProxyEvent::~OnStartRequestProxyEvent() -{ - PR_Free(mContentType); -} - -NS_IMETHODIMP -OnStartRequestProxyEvent::HandleEvent() -{ - return mProxy->mRealListener->OnStartRequest(mURL, mContentType); -} - - -/*-------------- OnProgress Proxy ------------------------------------------*/ - -struct OnProgressProxyEvent : public StreamListenerProxyEvent -{ - OnProgressProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL, - PRUint32 aProgress, PRUint32 aProgressMax); - NS_IMETHOD HandleEvent(); - - PRUint32 mProgress; - PRUint32 mProgressMax; -}; - -OnProgressProxyEvent::OnProgressProxyEvent(nsStreamListenerProxy* aProxy, - nsIURI* aURL, - PRUint32 aProgress, - PRUint32 aProgressMax) - : StreamListenerProxyEvent(aProxy, aURL) -{ - mProgress = aProgress; - mProgressMax = aProgressMax; -} - -NS_IMETHODIMP -OnProgressProxyEvent::HandleEvent() -{ - return mProxy->mRealListener->OnProgress(mURL, mProgress, mProgressMax); -} - -/*-------------- OnStatus Proxy --------------------------------------------*/ - -struct OnStatusProxyEvent : public StreamListenerProxyEvent -{ - OnStatusProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL, - const PRUnichar* aMsg); - NS_IMETHOD HandleEvent(); - - PRUnichar* mMsg; -}; - -OnStatusProxyEvent::OnStatusProxyEvent(nsStreamListenerProxy* aProxy, - nsIURI* aURL, - const PRUnichar* aMsg) - : StreamListenerProxyEvent(aProxy, aURL) -{ - mMsg = nsCRT::strdup(aMsg); -} - -NS_IMETHODIMP -OnStatusProxyEvent::HandleEvent() -{ - nsresult rv = mProxy->mRealListener->OnStatus(mURL, mMsg); - delete []mMsg; - mMsg = nsnull; - return rv; -} - - -/*-------------- OnStopRequest Proxy ---------------------------------------*/ - -struct OnStopRequestProxyEvent : public StreamListenerProxyEvent -{ - OnStopRequestProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL, - nsresult aStatus, const PRUnichar* aMsg); - NS_IMETHOD HandleEvent(); - - nsresult mStatus; - PRUnichar* mMsg; -}; - -OnStopRequestProxyEvent::OnStopRequestProxyEvent(nsStreamListenerProxy* aProxy, - nsIURI* aURL, - nsresult aStatus, - const PRUnichar* aMsg) - : StreamListenerProxyEvent(aProxy, aURL) -{ - mStatus = aStatus; - mMsg = nsCRT::strdup(aMsg); -} - -NS_IMETHODIMP -OnStopRequestProxyEvent::HandleEvent() -{ - nsresult rv = mProxy->mRealListener->OnStopRequest(mURL, mStatus, mMsg); - delete []mMsg; - mMsg = nsnull; - return rv; -} - - -/*-------------- OnDataAvailable Proxy -------------------------------------*/ - -struct OnDataAvailableProxyEvent : public StreamListenerProxyEvent -{ - OnDataAvailableProxyEvent(nsStreamListenerProxy* aProxy, nsIURI* aURL, - nsIInputStream* aStream, PRUint32 aLength); - virtual ~OnDataAvailableProxyEvent(); - NS_IMETHOD HandleEvent(); - - nsIInputStream* mStream; - PRUint32 mLength; -}; - -OnDataAvailableProxyEvent::OnDataAvailableProxyEvent(nsStreamListenerProxy* aProxy, - nsIURI* aURL, - nsIInputStream* aStream, - PRUint32 aLength) - : StreamListenerProxyEvent(aProxy, aURL) -{ - mStream = aStream; - NS_ADDREF(mStream); - - mLength = aLength; -} - -OnDataAvailableProxyEvent::~OnDataAvailableProxyEvent() -{ - NS_RELEASE(mStream); -} - -NS_IMETHODIMP -OnDataAvailableProxyEvent::HandleEvent() -{ - return mProxy->mRealListener->OnDataAvailable(mURL, mStream, mLength); -} - -/*--------------------------------------------------------------------------*/ - -nsStreamListenerProxy::nsStreamListenerProxy(nsIStreamListener* aListener, - nsIEventQueue* aEventQ) -{ - NS_INIT_REFCNT(); - - mRealListener = aListener; - NS_ADDREF(mRealListener); - - mEventQ = aEventQ; - NS_IF_ADDREF(mEventQ); - - mStatus = NS_OK; -} - - -void nsStreamListenerProxy::SetStatus(nsresult aStatus) -{ - NS_LOCK_INSTANCE(); - mStatus = aStatus; - NS_UNLOCK_INSTANCE(); -} - - -nsresult nsStreamListenerProxy::GetStatus() -{ - nsresult rv; - - NS_LOCK_INSTANCE(); - rv = mStatus; - NS_UNLOCK_INSTANCE(); - - return rv; -} - -/* - * Implementation of threadsafe ISupports methods... - */ -static NS_DEFINE_IID(kIStreamListenerIID, NS_ISTREAMLISTENER_IID); -NS_IMPL_THREADSAFE_ISUPPORTS(nsStreamListenerProxy, kIStreamListenerIID); - -NS_IMETHODIMP -nsStreamListenerProxy::OnStartRequest(nsIURI* aURL, const char *aContentType) -{ - nsresult rv; - - if (PR_GetCurrentThread() == gNetlibThread) { - OnStartRequestProxyEvent* ev; - - rv = GetStatus(); - if (NS_SUCCEEDED(rv)) { - ev = new OnStartRequestProxyEvent(this, aURL, aContentType); - if (nsnull == ev) { - rv = NS_ERROR_OUT_OF_MEMORY; - } else { - ev->Fire(mEventQ); - } - } - } else { - rv = mRealListener->OnStartRequest(aURL, aContentType); - } - return rv; -} - -NS_IMETHODIMP -nsStreamListenerProxy::OnProgress(nsIURI* aURL, PRUint32 aProgress, - PRUint32 aProgressMax) -{ - nsresult rv; - - if (PR_GetCurrentThread() == gNetlibThread) { - OnProgressProxyEvent* ev; - /* - * Only fire the OnProgress notification if the connection is still valid. - * ie. A previous call did not fail... - */ - rv = GetStatus(); - if (NS_SUCCEEDED(rv)) { - ev = new OnProgressProxyEvent(this, aURL, aProgress, aProgressMax); - if (nsnull == ev) { - rv = NS_ERROR_OUT_OF_MEMORY; - } else { - ev->Fire(mEventQ); - } - } - } else { - rv = mRealListener->OnProgress(aURL, aProgress, aProgressMax); - } - return rv; -} - -NS_IMETHODIMP -nsStreamListenerProxy::OnStatus(nsIURI* aURL, const PRUnichar* aMsg) -{ - nsresult rv; - - if (PR_GetCurrentThread() == gNetlibThread) { - OnStatusProxyEvent* ev; - /* - * Only fire the OnStatus notification if the connection is still valid. - * ie. A previous call did not fail... - */ - rv = GetStatus(); - if (NS_SUCCEEDED(rv)) { - ev = new OnStatusProxyEvent(this, aURL, aMsg); - if (nsnull == ev) { - rv = NS_ERROR_OUT_OF_MEMORY; - } else { - ev->Fire(mEventQ); - } - } - } else { - rv = mRealListener->OnStatus(aURL, aMsg); - } - return rv; -} - -NS_IMETHODIMP -nsStreamListenerProxy::OnStopRequest(nsIURI* aURL, nsresult aStatus, - const PRUnichar* aMsg) -{ - nsresult rv = NS_OK; - - if (PR_GetCurrentThread() == gNetlibThread) { - OnStopRequestProxyEvent* ev; - /* - * Always fire the OnStopRequest notification... - */ - ev = new OnStopRequestProxyEvent(this, aURL, aStatus, aMsg); - if (nsnull == ev) { - rv = NS_ERROR_OUT_OF_MEMORY; - } else { - ev->Fire(mEventQ); - } - } else { - rv = mRealListener->OnStopRequest(aURL, aStatus, aMsg); - } - return rv; -} - -/*--------------------------------------------------------------------------*/ - -NS_IMETHODIMP -nsStreamListenerProxy::GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* info) -{ - nsresult rv; - - if (PR_GetCurrentThread() == gNetlibThread) { - PR_ASSERT(0); - rv = NS_ERROR_FAILURE; - } else { - rv = mRealListener->GetBindInfo(aURL, info); - } - return rv; -} - -NS_IMETHODIMP -nsStreamListenerProxy::OnDataAvailable(nsIURI* aURL, nsIInputStream *aIStream, - PRUint32 aLength) -{ - nsresult rv = NS_OK; - - if (PR_GetCurrentThread() == gNetlibThread) { - OnDataAvailableProxyEvent* ev; - /* - * Only fire the OnDataAvailable notification if the connection is still valid. - * ie. A previous call did not fail... - */ - rv = GetStatus(); - if (NS_SUCCEEDED(rv)) { - ev = new OnDataAvailableProxyEvent(this, aURL, aIStream, aLength); - if (nsnull == ev) { - rv = NS_ERROR_OUT_OF_MEMORY; - } else { - ev->Fire(mEventQ); - } - } - } else { - rv = mRealListener->OnDataAvailable(aURL, aIStream, aLength); - } - return rv; -} - -/*--------------------------------------------------------------------------*/ - - -nsStreamListenerProxy::~nsStreamListenerProxy() -{ - NS_RELEASE(mRealListener); - NS_IF_RELEASE(mEventQ); -} - -nsIStreamListener* ns_NewStreamListenerProxy(nsIStreamListener* aListener, - nsIEventQueue* aEventQ) -{ - return new nsStreamListenerProxy(aListener, aEventQ); -} - - -/*----------- Proxy for net_CallExitRoutine(...) ---------------------------*/ -extern "C" MODULE_PRIVATE void -net_CallExitRoutine(Net_GetUrlExitFunc* exit_routine, - URL_Struct* URL_s, - int status, - FO_Present_Types format_out, - MWContext* window_id); - - -struct CallExitRoutineProxyEvent : public ProxyEvent -{ - CallExitRoutineProxyEvent(Net_GetUrlExitFunc* aExitRoutine, - URL_Struct* aURL_s, - int aStatus, - FO_Present_Types aFormatOut, - MWContext* aWindowId); - virtual ~CallExitRoutineProxyEvent(); - NS_IMETHOD HandleEvent(); - - Net_GetUrlExitFunc* exit_routine; - URL_Struct* URL_s; - int status; - FO_Present_Types format_out; - MWContext* window_id; -}; - -CallExitRoutineProxyEvent::CallExitRoutineProxyEvent(Net_GetUrlExitFunc* aExitRoutine, - URL_Struct* aURL_s, - int aStatus, - FO_Present_Types aFormatOut, - MWContext* aWindowId) -{ - exit_routine = aExitRoutine; - URL_s = aURL_s; - status = aStatus; - format_out = aFormatOut; - window_id = aWindowId; - - net_AddrefContext(window_id); - NET_HoldURLStruct(URL_s); -} - - -CallExitRoutineProxyEvent::~CallExitRoutineProxyEvent() -{ - NET_DropURLStruct(URL_s); - net_ReleaseContext(window_id); -} - - -NS_IMETHODIMP -CallExitRoutineProxyEvent::HandleEvent() -{ - net_CallExitRoutine(exit_routine, URL_s, status, format_out, window_id); - return NS_OK; -} - - -extern "C" MODULE_PRIVATE void -net_CallExitRoutineProxy(Net_GetUrlExitFunc* exit_routine, - URL_Struct* URL_s, - int status, - FO_Present_Types format_out, - MWContext* window_id) -{ - CallExitRoutineProxyEvent* ev; - - /* - * Make sure that the URL_Struct was opened by the nsINetService... - * Otherwise, we cannot look at the URL_s->owner_data - */ - if (NULL != window_id->modular_data) { - /* - * Always use a PLEvent to call the exit_routine(...). This is necessary - * because when a connection is interrupted, the exit_routine(...) is called - * inside of the LIBNET_LOCK(). - * - * By always using an event, we are sure that the exit_routine(...) is not - * called while the thread is holding the LIBNET_LOCK(). - */ - ev = new CallExitRoutineProxyEvent(exit_routine, URL_s, status, - format_out, window_id); - if (nsnull != ev) { - - nsIEventQueue* eventQueue = (nsIEventQueue*)(URL_s->owner_data); - if (eventQueue) - ev->Fire(eventQueue); - } - } else { - net_CallExitRoutine(exit_routine, URL_s, status, format_out, window_id); - } -} diff --git a/mozilla/network/module/nsNetThread.h b/mozilla/network/module/nsNetThread.h deleted file mode 100644 index 2f0ba51a274..00000000000 --- a/mozilla/network/module/nsNetThread.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsNetThread_h___ -#define nsNetThread_h___ - -#include "nspr.h" -#include "plevent.h" -#include "net.h" /* needed for net_CallExitRoutineProxy prototype below */ -#include "nsIStreamListener.h" /* needed for ns_NewStreamListenerProxy prototype below */ -#include "nsINetService.h" /* needed for NS_InitializeHttpURLFactory prototype below */ - -class nsNetlibThread -{ -public: - nsNetlibThread(); - ~nsNetlibThread(); - - nsresult Start(void); - nsresult Stop(void); - -private: - static void NetlibThreadMain(void* aParam); - - void NetlibMainLoop(void); - - PRBool mIsNetlibThreadRunning; - PREventQueue* mNetlibEventQueue; - PRThread* mThread; -}; - -extern "C" void NET_ClientProtocolInitialize(); -nsresult NS_InitNetlib(void); -nsIStreamListener* ns_NewStreamListenerProxy(nsIStreamListener* aListener); - -extern "C" MODULE_PRIVATE void -net_CallExitRoutineProxy(Net_GetUrlExitFunc* exit_routine, - URL_Struct* URL_s, - int status, - FO_Present_Types format_out, - MWContext* window_id); - -extern "C" NS_NET nsresult -NS_InitializeHttpURLFactory(nsINetService* inet); - -#endif /* nsNetThread_h__ */ - diff --git a/mozilla/network/module/nsRelatedLinks.cpp b/mozilla/network/module/nsRelatedLinks.cpp deleted file mode 100644 index c04cf7ffe31..00000000000 --- a/mozilla/network/module/nsRelatedLinks.cpp +++ /dev/null @@ -1,819 +0,0 @@ -#include "nsIRelatedLinks.h" -#include "net.h" -#include "merrors.h" -#include "plstr.h" -#include "proto.h" - -typedef uint8 RL_LOAD_STATUS; -char* relatedLinksProvider = NULL; - -#define RL_STATUS_WAITING_TO_LOAD 1 -#define RL_STATUS_LOADING 2 -#define RL_STATUS_ABORTED 3 -#define RL_STATUS_COMPLETED 4 -#define RL_STATUS_NOT_AVAILABLE 5 - -#define RL_MAX_URL 300 -#define RL_LINE_SIZE 1024 - -extern int XP_RL_FETCHING; -extern int XP_RL_UNAVAILABLE; - -#define validRLItem(item) ((item->type == RL_CONTAINER) || (item->type == RL_SEPARATOR) || (item->type == RL_LINK) || (item->type == RL_LINK_NEW_WINDOW)) - -int32 gInitialDiff = 4; -int32 gMaxDiff = 4; -PRBool enableRelatedLinksp = 1; - -struct _RL_Window { - char* url; - char* rlurl; - RL_LOAD_STATUS status; - uint8 parseStatus; - uint8 type; - char* holdOver; - char* line; - struct _RL_Item* items; - uint8 diff; - uint8 count; - void* fe_data; - struct _RL_Item* stack[3]; - uint8 depth; - RLCallBackProc callBack; - URL_Struct *currentlyLoading; - struct _RL_Item* prevItems; - PRBool demoUrlp; -}; - -struct _RL_Item { - RL_ItemType type; - char* name; - char* convertedName; - char* url; - char* rurl; - struct _RL_Item* child; - struct _RL_Item* next; -}; - - -typedef struct _RL_Get { - RL_Window win; - URL_Struct *url; -} *RL_Get; - -typedef struct _RL_SpecialItems { - RL_Item loading; - RL_Item noData; - RL_Item disabled; -} *RL_SpecialItems; - - -typedef struct _RL_EquivBucket { - char* jumpPoint; - char* seenAt; - struct _RL_EquivBucket* next; -} *RL_EquivBucket; - -RL_SpecialItems gRLSpecial = 0; - - -void RL_DestroyRLWindow(RL_Window win); -void RL_SetRLWindowURL(RL_Window win, char* url); -RL_Item RL_WindowItems (RL_Window win); -RL_Item RL_NextItem(RL_Item item); -RL_Item RL_ItemChild(RL_Item item); -uint8 RL_ItemCount(RL_Window win); -RL_ItemType RL_GetItemType(RL_Item item); -char* RL_ItemName(RL_Item item); -char* RL_ItemUrl(RL_Item item); -typedef void (*RLCallBackProc)(void* pdata, RL_Window win); -RL_Window RL_MakeRLWindowWithCallback(RLCallBackProc callBack, void* fedata); - -void freeMem(void* x); -RL_Window RL_MakeRLWindow(); -void RL_DestroyRLWindow(RL_Window win); -void RL_EnableRelatedLinks(); -void RL_DisableRelatedLinks(); -void RL_SetRLWindowURL(RL_Window win, char* url); -void RL_AddItem (RL_Window win, char* url, char* name, uint8 type); -RL_Item RL_WindowItems (RL_Window win); -RL_Item RL_NextItem(RL_Item item); -RL_ItemType RL_GetItemType(RL_Item item); -char* RL_ItemName(RL_Item item); -char* RL_ItemUrl(RL_Item item); -void GetRL (RL_Window win); -void cleanRLTree(RL_Item item); -MWContext* GetRLContext(RL_Window win); -void rl_GetUrlExitFunc (URL_Struct *urls, int status, MWContext *cx) ; -void TryLoadRLFromCache(RL_Window win) ; -void parseNextRDFXMLBlob (RL_Window f, char* blob, int32 size) ; -void parseNextRDFToken (RL_Window f, char* token) ; -void extractAttributes (char* attr, char** attlist) ; -PRBool tokenEquals(char* token, char* string, PRBool endp); -char* getAttributeValue(char** attlist, char* elName); -PUBLIC NET_StreamClass* RL_Converter(FO_Present_Types format_out, void -*data_object, URL_Struct *URL_s, MWContext *window_id) ; -int rl_write(void *obj, const char *str, int32 len) ; -unsigned int rl_write_ready(void *obj) ; -void rl_abort(void *obj, int status) ; -void rl_complete (void *obj) ; -PRBool startsWith (char* pattern, char* uuid) ; -PRBool rlStartsWith (char* pattern, char* uuid) ; -int16 charSearch (char c, char* data) ; -/*char* copyString (char* source) ; */ -void parseNextRLBlob (RL_Window f, char* blob, int32 len) ; -void parseNextAlexaLine (RL_Window f, char* line) ; -static PRBool findNextDomain(const char *inDomains, size_t *ioBegin, -size_t *outEnd); -static PRBool nextDomain (char* dom, size_t *n, size_t maxLength); -static PRBool validateDomain(const char *inDomains, size_t inBegin, -size_t inEnd); - -class nsRelatedLinks: public nsIRelatedLinks { - -public: - nsRelatedLinks() { - NS_INIT_REFCNT(); - } - - NS_DECL_ISUPPORTS - - void DestroyRLWindow (RL_Window win) { - RL_DestroyRLWindow (win); - } - - void SetRLWindowURL (RL_Window win, char* url) { - RL_SetRLWindowURL (win, url); - } - - RL_Item WindowItems (RL_Window win) { - return RL_WindowItems (win); - } - - RL_Item NextItem (RL_Item item) { - return RL_NextItem (item); - } - - RL_Item ItemChild (RL_Item item) { - return RL_ItemChild (item); - } - - uint8 ItemCount (RL_Window win) { - return RL_ItemCount (win); - } - - RL_ItemType GetItemType (RL_Item item) { - return RL_GetItemType (item); - } - - char* ItemName (RL_Item item) { - return RL_ItemName (item); - } - - char* ItemUrl (RL_Item item) { - return RL_ItemUrl (item); - } - - RL_Window MakeRLWindowWithCallback(RLCallBackProc callBack, void*fedata) { - return RL_MakeRLWindowWithCallback(callBack,fedata); - } - -}; - -NS_IMPL_ADDREF(nsRelatedLinks) -NS_IMPL_RELEASE(nsRelatedLinks) - -NS_DEFINE_IID(kIRelatedLinksIID, NS_IRELATEDLINKS_IID); - -nsresult nsRelatedLinks::QueryInterface(const nsIID &aIID, void** aInstancePtr) -{ - if (NULL == aInstancePtr) { - return NS_ERROR_NULL_POINTER; - } - static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); - - if (aIID.Equals(kISupportsIID)) { - *aInstancePtr = (void*) ((nsISupports *)this); - AddRef(); - return NS_OK; - } - if (aIID.Equals(kIRelatedLinksIID)) { - *aInstancePtr = (void*) ((nsIRelatedLinks *)this); - AddRef(); - return NS_OK; - } - return NS_NOINTERFACE; -} - -extern "C" nsIRelatedLinks * NS_NewRelatedLinks(void) { - nsRelatedLinks * pIObject= new nsRelatedLinks; - if (pIObject) { - pIObject->AddRef(); - return (nsIRelatedLinks*)pIObject; - } - return nsnull; -} - - -#define copyString(x) PL_strdup(x) - -PRBool startsWith (char* pattern, char* uuid) { - short l1 = strlen(pattern); - short l2 = strlen(uuid); - - if (l2 < l1) return PR_FALSE; - return (strncmp(pattern, uuid, l1) == 0) ? PR_TRUE : PR_FALSE; -} - -PRBool rlStartsWith (char* pattern, char* uuid) { - short l1 = strlen(pattern); - short l2 = strlen(uuid); - short index; - - if (l2 < l1) return PR_FALSE; - - for (index = 0; index < l1; index++) { - if ((index == l1-1) && (pattern[index] == '*')) return PR_TRUE; - if (pattern[index] != uuid[index]) return PR_FALSE; - } - - return PR_TRUE; -} - - -int16 charSearch (char c, char* data) { - int32 l1 = strlen(data); - int16 index; - - for (index = 0; index < l1; index++) { - if (data[index] == c) return index; - } - - return -1; -} - -PRIVATE -char* getMem(size_t x) { - char* ans = (char *)calloc(1,(x)); - if (ans != NULL) { - memset(ans, '\0', x); - } else { - ans = 0; - } - return ans; -} - -PRIVATE -RL_Item makeRLItem (char* name, char* url) { - RL_Item item = (RL_Item) getMem(sizeof(struct _RL_Item)); - if (item) { - item->name = name; - item->url = url; - item->type = RL_LINK; - return item; - } else return NULL; -} - -PRIVATE -PRBool specialItemp (RL_Item item) { - return ((item == gRLSpecial->loading) || - (item == gRLSpecial->noData) || - (item == gRLSpecial->disabled)) ? PR_TRUE : PR_FALSE; -} - - -PRIVATE -void readRLPrefs () { - int32 autoload = -1; -} - - -extern "C" void RL_Init () { - gRLSpecial = (RL_SpecialItems)getMem(sizeof(struct _RL_SpecialItems)); - if (gRLSpecial == NULL) { - enableRelatedLinksp = 0; - } - gRLSpecial->loading = makeRLItem("Fetching ...", NULL); - gRLSpecial->noData = makeRLItem("No data available", NULL); - gRLSpecial->disabled = makeRLItem("Related Links Disabled", NULL); - if (gRLSpecial->loading == NULL || gRLSpecial->noData == NULL || - gRLSpecial->disabled == NULL) { - enableRelatedLinksp = 0; - freeMem(gRLSpecial->loading); - freeMem(gRLSpecial->noData); - freeMem(gRLSpecial->disabled); - } - NET_RegisterContentTypeConverter( "*", FO_CACHE_AND_RDF, NULL, -NET_CacheConverter); - NET_RegisterContentTypeConverter( "*", FO_RDF, NULL, RL_Converter); - enableRelatedLinksp = 1; - gInitialDiff = gMaxDiff = 4; - relatedLinksProvider = copyString("http://www-rl.netscape.com/wtgn?"); - -} - -void freeMem(void* x) { - if (x != NULL) free(x); -} - -static RL_Window gRLWindow = 0; - -RL_Window RL_MakeRLWindowWithCallback (RLCallBackProc callBack, void* -fe_data) { - RL_Window win = RL_MakeRLWindow(); - if (win == NULL) return NULL; - win->callBack = callBack; - win->fe_data = fe_data; - gRLWindow = win; - return win; -} - - -RL_Window RL_MakeRLWindow() { - RL_Window ans = (RL_Window) getMem(sizeof(struct _RL_Window)); - if (ans == NULL) return NULL; - ans->line = getMem(RL_LINE_SIZE); - if (ans->line == NULL) { - freeMem(ans); - return NULL; - } - ans->holdOver = getMem(RL_LINE_SIZE); - if (ans->holdOver == NULL) { - freeMem(ans->line); - freeMem(ans); - return NULL; - } - ans->rlurl = getMem(RL_MAX_URL); - if (ans->rlurl == NULL) { - freeMem(ans->line); - freeMem(ans->rlurl); - freeMem(ans); - return NULL; - } - ans->diff = gInitialDiff; - return ans; -} - -void RL_DestroyRLWindow(RL_Window win) { - if (!win) return; - cleanRLTree(win->prevItems); - cleanRLTree(win->items); - if (win->currentlyLoading) { - win->currentlyLoading->fe_data = NULL; /* |fe_data| is really |win| -and will be */ - /* disposed of below */ - NET_InterruptStream (win->currentlyLoading); - } - freeMem(win->line); - freeMem(win->holdOver); - freeMem(win); -} - -PRIVATE -PRBool implicitDomainURL (char* url) { - uint16 n = 7; - uint16 size = strlen(url); - while (n < size) { - if (url[n] == '/') return PR_TRUE; - if (url[n] == '.') return PR_FALSE; - n++; - } - return PR_TRUE; -} - - -PRIVATE -PRBool relatedLinksEnabledURL (char* url) { - if (url == NULL) return PR_FALSE; - if (strlen(url) > 300) return PR_FALSE; - if (!startsWith("http:", url)) { - return PR_FALSE; - } else if (implicitDomainURL(url)) { - return PR_FALSE; - } else return PR_TRUE; -} - - -PRIVATE -PRBool getRLURL (RL_Window win, char* url) { - size_t n, m, l; - memset(win->rlurl, '\0', RL_MAX_URL); - if (!win->demoUrlp) { - if (!strstr(url, "http://")) return PR_FALSE; - } - if (strlen(url) > 370) return PR_FALSE; - sprintf(win->rlurl, "%s", relatedLinksProvider); - n = strlen(relatedLinksProvider) ; - m = (win->demoUrlp ? 25 : 7); - l = strlen(url); - while (m < l) { - if ((url[m] == '?') || (url[m] == '#') || (url[m] == '@')) { - win->rlurl[n++] = url[m++]; - break; - } - win->rlurl[n++] = url[m++]; - } - return PR_TRUE; -} - - -void RL_SetRLWindowURL(RL_Window win, char* url) { - if (!win || !relatedLinksProvider || !enableRelatedLinksp) return; - - cleanRLTree(win->prevItems); - win->prevItems = win->items; - win->items = NULL; - freeMem(win->url); - win->url = NULL; - if (win->currentlyLoading != NULL) { - NET_InterruptStream (win->currentlyLoading); - win->currentlyLoading = NULL; - } - win->count = 0; - if (win->url && url && !strcmp(url,win->url)) return; - win->demoUrlp = startsWith("file:///c%7C/NS1998Demos", url); - if (!win->demoUrlp && !relatedLinksEnabledURL(url)) { - win->status = RL_STATUS_NOT_AVAILABLE; - return; - } - if (!getRLURL(win, url)) return; - win->url = copyString(url); - win->diff++; - if (win->diff < gMaxDiff) { - win->status = RL_STATUS_LOADING; - GetRL(win); - } else { - win->status = RL_STATUS_WAITING_TO_LOAD; - } -} - -void cleanRLTree (RL_Item item) { - while (item) { - RL_Item old = item; - freeMem(item->name); - PL_strfree(item->convertedName); - freeMem(item->rurl); - item->name = item->url = NULL; - if (item->child) cleanRLTree(item->child); - item->child = NULL; - item = item->next; - freeMem(old); - } -} - -void RL_AddItem (RL_Window win, char* nurl, char* name, uint8 type) { - if (win != NULL && (win->status == RL_STATUS_LOADING)) { - RL_Item item = (RL_Item)getMem(sizeof(struct _RL_Item)); - PRBool zerop = (win->count == 0) ? PR_TRUE : PR_FALSE; - RL_Item existing; - char* url = NULL; - if (nurl) url = strstr(&nurl[7], "http://"); - if (!url) url = nurl; - if (item == NULL) return; - item->rurl = nurl; - item->name = name; - item->url = url; - item->type = type; - win->count++; - existing = (win->depth == 0 ? win->items : win->stack[win->depth-1]->child); - if (!existing) { - if (win->depth == 0) { - win->items = item; - } else { - win->stack[win->depth-1]->child = item; - } - } else { - while (existing->next) { - if (existing->url && url && (strcmp(existing->url, url) == 0)) { - freeMem(item); - return; - } - existing = existing->next; - } - existing->next = item; - } - if (type == RL_CONTAINER) win->stack[win->depth++] = item; - } -} - - -RL_Item RL_WindowItems (RL_Window win) { - if ((win != NULL) && (win->rlurl[0] != '\0') && enableRelatedLinksp) { - win->diff = 0; - gInitialDiff = 0; - if (win->items) { - return win->items; - } else if (win->status == RL_STATUS_WAITING_TO_LOAD) { - win->status = RL_STATUS_LOADING; - GetRL(win); - if (win->items == NULL) return gRLSpecial->loading; - return win->items; - } else if (win->status == RL_STATUS_LOADING) { - return gRLSpecial->loading; - } else return gRLSpecial->noData; - } else if (!enableRelatedLinksp) { - return gRLSpecial->disabled; - } else return gRLSpecial->noData; -} - -PRIVATE -void RL_PossiblyLoad (RL_Window win) { - if ((win != NULL) && (win->diff < gMaxDiff) && enableRelatedLinksp && - (win->status == RL_STATUS_WAITING_TO_LOAD)) { - win->status = RL_STATUS_LOADING; - GetRL(win); - } -} - -RL_Item RL_NextItem(RL_Item item) { - if (!validRLItem(item)) return NULL; - return item->next; -} - -RL_Item RL_ItemChild(RL_Item item) { - if (!validRLItem(item)) return NULL; - return item->child; -} - -uint8 RL_ItemCount(RL_Window win) { - return (win->count ? win->count : 1); -} - - -RL_ItemType RL_GetItemType(RL_Item item) { - if (!validRLItem(item)) return NULL; - return item->type; -} - -char* RL_ItemName(RL_Item item) { - if (!validRLItem(item)) return NULL; - return item->name; -} - - -char* RL_ItemUrl(RL_Item item) { - if (!validRLItem(item)) return NULL; - return item->url; -} - - -PRIVATE -char* RL_WinReferer(RL_Window win) { - return win->rlurl; -} - -void GetRL (RL_Window win) { - URL_Struct *urls; - - if (!enableRelatedLinksp) return; -/* XP_Trace("\nFetching %s", win->rlurl); */ - urls = NET_CreateURLStruct(win->rlurl, NET_DONT_RELOAD); - if (urls == NULL) return; - - urls->load_background = TRUE; - urls->fe_data = win; /* hookup url_struct to RL_Window and vice -versa */ - win->currentlyLoading = urls; /* so you can get one from the other */ - - win->status = RL_STATUS_LOADING; - MWContext * pContext = XP_FindContextOfType(0,MWContextBrowser); - NET_GetURL(urls, FO_CACHE_AND_RDF, pContext, -rl_GetUrlExitFunc); - -} - - - -void rl_GetUrlExitFunc (URL_Struct *urls, int status, MWContext *cx) { - if (urls != NULL) { - RL_Window win = (RL_Window)urls->fe_data; - if ( win != NULL ) { - win->status = RL_STATUS_ABORTED; - /* if (win->callBack) (*(win->callBack))(win->fe_data, win); */ - NET_FreeURLStruct (urls); - } - } -} - -PUBLIC NET_StreamClass * -RL_Converter(FO_Present_Types format_out, void *data_object, - URL_Struct *URL_s, MWContext *window_id) { - NET_StreamClass* stream; - RL_Window rl = (RL_Window) URL_s->fe_data; - RL_Get rg; - -/* XP_Trace("\nSetting up display stream. Have URL: %s\n", -URL_s->address); */ - if ((rl == NULL) || (rl->status != RL_STATUS_LOADING)) - return NULL; - - rg = (RL_Get) getMem(sizeof(struct _RL_Get)); - memset(rl->line, '\0', RL_LINE_SIZE); - memset(rl->holdOver, '\0', RL_LINE_SIZE); - rg->win = rl; - rl->depth = 0; - rg->url = URL_s; - rl->currentlyLoading = URL_s; - - stream = NET_NewStream("RL", - (MKStreamWriteFunc)rl_write, - (MKStreamCompleteFunc)rl_complete, - (MKStreamAbortFunc)rl_abort, - (MKStreamWriteReadyFunc)rl_write_ready, - rg, window_id); - - return(stream); -} - - -int rl_write(void *obj, const char *str, int32 len) { - RL_Get rg = (RL_Get)obj; - RL_Window win; - if (obj == NULL || len < 0) { - return MK_INTERRUPTED; - } - win = gRLWindow; - /* if (rg->url != win->currentlyLoading) return len; */ - parseNextRDFXMLBlob(win, (char *)str, len); - return(len); -} - -unsigned int rl_write_ready(void *obj) { - return RL_LINE_SIZE; -} - -void rl_abort(void *obj, int status) { - RL_Get rg = (RL_Get)obj; - RL_Window win ; - if (rg == NULL) return; - win = gRLWindow; - if (win->currentlyLoading == rg->url) - win->status = RL_STATUS_ABORTED; - if (win->callBack) (*(win->callBack))(win->fe_data, win); - freeMem(obj); -} - -void rl_complete (void *obj) { - RL_Get rg = (RL_Get)obj; - RL_Window win; - if (rg == NULL) return; - win = gRLWindow; - if (win->currentlyLoading == rg->url) win->status = -RL_STATUS_COMPLETED; - win->currentlyLoading = NULL; - -} - - - - -#define MAX_ATTRIBUTES 9 - -void parseNextRDFXMLBlob (RL_Window f, char* blob, int32 size) { - int32 n, last, m; - PRBool somethingseenp = PR_FALSE; - n = last = 0; - - while (n < size) { - char c = blob[n]; - m = 0; - somethingseenp = PR_FALSE; - memset(f->line, '\0', RL_LINE_SIZE); - if (f->holdOver[0] != '\0') { - memcpy(f->line, f->holdOver, strlen(f->holdOver)); - m = strlen(f->holdOver); - somethingseenp = PR_TRUE; - memset(f->holdOver, '\0', RL_LINE_SIZE); - } - while ((m < 300) && (c != '<') && (c != '>')) { - f->line[m] = c; - m++; - somethingseenp = (somethingseenp || ((c != ' ') && (c != '\r') && -(c != '\n'))) ? PR_TRUE : PR_FALSE; - n++; - if (n < size) c = blob[n]; - else break; - } - if (c == '>') f->line[m] = c; - n++; - if (m > 0) { - if ((c == '<') || (c == '>')) { - last = n; - if (c == '<') f->holdOver[0] = '<'; - if (somethingseenp == 1) parseNextRDFToken(f, f->line); - } else if (size > last) { - memcpy(f->holdOver, f->line, m); - } - } else if (c == '<') f->holdOver[0] = '<'; - } -} - -PRIVATE -void parseRDFProcessingInstruction (RL_Window win, char* token) { - char* attlist[MAX_ATTRIBUTES+1]; - char* newServer; - extractAttributes(token, attlist); - newServer = getAttributeValue(attlist, "relatedLinksServer"); - if (newServer) { - freeMem(relatedLinksProvider); - relatedLinksProvider = getMem(strlen(newServer)); - if (relatedLinksProvider) - memcpy(relatedLinksProvider, newServer, strlen(newServer)); - } -} - -char* getAttributeValue (char** attlist, char* elName) { - size_t n = 0; - while ((n < MAX_ATTRIBUTES) && (*(attlist + n) != NULL)) { - if (strcmp(*(attlist + n), elName) == 0) return *(attlist + n + 1); - n = n + 2; - } - return NULL; -} - -PRBool tokenEquals (char* token, char* elName, PRBool endp) { - if (endp) { - return ((token[1] == '/') && (strncmp(elName, &token[2], -strlen(elName)) ==0)) ? PR_TRUE : PR_FALSE; - } else { - return (strncmp(elName, &token[1], strlen(elName)) ==0) ? PR_TRUE : -PR_FALSE; - } -} - -void parseNextRDFToken (RL_Window f, char* token) { - if (token[0] != '<') { - return; - } else if (tokenEquals(token, "RelatedLinks", PR_TRUE)) { - (*f->callBack)(f->fe_data, f); - - } else if (tokenEquals(token, "Topic", PR_TRUE)) { - if (f->depth > 0) f->depth--; - } else if (token[1] == '?') { - parseRDFProcessingInstruction(f, token); - } else { - char* attlist[MAX_ATTRIBUTES+1]; - extractAttributes(token, attlist); - if (tokenEquals(token, "aboutPage", PR_FALSE)) { - } else if (tokenEquals(token, "child", PR_FALSE)) { - char* url = getAttributeValue(attlist, "href"); - char* name = getAttributeValue(attlist, "name"); - char* type = getAttributeValue(attlist, "instanceOf"); - if (url && name) RL_AddItem(f, copyString(url), copyString(name), -RL_LINK); - if (type && (strcmp(type, "Separator"))) RL_AddItem(f, NULL, NULL, -RL_SEPARATOR); - } else if (tokenEquals(token, "Topic", PR_FALSE)) { - char* name = getAttributeValue(attlist, "name"); - if (name) RL_AddItem(f, NULL, copyString(name), RL_CONTAINER); - } - } -} - - -void extractAttributes (char* attr, char** attlist) { - size_t n = 1; - size_t s = strlen(attr); - char c ; - size_t m = 0; - size_t atc = 0; - PRBool emptyTagp = (attr[s-2] == '/') ? PR_TRUE : PR_FALSE; - PRBool inAttrNamep = PR_TRUE; - c = attr[n++]; - while (n < s) { - if ((c == ' ') || (c == '\n') || (c == '\r')) break; - c = attr[n++]; - } - while (atc < MAX_ATTRIBUTES+1) {*(attlist + atc++) = NULL;} - atc = 0; - s = (emptyTagp ? s-2 : s-1); - while (n < s) { - PRBool attributeOpenStringSeenp = PR_FALSE; - m = 0; - c = attr[n++]; - while ((n <= s) && (atc < MAX_ATTRIBUTES)) { - if (inAttrNamep && (m > 0) && ((c == ' ') || (c == '\n') || (c == -'\r') || (c == '='))) { - attr[n-1] = '\0'; - *(attlist + atc++) = &attr[n-m-1]; - break; - } - if (!inAttrNamep && attributeOpenStringSeenp && (c == '"')) { - attr[n-1] = '\0'; - *(attlist + atc++) = &attr[n-m-1]; - break; - } - if (inAttrNamep) { - if ((m > 0) || (c != ' ')) m++; - } else { - if (c == '"') { - attributeOpenStringSeenp = PR_TRUE; - } else { - if ((m > 0) || (c != ' ')) m++; - } - } - c = attr[n++]; - } - inAttrNamep = (inAttrNamep ? PR_FALSE : PR_TRUE); - } -} diff --git a/mozilla/network/module/nsSocketTransport.cpp b/mozilla/network/module/nsSocketTransport.cpp deleted file mode 100644 index 4026ed9b425..00000000000 --- a/mozilla/network/module/nsSocketTransport.cpp +++ /dev/null @@ -1,427 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "nsIComponentManager.h" -#include "nsNetStream.h" -#include "nsSocketTransport.h" -#include "nsINetService.h" -#include "nsINetlibURL.h" - -#include "nsIServiceManager.h" - -#include "netutils.h" -#include "mktcp.h" -#include "sockstub.h" - -#include "plstr.h" - -extern nsIStreamListener* ns_NewStreamListenerProxy(nsIStreamListener* aListener, nsIEventQueue* aEventQ); -static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID); -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static NS_DEFINE_IID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID); -static NS_DEFINE_IID(kIEventQueueServiceIID, NS_IEVENTQUEUESERVICE_IID); - -//////////////////////////////////////////////////////////////////////////// -// from nsISupports - -static NS_DEFINE_IID(kITransportIID, NS_ITRANSPORT_IID); -NS_IMPL_ADDREF(nsSocketTransport) -NS_IMPL_RELEASE(nsSocketTransport) -NS_IMPL_QUERY_INTERFACE(nsSocketTransport, kITransportIID); - -//////////////////////////////////////////////////////////////////////////// -// from nsITransport: - -NS_METHOD -nsSocketTransport::GetURL(nsIURI* *result) -{ - *result = m_url; - return NS_OK; -} - - -static NS_DEFINE_IID(kINetlibURLIID, NS_INETLIBURL_IID); - -NS_METHOD nsSocketTransport::IsTransportOpen(PRBool * aSocketOpen) -{ - nsresult rv = NS_OK; - if (aSocketOpen) - *aSocketOpen = m_socketIsOpen; - - return rv; -} - -/* Open means take the url and make a socket connection with the host... - The user will then write data to be sent to the host via our input stream... - */ - -NS_METHOD nsSocketTransport::Open(nsIURI *pURL) -{ - nsresult rv = NS_OK; - - // only actually try to do anything if we aren't open for business yet... - if (m_socketIsOpen == PR_FALSE) - { - m_socketIsOpen = PR_TRUE; - - if (nsnull == pURL) - return NS_ERROR_NULL_POINTER; - - if (nsnull == m_inputStreamConsumer) - return NS_ERROR_NULL_POINTER; - - NS_IF_ADDREF(pURL); - m_url = pURL; - - if (!m_isFileConnection) - { - pURL->SetHostPort(m_port); - const char * hostName = nsnull; - pURL->GetHost(&hostName); - if (hostName) - { - PR_FREEIF(m_hostName); - m_hostName = PL_strdup(hostName); - } - } - - // mscott --> okay here's where the fact that the transport implementation is just a hack on - // the old world comes in....right now this transport class supports both socket and file based - // connections. The protocol is blind to this. They just gave us a url like: news://newshost. - // this particular url wants a network based socket so we need to use the sockstub hack. In order - // to do this, we need to change the protocol part of the url string to sockstub.... - // if the url wants a file based socket connection, we change the protocol part of the url to - // file:// and piggy back off of the file protocol code. Why do we do this here? Well the rest of the - // app (both the app who runs the url and the protocol which is handling the url) can use protocol - // url parts like imap, mailbox, http, etc. Then when they are done with it and hand it to us for - // the underlying socket to be opened, we can turn around and tweek the protocol name to use the old - // world technology to build it (sockstub and file). - - if (m_isFileConnection) - pURL->SetProtocol("file"); - else // we want a network socket so use sockstub - pURL->SetProtocol("sockstub"); - - // now the right protocol is set for the old networking world to use to complete the task - // so we can open it now.. - rv = NS_OpenURL(pURL, m_inputStreamConsumer); - - m_socketIsOpen = PR_TRUE; - } - - return rv; -} - -NS_METHOD -nsSocketTransport::SetInputStreamConsumer(nsIStreamListener* aListener) -{ - // generates the thread safe proxy - m_inputStreamConsumer = ns_NewStreamListenerProxy(aListener, m_evQueue); - NS_IF_ADDREF(m_inputStreamConsumer); - return NS_OK; -} - - -NS_METHOD -nsSocketTransport::GetOutputStreamConsumer(nsIStreamListener ** aConsumer) -{ - if (aConsumer) - { - // assuming the transport layer is a nsIStreamListener - *aConsumer = ns_NewStreamListenerProxy(this, m_evQueue); - // add ref bfore returning... - NS_IF_ADDREF(*aConsumer); - } - return NS_OK; -} - - -NS_METHOD -nsSocketTransport::GetOutputStream(nsIOutputStream ** aOutputStream) -{ - if (aOutputStream) { - // a buffered stream supports the nsIOutputStream interface - nsBufferedStream * stream = new nsBufferedStream(); - if (stream) // return the buffer in the format they want - stream->QueryInterface(kIOutputStreamIID, (void **) aOutputStream); - else - *aOutputStream = NULL; - } - return NS_OK; -} - - -NS_IMETHODIMP -nsSocketTransport::OnStartRequest(nsIURI* pURL, const char *aContentType) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsSocketTransport::OnProgress(nsIURI* pURL, - PRUint32 aProgress, - PRUint32 aProgressMax) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsSocketTransport::OnStatus(nsIURI* pURL, const PRUnichar* aMsg) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsSocketTransport::OnStopRequest(nsIURI* pURL, - nsresult aStatus, - const PRUnichar* aMsg) -{ -// if the protocol instance called OnStopRequest then they are effectively asking us -// to close the connection. But they don't want US to go away..... -// so we need to close the underlying socket.... - CloseCurrentConnection(); - return NS_OK; -} - -NS_IMETHODIMP -nsSocketTransport::GetBindInfo(nsIURI* pURL, - nsStreamBindingInfo* aInfo) -{ - return NS_OK; -} - -NS_IMETHODIMP -nsSocketTransport::OnDataAvailable(nsIURI* pURL, - nsIInputStream *aIStream, - PRUint32 aLength) -{ - nsresult rv = NS_OK; - PRUint32 len, lenRead; - URL_Struct* URL_s; - m_ready_fd = NULL; - - /* XXX: HACK The following is a hack. - * Get the URL_s structure and pass it to sockstub protocol code to get the - * socket FD so that we could write the data back. - */ - - NS_PRECONDITION(m_socketIsOpen, "Uhoh, you tried to write to a socket before opening it by calling open..."); - - if (m_socketIsOpen == PR_TRUE) // only do something useful if we are open... - { - rv = GetURLInfo(pURL, &URL_s); // this call is necessay 'cause it forces us to get m_bindedUrlStruct if we don't have it. - - if (NS_SUCCEEDED(rv)) - { - if (nsnull != m_bindedUrlStruct) - /* Find the socket given URL_s pointer */ - m_ready_fd = NET_GetSocketToHashTable(m_bindedUrlStruct); - } - else - return rv; - - if (m_ready_fd == NULL) - return NS_ERROR_NULL_POINTER; - - aIStream->GetLength(&len); - - memset(m_buffer, '\0', NET_SOCKSTUB_BUF_SIZE); - while (len > 0) - { - if (len < NET_SOCKSTUB_BUF_SIZE) - lenRead = len; - else - lenRead = NET_SOCKSTUB_BUF_SIZE; - - rv = aIStream->Read(m_buffer, lenRead, &lenRead); - if (NS_OK != rv) - return rv; - - /* XXX: We should check if the write has succeeded or not */ - (int) NET_BlockingWrite(m_ready_fd, m_buffer, lenRead); - len -= lenRead; - } - } - else - rv = NS_ERROR_FAILURE; // stream was not open... - - return rv; -} - - - -//////////////////////////////////////////////////////////////////////////// -// from nsSocketTransport: - -nsSocketTransport::nsSocketTransport(PRUint32 aPortToUse, const char * aHostName) -{ - NS_INIT_REFCNT(); - - // remember the port and host name - NS_PRECONDITION(aPortToUse > 0 && aHostName, "Creating a socket transport with an invalid port or host name."); - m_fileName = nsnull; - m_port = aPortToUse; - if (aHostName) - m_hostName = PL_strdup(aHostName); - else - m_hostName = PL_strdup(""); - - m_isFileConnection = PR_FALSE; - - // common initialization code - Initialize(); -} - -nsSocketTransport::nsSocketTransport(const char * fileName) -{ - NS_INIT_REFCNT(); - m_fileName = nsnull; - NS_PRECONDITION(fileName && *fileName, "Creating a socket with an invalid file name."); - if (fileName) - { - m_fileName = PL_strdup(fileName); - } - - m_isFileConnection = PR_TRUE; - m_hostName = nsnull; // initialize value - - // common initialization code - Initialize(); -} - -void nsSocketTransport::Initialize() -{ - m_inputStream = NULL; - m_inputStreamConsumer = NULL; - m_url = NULL; - m_bindedUrlStruct = NULL; - - m_outStream = NULL; - m_outStreamSize = 0; - m_socketIsOpen = PR_FALSE; // initially, we have not opened the socket... - - /* - * Cache the EventQueueService... - */ - // XXX: What if this fails? - - mEventQService = nsnull; - m_evQueue = nsnull; - nsresult rv = nsServiceManager::GetService(kEventQueueServiceCID, - kIEventQueueServiceIID, - (nsISupports **)&mEventQService); - - if (nsnull != mEventQService) - mEventQService->GetThreadEventQueue(NS_CURRENT_THREAD, &m_evQueue); -} - -nsSocketTransport::~nsSocketTransport() -{ - nsresult rv = NS_OK; - - /* XXX: HACK The following is a hack. - * Get the URL_s structure and pass it to sockstub protocol code to delete it - */ - - rv = CloseCurrentConnection(); - - PR_FREEIF(m_fileName); - - NS_IF_RELEASE(mEventQService); - NS_IF_RELEASE(m_evQueue); - NS_IF_RELEASE(m_outStream); - NS_IF_RELEASE(m_url); - NS_IF_RELEASE(m_inputStreamConsumer); -} - -NS_IMETHODIMP nsSocketTransport::SetSocketBinding(nsIURI* pURL, URL_Struct_ ** aResult) -{ - nsresult rv = NS_OK; - nsINetlibURL *pNetlibURL = NULL; - if (pURL && aResult) - { - if (pURL) - rv = pURL->QueryInterface(kINetlibURLIID, (void**)&pNetlibURL); - if (NS_SUCCEEDED(rv) && pNetlibURL) - { - pNetlibURL->GetURLInfo(aResult); - NS_RELEASE(pNetlibURL); - } - } - - return rv; -} - -NS_IMETHODIMP -nsSocketTransport::GetURLInfo(nsIURI* pURL, URL_Struct_ **aResult) -{ - // hack alert!!! we use a url struct to bind a socket transport to an active entry - // running the sockstub protocol. however the url struct is bound to the url. if you run - // another url through the socket, you'll get a different active entry back! (i.e. - // you won't get the original active entry that should be bound to the transport. - // so i'm going to remember the url_struct used to create the active entry and we'll - // always return that url struct for the lifetime ofthe transport. This will ensure, - // that we always get the original active entry and those allows us to run multiple - // urls through this connection. - - SetSocketBinding(pURL, aResult); - - if (!m_bindedUrlStruct && aResult) - m_bindedUrlStruct = *aResult; - else // we must be running a new url..... - { - // this is a god awful hack...i'm ashamed.....swap the url associated with - // the connection info out from under us with the new url...pURL. - - nsIConnectionInfo * pConn = (nsIConnectionInfo *) m_bindedUrlStruct->fe_data; - if (pConn) - pConn->SetURL(pURL); - } - return NS_OK; -} - -nsresult nsSocketTransport::CloseCurrentConnection() -{ - nsresult rv = NS_OK; - URL_Struct_ * URL_s = nsnull; - - // mscott --> we used to interrupt the stream for the current url - // here. However, the stream has already been interrupted! A typical - // scenario: we lose a connection with the server. the stream is interrupted - // and it tells the protocol that the connection is going down (through an - // on stop binding call). The protocol is then releasing the transport which - // is causing close current connection to get called. But the stream - // has already been interrupted.....that's what started the whole process. - // so don't add code to interrupt it again. - - // Note: If we need to provide the ability for the protocol to interrupt - // the stream manually then we need a separate method in the transport - // interface which would be used explicitly for protocol driven close - // connection rather than netlib driven close connection... - - // now free any per socket state information... - m_socketIsOpen = PR_FALSE; - - NS_IF_RELEASE(m_url); - m_url = nsnull; - PR_FREEIF(m_hostName); - return rv; -} diff --git a/mozilla/network/module/nsSocketTransport.h b/mozilla/network/module/nsSocketTransport.h deleted file mode 100644 index 6380d7a966f..00000000000 --- a/mozilla/network/module/nsSocketTransport.h +++ /dev/null @@ -1,130 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsSocketTransport_h__ -#define nsSocketTransport_h__ - -#include "nsIComponentManager.h" -#include "nsITransport.h" -#include "nsIStreamListener.h" -#include "nsIInputStream.h" -#include "nsIOutputStream.h" -#include "nsIEventQueueService.h" -#include "nsAgg.h" -#include "nsString.h" - -#define NET_SOCKSTUB_BUF_SIZE 1024 - -/* forward declaration */ -struct URL_Struct_; - -class nsSocketTransport : public nsITransport -{ -public: - //////////////////////////////////////////////////////////////////////////// - // from nsISupports: - - NS_DECL_ISUPPORTS - - - //////////////////////////////////////////////////////////////////////////// - // from nsITransport: - - NS_IMETHOD GetURL(nsIURI* *result); - - NS_IMETHOD SetInputStreamConsumer(nsIStreamListener* aListener); - - NS_IMETHOD GetOutputStreamConsumer(nsIStreamListener ** aConsumer); - - NS_IMETHOD GetOutputStream(nsIOutputStream ** aOutputStream); - - NS_IMETHOD IsTransportOpen(PRBool * aSocketOpen); - - NS_IMETHOD Open(nsIURI * aUrl); - - //////////////////////////////////////////////////////////////////////////// - // from nsIStreamListener: - - NS_IMETHOD OnStartRequest(nsIURI* aURL, const char *aContentType); - NS_IMETHOD OnProgress(nsIURI* aURL, PRUint32 aProgress, PRUint32 aProgressMax); - NS_IMETHOD OnStatus(nsIURI* aURL, const PRUnichar* aMsg); - NS_IMETHOD OnStopRequest(nsIURI* aURL, nsresult aStatus, const PRUnichar* aMsg); - NS_IMETHOD GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* aInfo); - NS_IMETHOD OnDataAvailable(nsIURI* aURL, nsIInputStream *aIStream, - PRUint32 aLength); - - - //////////////////////////////////////////////////////////////////////////// - // nsSocketTransport: - - // we have two types of connections: socket and file based.... - nsSocketTransport(PRUint32 aPortToUse, const char * aHostName); - nsSocketTransport(const char * fileName); - - virtual ~nsSocketTransport(void); - NS_IMETHOD GetURLInfo(nsIURI* pURL, URL_Struct_ **aResult); - NS_IMETHOD SetSocketBinding(nsIURI* pURL, URL_Struct_ ** aResult); - - // the following routines are called by the sock stub protocol hack.... - // we should be able to remove this dependency once we move things to the new - // net lib world... - PRUint32 GetPort() {return m_port;} - const char * GetHostName() { return m_hostName;} - const char * GetFileName() { return m_fileName;} - -protected: - - // use this function to close the underlying connection.... - nsresult CloseCurrentConnection(); - // common initialization code.. - void Initialize(); - - // socket specific information... - PRUint32 m_port; - char *m_hostName; - char *m_fileName; - PRBool m_socketIsOpen; // set when we have opened a socket.... - PRBool m_isFileConnection; - - // the stream we write data from the socket into - nsIInputStream * m_inputStream; - - // XXX sock stub hack..need to remember stream with data to be written to the socket - nsIInputStream * m_outStream; - PRUint32 m_outStreamSize; - - // the proxied stream listener. Whenever the transport layer - // writes socket date to input stream, it calls OnDataAvailable - // through the inputStreamConsumer any socket specific data - nsIStreamListener *m_inputStreamConsumer; - - nsIURI *m_url; // the url we are currently running... - nsString* mData; - PRFileDesc *m_ready_fd; - nsIEventQueueService* mEventQService; - nsIEventQueue* m_evQueue; - char m_buffer[NET_SOCKSTUB_BUF_SIZE]; - - URL_Struct_ * m_bindedUrlStruct; -}; - -#endif // nsSocketTransport_h__ diff --git a/mozilla/network/module/nsStubContext.cpp b/mozilla/network/module/nsStubContext.cpp deleted file mode 100644 index 59d83967c78..00000000000 --- a/mozilla/network/module/nsStubContext.cpp +++ /dev/null @@ -1,990 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "nsStubContext.h" - -#include "net.h" -#include "mktrace.h" -#include "structs.h" -#include "ctxtfunc.h" -#include "xp_list.h" -#include "plstr.h" -#include "fe_proto.h" // Needed for prototype of FE_Alert(). -#include "proto.h" // Needed for prototype of XP_FindContextOfType(). - -#include "nsString.h" -#include "nsIStreamListener.h" -#include "nsINetSupport.h" -#include "nsNetStream.h" - - -/* forward declaration */ -extern "C" void NET_ResumeWithAuth (void *); - -void free_stub_context(MWContext *window_id); - - -/****************************************************************************/ -/* Beginning of MWContext Evil!!! */ -/* ------------------------------- */ -/* */ -/* Define a dummy MWContext where all of the upcalls are stubbed out. */ -/* */ -/****************************************************************************/ - -PRIVATE int -stub_noop(int x, ...) -{ -#ifdef XP_MAC -#pragma unused (x) -#endif -/* DebugBreak(); */ - return 0; -} - -static nsIStreamListener *getStreamListener(URL_Struct *URL_s) -{ - nsIStreamListener *res = NULL; - - if (URL_s && URL_s->fe_data) { - /* - * Retrieve the nsConnectionInfo object from the fe_data field - * of the URL_Struct... - */ - nsConnectionInfo *pConn = (nsConnectionInfo *)URL_s->fe_data; - if (pConn) { - res = pConn->pConsumer; - } - } - - NS_IF_ADDREF(res); - - return res; -} - -static NS_DEFINE_IID(kINetSupportIID, NS_INETSUPPORT_IID); - -static nsINetSupport *getNetSupport(URL_Struct *URL_s) -{ - nsINetSupport *netSupport = nsnull; - - /* Access the nsConnectionInfo object off of the URL Struct fe_data */ - if ((nsnull != URL_s) && (nsnull != URL_s->fe_data)) { - nsConnectionInfo *pConn = (nsConnectionInfo *)URL_s->fe_data; - - /* Now get the nsIURL.held by the nsConnectionInfo... */ - if ((nsnull != pConn) && (nsnull != pConn->pURL)) { - nsISupports *container; - - /* The nsINetSupport interface will be implemented by the container */ - nsresult err = pConn->pURL->GetContainer(&container); - if (NS_SUCCEEDED(err) && (nsnull != container)) { - container->QueryInterface(kINetSupportIID, (void **) &netSupport); - NS_RELEASE(container); - } - } - } - return netSupport; -} - -PRIVATE -void stub_Alert(MWContext *context, - const char *msg) -{ - nsINetSupport *ins; - - if (nsnull != (ins = getNetSupport(context->modular_data))) { - nsAutoString str(msg); - - ins->Alert(str); - NS_RELEASE(ins);; - } - /* No nsINetSupport interface... */ - else { - printf("%cAlert: %s", '\007', msg); - } -} - -extern "C" void FE_Alert(MWContext *context, const char *msg) -{ - stub_Alert(context, msg); -} - -#if defined (WIN32) -extern "C" char * FE_GetProgramDirectory(char *buffer, int length) { - printf("XXX: returning c:\\temp\\ for the FE_GetProgramDirectory!\n"); - strcpy(buffer, "c:\\temp\\"); - return buffer; -} -#elif defined (XP_UNIX) -extern "C" char * fe_GetProgramDirectory(char *buffer, int length) { - printf("XXX: returning /tmp for the fe_GetProgramDirectory!\n"); - strcpy(buffer, "/tmp/"); - return buffer; -} -#endif - -PRIVATE -XP_Bool stub_Confirm(MWContext *context, - const char *msg) -{ - nsINetSupport *ins; - XP_Bool bResult = FALSE; - - if (nsnull != (ins = getNetSupport(context->modular_data))) { - nsAutoString str(msg); - - bResult = ins->Confirm(str); - NS_RELEASE(ins); - } - /* No nsINetSupport interface... */ - else { - printf("%cConfirm: %s (y/n)? ", '\007', msg); - char c; - for (;;) { - c = getchar(); - if (tolower(c) == 'y') { - bResult = TRUE; - } - if (tolower(c) == 'n') { - bResult = FALSE; - } - } - } - return bResult; -} - -PRIVATE -char *stub_Prompt(MWContext *context, - const char *msg, - const char *def) -{ - nsINetSupport *ins; - char *result = nsnull; - - if (nsnull != (ins = getNetSupport(context->modular_data))) { - nsAutoString str(msg); - nsAutoString defStr(def); - nsAutoString res; - - if (ins->Prompt(msg, defStr, res)) { - NS_RELEASE(ins); - result = res.ToNewCString(); - } - NS_RELEASE(ins); - - } - /* No nsINetSupport interface... */ - else { - char buf[256]; - - printf("%s\n", msg); - printf("%cPrompt (default=%s): ", '\007', def); - fgets(buf, sizeof buf, stdin); - if (PL_strlen(buf)) { - result = PL_strdup(buf); - } else { - result = PL_strdup(def); - } - } - - return result; -} - -// Choose between using the command line and the UI for getting the new password -#if 1 -#include "nsIComponentManager.h" -#include "nsIBlockingNotification.h" -#include "nsAppShellCIDs.h" -#include "plevent.h" - -static NS_DEFINE_IID(kProtocolHelperCID, NS_PROTOCOL_HELPER_CID); -// static NS_DEFINE_IID(kDefaultNotificationCID, NS_DEFAULT_NOTIFICATION_CID); - -static NS_DEFINE_IID(kIBlockingNotificationObserverIID, - NS_IBLOCKINGNOTIFICATION_OBSERVER_IID); -static NS_DEFINE_IID(kIBlockingNotificationIID, NS_IBLOCKINGNOTIFICATION_IID); - -/*-------------------- nsDefaultNotification ----------------------------*/ - -// our notification object -class nsDefaultNotification : public nsIBlockingNotification -{ -public: - nsDefaultNotification(); - - /* nsISupports interface... */ - NS_DECL_ISUPPORTS - - /* nsIBlockingNotification interface... */ - NS_IMETHOD IsBlocked(nsIURI *aURL, PRBool *aResult); - NS_IMETHOD Resume(nsIURI *aUrl, void *aExtraInfo); -}; - -nsDefaultNotification::nsDefaultNotification() -{ - NS_INIT_REFCNT(); -} - -/* - * Implementations of nsISupports interface methods... - */ -NS_IMPL_ADDREF(nsDefaultNotification); -NS_IMPL_RELEASE(nsDefaultNotification); -NS_IMPL_QUERY_INTERFACE(nsDefaultNotification, kIBlockingNotificationIID); - -NS_IMETHODIMP -nsDefaultNotification::IsBlocked(nsIURI *aURL, PRBool *aResult) -{ - nsresult rv = NS_NOTIFY_BLOCKED; - return rv; -} - -NS_IMETHODIMP -nsDefaultNotification::Resume(nsIURI *aURL, void *aExtraInfo) -{ - nsresult rv = NS_NOTIFY_SUCCEEDED; - NET_ResumeWithAuth((void *) aExtraInfo); - return rv; -} - -/*--------------------------------------------------------------*/ -#if 0 -#include "nsXPComFactory.h" - -/* forward declaration */ -class nsDefaultNotification; - -NS_DEF_FACTORY(DefaultNotification,nsDefaultNotification) - -nsresult NS_NewDefaultNotificationFactory(nsIFactory** aResult) -{ - nsresult rv = NS_OK; - nsIFactory* inst; - - inst = new nsDefaultNotificationFactory; - if (nsnull == inst) { - rv = NS_ERROR_OUT_OF_MEMORY; - } - else { - NS_ADDREF(inst); - } - *aResult = inst; - return rv; -} -#endif -/*--------------------------------------------------------------*/ - - -PRIVATE XP_Bool -_stub_PromptUsernameAndPassword(MWContext *context, - const char *msg, - char **username, - char **password, - void *closure) -{ - nsIBlockingNotificationObserver *helper; - nsIBlockingNotification *caller; - nsConnectionInfo *pConn = nsnull; - URL_Struct *URL_s = context->modular_data; - nsIURI *base = nsnull; - nsresult rv; - - printf ("stub_PromptUsernameAndPassword()\n"); - - /* Access the nsConnectionInfo object off of the URL Struct fe_data */ - if ((nsnull != URL_s) && (nsnull != URL_s->fe_data)) { - pConn = (nsConnectionInfo *)URL_s->fe_data; - } -#if 0 - // create an object that calls Resume() XXX - rv = nsComponentManager::CreateInstance(kProtocolHelperCID, nsnull, kIBlockingNotificationIID, (void**)&caller); - if (NS_FAILED(rv)) { - return FALSE; - } -#else - caller = new nsDefaultNotification; - if ( ! caller ) - return FALSE; -#endif - // build an nsIURI - rv = NS_NewURL(&base, URL_s->address); - if (NS_FAILED(rv)) { - return FALSE; - } - - rv = nsComponentManager::CreateInstance(kProtocolHelperCID, nsnull, kIBlockingNotificationObserverIID, (void**)&helper); - if (NS_SUCCEEDED(rv)) { - rv = helper->Notify(caller, base, pConn->mRequestingThread, 0, closure); - NS_RELEASE(helper); - } else { - return FALSE; - } - *username = nsnull; - *password = nsnull; - - // XXX we can't return TRUE anymore, since the ProtocolHelper is - // is still waiting for the user ... - // return TRUE; - - return FALSE; -} -#else - - -PRIVATE XP_Bool _stub_PromptUsernameAndPassword(MWContext *context, - const char *msg, - char **username, - char **password, - void *closure) -{ - nsINetSupport *ins; - XP_Bool bResult = FALSE; - -#ifndef XP_UNIX - if (nsnull != (ins = getNetSupport(context->modular_data))) { - nsAutoString str(msg); - nsAutoString userStr(*username); - nsAutoString pwdStr(*password); - - if (ins->PromptUserAndPassword(msg, userStr, pwdStr)) { - *username = userStr.ToNewCString(); - *password = pwdStr.ToNewCString(); - bResult = TRUE; - } - NS_RELEASE(ins); - - } - /* No nsINetSupport interface... */ - else -#endif /* !XP_UNIX */ - { - NET_AuthClosure *auth_closure = (NET_AuthClosure *) closure; - char buf[256]; - char *tmp_user = *username; - char *tmp_pass = *password; - - printf("%s\n", msg); - printf("%cUser: ", '\007'); - fgets(buf, sizeof buf, stdin); - if (strlen(buf)) { - tmp_user = PL_strdup(buf); - tmp_user[strlen(tmp_user)-1] = '\0'; - } - - printf("%cPassword: ", '\007'); - fgets(buf, sizeof buf, stdin); - if (strlen(buf)) { - tmp_pass = PL_strdup(buf); - tmp_pass[strlen(tmp_pass)-1] = '\0'; - } - - if (tmp_user) { - bResult = FALSE; /* XXX false because the callback will finalize */ - auth_closure->user = tmp_user; - auth_closure->pass = tmp_pass; - NET_ResumeWithAuth (closure); - } else { - PR_FREEIF(tmp_user); - PR_FREEIF(tmp_pass); - } - } - - return bResult; -} -#endif //0 -PRIVATE -char *_stub_PromptPassword(MWContext *context, - char *msg, - XP_Bool *remember, - XP_Bool is_secure, - void *closure) -{ - nsINetSupport *ins; - char *result = nsnull; - -#ifndef XP_UNIX - if (nsnull != (ins = getNetSupport(context->modular_data))) { - nsAutoString str(msg); - nsAutoString res; - - if (ins->PromptPassword(msg, res)) { - result = res.ToNewCString(); - } - NS_RELEASE(ins); - - } - /* No nsINetSupport interface... */ - else -#endif /* !XP_UNIX */ - { - NET_AuthClosure *auth_closure = (NET_AuthClosure *) closure; - char buf[256]; - - printf("%s\n", msg); - printf("%cPassword: ", '\007'); - fgets(buf, sizeof buf, stdin); - if (PL_strlen(buf)) { - auth_closure->pass = PL_strdup(buf); - auth_closure->pass[strlen(buf)-1] = '\0'; - NET_ResumeWithAuth (closure); - } - } - - return result; -} - -extern "C" char * -stub_PromptPassword(MWContext *context, - char *msg, - XP_Bool *remember, - XP_Bool is_secure, - void * closure) -{ - return _stub_PromptPassword(context, msg, remember, - is_secure, closure); -} - -extern "C" XP_Bool -stub_PromptUsernameAndPassword(MWContext *context, - const char *msg, - char **username, - char **password, - void *closure) -{ - return _stub_PromptUsernameAndPassword(context, msg, - username, password, - closure); -} - -PRIVATE void stub_GraphProgressInit(MWContext *context, - URL_Struct *URL_s, - int32 content_length) -{ - nsIStreamListener *pListener; - - if (URL_s->load_background) - return; - - if (nsnull != (pListener = getStreamListener(URL_s))) { - nsConnectionInfo *pConn = (nsConnectionInfo *) URL_s->fe_data; - NS_ASSERTION(content_length >= 0, "negative content_length"); - pListener->OnProgress(pConn->pURL, 0, (PRUint32)content_length); - NS_RELEASE(pListener); - } -} - - -PRIVATE void stub_GraphProgress(MWContext *context, - URL_Struct *URL_s, - int32 bytes_received, - int32 bytes_since_last_time, - int32 content_length) -{ - nsIStreamListener *pListener; - - if (URL_s->load_background) - return; - - if (nsnull != (pListener = getStreamListener(URL_s))) { - nsConnectionInfo *pConn = (nsConnectionInfo *) URL_s->fe_data; - NS_ASSERTION(bytes_received >= 0, "negative bytes_received"); - NS_ASSERTION(content_length >= 0, "negative content_length"); - pListener->OnProgress(pConn->pURL, (PRUint32)bytes_received, - (PRUint32)content_length); - NS_RELEASE(pListener); - } -} - -PRIVATE void stub_GraphProgressDestroy(MWContext *context, - URL_Struct *URL_s, - int32 content_length, - int32 total_bytes_read) -{ - /* - * XXX: Currently this function never calls OnProgress(...) because - * netlib calls FE_GraphProgressDestroy(...) after closing the - * stream... So, OnStopRequest(...) has already been called and - * the nsConnectionInfo->pConsumer has been released and NULLed... - */ - nsIStreamListener *pListener; - - if (URL_s->load_background) - return; - - if (nsnull != (pListener = getStreamListener(URL_s))) { - nsConnectionInfo *pConn = (nsConnectionInfo *) URL_s->fe_data; - NS_ASSERTION(total_bytes_read >= 0, "negative total_bytes_read"); - NS_ASSERTION(content_length >= 0, "negative content_length"); - pListener->OnProgress(pConn->pURL, (PRUint32)total_bytes_read, - (PRUint32)content_length); - // XXX The comment above no longer applies, and this function does - // get called... - NS_RELEASE(pListener); - } -} - -PRIVATE void stub_Progress(MWContext *context, const char *msg) -{ - nsIStreamListener *pListener; - - if (nsnull != (pListener = getStreamListener(context->modular_data))) { - nsConnectionInfo *pConn = - (nsConnectionInfo *) context->modular_data->fe_data; - nsAutoString status(msg); - pListener->OnStatus(pConn->pURL, status.GetUnicode()); - NS_RELEASE(pListener); - } else { - printf("%s\n", msg); - } -} - -PRIVATE void stub_AllConnectionsComplete(MWContext *context) -{ -} - -#define MAKE_FE_TYPES_PREFIX(func) func##_t -#define MAKE_FE_FUNCS_TYPES -#include "mk_cx_fn.h" -#undef MAKE_FE_FUNCS_TYPES - -#define stub_CreateNewDocWindow (CreateNewDocWindow_t)stub_noop -#define stub_LayoutNewDocument (LayoutNewDocument_t)stub_noop -#define stub_SetDocTitle (SetDocTitle_t)stub_noop -#define stub_FinishedLayout (FinishedLayout_t)stub_noop -#define stub_TranslateISOText (TranslateISOText_t)stub_noop -#define stub_GetTextInfo (GetTextInfo_t)stub_noop -#define stub_MeasureText (MeasureText_t)stub_noop -#define stub_GetEmbedSize (GetEmbedSize_t)stub_noop -#define stub_GetJavaAppSize (GetJavaAppSize_t)stub_noop -#define stub_GetFormElementInfo (GetFormElementInfo_t)stub_noop -#define stub_GetFormElementValue (GetFormElementValue_t)stub_noop -#define stub_ResetFormElement (ResetFormElement_t)stub_noop -#define stub_SetFormElementToggle (SetFormElementToggle_t)stub_noop -#define stub_FreeFormElement (FreeFormElement_t)stub_noop -#define stub_FreeImageElement (FreeImageElement_t)stub_noop -#define stub_FreeEmbedElement (FreeEmbedElement_t)stub_noop -#define stub_FreeBuiltinElement (FreeBuiltinElement_t)stub_noop -#define stub_FreeJavaAppElement (FreeJavaAppElement_t)stub_noop -#define stub_CreateEmbedWindow (CreateEmbedWindow_t)stub_noop -#define stub_SaveEmbedWindow (SaveEmbedWindow_t)stub_noop -#define stub_RestoreEmbedWindow (RestoreEmbedWindow_t)stub_noop -#define stub_DestroyEmbedWindow (DestroyEmbedWindow_t)stub_noop -#define stub_HideJavaAppElement (HideJavaAppElement_t)stub_noop -#define stub_FreeEdgeElement (FreeEdgeElement_t)stub_noop -#define stub_FormTextIsSubmit (FormTextIsSubmit_t)stub_noop -#define stub_DisplaySubtext (DisplaySubtext_t)stub_noop -#define stub_DisplayText (DisplayText_t)stub_noop -#define stub_DisplayImage (DisplayImage_t)stub_noop -#define stub_DisplayEmbed (DisplayEmbed_t)stub_noop -#define stub_DisplayBuiltin (DisplayBuiltin_t)stub_noop -#define stub_DisplayJavaApp (DisplayJavaApp_t)stub_noop -#define stub_DisplaySubImage (DisplaySubImage_t)stub_noop -#define stub_DisplayEdge (DisplayEdge_t)stub_noop -#define stub_DisplayTable (DisplayTable_t)stub_noop -#define stub_DisplayCell (DisplayCell_t)stub_noop -#define stub_InvalidateEntireTableOrCell (InvalidateEntireTableOrCell_t)stub_noop -#define stub_DisplayAddRowOrColBorder (DisplayAddRowOrColBorder_t)stub_noop -#define stub_DisplaySubDoc (DisplaySubDoc_t)stub_noop -#define stub_DisplayLineFeed (DisplayLineFeed_t)stub_noop -#define stub_DisplayHR (DisplayHR_t)stub_noop -#define stub_DisplayBullet (DisplayBullet_t)stub_noop -#define stub_DisplayFormElement (DisplayFormElement_t)stub_noop -#define stub_DisplayBorder (DisplayBorder_t)stub_noop -#define stub_UpdateEnableStates (UpdateEnableStates_t)stub_noop -#define stub_DisplayFeedback (DisplayFeedback_t)stub_noop -#define stub_ClearView (ClearView_t)stub_noop -#define stub_SetDocDimension (SetDocDimension_t)stub_noop -#define stub_SetDocPosition (SetDocPosition_t)stub_noop -#define stub_GetDocPosition (GetDocPosition_t)stub_noop -#define stub_BeginPreSection (BeginPreSection_t)stub_noop -#define stub_EndPreSection (EndPreSection_t)stub_noop -#define stub_SetProgressBarPercent (SetProgressBarPercent_t)stub_noop -#define stub_SetBackgroundColor (SetBackgroundColor_t)stub_noop -#define stub_Progress (Progress_t)stub_Progress -#define stub_Alert (Alert_t)stub_Alert -#define stub_SetCallNetlibAllTheTime (SetCallNetlibAllTheTime_t)stub_noop -#define stub_ClearCallNetlibAllTheTime (ClearCallNetlibAllTheTime_t)stub_noop -#define stub_GraphProgressInit (GraphProgressInit_t)stub_GraphProgressInit -#define stub_GraphProgressDestroy (GraphProgressDestroy_t)stub_GraphProgressDestroy -#define stub_GraphProgress (GraphProgress_t)stub_GraphProgress -#define stub_UseFancyFTP (UseFancyFTP_t)stub_noop -#define stub_UseFancyNewsgroupListing (UseFancyNewsgroupListing_t)stub_noop -#define stub_FileSortMethod (FileSortMethod_t)stub_noop -#define stub_ShowAllNewsArticles (ShowAllNewsArticles_t)stub_noop -#define stub_Confirm (Confirm_t)stub_Confirm -#define stub_CheckConfirm (CheckConfirm_t)stub_noop -#define stub_SelectDialog (SelectDialog_t)stub_noop -#define stub_Prompt (Prompt_t)stub_Prompt -#define stub_PromptWithCaption (PromptWithCaption_t)stub_noop -#define stub_PromptUsernameAndPassword (PromptUsernameAndPassword_t)stub_PromptUsernameAndPassword -#define stub_PromptPassword (PromptPassword_t)stub_PromptPassword -#define stub_EnableClicking (EnableClicking_t)stub_noop -#define stub_AllConnectionsComplete (AllConnectionsComplete_t)stub_AllConnectionsComplete -#define stub_ImageSize (ImageSize_t)stub_noop -#define stub_ImageData (ImageData_t)stub_noop -#define stub_ImageIcon (ImageIcon_t)stub_noop -#define stub_ImageOnScreen (ImageOnScreen_t)stub_noop -#define stub_SetColormap (SetColormap_t)stub_noop -#ifdef LAYERS -#define stub_EraseBackground (EraseBackground_t)stub_noop -#define stub_SetDrawable (SetDrawable_t)stub_noop -#define stub_GetTextFrame (GetTextFrame_t)stub_noop -#define stub_SetClipRegion (SetClipRegion_t)stub_noop -#define stub_SetOrigin (SetOrigin_t)stub_noop -#define stub_GetOrigin (GetOrigin_t)stub_noop -#define stub_GetTextFrame (GetTextFrame_t)stub_noop -#endif - -#define stub_GetDefaultBackgroundColor (GetDefaultBackgroundColor_t)stub_noop -#define stub_LoadFontResource (LoadFontResource_t)stub_noop - -#define stub_DrawJavaApp (DrawJavaApp_t)stub_noop -#define stub_HandleClippingView (HandleClippingView_t)stub_noop - -/* Just reuse the same set of context functions: */ -ContextFuncs stub_context_funcs; - -XP_List *stub_context_list = NULL; - -MWContext *new_stub_context(URL_Struct *URL_s) -{ - static int funcsInitialized = 0; - MWContext *context; - - if (!funcsInitialized) { -#define MAKE_FE_FUNCS_PREFIX(f) stub_##f -#define MAKE_FE_FUNCS_ASSIGN stub_context_funcs. -#include "mk_cx_fn.h" - - funcsInitialized = 1; - - stub_context_list = XP_ListNew(); - } - - context = (MWContext *)calloc(sizeof(struct MWContext_), 1); - - if (nsnull != context) { - context->funcs = &stub_context_funcs; - context->type = MWContextBrowser; - context->modular_data = URL_s; - context->ref_count = 0; - - if (nsnull != stub_context_list) { - XP_ListAddObjectToEnd(stub_context_list, context); - } - } - - return context; -} - -void free_stub_context(MWContext *window_id) -{ - TRACEMSG(("Freeing stub context...\n")); - - if (window_id) { - if (stub_context_list) { - PRBool result; - - result = XP_ListRemoveObject(stub_context_list, window_id); - PR_ASSERT(PR_TRUE == result); - } - free(window_id); - } -} - - -extern "C" MWContext * XP_FindContextOfType (MWContext * context, - MWContextType type) -{ - MWContext *window_id = 0; - - /* - * Return the context that was passed in if it is the correct type - */ - if (nsnull != context) { - if (context->type == type) { - window_id = context; - } - } - /* - * Otherwise, the type MUST be a MWBrowserContext, since that is the - * only type of context that is created... - * - * Return the first stub context, since it is as good as any... :-) - */ - else if (MWContextBrowser == type) { - window_id = (MWContext *)XP_ListTopObject(stub_context_list); - } - - return window_id; -} - - -/****************************************************************************/ -/* End of MWContext Evil!!! */ -/****************************************************************************/ - -PRIVATE -nsConnectionInfo *GetConnectionInfoFromStream(NET_StreamClass *stream) -{ - URL_Struct *URL_s = (URL_Struct *)stream->data_object; - - return (URL_s) ? (nsConnectionInfo *)URL_s->fe_data : NULL; -} - - -/* - * Define a NET_StreamClass which pushes its data into an nsIStream - * and fires off notifications through the nsIStreamListener interface - */ - -PRIVATE -void stub_complete(NET_StreamClass *stream) -{ - URL_Struct *URL_s = (URL_Struct *)stream->data_object; - nsConnectionInfo *pConn = GetConnectionInfoFromStream(stream); - - TRACEMSG(("+++ stream complete.\n")); - - /* Close the stream and remove it from the ConnectionInfo... */ - pConn->pNetStream->Close(); - NS_RELEASE(pConn->pNetStream); - - - /* Notify the Data Consumer that the Binding has completed... */ - if (pConn->pConsumer) { - nsAutoString status; - pConn->pConsumer->OnStopRequest(pConn->pURL, NS_BINDING_SUCCEEDED, status.GetUnicode()); - pConn->mStatus = nsConnectionSucceeded; - } - - /* Release the URL_Struct hanging off of the data_object */ - stream->data_object = NULL; - NET_DropURLStruct(URL_s); -} - -PRIVATE -void stub_abort(NET_StreamClass *stream, int status) -{ - URL_Struct *URL_s = (URL_Struct *)stream->data_object; - nsConnectionInfo *pConn = GetConnectionInfoFromStream(stream); - - TRACEMSG(("+++ stream abort. Status = %d\n", status)); - - NS_ASSERTION(pConn, "pConn == nsnull"); - if (!pConn) { - return; - } - - NS_ASSERTION(pConn->pNetStream, "pConn->pNetStream == nsnull"); - if (!pConn->pNetStream) { - return; - } - - /* Close the stream and remove it from the ConnectionInfo... */ - pConn->pNetStream->Close(); - NS_RELEASE(pConn->pNetStream); - - /* Notify the Data Consumer that the Binding has completed... */ - /* - * XXX: Currently, there is no difference between complete and - * abort... - */ - if (pConn->pConsumer) { - nsAutoString status; - - // mscott --> this code used to pass in NS_BINDING_ABORTED into the OnStopRequest - // call. But NS_BINDING_ABORTED is an error code!!! And aborting a stream - // is NOT an error condition. nsDocumentLoader::OnStopRequest was issuing - // printfs complaining that the status code was a failure code. - // I'm going to pass in NS_BINDING_SUCCEEDED instead. - pConn->pConsumer->OnStopRequest(pConn->pURL, NS_BINDING_SUCCEEDED, status.GetUnicode()); - pConn->mStatus = nsConnectionAborted; - } - - /* Release the URL_Struct hanging off of the data_object */ - stream->data_object = NULL; - NET_DropURLStruct(URL_s); -} - -PRIVATE -int stub_put_block(NET_StreamClass *stream, const char *buffer, int32 length) -{ - PRUint32 bytesWritten; - nsresult errorCode; - nsConnectionInfo *pConn = GetConnectionInfoFromStream(stream); - - TRACEMSG(("+++ stream put_block. Length = %d\n", length)); - - /* - * XXX: Sometimes put_block(...) will be called without having - * called is_write_ready(...) first. One case is when a stream - * is interrupted... In this case, Netlib will call put_block(...) - * with the string "Transfer Interrupted!" - */ - NS_ASSERTION(length >= 0, "negative length"); - errorCode = pConn->pNetStream->Write(buffer, (PRUint32)length, &bytesWritten); - - /* Abort the connection... */ - if (NS_BASE_STREAM_EOF == errorCode) { - return -1; - } - - if (pConn->pConsumer && (0 < bytesWritten)) { - errorCode = pConn->pConsumer->OnDataAvailable(pConn->pURL, pConn->pNetStream, bytesWritten); - } - - /* Abort the connection if an error occurred... */ - NS_ASSERTION(bytesWritten >= 0, "negative bytesWritten"); - if (NS_FAILED(errorCode) || ((int32)bytesWritten != length)) { - return -1; - } - return 1; -} - -PRIVATE -unsigned int stub_is_write_ready(NET_StreamClass *stream) -{ - nsresult errorCode; - PRUint32 free_space = 0; - /* URL_Struct *URL_s = (URL_Struct *)stream->data_object; */ - nsConnectionInfo *pConn = GetConnectionInfoFromStream(stream); - - errorCode = pConn->pNetStream->GetAvailableSpace(&free_space); - - /* - * If the InputStream has been closed... Return 1 byte available so - * Netlib will call put_block(...) one more time... - */ - if (NS_BASE_STREAM_EOF == errorCode) { - free_space = 1; - } - - TRACEMSG(("+++ stream is_write_ready. Returning %d\n", free_space)); - return (int)free_space; -} - - -extern "C" { - -PUBLIC NET_StreamClass * -NET_NGLayoutConverter(FO_Present_Types format_out, - void *converter_obj, - URL_Struct *URL_s, - MWContext *context); - -/* - *Find a converter routine to create a stream and return the stream struct - */ -PUBLIC NET_StreamClass * -NET_NGLayoutConverter(FO_Present_Types format_out, - void *converter_obj, - URL_Struct *URL_s, - MWContext *context) -{ - NET_StreamClass *stream = NULL; - - /* - * Only create a stream if an nsConnectionInfo object is - * available from the fe_data... - */ - if (NULL != URL_s->fe_data) { - stream = (NET_StreamClass *)calloc(sizeof(NET_StreamClass), 1); - - if (NULL != stream) { - nsConnectionInfo *pConn; - - /* - * Initialize the NET_StreamClass instance... - */ - stream->name = "Stub Stream"; - stream->window_id = context; - - stream->complete = stub_complete; - stream->abort = stub_abort; - stream->put_block = stub_put_block; - stream->is_write_ready = stub_is_write_ready; - - /* - * Retrieve the nsConnectionInfo object from the fe_data field - * of the URL_Struct... - */ - pConn = (nsConnectionInfo *)URL_s->fe_data; - - /* Mark the connection as active... */ - pConn->mStatus = nsConnectionActive; - - /* - * If the URL address has been rewritten by netlib then update - * the cached info in the URL object... - */ - if ((URL_s->address_modified) && (NULL != pConn->pURL)) { - pConn->pURL->SetSpec(URL_s->address); - } - - /* - * Create an Async stream unless a blocking stream is already - * available in the ConnectionInfo... - */ - if (NULL == pConn->pNetStream) { - pConn->pNetStream = new nsAsyncStream(8192); - if (NULL == pConn->pNetStream) { - free(stream); - return NULL; - } - NS_ADDREF(pConn->pNetStream); - } - - /* Hang the URL_Struct off of the NET_StreamClass */ - NET_HoldURLStruct(URL_s); - stream->data_object = URL_s; - -#ifdef NOISY - printf("+++ Created a stream for %s\n", URL_s->address); -#endif - /* Notify the data consumer that Binding is beginning...*/ - if (nsnull != pConn->pConsumer) { - nsresult rv; - - rv = pConn->pConsumer->OnStartRequest(pConn->pURL, URL_s->content_type); - /* - * If OnStartRequest fails, then tear down the NET_StreamClass - * and release all references... - */ - if (NS_OK != rv) { - NET_DropURLStruct(URL_s); - free(stream); - stream = NULL; - - /* - * The NET_GetURL(...) exit_routine will clean up the - * nsConnectionInfo and associated objects. - */ - } - } - } - } - - return stream; -} - -} /* extern "C" */ diff --git a/mozilla/network/module/nsStubContext.h b/mozilla/network/module/nsStubContext.h deleted file mode 100644 index 4b24c401d6d..00000000000 --- a/mozilla/network/module/nsStubContext.h +++ /dev/null @@ -1,4 +0,0 @@ -#include "ntypes.h" - -MWContext *new_stub_context(URL_Struct *URL_s); -void free_stub_context(MWContext *window_id); diff --git a/mozilla/network/module/res/gopher-audio.gif b/mozilla/network/module/res/gopher-audio.gif deleted file mode 100644 index a23232f8f83..00000000000 Binary files a/mozilla/network/module/res/gopher-audio.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-binary.gif b/mozilla/network/module/res/gopher-binary.gif deleted file mode 100644 index ec3bf24ed69..00000000000 Binary files a/mozilla/network/module/res/gopher-binary.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-find.gif b/mozilla/network/module/res/gopher-find.gif deleted file mode 100644 index 31616c06cfc..00000000000 Binary files a/mozilla/network/module/res/gopher-find.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-image.gif b/mozilla/network/module/res/gopher-image.gif deleted file mode 100644 index d6e4b5f747c..00000000000 Binary files a/mozilla/network/module/res/gopher-image.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-menu.gif b/mozilla/network/module/res/gopher-menu.gif deleted file mode 100644 index 0c7dd2f7f7b..00000000000 Binary files a/mozilla/network/module/res/gopher-menu.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-movie.gif b/mozilla/network/module/res/gopher-movie.gif deleted file mode 100644 index bc886584bd9..00000000000 Binary files a/mozilla/network/module/res/gopher-movie.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-telnet.gif b/mozilla/network/module/res/gopher-telnet.gif deleted file mode 100644 index d83cf47dc7b..00000000000 Binary files a/mozilla/network/module/res/gopher-telnet.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-text.gif b/mozilla/network/module/res/gopher-text.gif deleted file mode 100644 index e92632e47ae..00000000000 Binary files a/mozilla/network/module/res/gopher-text.gif and /dev/null differ diff --git a/mozilla/network/module/res/gopher-unknown.gif b/mozilla/network/module/res/gopher-unknown.gif deleted file mode 100644 index 3c07b2f024e..00000000000 Binary files a/mozilla/network/module/res/gopher-unknown.gif and /dev/null differ diff --git a/mozilla/network/module/tests/Makefile.in b/mozilla/network/module/tests/Makefile.in deleted file mode 100644 index 78b4c2f8ae2..00000000000 --- a/mozilla/network/module/tests/Makefile.in +++ /dev/null @@ -1,64 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -PROGRAM = nettest -CPPSRCS = nettest.cpp - -REQUIRES = raptor netlib xpcom pref - -LOCAL_INCLUDES = -I$(srcdir)/../src - -LIBS = \ - -lnetlib \ - -labouturl \ - -lfileurl \ - -lremoturl \ - -lgophurl \ - -lnetcnvts \ - -lsockstuburl \ - -lftpurl \ - -lmimetype \ - -lpwcac \ - -lhttpurl \ - -lnetwork \ - -lnetcache \ - -lpref \ - -lsecfree \ - -lmozjs \ - -limg \ - -lmozutil \ - -lxp \ - -lxpcom \ - $(MOZ_TIMER_LIBS) \ - $(TK_LIBS) \ - $(ZLIB_LIBS) \ - $(NSPR_LIBS) \ - $(NULL) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/module/tests/makefile.win b/mozilla/network/module/tests/makefile.win deleted file mode 100644 index 99bdb691e79..00000000000 --- a/mozilla/network/module/tests/makefile.win +++ /dev/null @@ -1,100 +0,0 @@ -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -IGNORE_MANIFEST = 1 - -#//------------------------------------------------------------------------ -#// -# New build system where zip dll is build indepenant of java stubs. -#// -#//------------------------------------------------------------------------ -MODULE = nettest -#EXPORTS = \ -# $(NULL) - - -#//------------------------------------------------------------------------ -#// -#// Specify the depth of the current directory relative to the -#// root of NS -#// -#//------------------------------------------------------------------------ -DEPTH= ..\..\.. - -MAKE_OBJ_TYPE=EXE -#//------------------------------------------------------------------------ -#// -#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...) -#// -#//------------------------------------------------------------------------ -EXENAME=nettest -PDBFILE=nettest.pdb -MAPFILE=nettest.map - -#//------------------------------------------------------------------------ -#// -#// Define the files necessary to build the target (ie. OBJS) -#// -#//------------------------------------------------------------------------ -OBJS= \ - .\$(OBJDIR)\nettest.obj \ - $(NULL) -#//------------------------------------------------------------------------ -#// -#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...) -#// (these must be defined before the common makefiles are included) -#// -#//------------------------------------------------------------------------ - -PROGRAM=.\$(OBJDIR)\$(EXENAME).EXE - - -#//------------------------------------------------------------------------ -#// -#// Define any local options for the make tools -#// (ie. LCFLAGS, LLFLAGS, LLIBS, LINCS) -#// -#//------------------------------------------------------------------------ -LCFLAGS=-DNETSCAPE -LLIBS=$(LLIBS) \ - $(LIBNSPR) \ - $(DIST)\lib\xpcom.lib \ - $(DIST)\lib\netlib.lib - -LINCS=$(LINCS) -I. \ - -I$(PUBLIC)\raptor \ - -I$(PUBLIC)\netlib \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\xpcom - -# clobber and clobber_all will remove the following garbage: -GARBAGE = $(GARBAGE) _gen - -#//------------------------------------------------------------------------ -#// -#// Include the common makefile rules -#// -#//------------------------------------------------------------------------ -include <$(DEPTH)/config/rules.mak> - -install:: $(PROGRAM) - $(MAKE_INSTALL) $(PROGRAM) $(DIST)\bin - -clobber:: - rm -f $(DIST)\bin\$(EXENAME).exe diff --git a/mozilla/network/module/tests/nettest.cpp b/mozilla/network/module/tests/nettest.cpp deleted file mode 100644 index e19d6cf3ebf..00000000000 --- a/mozilla/network/module/tests/nettest.cpp +++ /dev/null @@ -1,338 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include <stdio.h> -#include <assert.h> - -#ifdef XP_PC -#include <windows.h> -#endif - -#include "plstr.h" -#include "plevent.h" - -#include "nsIStreamListener.h" -#include "nsIInputStream.h" -#include "nsIURL.h" -#include "nsINetService.h" -#include "nsIComponentManager.h" -#include "nsIServiceManager.h" -#include "nsIEventQueueService.h" -#include "nsString.h" - - -int urlLoaded; -PRBool bTraceEnabled; -PRBool bLoadAsync; - -#include "nsIPostToServer.h" -#include "nsINetService.h" - -#ifdef XP_PC -#define NETLIB_DLL "netlib.dll" -#define XPCOM_DLL "xpcom32.dll" -#else -#ifdef XP_MAC -#include "nsMacRepository.h" -#else -#define NETLIB_DLL "libnetlib"MOZ_DLL_SUFFIX -#define XPCOM_DLL "libxpcom"MOZ_DLL_SUFFIX -#endif -#endif - -// Define CIDs... -static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID); -static NS_DEFINE_IID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID); - -// Define IIDs... -static NS_DEFINE_IID(kIEventQueueServiceIID, NS_IEVENTQUEUESERVICE_IID); -NS_DEFINE_IID(kIPostToServerIID, NS_IPOSTTOSERVER_IID); - - -/* XXX: Don't include net.h... */ -extern "C" { -extern void NET_ToggleTrace(); -}; - -class TestConsumer : public nsIStreamListener -{ - -public: - NS_DECL_ISUPPORTS - - TestConsumer(); - virtual ~TestConsumer(); - - NS_IMETHOD GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* info); - NS_IMETHOD OnProgress(nsIURI* aURL, PRUint32 Progress, PRUint32 ProgressMax); - NS_IMETHOD OnStatus(nsIURI* aURL, const PRUnichar* aMsg); - NS_IMETHOD OnStartRequest(nsIURI* aURL, const char *aContentType); - NS_IMETHOD OnDataAvailable(nsIURI* aURL, nsIInputStream *pIStream, PRUint32 length); - NS_IMETHOD OnStopRequest(nsIURI* aURL, nsresult status, const PRUnichar* aMsg); -}; - - -TestConsumer::TestConsumer() -{ - NS_INIT_REFCNT(); -} - - -NS_DEFINE_IID(kIStreamListenerIID, NS_ISTREAMLISTENER_IID); -NS_IMPL_ISUPPORTS(TestConsumer,kIStreamListenerIID); - - -TestConsumer::~TestConsumer() -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer is being deleted...\n"); - } -} - - -NS_IMETHODIMP TestConsumer::GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* info) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::GetBindInfo: URL: %p\n", aURL); - } - - return 0; -} - -NS_IMETHODIMP TestConsumer::OnProgress(nsIURI* aURL, PRUint32 Progress, - PRUint32 ProgressMax) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnProgress: URL: %p - %d of total %d\n", aURL, Progress, ProgressMax); - } - - return 0; -} - -NS_IMETHODIMP TestConsumer::OnStatus(nsIURI* aURL, const PRUnichar* aMsg) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnStatus: "); - nsAutoString str(aMsg); - char* c = str.ToNewCString(); - fputs(c, stdout); - delete[] c; - fputs("\n", stdout); - } - - return 0; -} - -NS_IMETHODIMP TestConsumer::OnStartRequest(nsIURI* aURL, const char *aContentType) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnStartRequest: URL: %p, Content type: %s\n", aURL, aContentType); - } - - return 0; -} - - -NS_IMETHODIMP TestConsumer::OnDataAvailable(nsIURI* aURL, nsIInputStream *pIStream, PRUint32 length) -{ - PRUint32 len; - - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnDataAvailable: URL: %p, %d bytes available...\n", aURL, length); - } - - do { - nsresult err; - char buffer[80]; - PRUint32 i; - - err = pIStream->Read(buffer, 80, &len); - if (err == NS_OK) { - for (i=0; i<len; i++) { - putchar(buffer[i]); - } - } - } while (len > 0); - - return 0; -} - - -NS_IMETHODIMP TestConsumer::OnStopRequest(nsIURI* aURL, nsresult status, const PRUnichar* aMsg) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnStopRequest... URL: %p status: %d\n", aURL, status); - } - - if (NS_FAILED(status)) { - const char* url; - aURL->GetSpec(&url); - - printf("Unable to load URL %s\n", url); - } - /* The document has been loaded, so drop out of the message pump... */ - urlLoaded = 1; - return 0; -} - - -nsresult ReadStreamSynchronously(nsIInputStream* aIn) -{ - nsresult rv; - char buffer[1024]; - - if (nsnull != aIn) { - PRUint32 len; - - do { - PRUint32 i; - - rv = aIn->Read(buffer, sizeof(buffer), &len); - for (i=0; i<len; i++) { - putchar(buffer[i]); - } - } while (len > 0); - } - return NS_OK; -} - - - -int main(int argc, char **argv) -{ - nsAutoString url_address; - char buf[256]; - nsIStreamListener *pConsumer; - nsIEventQueueService* pEventQService; - nsIURI *pURL; - nsresult result; - int i; - - if (argc < 2) { - printf("test: [-trace] [-sync] <URL>\n"); - return 0; - } - - nsComponentManager::RegisterComponent(kEventQueueServiceCID, NULL, NULL, XPCOM_DLL, PR_FALSE, PR_FALSE); - nsComponentManager::RegisterComponent(kNetServiceCID, NULL, NULL, NETLIB_DLL, PR_FALSE, PR_FALSE); - - // Create the Event Queue for this thread... - pEventQService = nsnull; - result = nsServiceManager::GetService(kEventQueueServiceCID, - kIEventQueueServiceIID, - (nsISupports **)&pEventQService); - if (NS_SUCCEEDED(result)) { - // XXX: What if this fails? - result = pEventQService->CreateThreadEventQueue(); - } - - bTraceEnabled = PR_FALSE; - bLoadAsync = PR_TRUE; - - for (i=1; i < argc; i++) { - // Turn on netlib tracing... - if (PL_strcasecmp(argv[i], "-trace") == 0) { - NET_ToggleTrace(); - bTraceEnabled = PR_TRUE; - continue; - } - // Turn on synchronous URL loading... - if (PL_strcasecmp(argv[i], "-sync") == 0) { - bLoadAsync = PR_FALSE; - continue; - } - - urlLoaded = 0; - - url_address = argv[i]; - if (bTraceEnabled) { - url_address.ToCString(buf, 256); - printf("+++ loading URL: %s...\n", buf); - } - - pConsumer = new TestConsumer; - pConsumer->AddRef(); - - // Create the URL object... - pURL = NULL; - result = NS_NewURL(&pURL, url_address); - if (NS_OK != result) { - if (bTraceEnabled) { - printf("NS_NewURL() failed...\n"); - } - return 1; - } - -#if 0 - nsIPostToServer *pPoster; - result = pURL->QueryInterface(kIPostToServerIID, (void**)&pPoster); - if (result == NS_OK) { - pPoster->SendFile("foo.txt"); - } - NS_IF_RELEASE(pPoster); -#endif - - // Start the URL load... - if (PR_TRUE == bLoadAsync) { - result = NS_OpenURL(pURL, pConsumer); - - /* If the open failed, then do not drop into the message loop... */ - if (NS_OK != result) { - const char* url; - pURL->GetSpec(&url); - - printf("Unable to load URL %s\n", url); - urlLoaded = 1; - } - } - // Load the URL synchronously... - else { - nsIInputStream *in; - - result = NS_OpenURL(pURL, &in); - ReadStreamSynchronously(in); - NS_IF_RELEASE(in); - urlLoaded = 1; - } - - - // Enter the message pump to allow the URL load to proceed. - while ( !urlLoaded ) { -#ifdef XP_PC - MSG msg; - - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } -#endif - } - - pURL->Release(); - } - - if (nsnull != pEventQService) { - pEventQService->DestroyThreadEventQueue(); - nsServiceManager::ReleaseService(kEventQueueServiceCID, pEventQService); - } - return 0; -} diff --git a/mozilla/network/module/tests/transportTest.cpp b/mozilla/network/module/tests/transportTest.cpp deleted file mode 100644 index 8a226bf5974..00000000000 --- a/mozilla/network/module/tests/transportTest.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -/*============================================================================= - * This test program is designed to test netlib's implementation of nsITransport. - * In particular, it is currently geared towards testing their socket implemnation. - * When the test program starts up, you are prompted for a port and domain - * (I may have these hard coded right now to be nsmail-2 and port 143). - * After entering this information, we'll build a connection to the host name. - * You can then enter raw protocol text (i.e. "1 capability") and watch the data - * that comes back from the socket. After data is returned, you can enter another - * line of protocol. -*===============================================================================*/ - -#include <stdio.h> -#include <assert.h> - -#ifdef XP_PC -#include <windows.h> -#endif - -#include "plstr.h" -#include "plevent.h" - -#include "nsIStreamListener.h" -#include "nsIInputStream.h" -#include "nsITransport.h" -#include "nsIURL.h" -#include "nsINetService.h" -#include "nsIComponentManager.h" -#include "nsString.h" - - -int urlLoaded; -PRBool bTraceEnabled; -PRBool bLoadAsync; - -#include "nsIPostToServer.h" -#include "nsINetService.h" -#include "nsIServiceManager.h" -#include "nsIEventQueueService.h" - -#ifdef XP_PC -#define NETLIB_DLL "netlib.dll" -#define XPCOM_DLL "xpcom32.dll" -#else -#ifdef XP_MAC -#include "nsMacRepository.h" -#else -#define NETLIB_DLL "libnetlib"MOZ_DLL_SUFFIX -#endif -#endif - -static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID); -static NS_DEFINE_IID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID); - -static NS_DEFINE_IID(kIInputStreamIID, NS_IINPUTSTREAM_IID); - -static NS_DEFINE_IID(kIPostToServerIID, NS_IPOSTTOSERVER_IID); -static NS_DEFINE_IID(kIEventQueueServiceIID, NS_IEVENTQUEUESERVICE_IID); - -/* XXX: Don't include net.h... */ -extern "C" { -extern void NET_ToggleTrace(); -}; - -class TestConsumer : public nsIStreamListener -{ - -public: - NS_DECL_ISUPPORTS - - PRBool m_runningURL; - PRBool m_waitingForData; - - TestConsumer(nsITransport * transport); - - void LoadURL(nsIURI * urlToLoad); - nsresult Write(const char * writeData); - - NS_IMETHOD GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* info); - NS_IMETHOD OnProgress(nsIURI* aURL, PRUint32 Progress, PRUint32 ProgressMax); - NS_IMETHOD OnStatus(nsIURI* aURL, const PRUnichar* aMsg); - NS_IMETHOD OnStartRequest(nsIURI* aURL, const char *aContentType); - NS_IMETHOD OnDataAvailable(nsIURI* aURL, nsIInputStream *pIStream, PRUint32 length); - NS_IMETHOD OnStopRequest(nsIURI* aURL, nsresult status, const PRUnichar* aMsg); - -protected: - ~TestConsumer(); - - nsITransport * m_transport; - nsIURI * m_url; - nsIOutputStream * m_outputStream; - nsIStreamListener * m_outputConsumer; -}; - - -TestConsumer::TestConsumer(nsITransport * transport) -{ - NS_PRECONDITION(transport != nsnull, "invalid transport"); - - NS_INIT_REFCNT(); - if (transport) - { - m_transport = transport; - NS_ADDREF(m_transport); - - // register ourselves as a stream listener for the transport interface - m_transport->SetInputStreamConsumer(this); - m_transport->GetOutputStreamConsumer(&m_outputConsumer); - m_transport->GetOutputStream(&m_outputStream); - } - else - { - m_outputStream = NULL; - m_outputConsumer = NULL; - } - - m_url = NULL; -} - -void TestConsumer::LoadURL(nsIURI * urlToLoad) -{ - // give the transport layer the url to load - m_transport->Open(urlToLoad); - m_runningURL = PR_TRUE; - m_waitingForData = PR_TRUE; - - if (m_url) - { - NS_RELEASE(m_url); - m_url = NULL; - } - - m_url = urlToLoad; - NS_ADDREF(urlToLoad); -} - - -NS_DEFINE_IID(kIStreamListenerIID, NS_ISTREAMLISTENER_IID); -NS_IMPL_ISUPPORTS(TestConsumer,kIStreamListenerIID); - - -TestConsumer::~TestConsumer() -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer is being deleted...\n"); - } - - if (m_url) - NS_RELEASE(m_url); -} - -nsresult TestConsumer::Write(const char * writeData) -{ - PRUint32 numBytes = 0; - nsresult rv = NS_OK; - - // write the data out through our output stream. - NS_PRECONDITION(m_outputStream && m_outputConsumer, "transport not configured for output"); - if (writeData && *writeData) - { - rv = m_outputStream->Write(writeData, PL_strlen(writeData), &numBytes); - if (NS_SUCCEEDED(rv)) - { - nsIInputStream * inputStream = NULL; - rv = m_outputStream->QueryInterface(kIInputStreamIID, (void **) &inputStream); - if (inputStream && NS_SUCCEEDED(rv)) - { - rv = m_outputConsumer->OnDataAvailable(m_url, inputStream, PL_strlen(writeData)); - m_waitingForData = PR_TRUE; - NS_RELEASE(inputStream); - } - } - } - - return rv; -} - -NS_IMETHODIMP TestConsumer::GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* info) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::GetBindInfo: URL: %p\n", aURL); - } - - return 0; -} - -NS_IMETHODIMP TestConsumer::OnProgress(nsIURI* aURL, PRUint32 Progress, - PRUint32 ProgressMax) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnProgress: URL: %p - %d of total %d\n", aURL, Progress, ProgressMax); - } - - return 0; -} - -NS_IMETHODIMP TestConsumer::OnStatus(nsIURI* aURL, const PRUnichar* aMsg) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnStatus: "); - nsString str(aMsg); - char* c = str.ToNewCString(); - fputs(c, stdout); - delete[] c; - fputs("\n", stdout); - } - - return 0; -} - -NS_IMETHODIMP TestConsumer::OnStartRequest(nsIURI* aURL, const char *aContentType) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnStartRequest: URL: %p, Content type: %s\n", aURL, aContentType); - } - - return 0; -} - - -NS_IMETHODIMP TestConsumer::OnDataAvailable(nsIURI* aURL, nsIInputStream *pIStream, PRUint32 length) -{ - PRUint32 totalBytesRead, len = 0; - - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnDataAvailable: URL: %p, %d bytes available...\n", aURL, length); - } - - do { - - nsresult err; - char buffer[1000]; - PRUint32 i; - - PRUint32 numToRead = length > 1000 ? 1000 : length; - err = pIStream->Read(buffer, numToRead, &len); - totalBytesRead += len; - if (err == NS_OK) { - for (i=0; i<len; i++) { - putchar(buffer[i]); - } - } - } while (totalBytesRead < length && (len > 0) ); - - m_waitingForData = PR_FALSE; - - return 0; -} - - -NS_IMETHODIMP TestConsumer::OnStopRequest(nsIURI* aURL, nsresult status, const PRUnichar* aMsg) -{ - if (bTraceEnabled) { - printf("\n+++ TestConsumer::OnStopRequest... URL: %p status: %d\n", aURL, status); - } - - /* The document has been loaded, so drop out of the message pump... */ - urlLoaded = 1; - - m_runningURL = PR_FALSE; - return 0; -} - - -nsresult ReadStreamSynchronously(nsIInputStream* aIn) -{ - nsresult rv; - char buffer[1024]; - - if (nsnull != aIn) { - PRUint32 len; - - do { - PRUint32 i; - - rv = aIn->Read(buffer, sizeof(buffer), &len); - for (i=0; i<len; i++) { - putchar(buffer[i]); - } - } while (len > 0); - } - return NS_OK; -} - - - -int main() -{ - char buf[256]; - nsIStreamListener *pConsumer; - nsINetService * pNetService; - nsresult result; - int i; - - nsComponentManager::RegisterComponent(kNetServiceCID, NULL, NULL, NETLIB_DLL, PR_FALSE, PR_FALSE); - nsComponentManager::RegisterComponent(kEventQueueServiceCID, NULL, NULL, XPCOM_DLL, PR_FALSE, PR_FALSE); - - // Create the Event Queue for this thread... - nsIEventQueueService *pEventQService = nsnull; - result = nsServiceManager::GetService(kEventQueueServiceCID, - kIEventQueueServiceIID, - (nsISupports **)&pEventQService); - if (NS_SUCCEEDED(result)) { - // XXX: What if this fails? - result = pEventQService->CreateThreadEventQueue(); - } - - bTraceEnabled = PR_FALSE; - bLoadAsync = PR_TRUE; - - NET_ToggleTrace(); - bTraceEnabled = PR_TRUE; - - // ask the net lib service for a nsINetStream: - result = NS_NewINetService(&pNetService, NULL); - if (NS_FAILED(result) || !pNetService) - { - printf("unable to initialize net serivce. \n"); - return 1; - } - - // Create the URL object... - nsIURI * pURL = NULL; - - // prompt the user for port and host name - PRUint32 portToUse = 143; // default to imap... - char hostName[100]; - char urlToRun[200]; - char portString[100]; - portString[0] = '\0'; - hostName[0] = '\0'; - urlToRun[0] = '\0'; - - PL_strncpy(hostName, "nsmail-2.mcom.com", 100); - PL_strncpy(urlToRun, "sockstub://", 200); - - printf("Enter port to use [%d]: ", portToUse); - scanf("%[^\n]", portString); - if (portString && *portString) - { - PRUint32 temp = atoi(portString); - if (temp > 0) - portToUse = temp; - } - scanf("%c", portString); // eat the extra CR - - // now prompt for the host name.... - printf("Enter host name to use [%s]: ", hostName); - scanf("%[^\n]", &hostName); - PL_strcat(urlToRun, hostName); - scanf("%c", portString); // eat the extra CR - - result = NS_NewURL(&pURL, urlToRun); - - // create a transport socket... - nsITransport * transport = NULL; - pNetService->CreateSocketTransport(&transport, portToUse, "nsmail-2.mcom.com"); - - if (transport) - { - TestConsumer * pTestConsumer = NULL; - - pTestConsumer = new TestConsumer(transport); - NS_ADDREF(pTestConsumer); - if (pTestConsumer) - { - pTestConsumer->LoadURL(pURL); - char userText[1000]; - while (pTestConsumer->m_runningURL) - { - // if we are waiting for data don't read the next command - if (!pTestConsumer->m_waitingForData) - { - userText[0] = '\0'; - scanf("%[^\n]", &userText); - if (*userText) - { - if (userText[0]) // append a line return - { - PRUint32 length = PL_strlen(userText); - userText[length] = '\n'; - userText[length+1] = '\0'; - } - if (PL_strncasecmp("exit", userText, 4) == 0) - pTestConsumer->m_runningURL = 0; - else - pTestConsumer->Write(userText); - } - else - scanf("%c", userText); - } - - MSG msg; - - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - - - } - - NS_RELEASE(pTestConsumer); - } - - NS_RELEASE(transport); - } - - // shut down: - NS_RELEASE(pNetService); - - return 0; -} diff --git a/mozilla/network/protocol/Makefile.in b/mozilla/network/protocol/Makefile.in deleted file mode 100644 index bc9cbf35018..00000000000 --- a/mozilla/network/protocol/Makefile.in +++ /dev/null @@ -1,50 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -DIRS = about file ftp gopher remote sockstub - -ifdef MOZ_LDAP -DIRS += ldap -endif - -ifdef SMART_MAIL -DIRS += pop3 -endif - -ifdef OLD_MOZ_MAIL_NEWS -DIRS += mailbox smtp pop3 imap4 certld -else -ifdef MOZ_MAIL_COMPOSE -DIRS += smtp -endif -endif - -DIRS += http - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/protocol/about/MANIFEST b/mozilla/network/protocol/about/MANIFEST deleted file mode 100644 index 886cf1cdd57..00000000000 --- a/mozilla/network/protocol/about/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -abouturl.h diff --git a/mozilla/network/protocol/about/Makefile.in b/mozilla/network/protocol/about/Makefile.in deleted file mode 100644 index 6df93d496d3..00000000000 --- a/mozilla/network/protocol/about/Makefile.in +++ /dev/null @@ -1,39 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = abouturl -LIBRARY_NAME = abouturl - -CSRCS = mkabout.c - -EXPORTS = $(srcdir)/abouturl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/about/abouturl.h b/mozilla/network/protocol/about/abouturl.h deleted file mode 100644 index 5a86c361c33..00000000000 --- a/mozilla/network/protocol/about/abouturl.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef ABOUTURL_H -#define ABOUTURL_H - -PUBLIC void NET_InitAboutProtocol(void); - -/* - * About protocol registration stuff - */ - -/* Callback for registered about protocols. - * Should return PR_TRUE if the token was handled */ -typedef PRBool (*NET_AboutCB)(const char *token, - FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *window_id); - -/* Wildcard token for FE about protocol handling - * Otherwise unhandled tokens will match on this */ -#define FE_ABOUT_TOKEN ("FEABOUT") - -/* About protocol registration function. - * Returns PR_TRUE if registration succeeds. - * Registration will fail if token or callback is null, - * or token has already been registered */ -PUBLIC PRBool NET_RegisterAboutProtocol(const char *token, - NET_AboutCB callback); - - -#endif /* ABOUTURL_H */ diff --git a/mozilla/network/protocol/about/makefile.win b/mozilla/network/protocol/about/makefile.win deleted file mode 100644 index 61db195a8d8..00000000000 --- a/mozilla/network/protocol/about/makefile.win +++ /dev/null @@ -1,87 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkabout.obj \ - $(NULL) - - -CSRCS = \ - mkabout.c \ - $(NULL) - - -LIBRARY_NAME=abouturl -MODULE=abouturl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= abouturl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\netcache \ - -I$(XPDIST)\public\httpurl \ - -I$(XPDIST)\public\jtools \ - -I$(XPDIST)\public\network -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/about/mkabout.c b/mozilla/network/protocol/about/mkabout.c deleted file mode 100644 index 66a42ecc427..00000000000 --- a/mozilla/network/protocol/about/mkabout.c +++ /dev/null @@ -1,950 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "rosetta.h" -#include "xp.h" -#include "net.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "netcache.h" -#include "xpgetstr.h" -#include "xplocale.h" -#include "prefapi.h" -#include "secnav.h" -#include "il_strm.h" -#include "cookies.h" -#include "httpauth.h" -#include "mkstream.h" -#include "glhist.h" -#include "shist.h" -#include "prmem.h" -#include "plstr.h" -#include "plhash.h" - -#include "abouturl.h" - -/* XXX ugh. FE_GetNetDir returns XP_STRDUP'd result, must be XP_FREE'd */ -#include "xp_mem.h" - -extern int XP_NETSITE_ ; -extern int XP_LOCATION_ ; -extern int XP_FILE_MIME_TYPE_ ; -extern int XP_CURRENTLY_UNKNOWN; -extern int XP_SOURCE_ ; -extern int XP_CURRENTLY_IN_DISK_CACHE ; -extern int XP_CURRENTLY_IN_MEM_CACHE; -extern int XP_CURRENTLY_NO_CACHE ; -extern int XP_LOCAL_CACHE_FILE_ ; -extern int XP_NONE ; -extern int XP_LOCAL_TIME_FMT ; -extern int XP_LAST_MODIFIED ; -extern int XP_GMT_TIME_FMT ; -extern int XP_CONTENT_LENGTH_ ; -extern int XP_NO_DATE_GIVEN; -extern int XP_EXPIRES_ ; -extern int XP_MAC_TYPE_ ; -extern int XP_MAC_CREATOR_ ; -extern int XP_CHARSET_ ; -extern int XP_STATUS_UNKNOWN ; -extern int XP_MSG_UNKNOWN ; -HG42784 -extern int XP_UNTITLED_DOCUMENT ; -extern int XP_HAS_THE_FOLLOWING_STRUCT ; -extern int XP_DOCUMENT_INFO ; -extern int XP_THE_WINDOW_IS_NOW_INACTIVE ; -extern int MK_MALFORMED_URL_ERROR; - -static PRHashTable *net_AboutTable = NULL; - -PRIVATE PRIntn net_AboutComparator(const void *v1, const void *v2) -{ - char *idx = NULL; - if ((idx = PL_strchr((char *) v1, '?')) != 0) { - int len = (int)(idx - (char *) v1); - return PL_strncasecmp((char *) v1, (char *) v2, len) == 0; - } else { - return PL_strcasecmp((char *) v1, (char *) v2) == 0; - } -} - -PRIVATE PLHashNumber net_HashAbout(const void *key) -{ - PLHashNumber h; - const PRUint8 *s; - - h = 0; - for (s = (const PRUint8*)key; *s && *s != (PRUint8) '?'; s++) - h = (h >> 28) ^ (h << 4) ^ *s; - return h; -} - -PRIVATE PRBool net_DoRegisteredAbout(const char *which, ActiveEntry *entry) -{ - NET_AboutCB cb; - if ((cb = (NET_AboutCB) PL_HashTableLookup(net_AboutTable, which))!= 0) { - return cb(which, entry->format_out, entry->URL_s, entry->window_id); - } - return PR_FALSE; -} - -PRIVATE PRBool net_about_enabled(const char *which) -{ - char *which2; - char buf[256]; - PRBool res = FALSE; - if (!which) - return PR_FALSE; - - which2 = PL_strdup(which); - if (which2) { - char *args = PL_strchr(which2, '?'); - if (args) - *args = '\0'; - - PR_snprintf(buf, 246, "network.about-enabled.%s", which2); - res = TRUE; - PREF_GetBoolPref(buf, &res); - PR_Free(which2); - } - return res; -} - -PRIVATE void -net_OutputURLDocInfo(MWContext *ctxt, char *which, char **data, int32 *length) -{ - char *output=0; - URL_Struct *URL_s = NET_CreateURLStruct(which, NET_DONT_RELOAD); - struct tm *tm_struct_p; - char buf[64]; - char *tmp=0; - char *escaped; - char *il_msg; - - NET_FindURLInCache(URL_s, ctxt); - -#define CELL_TOP \ - StrAllocCat(output, \ - "<TR><TD VALIGN=BASELINE ALIGN=RIGHT><B>"); -#define CELL_TITLE(title) \ - StrAllocCat(output, title); -#define CELL_MIDDLE \ - StrAllocCat(output, \ - "</B></TD>" \ - "<TD>"); -#define CELL_BODY(body) \ - StrAllocCat(output, body); -#define CELL_END \ - StrAllocCat(output, \ - "</TD></TR>"); -#define ADD_CELL(c_title, c_body) \ - CELL_TOP; \ - CELL_TITLE(c_title); \ - CELL_MIDDLE; \ - CELL_BODY(c_body); \ - CELL_END; - - StrAllocCopy(output, "<TABLE>"); - - StrAllocCopy(tmp, "<A HREF=\""); - escaped = NET_EscapeDoubleQuote(URL_s->address); - StrAllocCat(tmp, escaped); - PR_Free(escaped); - StrAllocCat(tmp, "\">"); - escaped = NET_EscapeHTML(URL_s->address); - StrAllocCat(tmp, escaped); - PR_Free(escaped); - StrAllocCat(tmp, "</a>"); - if(URL_s->is_netsite) - { - ADD_CELL(XP_GetString(XP_NETSITE_), tmp); - } - else - { - ADD_CELL(XP_GetString(XP_LOCATION_), tmp); - } - PR_Free(tmp); - - ADD_CELL(XP_GetString(XP_FILE_MIME_TYPE_), - URL_s->content_type ? URL_s->content_type : XP_GetString(XP_CURRENTLY_UNKNOWN)); -#ifdef NU_CACHE - ADD_CELL(XP_GetString(XP_SOURCE_), URL_s->cache_file - ? XP_GetString(XP_CURRENTLY_IN_DISK_CACHE) - : URL_s->cache_object ? - XP_GetString(XP_CURRENTLY_IN_MEM_CACHE) - : XP_GetString(XP_CURRENTLY_NO_CACHE)); -#else - - ADD_CELL(XP_GetString(XP_SOURCE_), URL_s->cache_file - ? XP_GetString(XP_CURRENTLY_IN_DISK_CACHE) - : URL_s->memory_copy ? - XP_GetString(XP_CURRENTLY_IN_MEM_CACHE) - : XP_GetString(XP_CURRENTLY_NO_CACHE)); -#endif /* NU_CACHE */ - - ADD_CELL(XP_GetString(XP_LOCAL_CACHE_FILE_), URL_s->cache_file - ? URL_s->cache_file - : XP_GetString(XP_NONE)); - - tm_struct_p = localtime(&URL_s->last_modified); - - if(tm_struct_p) - { -#ifdef XP_UNIX - strftime(buf, 64, XP_GetString(XP_LOCAL_TIME_FMT), - tm_struct_p); -#else - char tmpbuf[64]; - XP_StrfTime(ctxt,tmpbuf,64,XP_LONG_DATE_TIME_FORMAT, - tm_struct_p); - /* NOTE: XP_LOCAL_TIME_FMT is different depend on platform */ - PR_snprintf(buf, 64, XP_GetString(XP_LOCAL_TIME_FMT), tmpbuf); -#endif - } - else - { - buf[0] = 0; - } - ADD_CELL(XP_GetString(XP_LAST_MODIFIED), URL_s->last_modified ? buf : XP_GetString(XP_MSG_UNKNOWN)); - - tm_struct_p = gmtime(&URL_s->last_modified); - - if(tm_struct_p) - { -#ifdef XP_UNIX - strftime(buf, 64, XP_GetString(XP_GMT_TIME_FMT), - tm_struct_p); -#else - char tmpbuf[64]; - XP_StrfTime(ctxt,tmpbuf,64,XP_LONG_DATE_TIME_FORMAT, - tm_struct_p); - /* NOTE: XP_GMT_TIME_FMT is different depend on platform */ - PR_snprintf(buf, 64, XP_GetString(XP_GMT_TIME_FMT), tmpbuf); -#endif - } - else - { - buf[0] = 0; - } - - ADD_CELL(XP_GetString(XP_LAST_MODIFIED), URL_s->last_modified ? buf : XP_GetString(XP_MSG_UNKNOWN)); - -#ifdef DEBUG - PR_snprintf(buf, 64, "%lu seconds since 1-1-70 GMT", URL_s->last_modified); - ADD_CELL("Last Modified:", URL_s->last_modified ? buf : "Unknown"); -#endif - - sprintf(buf, "%lu", URL_s->content_length); - ADD_CELL(XP_GetString(XP_CONTENT_LENGTH_), URL_s->content_length - ? buf - : XP_GetString(XP_MSG_UNKNOWN)); - ADD_CELL(XP_GetString(XP_EXPIRES_), URL_s->expires > 0 - ? INTL_ctime(ctxt, &URL_s->expires) - : XP_GetString(XP_NO_DATE_GIVEN)); - - if (URL_s->x_mac_type && *URL_s->x_mac_type) - { - ADD_CELL(XP_GetString(XP_MAC_TYPE_), URL_s->x_mac_type); - } - if (URL_s->x_mac_creator && *URL_s->x_mac_creator) - { - ADD_CELL(XP_GetString(XP_MAC_CREATOR_), URL_s->x_mac_creator); - } - - if (URL_s->charset) - { - ADD_CELL(XP_GetString(XP_CHARSET_), URL_s->charset); - } - else - { - ADD_CELL(XP_GetString(XP_CHARSET_), XP_GetString(XP_MSG_UNKNOWN)); - } - - HG76363 - - StrAllocCat(output, "</TABLE>"); - - if(URL_s->content_type - && !PL_strncasecmp(URL_s->content_type, "image", 5)) - { - /* Have a seat. Lie down. Tell me about yourself. */ - il_msg = NULL; -#if 0 /* Used to be MODULAR_NETLIB */ - il_msg = IL_HTMLImageInfo(URL_s->address); -#endif - if (il_msg) { - StrAllocCat(output, "<HR>\n"); - StrAllocCat(output, il_msg); - PR_Free(il_msg); - } - } - - *data = output; - *length = PL_strlen(output); - - NET_FreeURLStruct(URL_s); - return; -} - -/* prints information about a context usint HTML. - * - * The context passed in as arg2 is the context that - * we are printing info about and the context that - * is in the ActiveEntry is the window we are displaying - * within - */ -PRIVATE -int -net_PrintContextInfo(ActiveEntry *cur_entry, MWContext *context) -{ - History_entry *his; - NET_StreamClass *stream; - char buf[64]; - char *tmp; - - /* get the current history entry and - * extract the URL from it. That has - * the top level document URL and the title - */ - his = SHIST_GetCurrent (&context->hist); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, cur_entry->window_id); - - if(!stream) - return(MK_UNABLE_TO_CONVERT); - - PL_strcpy(buf, "<FONT SIZE=+2><b>"); - (*stream->put_block)(stream, buf, PL_strlen(buf)); - - if(his && his->title) - tmp = PL_strdup(his->title); - else - tmp = PL_strdup(XP_GetString(XP_UNTITLED_DOCUMENT)); - - (*stream->put_block)(stream, tmp, PL_strlen(tmp)); - - PL_strcpy(buf, XP_GetString(XP_HAS_THE_FOLLOWING_STRUCT)); - (*stream->put_block)(stream, buf, PL_strlen(buf)); - - LO_DocumentInfo(context, stream); - - (*stream->complete)(stream); - cur_entry->status = MK_DATA_LOADED; - cur_entry->status = MK_DATA_LOADED; - - return(-1); -} - -PRIVATE char * -net_gen_pics_document(ActiveEntry *cur_entry) -{ - char *rv = NULL; - char *help_dir = FE_GetNetHelpDir(); - - if(help_dir) - { - if (help_dir[PL_strlen(help_dir)-1] != '/') - StrAllocCat(help_dir, "/"); - - if (!help_dir) - return NULL; - -#define PICS_HTML " \ -<TITLE>XXXXXXXXXXXXXXX</TITLE> \ -<FRAMESET border=no cols=1,100%%> \ -<FRAME src=about:blank> \ -<FRAME src='%spicsfail.htm'> \ -</FRAMESET>" - - rv = PR_smprintf(PICS_HTML, help_dir); - - XP_FREE(help_dir); - } - - - return rv; -} - -/* print out silly about type URL - */ -PRIVATE int net_output_about_url(ActiveEntry * cur_entry) -{ - NET_StreamClass * stream; - char * data=0; - char * content_type=0; - int32 length; - char * which = cur_entry->URL_s->address; - char * colon = strchr (which, ':'); - void * fe_data = NULL; - Bool uses_fe_data=FALSE; - - if (colon) - which = colon + 1; - - - if (NET_URL_Type(which)) { - if (!net_about_enabled("current")) - return MK_MALFORMED_URL_ERROR; - } else { - if (!net_about_enabled(which)) - return MK_MALFORMED_URL_ERROR; - } - - if(0) - { - /* placeholder to make ifdef's easier */ - } -#ifdef MOZILLA_CLIENT - else if(NET_URL_Type(which)) - { - /* this url is asking for document info about this - * URL. - * Call a NET function to generate the HTML block - */ - net_OutputURLDocInfo(cur_entry->window_id, which, &data, &length); - StrAllocCopy(content_type, TEXT_HTML); - } - else if(!PL_strncasecmp(which, "pics", 4)) - { - data = net_gen_pics_document(cur_entry); - if (data) { - length = PL_strlen(data); - content_type = PL_strdup(TEXT_HTML); - uses_fe_data = FALSE; - } - } -#if defined(CookieManagement) - else if(!PL_strcasecmp(which, "cookies")) - { -/* NET_DisplayCookieInfoAsHTML(cur_entry->window_id); */ - return(-1); - } -#endif -#if defined(SingleSignon) - else if(!PL_strcasecmp(which, "signons")) - { - SI_DisplaySignonInfoAsHTML(cur_entry->window_id); - return(-1); - } -#endif - else if(!PL_strncasecmp(which, "cache", 5)) - { - NET_DisplayCacheInfoAsHTML(cur_entry); - return(-1); - } - else if(!PL_strcasecmp(which, "memory-cache")) - { - NET_DisplayMemCacheInfoAsHTML(cur_entry); - return(-1); - } - else if(!PL_strcasecmp(which, "logout")) - { - NET_RemoveAllAuthorizations(); - return(-1); - } -#ifdef DEBUG - else if(!PL_strcasecmp(which, "streams")) - { - NET_DisplayStreamInfoAsHTML(cur_entry); - return(-1); - } -#endif /* DEBUG */ - else if(!PL_strcasecmp(which, "document")) - { - char buf[64]; - History_entry *his; - MWContext *context; - - /* output a Grid here with the first grid - * cell containing an about: url with the - * context pointer as the argument. - * - * also put the context pointer in as the post data - * if it's not there already so that history will - * do the right thing. - * - * also output blank string for all FO's not view source - * and save - */ - - /* if there is post data then a context ID is hiding - * in there. Get it and verify it - */ - if(cur_entry->URL_s->post_data) - { -#if defined(__sun) && !defined(SVR4) /* sun 4.1.3 */ - sscanf(cur_entry->URL_s->post_data, "%lu", &context); -#else - sscanf(cur_entry->URL_s->post_data, "%p", &context); -#endif - if(!XP_IsContextInList(context)) - context = cur_entry->window_id; - } - else - { - context = cur_entry->window_id; - } - - /* get the current history entry and - * extract the URL from it. That has - * the top level document URL - */ - his = SHIST_GetCurrent (&context->hist); - - StrAllocCat(data, "<TITLE>"); - StrAllocCat(data, XP_GetString(XP_DOCUMENT_INFO)); - StrAllocCat(data, "</TITLE>" - "<frameset rows=\"40%,60%\">" - "<frame src=about:"); - - StrAllocCopy(cur_entry->URL_s->window_target, "%DocInfoWindow"); - /* add a Chrome Struct so that we can control the window */ - cur_entry->URL_s->window_chrome = PR_NEW(Chrome); - - if(cur_entry->URL_s->window_chrome) - { - memset(cur_entry->URL_s->window_chrome, 0, sizeof(Chrome)); - cur_entry->URL_s->window_chrome->type = MWContextDialog; - cur_entry->URL_s->window_chrome->show_scrollbar = TRUE; - cur_entry->URL_s->window_chrome->allow_resize = TRUE; - cur_entry->URL_s->window_chrome->allow_close = TRUE; - } - - /* You can't edit "about:document"! */ - if ( FO_CACHE_AND_EDIT == cur_entry->format_out ) { - cur_entry->format_out = FO_CACHE_AND_PRESENT; - } - - /* don't let people really view the source of this... */ - if(FO_PRESENT != CLEAR_CACHE_BIT(cur_entry->format_out)) - { - StrAllocCat(data, "blank"); - } - else - { - StrAllocCat(data, "FeCoNtExT="); - - if(!cur_entry->URL_s->post_data) - { - PR_snprintf(buf, 64, "%p", context); - StrAllocCat(data, buf); - StrAllocCopy(cur_entry->URL_s->post_data, buf); - } - else - { - StrAllocCat(data, cur_entry->URL_s->post_data); - } - } - - StrAllocCat(data, "><frame name=Internal_URL_Info src=about:"); - - if(his && his->address) - StrAllocCat(data, his->address); - else - StrAllocCat(data, "blank"); - - StrAllocCat(data, "></frameset>"); - - length = PL_strlen(data); - StrAllocCopy(content_type, TEXT_HTML); - } - else if(!PL_strncasecmp(which, "Global", 6)) - { - cur_entry->status = NET_DisplayGlobalHistoryInfoAsHTML( - cur_entry->window_id, - cur_entry->URL_s, - cur_entry->format_out); - - return(-1); - - } - else if(!PL_strncmp(which, "FeCoNtExT=", 10)) - { - MWContext *old_ctxt; - -#if defined(__sun) && !defined(SVR4) /* sun 4.1.3 */ - sscanf(which+10, "%lu", &old_ctxt); -#else - sscanf(which+10, "%p", &old_ctxt); -#endif - - /* verify that we have the right context - * - */ - if(!XP_IsContextInList(old_ctxt)) - { - StrAllocCopy(data, XP_GetString(XP_THE_WINDOW_IS_NOW_INACTIVE)); - } - else - { - return(net_PrintContextInfo(cur_entry, old_ctxt)); - } - - length = PL_strlen(data); - StrAllocCopy(content_type, TEXT_HTML); - - } -#endif /* MOZILLA_CLIENT */ - else if(!PL_strncasecmp(which, "authors", 7)) - { - static const char *d = - ("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html\" " - "CHARSET=\"iso-8859-1\"><TITLE>Mozilla &Uuml;ber Alles</TITLE>" - "<BODY BGCOLOR=\"#C0C0C0\" TEXT=\"#000000\">" - "<TABLE width=\"100%\" height=\"100%\"><TR><TD ALIGN=CENTER>" - "<FONT SIZE=5><FONT COLOR=\"#0000EE\">about:authors</FONT> " - "removed.</FONT></TD></TR></TABLE>"); - data = PL_strdup(d); - length = (d ? PL_strlen(d) : 0); - content_type = PL_strdup(TEXT_HTML); - uses_fe_data = FALSE; - } - /* Admin Kit/xp prefs diagnostic support */ - else if (!PL_strncasecmp(which, "config", 6)) - { - data = PREF_AboutConfig(); - if (data) { - length = PL_strlen(data); - content_type = PL_strdup(TEXT_HTML); - } - } - else if (PL_strncasecmp(which, "blank", 5) == 0) { - static const char *d = - ("<HTML>" - "<HEAD>" - "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html\">" - "<TITLE>blank</TITLE>" - "</HEAD>" - "<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\">" - "</BODY>" - "</HTML>"); - data = PL_strdup(d); - length = (d ? PL_strlen(d) : 0); - content_type = PL_strdup(TEXT_HTML); - uses_fe_data = FALSE; - } - else - { - if (net_DoRegisteredAbout(which, cur_entry)) { - return -1; - } - fe_data = FE_AboutData(which, &data, &length, &content_type); - uses_fe_data=TRUE; - } - - if (!data || !content_type) - { - cur_entry->status = MK_MALFORMED_URL_ERROR; - } - else - { - int status; - StrAllocCopy(cur_entry->URL_s->content_type, content_type); - - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - - stream = NET_StreamBuilder(cur_entry->format_out, - cur_entry->URL_s, cur_entry->window_id); - - if(!stream) - { - cur_entry->status = MK_UNABLE_TO_CONVERT; - return(MK_UNABLE_TO_CONVERT); - } - - status = (*stream->put_block)(stream, data, length); - - if (status >= 0) { - /* Append optional Admin Kit-specified about page text */ - char* custom_text = NULL; - if (PL_strcmp(which, "") == 0 && - PREF_CopyConfigString("about_text", &custom_text) == PREF_NOERROR) { - (*stream->put_block)(stream, custom_text, PL_strlen(custom_text)); - } - - (*stream->complete) (stream); - - PR_FREEIF(custom_text); - } - else - (*stream->abort) (stream, status); - - cur_entry->status = status; - - PR_Free(stream); - } - - if(uses_fe_data) - { -#if defined(XP_MAC) || defined(XP_UNIX) || defined (XP_WIN) - FE_FreeAboutData (fe_data, which); -#endif /* XP_MAC || XP_UNIX */ - } - else - { - PR_Free(data); - PR_Free(content_type); - } - - return(-1); -} - - -PRIVATE Bool net_about_kludge(URL_Struct *URL_s) -{ - unsigned char *url = (unsigned char *) URL_s->address; - unsigned char *user = (unsigned char *) PL_strdup ((char*)(url + 6)); - unsigned char *tmp; - - if (user == NULL) - return FALSE; - - for (tmp = user; *tmp; tmp++) *tmp += 23; - - if ( !PL_strcmp((char*)user, "\170\202\202\170\205\170") || /* akkana */ - !PL_strcmp((char*)user, "\170\211\200") || /* ari */ - !PL_strcmp((char*)user, "\170\211\212\177\170\173") || /* arshad */ - !PL_strcmp((char*)user, "\170\213\206\213\200\172") || /* atotic */ - !PL_strcmp((char*)user, "\171\176\170\220") || /* bgay */ - !PL_strcmp((char*)user, "\171\201\206\205\174\212") || /* bjones */ - !PL_strcmp((char*)user, "\171\203\220\213\177\174") || /* blythe */ - !PL_strcmp((char*)user, "\171\205\174\203\212\206\205") || /* bnelson */ - !PL_strcmp((char*)user, "\171\206\171") || /* bob */ - !PL_strcmp((char*)user, "\171\206\171\201") || /* bobj */ - !PL_strcmp((char*)user, "\171\211\170\173\174") || /* brade */ - !PL_strcmp((char*)user, "\171\211\200\170\205\206") || /* briano */ - !PL_strcmp((char*)user, "\171\211\200\173\176\174") || /* bridge */ - !PL_strcmp((char*)user, "\172\170\213\177\203\174\174\204") || /* cathleen */ - !PL_strcmp((char*)user, "\172\177\206\214\172\202") || /* chouck */ - !PL_strcmp((char*)user, "\172\177\211\200\212\175") || /* chrisf */ - !PL_strcmp((char*)user, "\172\202\211\200\213\221\174\211") || /* ckritzer */ - !PL_strcmp((char*)user, "\172\204\170\205\212\202\174") || /* cmanske */ - !PL_strcmp((char*)user, "\172\206\205\215\174\211\212\174") || /* converse */ - !PL_strcmp((char*)user, "\172\206\211\171\170\205") || /* corban */ - !PL_strcmp((char*)user, "\172\217\214\174") || /* cxue */ - !PL_strcmp((char*)user, "\172\220\174\177") || /* cyeh */ - !PL_strcmp((char*)user, "\173\170\205\173\170") || /* danda */ - !PL_strcmp((char*)user, "\173\170\205\204") || /* danm */ - !PL_strcmp((char*)user, "\173\170\215\200\173\204") || /* davidm */ - !PL_strcmp((char*)user, "\173\174\172\170\212\213\211\200") || /* decastri */ - !PL_strcmp((char*)user, "\173\175\204") || /* dfm */ - !PL_strcmp((char*)user, "\173\201\216") || /* djw */ - !PL_strcmp((char*)user, "\173\202\170\211\203\213\206\205") || /* dkarlton */ - !PL_strcmp((char*)user, "\173\204\206\212\174") || /* dmose */ - !PL_strcmp((char*)user, "\173\206\205") || /* don */ - !PL_strcmp((char*)user, "\173\206\211\170") || /* dora */ - !PL_strcmp((char*)user, "\173\206\214\176") || /* doug */ - !PL_strcmp((char*)user, "\173\206\214\176\213") || /* dougt */ - !PL_strcmp((char*)user, "\173\207") || /* dp */ - !PL_strcmp((char*)user, "\174\171\200\205\170") || /* ebina */ - !PL_strcmp((char*)user, "\174\204\170\173\174\211") || /* emader */ - !PL_strcmp((char*)user, "\174\211\200\202") || /* erik */ - !PL_strcmp((char*)user, "\175\211\200\174\173\204\170\205") || /* friedman */ - !PL_strcmp((char*)user, "\175\213\170\205\176") || /* ftang */ - !PL_strcmp((char*)user, "\175\214\171\200\205\200") || /* fubini */ - !PL_strcmp((char*)user, "\175\214\211") || /* fur */ - !PL_strcmp((char*)user, "\176\170\176\170\205") || /* gagan */ - !PL_strcmp((char*)user, "\176\203\220\205\205") || /* glynn */\ - !PL_strcmp((char*)user, "\176\211\206\216\203\213\200\176\174\211") || /* growltiger */\ - !PL_strcmp((char*)user, "\177\170\176\170\205") || /* hagan */ - !PL_strcmp((char*)user, "\177\170\211\173\213\212") || /* hardts */ - !PL_strcmp((char*)user, "\177\212\177\170\216") || /* hshaw */ - !PL_strcmp((char*)user, "\177\220\170\213\213") || /* hyatt */ - !PL_strcmp((char*)user, "\200\211\174\205\174") || /* irene */ - !PL_strcmp((char*)user, "\201\170\211") || /* jar */ - !PL_strcmp((char*)user, "\201\174\175\175") || /* jeff */ - !PL_strcmp((char*)user, "\201\174\215\174\211\200\205\176") || /* jevering */ - !PL_strcmp((char*)user, "\201\176") || /* jg */ - !PL_strcmp((char*)user, "\201\176\174\203\203\204\170\205") || /* jgellman */ - !PL_strcmp((char*)user, "\201\201") || /* jj */ - !PL_strcmp((char*)user, "\201\206\174\211\214\175\175") || /* joeruff */ - !PL_strcmp((char*)user, "\201\206\202\200") || /* joki */ - !PL_strcmp((char*)user, "\201\206\205\170\212") || /* jonas */ - !PL_strcmp((char*)user, "\201\207\204") || /* jpm */ - !PL_strcmp((char*)user, "\201\212\216") || /* jsw */ - !PL_strcmp((char*)user, "\201\216\221") || /* jwz */ - !PL_strcmp((char*)user, "\202\170\177\174\211\205") || /* kahern */ - !PL_strcmp((char*)user, "\202\170\211\203\213\206\205") || /* karlton */ - !PL_strcmp((char*)user, "\202\200\207\207") || /* kipp */ - !PL_strcmp((char*)user, "\202\204\172\174\205\213\174\174") || /* kmcentee */ - !PL_strcmp((char*)user, "\202\206\174\177\204") || /* koehm */ - !PL_strcmp((char*)user, "\202\211\200\212\213\200\205") || /* kristin */ - !PL_strcmp((char*)user, "\203\170\211\214\171\171\200\206") || /* larubbio */ - !PL_strcmp((char*)user, "\203\170\216") || /* law */ - !PL_strcmp((char*)user, "\203\174\170\175") || /* leaf */ - !PL_strcmp((char*)user, "\203\174\205\221") || /* lenz */ - !PL_strcmp((char*)user, "\203\206\211\200\202") || /* lorik */ - !PL_strcmp((char*)user, "\203\213\170\171\171") || /* ltabb */ - !PL_strcmp((char*)user, "\204\170\203\204\174\211") || /* malmer */ - !PL_strcmp((char*)user, "\204\170\211\172\170") || /* marca */ - !PL_strcmp((char*)user, "\204\170\213\213") || /* matt */ - !PL_strcmp((char*)user, "\204\172\170\175\174\174") || /* mcafee */ - !PL_strcmp((char*)user, "\204\172\204\214\203\203\174\205") || /* mcmullen */ - !PL_strcmp((char*)user, "\204\174\173\200\213\170\213\200\206\205") || /* meditation */ - !PL_strcmp((char*)user, "\204\203\204") || /* mlm */ - !PL_strcmp((char*)user, "\204\206\205\200\210\214\174") || /* monique */ - !PL_strcmp((char*)user, "\204\206\205\213\214\203\203\200")|| /* montulli */ - !PL_strcmp((char*)user, "\204\206\211\212\174") || /* morse */ - !PL_strcmp((char*)user, "\204\206\214\211\174\220")|| /* mourey */ - !PL_strcmp((char*)user, "\204\213\206\220") || /* mtoy */ - !PL_strcmp((char*)user, "\204\216\174\203\172\177") || /* mwelch */ - !PL_strcmp((char*)user, "\205\174\203\212\206\205\171") || /* nelsonb */ - !PL_strcmp((char*)user, "\205\200\212\177\174\174\213\177") || /* nisheeth */ - !PL_strcmp((char*)user, "\206\200\205\202") || /* oink */ - !PL_strcmp((char*)user, "\207\170\203\174\215\200\172\177") || /* palevich */ - !PL_strcmp((char*)user, "\207\170\210\214\200\205") || /* paquin */ - !PL_strcmp((char*)user, "\207\170\214\203\173") || /* pauld */ - !PL_strcmp((char*)user, "\207\170\215\203\206\215") || /* pavlov */ - !PL_strcmp((char*)user, "\207\172\177\174\205") || /* pchen */ - !PL_strcmp((char*)user, "\207\177\200\203") || /* phil */ - !PL_strcmp((char*)user, "\207\200\174\211\211\174") || /* pierre */ - !PL_strcmp((char*)user, "\207\200\176\203\174\213") || /* piglet */ - !PL_strcmp((char*)user, "\207\200\205\202\174\211\213\206\205") || /* pinkerton */ - !PL_strcmp((char*)user, "\211\170\204\170\205") || /* raman */ - !PL_strcmp((char*)user, "\211\170\204\200\211\206") || /* ramiro */ - !PL_strcmp((char*)user, "\211\174\172\214\211\212\200\206\205") || /* recursion */ - !PL_strcmp((char*)user, "\211\174\207\202\170") || /* repka */ - !PL_strcmp((char*)user, "\211\200\172\170\211\173\206\171") || /* ricardob */ - !PL_strcmp((char*)user, "\211\201\172") || /* rjc */ - !PL_strcmp((char*)user, "\211\204\216") || /* rmw */ - !PL_strcmp((char*)user, "\211\170\204\211\170\201") || /* ramraj */ - !PL_strcmp((char*)user, "\211\200\172\170\211\173\206\171") || /* ricardob */ - !PL_strcmp((char*)user, "\211\206\171\204") || /* robm */ - !PL_strcmp((char*)user, "\211\206\174\171\174\211") || /* roeber */ - !PL_strcmp((char*)user, "\211\207\206\213\213\212") || /* rpotts */ - !PL_strcmp((char*)user, "\211\214\212\203\170\205") || /* ruslan */ - !PL_strcmp((char*)user, "\212\172\172") || /* scc */ - !PL_strcmp((char*)user, "\212\172\214\203\203\200\205") || /* scullin */ - !PL_strcmp((char*)user, "\212\173\170\176\203\174\220") || /* sdagley */ - !PL_strcmp((char*)user, "\212\177\170\211\206\205\200") || /* sharoni */ - !PL_strcmp((char*)user, "\212\177\170\215\174\211") || /* shaver */ - !PL_strcmp((char*)user, "\212\177\214\170\205\176") || /* shuang */ - !PL_strcmp((char*)user, "\212\202") || /* sk */ - !PL_strcmp((char*)user, "\212\202\220\174") || /* skye */ - !PL_strcmp((char*)user, "\212\203\170\204\204") || /* slamm */ - !PL_strcmp((char*)user, "\212\204\212\200\203\215\174\211") || /* smsilver */ - !PL_strcmp((char*)user, "\212\207\174\205\172\174") || /* spence */ - !PL_strcmp((char*)user, "\212\207\200\173\174\211") || /* spider */ - !PL_strcmp((char*)user, "\212\212\207\200\213\221\174\211") || /* sspitzer */ - !PL_strcmp((char*)user, "\212\213\174\211\205") || /* stern */ - !PL_strcmp((char*)user, "\213\170\211\170\177") || /* tarah */ - !PL_strcmp((char*)user, "\213\174\211\211\220") || /* terry */ - !PL_strcmp((char*)user, "\213\175\203\200\205\213") || /* tflint */ - !PL_strcmp((char*)user, "\213\200\204\204") || /* timm */ - !PL_strcmp((char*)user, "\213\206\212\177\206\202") || /* toshok */ - !PL_strcmp((char*)user, "\213\211\170\172\220") || /* tracy */ - !PL_strcmp((char*)user, "\213\211\200\212\213\170\205") || /* tristan */ - !PL_strcmp((char*)user, "\213\211\214\173\174\203\203\174") || /* trudelle */ - !PL_strcmp((char*)user, "\215\170\203\174\212\202\200") || /* valeski */ - !PL_strcmp((char*)user, "\216\170\211\211\174\205") || /* warren */ - !PL_strcmp((char*)user, "\216\201\212") ) /* wjs */ - { - /* "http://people.netscape.com/" */ - char *head = ("\177\213\213\207\121\106\106\207\174\206\207\203\174\105" - "\205\174\213\212\172\170\207\174\105\172\206\204\106"); - unsigned char *location = (unsigned char *) - PR_Malloc (PL_strlen ((char *) head) + PL_strlen ((char *) user) + 2); - if (! location) - { - PR_Free (user); - return FALSE; - } - PL_strcpy ((char *) location, (char *) head); - PL_strcat ((char *) location, (char *) user); - for (tmp = location; *tmp; tmp++) *tmp -= 23; - PL_strcat ((char *) location, "/"); - PR_Free (user); - PR_Free (URL_s->address); - URL_s->address = (char *) location; - URL_s->address_modified = TRUE; - return TRUE; - } - else - { - PR_Free (user); - return FALSE; - } -} - -PRBool NET_RegisterAboutProtocol(const char *token, - NET_AboutCB callback) -{ - if (!token || !callback) { - return PR_FALSE; - } - if (PL_HashTableLookup(net_AboutTable, token) != NULL) { - return PR_FALSE; - } - PL_HashTableAdd(net_AboutTable, token, callback); - return PR_TRUE; -} - -PRIVATE int32 -net_AboutLoad(ActiveEntry *ce) -{ - if(net_about_kludge (ce->URL_s)) - { - ce->status = MK_DO_REDIRECT; - return MK_DO_REDIRECT; - } - - return net_output_about_url(ce); -} - -PRIVATE int32 -net_AboutStub(ActiveEntry *ce) -{ -#ifdef DO_ANNOYING_ASSERTS_IN_STUBS - PR_ASSERT(0); -#endif - return -1; -} - -PRIVATE void -net_CleanupAbout(void) -{ - PL_HashTableDestroy(net_AboutTable); -} - -PUBLIC void -NET_InitAboutProtocol(void) -{ - static NET_ProtoImpl about_proto_impl; - - about_proto_impl.init = net_AboutLoad; - about_proto_impl.process = net_AboutStub; - about_proto_impl.interrupt = net_AboutStub; - about_proto_impl.resume = NULL; - about_proto_impl.cleanup = net_CleanupAbout; - - NET_RegisterProtocolImplementation(&about_proto_impl, ABOUT_TYPE_URL); - - net_AboutTable = PL_NewHashTable(32, - net_HashAbout, - net_AboutComparator, - PL_CompareValues, - NULL, NULL); -} diff --git a/mozilla/network/protocol/callback/Makefile.in b/mozilla/network/protocol/callback/Makefile.in deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/mozilla/network/protocol/callback/makefile.win b/mozilla/network/protocol/callback/makefile.win deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/mozilla/network/protocol/callback/mkcburl.c b/mozilla/network/protocol/callback/mkcburl.c deleted file mode 100644 index fbea16e24f5..00000000000 --- a/mozilla/network/protocol/callback/mkcburl.c +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -#include "xp.h" -#include "mkgeturl.h" -#include "netcburl.h" -#include "secrng.h" /* For RNG_GenerateGlobalRandomBytes */ - -typedef struct _NET_CallbackURLData { - int id; - char* match; - NET_CallbackURLFunc func; - void* closure; - struct _NET_CallbackURLData* next; -} NET_CallbackURLData; - -static NET_CallbackURLData* First = NULL; -static int Counter = 1; - - -char* -NET_CallbackURLCreate(NET_CallbackURLFunc func, void* closure) { - unsigned char rand_buf[13]; - char* result = NULL; - NET_CallbackURLData* tmp; - NET_CallbackURLFree(func, closure); - tmp = XP_NEW(NET_CallbackURLData); - if (!tmp) return NULL; - tmp->id = Counter++; - RNG_GenerateGlobalRandomBytes((void *) rand_buf, 12); - tmp->match = - PR_smprintf("%02X%02X%02X%02X" - "%02X%02X%02X%02X" - "%02X%02X%02X%02X", - rand_buf[0], rand_buf[1], rand_buf[2], rand_buf[3], - rand_buf[4], rand_buf[5], rand_buf[6], rand_buf[7], - rand_buf[8], rand_buf[9], rand_buf[10], rand_buf[11]); - if (tmp->match) { - result = PR_smprintf("internal-callback-handler:%d/%s", - tmp->id, tmp->match); - } - if (result == NULL) { - if (tmp->match) XP_FREE(tmp->match); - XP_FREE(tmp); - return NULL; - } - tmp->next = First; - First = tmp; - tmp->func = func; - tmp->closure = closure; - return result; -} - - -int -NET_CallbackURLFree(NET_CallbackURLFunc func, void* closure) { - NET_CallbackURLData** tmp; - NET_CallbackURLData* t; - for (tmp = &First ; *tmp ; tmp = &((*tmp)->next)) { - t = *tmp; - if (t->func == func && t->closure == closure) { - *tmp = t->next; - XP_FREE(t->match); - XP_FREE(t); - return 0; - } - } - return -1; -} - - - -int NET_LoadCallbackURL (ActiveEntry* ce) -{ - char* url = ce->URL_s->address; - char* path; - char* match; - int id; - NET_CallbackURLData* tmp; - - path = NET_ParseURL(url, GET_PATH_PART); - if (path == NULL) return -1; - id = XP_ATOI(path); - match = XP_STRCHR(path, '/'); - if (match) match++; - else match = ""; - - for (tmp = First ; tmp ; tmp = tmp->next) { - if (id == tmp->id && XP_STRCMP(match, tmp->match) == 0) { - (*tmp->func)(tmp->closure, url); - break; - } - } - XP_FREE(path); - return -1; -} - - -int NET_ProcessCallbackURL(ActiveEntry* ce) -{ - return -1; /* Should never get here */ -} - - -int NET_InterruptCallbackURL(ActiveEntry* ce) -{ - return -1; /* Should never get here */ -} - diff --git a/mozilla/network/protocol/certld/MANIFEST b/mozilla/network/protocol/certld/MANIFEST deleted file mode 100644 index 7405ac50307..00000000000 --- a/mozilla/network/protocol/certld/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mkcertld.h diff --git a/mozilla/network/protocol/certld/Makefile.in b/mozilla/network/protocol/certld/Makefile.in deleted file mode 100644 index b8ee2191c0f..00000000000 --- a/mozilla/network/protocol/certld/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = crtldurl -LIBRARY_NAME = crtldurl - -REQUIRES = ldap network dbm util pref js java fileurl security layer img httpurl - -CSRCS = mkcertld.c - -EXPORTS = $(srcdir)/mkcertld.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/certld/makefile.win b/mozilla/network/protocol/certld/makefile.win deleted file mode 100644 index f0b2a7d4b75..00000000000 --- a/mozilla/network/protocol/certld/makefile.win +++ /dev/null @@ -1,85 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkcertld.obj \ - $(NULL) - - -CSRCS = \ - mkcertld.c \ - $(NULL) - - -LIBRARY_NAME=certurl -MODULE=certurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network ldap -EXPORTS= mkcertld.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\ldap \ - -I$(XPDIST)\public\network -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/certld/mkcertld.c b/mozilla/network/protocol/certld/mkcertld.c deleted file mode 100644 index 0be51721b9c..00000000000 --- a/mozilla/network/protocol/certld/mkcertld.c +++ /dev/null @@ -1,146 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" -#include "mkgeturl.h" -#include "net.h" -#include "secnav.h" -#include "ldap.h" - -#ifdef MOZ_SECURITY -#include "certldap.h" -#include "mkcertld.h" -#endif - -PRIVATE int32 -net_CertLdapLoad(ActiveEntry *ce) -{ - int err = 0; -#ifdef MOZ_SECURITY - CertLdapConnData *connData; - - connData = SECNAV_CertLdapLoad(ce->URL_s); - ce->con_data = connData; - if ( connData == NULL ) { - err = -1; - } - - if ( err ) { - ce->status = err; - } else { -#endif - - PR_ASSERT(0); - -#ifdef XP_UNIX - NET_SetConnectSelect(ce->window_id, ce->socket); - NET_TotalNumberOfOpenConnections++; -#else - NET_SetCallNetlibAllTheTime(ce->window_id, "mkcertld"); -#endif -#ifdef MOZ_SECURITY - } -#endif - return(err); -} - -PRIVATE int32 -net_ProcessCertLdap(ActiveEntry *ce) -{ - int err = 0; -#ifdef MOZ_SECURITY - CertLdapConnData *connData; - - connData = (CertLdapConnData *)ce->con_data; - -#ifdef XP_UNIX - NET_ClearConnectSelect(ce->window_id, connData->fd); - NET_SetReadSelect(ce->window_id, connData->fd); -#endif - - err = SECNAV_CertLdapProcess(connData); -#endif - if ( err ) { - if ( err == 1 ) { - /* done */ - ce->status = 0; - err = -1; - } else { - ce->status = err; - } -#ifdef XP_UNIX -#ifdef MOZ_SECURITY - NET_ClearReadSelect(ce->window_id, connData->fd); -#endif - NET_TotalNumberOfOpenConnections--; -#else - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkcertld"); -#endif - - } - - return(err); -} - -PRIVATE int32 -net_InterruptCertLdap(ActiveEntry *ce) -{ - int err; -#ifdef MOZ_SECURITY - CertLdapConnData *connData; - - connData = (CertLdapConnData *)ce->con_data; - - err = SECNAV_CertLdapInterrupt(connData); -#endif - ce->status = MK_INTERRUPTED; - -#ifdef XP_UNIX -#ifdef MOZ_SECURITY - NET_ClearReadSelect(ce->window_id, connData->fd); -#endif - NET_TotalNumberOfOpenConnections--; -#else - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkcertld"); -#endif - - return(err); -} - -PRIVATE void -net_CleanupCertLdap(void) -{ -} - -MODULE_PRIVATE void -NET_InitCertLdapProtocol(void) -{ - static NET_ProtoImpl certldap_proto_impl; - - certldap_proto_impl.init = net_CertLdapLoad; - certldap_proto_impl.process = net_ProcessCertLdap; - certldap_proto_impl.interrupt = net_InterruptCertLdap; - certldap_proto_impl.resume = NULL; - certldap_proto_impl.cleanup = net_CleanupCertLdap; - - NET_RegisterProtocolImplementation(&certldap_proto_impl, INTERNAL_CERTLDAP_TYPE_URL); -} - diff --git a/mozilla/network/protocol/certld/mkcertld.h b/mozilla/network/protocol/certld/mkcertld.h deleted file mode 100644 index 2bfa5945391..00000000000 --- a/mozilla/network/protocol/certld/mkcertld.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef _MKCERTLD_H_ -#define _MKCERTLD_H_ -/* - * mkcertld.h - api to cert ldap protocol code - * - * $Id: mkcertld.h,v 1.3 1999-11-06 02:33:01 dmose%mozilla.org Exp $ - */ - -PR_BEGIN_EXTERN_C -void NET_InitCertLdapProtocol(void); -PR_END_EXTERN_C - -#endif /* _MKCERTLD_H_ */ - - diff --git a/mozilla/network/protocol/dataurl/MANIFEST b/mozilla/network/protocol/dataurl/MANIFEST deleted file mode 100644 index 0a93b26626b..00000000000 --- a/mozilla/network/protocol/dataurl/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -dataurl.h diff --git a/mozilla/network/protocol/dataurl/Makefile.in b/mozilla/network/protocol/dataurl/Makefile.in deleted file mode 100644 index 197b14d124c..00000000000 --- a/mozilla/network/protocol/dataurl/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = dataurl -LIBRARY_NAME = dataurl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl netcnvts - -CSRCS = mkdaturl.c - -EXPORTS = $(srcdir)/dataurl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/dataurl/dataurl.h b/mozilla/network/protocol/dataurl/dataurl.h deleted file mode 100644 index 02dbe0b1ba5..00000000000 --- a/mozilla/network/protocol/dataurl/dataurl.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKDATURL_H -#define MKDATURL_H - -extern void NET_InitDataURLProtocol(void); - -#endif /* MKDATURL_H */ diff --git a/mozilla/network/protocol/dataurl/makefile.win b/mozilla/network/protocol/dataurl/makefile.win deleted file mode 100644 index b028f20afed..00000000000 --- a/mozilla/network/protocol/dataurl/makefile.win +++ /dev/null @@ -1,87 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -LLIBS= \ - $(NULL) -OBJS= \ - .\$(OBJDIR)\mkdaturl.obj \ - $(NULL) - - -CSRCS = \ - mkdaturl.c \ - $(NULL) - - -LIBRARY_NAME=dataurl -MODULE=dataurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network security -EXPORTS= dataurl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\netcnvts \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\network -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/dataurl/mkdaturl.c b/mozilla/network/protocol/dataurl/mkdaturl.c deleted file mode 100644 index 319022f1f4a..00000000000 --- a/mozilla/network/protocol/dataurl/mkdaturl.c +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "net.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "dataurl.h" -#include "cvmime.h" - -extern int MK_OUT_OF_MEMORY; -extern int MK_MALFORMED_URL_ERROR; - -/* format of the DATA: URL - * - * data:[CONTENT-TYPE][;base64],DATA - */ -PRIVATE int32 -net_DataURLLoad (ActiveEntry * ce) -{ - char *data_buffer; - XP_Bool is_base64 = FALSE; - NET_StreamClass *stream; - char *comma; - - ce->protocol = DATA_TYPE_URL; - - /* we need a buffer equal to or smaller than the size of the URL - */ - data_buffer = (char *)PR_Malloc(PL_strlen(ce->URL_s->address)+1); - - if(!data_buffer) - return(MK_OUT_OF_MEMORY); - - /* determine the content type */ - - /* find the first comma */ - comma = PL_strchr(ce->URL_s->address, ','); - - /* if no comma abort */ - if(!comma) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_MALFORMED_URL_ERROR, ce->URL_s->address); - return(MK_MALFORMED_URL_ERROR); - } - - /* fill in default content type */ - StrAllocCopy(ce->URL_s->content_type, TEXT_PLAIN); - - /* check for a content type */ - if(comma != ce->URL_s->address + PL_strlen("data:")) - { - *comma = '\0'; - PL_strcpy(data_buffer, ce->URL_s->address + PL_strlen("data:")); - *comma = ','; - - /* check for base 64 encoding */ - if(PL_strcasestr(data_buffer, "base64")) - is_base64 = TRUE; - - /* parse the rest as a content-type */ - NET_ParseContentTypeHeader(ce->window_id, data_buffer, ce->URL_s, FALSE); - - } - - if(is_base64) - { - stream = NET_MimeEncodingConverter(ce->format_out, ENCODING_BASE64, ce->URL_s, ce->window_id); - } - else - { - /* open the outgoing stream - */ - stream = NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - } - - if(!stream) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - ce->status = MK_UNABLE_TO_CONVERT; - return (ce->status); - } - - /* @@@@ bug: ignore is_write_ready */ - - /* copy the data part of the URL into a scratch buffer */ - PL_strcpy(data_buffer, comma+1); - - ce->status = (*stream->put_block)(stream, - data_buffer, - PL_strlen(data_buffer)); - if(ce->status < 0) - { - (*stream->abort)(stream, ce->status); - return (ce->status); - } - - (*stream->complete)(stream); - - ce->status = MK_DATA_LOADED; - return(-1); /* all done */ - -} - -/* called repeatedly from NET_ProcessNet to push all the - * data up the stream - */ -PRIVATE int32 -net_ProcessDataURL (ActiveEntry * cur_entry) -{ - PR_ASSERT(0); - return(-1); -} - -/* called by functions in mkgeturl to interrupt the loading of - * an object. (Usually a user interrupt) - */ -PRIVATE int32 -net_InterruptDataURL (ActiveEntry * cur_entry) -{ - PR_ASSERT(0); - return(-1); -} - -PRIVATE void -net_CleanupDataURL(void) -{ - -} - -MODULE_PRIVATE void -NET_InitDataURLProtocol(void) -{ - static NET_ProtoImpl dataurl_proto_impl; - - dataurl_proto_impl.init = net_DataURLLoad; - dataurl_proto_impl.process = net_ProcessDataURL; - dataurl_proto_impl.interrupt = net_InterruptDataURL; - dataurl_proto_impl.resume = NULL; - dataurl_proto_impl.cleanup = net_CleanupDataURL; - - NET_RegisterProtocolImplementation(&dataurl_proto_impl, DATA_TYPE_URL); -} - diff --git a/mozilla/network/protocol/file/MANIFEST b/mozilla/network/protocol/file/MANIFEST deleted file mode 100644 index f3e8a623092..00000000000 --- a/mozilla/network/protocol/file/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -fileurl.h diff --git a/mozilla/network/protocol/file/Makefile.in b/mozilla/network/protocol/file/Makefile.in deleted file mode 100644 index 0501adac382..00000000000 --- a/mozilla/network/protocol/file/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = fileurl -LIBRARY_NAME = fileurl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl jtools mimetype progress - -CSRCS = mkfile.c - -EXPORTS = $(srcdir)/fileurl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/file/fileurl.h b/mozilla/network/protocol/file/fileurl.h deleted file mode 100644 index c0dcd63ebbc..00000000000 --- a/mozilla/network/protocol/file/fileurl.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef FILEURL_H -#define FILEURL_H - -extern void NET_InitFileProtocol(void); - -extern NET_StreamClass * -net_CloneWysiwygLocalFile(MWContext *window_id, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href); - -#endif /* FILEURL_H */ diff --git a/mozilla/network/protocol/file/makefile.win b/mozilla/network/protocol/file/makefile.win deleted file mode 100644 index 6c09b85db58..00000000000 --- a/mozilla/network/protocol/file/makefile.win +++ /dev/null @@ -1,90 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkfile.obj \ - $(NULL) - - -CSRCS = \ - mkfile.c \ - $(NULL) - - -LIBRARY_NAME=fileurl -MODULE=fileurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network security -EXPORTS= fileurl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\jtools \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\mimetype \ - -I$(PUBLIC)\security \ -!ifdef MOZ_SMOOTH_PROGRESS - -I$(PUBLIC)\progress \ -!endif - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/file/mkfile.c b/mozilla/network/protocol/file/mkfile.c deleted file mode 100644 index a302061abc7..00000000000 --- a/mozilla/network/protocol/file/mkfile.c +++ /dev/null @@ -1,1867 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * state machine to handle local file and directory URL's - * and to retreive file cache objects - * - * Designed and implemented by Lou Montulli '94 - */ - -#if defined(CookieManagement) -/* #define TRUST_LABELS 1 */ -#endif - -#include "xp.h" -#include "net_xp_file.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "mkstream.h" -#include "mkformat.h" -#include "mkparse.h" -#include "mkfsort.h" -#include "mkfile.h" -#include "merrors.h" -#include "glhist.h" - -#include "il_strm.h" /* Image Lib stream converters. */ -#include "il_types.h" -IL_EXTERN(int) -IL_Type(const char *buf, int32 len); - -#if defined(XP_WIN) || defined(XP_OS2) -#include "errno.h" -#endif - -#include "prefapi.h" - -#ifdef TRUST_LABELS -extern void ProcessCookiesAndTrustLabels( ActiveEntry *ce ); -#endif - -#if defined(SMOOTH_PROGRESS) -#include "progress.h" -#endif - -#ifdef HAVE_UNISTD_H -#include <unistd.h> /* for SEEK_SET on some platforms */ -#endif - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_ALERT_OUTMEMORY; -extern int XP_PROGRESS_DIRDONE; -extern int XP_PROGRESS_FILEDONE; -extern int XP_PROGRESS_FILEZEROLENGTH; -extern int XP_PROGRESS_READDIR; -extern int XP_PROGRESS_READFILE; -extern int MK_OUT_OF_MEMORY; -extern int MK_UNABLE_TO_LOCATE_FILE; -extern int MK_UNABLE_TO_OPEN_FILE; -extern int MK_ZERO_LENGTH_FILE; -extern int MK_UNABLE_TO_DELETE_FILE; -extern int MK_UNABLE_TO_DELETE_DIRECTORY; -extern int MK_MKDIR_FILE_ALREADY_EXISTS; -extern int MK_COULD_NOT_CREATE_DIRECTORY; -extern int MK_ERROR_WRITING_FILE; -extern int MK_NOT_A_DIRECTORY; -extern int XP_READING_SEGMENT; -extern int XP_TITLE_DIRECTORY_LISTING; -extern int XP_H1_DIRECTORY_LISTING; -extern int XP_UPTO_HIGHER_LEVEL_DIRECTORY; -extern int XP_TITLE_DIRECTORY_OF_ETC; - -/* states of the machine - */ -typedef enum { - NET_CHECK_FILE_TYPE, - NET_DELETE_FILE, - NET_MOVE_FILE, - NET_PUT_FILE, - NET_MAKE_DIRECTORY, - NET_FILE_SETUP_STREAM, - NET_OPEN_FILE, - NET_SETUP_FILE_STREAM, - NET_OPEN_DIRECTORY, - NET_READ_FILE_CHUNK, - NET_READ_DIRECTORY_CHUNK, - NET_BEGIN_PRINT_DIRECTORY, - NET_PRINT_DIRECTORY, - NET_FILE_DONE, - NET_FILE_ERROR_DONE, - NET_FILE_FREE -} net_FileStates; - -/* forward decl */ -PRIVATE int32 net_ProcessFile (ActiveEntry * cur_entry); - -/* allow URL byterange requests for backwards compatibility, - * but only leave this in for a short while - */ -#define URL_BYTERANGE_METHOD - -#define DIR_STRUCT struct dirent - -typedef struct _FILEConData { - XP_File file_ptr; - PRDir *dir_ptr; - net_FileStates next_state; - NET_StreamClass * stream; - char * filename; - Bool is_dir; - SortStruct * sort_base; - Bool pause_for_read; - Bool is_cache_file; - Bool calling_netlib_all_the_time; - Bool destroy_graph_progress; /* do we need to destroy graph progress? */ - int32 original_content_length; /* the content length at the time of - * calling graph progress - */ - char * byterange_string; - int32 range_length; /* the length of the current byte range */ -} FILEConData; - -#define CE_WINDOW_ID cur_entry->window_id -#define CE_STATUS cur_entry->status -#define CE_SOCK cur_entry->socket -#define CE_BYTES_RECEIVED cur_entry->bytes_received -#define CE_FORMAT_OUT cur_entry->format_out -#define CD_DESTROY_GRAPH_PROGRESS con_data->destroy_graph_progress -#define CD_ORIGINAL_CONTENT_LENGTH con_data->original_content_length -#define CD_BYTERANGE_STRING con_data->byterange_string -#define CD_RANGE_LENGTH con_data->range_length - -#define PUTS(s) (*con_data->stream->put_block) \ - (con_data->stream, s, PL_strlen(s)) -#define IS_WRITE_READY (*con_data->stream->is_write_ready) \ - (con_data->stream) -#define PUTB(b,l) (*con_data->stream->put_block) \ - (con_data->stream, b, l) -#define COMPLETE_STREAM (*con_data->stream->complete) \ - (con_data->stream) -#define ABORT_STREAM(s) (*con_data->stream->abort) \ - (con_data->stream, s) - -/* try and open the URL path as a normal file - * if it fails set the next state to try and open - * a directory. - */ -PRIVATE int -net_check_file_type (ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - XP_StatStruct stat_entry; - - TRACEMSG(("Looking for file: %s", con_data->filename)); - - /* larubbio added xpSARCache check */ - if(-1 == NET_XP_Stat (con_data->filename, - &stat_entry, - con_data->is_cache_file ? - (cur_entry->URL_s->ext_cache_file ? - (cur_entry->URL_s->SARCache ? xpSARCache : xpExtCache) : xpCache) : xpURL)) - { - if(cur_entry->URL_s->method == URL_PUT_METHOD) - { - con_data->next_state = NET_PUT_FILE; - return(0); - } - else if(cur_entry->URL_s->method == URL_MKDIR_METHOD) - { - con_data->next_state = NET_MAKE_DIRECTORY; - return(0); - } - - - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_LOCATE_FILE, - *con_data->filename ? con_data->filename : "/"); - return(MK_UNABLE_TO_LOCATE_FILE); - } - - if(!con_data->is_cache_file) - { - cur_entry->URL_s->last_modified = stat_entry.st_mtime; - } - - if(S_ISDIR(stat_entry.st_mode)) - { - /* if the current address doesn't end with a - * slash, add it now. - */ - if(cur_entry->URL_s->address[PL_strlen(cur_entry->URL_s->address)-1] != '/') - StrAllocCat(cur_entry->URL_s->address, "/"); - - cur_entry->URL_s->is_directory = TRUE; - con_data->is_dir = TRUE; - } - else - { - cur_entry->URL_s->content_length = (int32) stat_entry.st_size; - } - - if(con_data->is_cache_file) - { - /* if we are looking for a cache file then - * we are always looking to do a GET of - * the file regardless of the method in - * the URL_s - */ - con_data->next_state = NET_FILE_SETUP_STREAM; - } - else switch(cur_entry->URL_s->method) - { - case URL_PUT_METHOD: - { - char * msg; - msg = PR_smprintf("Overwrite file %s?", con_data->filename); - if(FE_Confirm(CE_WINDOW_ID, msg)) - con_data->next_state = NET_PUT_FILE; - else - con_data->next_state = NET_FILE_DONE; - } - break; - - case URL_MKDIR_METHOD: - /* error, can't create a directory over - * an existing file or directory - */ - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails( - MK_MKDIR_FILE_ALREADY_EXISTS, - con_data->filename); - return(MK_MKDIR_FILE_ALREADY_EXISTS); - - case URL_HEAD_METHOD: - /* we just need the relavent file info. - * it is currently filled into the URL struct - */ - con_data->next_state = NET_FILE_DONE; - break; - - case URL_MOVE_METHOD: - con_data->next_state = NET_MOVE_FILE; - break; - - case URL_DELETE_METHOD: - con_data->next_state = NET_DELETE_FILE; - break; - - case URL_GET_METHOD: - con_data->next_state = NET_FILE_SETUP_STREAM; - break; - - case URL_INDEX_METHOD: - if(!cur_entry->URL_s->is_directory) - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_NOT_A_DIRECTORY, con_data->filename); - return(MK_NOT_A_DIRECTORY); - } - con_data->next_state = NET_FILE_SETUP_STREAM; - break; - - default: - PR_ASSERT(0); - con_data->next_state = NET_FILE_DONE; - break; - } - - return(0); -} - -PRIVATE int -net_delete_file (ActiveEntry * ce) -{ -#ifndef LIVEWIRE - PR_ASSERT(0); - return(MK_OUT_OF_MEMORY); - -#else - FILEConData * cd = (FILEConData *) ce->con_data; - - TRACEMSG(("Deleteing file: %s", cd->filename)); - - if(cd->is_dir) - { - if(0 != XP_RemoveDirectory(cd->filename, xpURL)) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_DELETE_DIRECTORY, - cd->filename); - return(MK_UNABLE_TO_DELETE_DIRECTORY); - } - } - else - { - if(0 != NET_XP_FileRemove(cd->filename, xpURL)) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_DELETE_FILE, - cd->filename); - return(MK_UNABLE_TO_DELETE_FILE); - } - } - - /* success */ - cd->next_state = NET_FILE_DONE; - return(0); -#endif /* NOT LIVEWIRE */ -} - -PRIVATE int -net_move_file (ActiveEntry * ce) -{ -#ifndef LIVEWIRE - PR_ASSERT(0); - return(MK_OUT_OF_MEMORY); - -#else - FILEConData * cd = (FILEConData *) ce->con_data; - char *destination; - - PR_ASSERT(ce->URL_s->destination); - if(!ce->URL_s->destination) - return(MK_UNABLE_TO_LOCATE_FILE); - - destination = NET_ParseURL(ce->URL_s->destination, GET_PATH_PART); - - if(!destination) - return(MK_OUT_OF_MEMORY); - - TRACEMSG(("Moving file: %s", cd->filename)); - - if(0 != XP_FileRename(cd->filename, xpURL, destination, xpURL)) - { - /* error! */ - PR_ASSERT(0); - /* @@@@@ */ - return(MK_UNABLE_TO_LOCATE_FILE); - } - - /* success */ - cd->next_state = NET_FILE_DONE; - return(0); -#endif /* !LIVEWIRE */ -} - -PRIVATE int -net_put_file (ActiveEntry * ce) -{ -#ifndef LIVEWIRE - PR_ASSERT(0); - return(MK_OUT_OF_MEMORY); - -#else - FILEConData * cd = (FILEConData *) ce->con_data; - XP_File fp; - int status; - - if(!(fp = NET_XP_FileOpen(cd->filename, xpURL, XP_FILE_WRITE_BIN))) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_OPEN_FILE, - cd->filename); - return(MK_UNABLE_TO_OPEN_FILE); - } - - PR_ASSERT(ce->URL_s->post_data); - PR_ASSERT(!ce->URL_s->post_data_is_file); - - status = NET_XP_FileWrite(ce->URL_s->post_data, ce->URL_s->post_data_size, fp); - - NET_XP_FileClose(fp); - - if(status < ce->URL_s->post_data_size) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_FILE_WRITE_ERROR, - cd->filename); - return(MK_FILE_WRITE_ERROR); - } - - /* success */ - cd->next_state = NET_FILE_DONE; - return(0); -#endif /* !LIVEWIRE */ -} - -PRIVATE int -net_make_directory (ActiveEntry * ce) -{ -#ifndef LIVEWIRE - PR_ASSERT(0); - return(MK_OUT_OF_MEMORY); - -#else - FILEConData * cd = (FILEConData *) ce->con_data; - - if(0 != XP_MakeDirectory(cd->filename, xpURL)) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_COULD_NOT_CREATE_DIRECTORY, - cd->filename); - return(MK_COULD_NOT_CREATE_DIRECTORY); - } - - /* success */ - cd->next_state = NET_FILE_DONE; - return (0); -#endif /* !LIVEWIRE */ -} - -/* setup the output stream - */ -PRIVATE int -net_file_setup_stream(ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - - if(con_data->is_dir) - { - char * pUrl ; - int status; - - status = PREF_CopyCharPref("protocol.mimefor.file",&pUrl); - - if (status >= 0 && pUrl) { - StrAllocCopy(cur_entry->URL_s->content_type, pUrl); - PR_Free(pUrl); - } else { - StrAllocCopy(cur_entry->URL_s->content_type, APPLICATION_HTTP_INDEX); - } - - con_data->stream = NET_StreamBuilder(CE_FORMAT_OUT, cur_entry->URL_s, CE_WINDOW_ID); - - if(!con_data->stream) - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return(MK_UNABLE_TO_CONVERT); - } - -#ifdef MOZILLA_CLIENT - GH_UpdateGlobalHistory(cur_entry->URL_s); -#endif /* MOZILLA_CLIENT */ - - con_data->next_state = NET_OPEN_DIRECTORY; - } - else - { - /* - * don't open the stream yet for files - */ - con_data->next_state = NET_OPEN_FILE; - } - - return(0); /* OK */ -} - -PRIVATE int -net_open_file (ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - - TRACEMSG(("MKFILE: Trying to open: %s\n",con_data->filename)); - - if((con_data->file_ptr = NET_XP_FileOpen(con_data->filename, - (con_data->is_cache_file ? - (cur_entry->URL_s->ext_cache_file ? - (cur_entry->URL_s->SARCache ? xpSARCache : xpExtCache) : xpCache) : xpURL), - XP_FILE_READ_BIN)) != NULL) - { - con_data->next_state = NET_READ_FILE_CHUNK; - } - else - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_OPEN_FILE, - con_data->filename); - - /* if errno is equal to "Too many open files" - * return a special error - */ -#ifdef EMFILE /* Mac doesn't have EMFILE. */ - if(errno == EMFILE) - return(MK_TOO_MANY_OPEN_FILES); - else -#endif - return(MK_UNABLE_TO_OPEN_FILE); - } - -#if defined(SMOOTH_PROGRESS) - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_PROGRESS_READFILE)); -#else - if (!cur_entry->URL_s->load_background) - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_READFILE)); -#endif - - /* CE_SOCK = XP_Fileno(con_data->file_ptr); */ - CE_SOCK = NULL; - cur_entry->local_file = TRUE; - NET_SetFileReadSelect(CE_WINDOW_ID, NET_XP_Fileno(con_data->file_ptr)); - - /* @@@ now that we have determined that it is a local file - * set URL_s->cache_file so that the streams think - * that this file came from the cache - */ - StrAllocCopy(cur_entry->URL_s->cache_file, con_data->filename); - - con_data->pause_for_read = TRUE; - - con_data->next_state = NET_SETUP_FILE_STREAM; - -#if defined(SMOOTH_PROGRESS) - PM_Progress(cur_entry->window_id, - cur_entry->URL_s, - 0, - cur_entry->URL_s->content_length); -#else - if (!cur_entry->URL_s->load_background) { - FE_GraphProgressInit(CE_WINDOW_ID, cur_entry->URL_s, cur_entry->URL_s->content_length); - CD_DESTROY_GRAPH_PROGRESS = TRUE; /* we will need to destroy it */ - } -#endif - CD_ORIGINAL_CONTENT_LENGTH = cur_entry->URL_s->content_length; - - return(0); /* ok */ -} - - -#ifdef MOZILLA_CLIENT -#ifdef OLD_MOZ_MAIL_NEWS -extern int net_InitializeNewsFeData (ActiveEntry * cur_entry); -extern int IMAP_InitializeImapFeData (ActiveEntry * cur_entry); -#endif /* OLD_MOZ_MAIL_NEWS */ -#endif /* MOZILLA_CLIENT */ - -PRIVATE int -net_setup_file_stream (ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - int32 count; - - /* set up the stream now - */ - TRACEMSG(("Trying to look at content type: %s",cur_entry->URL_s->content_type)); - if(!cur_entry->URL_s->content_type) - { - int img_type; - - /* read the first chunk of the file - */ - count = NET_XP_FileRead(NET_Socket_Buffer, NET_Socket_Buffer_Size, con_data->file_ptr); - - if(!count) - { - NET_ClearFileReadSelect(CE_WINDOW_ID, NET_XP_Fileno(con_data->file_ptr)); -#if defined(SMOOTH_PROGRESS) - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_PROGRESS_FILEZEROLENGTH)); -#else - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_FILEZEROLENGTH)); -#endif - NET_XP_FileClose(con_data->file_ptr); - CE_SOCK = NULL; - con_data->file_ptr = 0; - con_data->next_state = NET_FILE_ERROR_DONE; - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_ZERO_LENGTH_FILE, - con_data->filename); - return(MK_ZERO_LENGTH_FILE); - } - -#ifdef MOZILLA_CLIENT - img_type = IL_Type(NET_Socket_Buffer, count); - if (img_type && img_type != IL_NOTFOUND) - { - switch(img_type) - { - case IL_GIF: - StrAllocCopy(cur_entry->URL_s->content_type, IMAGE_GIF); - break; - case IL_XBM: - StrAllocCopy(cur_entry->URL_s->content_type, IMAGE_XBM); - break; - case IL_JPEG: - StrAllocCopy(cur_entry->URL_s->content_type, IMAGE_JPG); - break; - case IL_PNG: - StrAllocCopy(cur_entry->URL_s->content_type, IMAGE_PNG); - break; - - case IL_PPM: - StrAllocCopy(cur_entry->URL_s->content_type, IMAGE_PPM); - break; - default: - assert(0); /* should NEVER get this!! */ - break; - } - - } - else -#endif /* MOZILLA_CLIENT */ - { -#if defined(XP_MAC) - char * macType, *macEncoding; - Bool useDefault; - - FE_FileType(cur_entry->URL_s->address, &useDefault, &macType, &macEncoding); - if (useDefault) - { -#endif - NET_cinfo * type = NET_cinfo_find_type(cur_entry->URL_s->address); - NET_cinfo * enc = NET_cinfo_find_enc(cur_entry->URL_s->address); - -#if defined(XP_MAC) - if (macType) - PR_Free(macType); -#endif - - StrAllocCopy(cur_entry->URL_s->content_type, type->type); - StrAllocCopy(cur_entry->URL_s->content_encoding, enc->encoding); - - - if(type->is_default && NET_ContainsHTML(NET_Socket_Buffer, count)) - StrAllocCopy(cur_entry->URL_s->content_type, TEXT_HTML); - -#if defined(XP_MAC) - } - else - { - cur_entry->URL_s->content_type = macType; - cur_entry->URL_s->content_encoding = macEncoding; - } -#endif - } - } - - CD_RANGE_LENGTH = 0; - CE_BYTES_RECEIVED = 0; - - /* check to see if we need to do a byterange here - * If we are then set the ranges in the URL - * so that the streams know the byte range. - * Once we parse one byterange copy - */ - if(CD_BYTERANGE_STRING && *CD_BYTERANGE_STRING) - { - int32 low=0, high=0; - char *cp, *dash; - - cp = PL_strchr(CD_BYTERANGE_STRING, ','); - if(cp) - *cp = '\0'; - - dash = PL_strchr(CD_BYTERANGE_STRING, '-'); - - if(!dash) - { - /* no dash is an invalid byte range - * return zero and we will come back - * in here and give the whole file or - * the next byterange - */ - return(0); - } - else - { - *dash = '\0'; - - if(CD_BYTERANGE_STRING == dash) - low = -1; - else - low = atol(CD_BYTERANGE_STRING); - high = atol(dash+1); - } - - - if(low < 0 && high < 1) - { - /* if both low and high are non-positive - * it's an error - */ - return(0); - } - else if(low < 0) - { - /* This is a byte range that specifies - * the last bytes of a file. For - * instance http://host/dir/foo;byterange=-500 - */ - low = cur_entry->URL_s->content_length-(atoi(CD_BYTERANGE_STRING+1)); - high = cur_entry->URL_s->content_length; - } - else if(high < 1) - { - /* This is a byte range that specifies - * the a byte range from a specified point - * till the end of the file. For - * instance http://host/dir/foo;byterange=500- - */ - high = cur_entry->URL_s->content_length; - } - - if(low >= cur_entry->URL_s->content_length) - { - /* error to have the low byte range be larger than - * the file - */ - return(0); - } - else if(high >= cur_entry->URL_s->content_length) - { - high = cur_entry->URL_s->content_length; - } - - cur_entry->URL_s->low_range = low; - cur_entry->URL_s->high_range = high; - - CD_RANGE_LENGTH = (high-low)+1; - - if(cp) - memcpy(CD_BYTERANGE_STRING, cp+1, PL_strlen(cp+1)+1); - else - CD_BYTERANGE_STRING = 0; - } - - if (CLEAR_CACHE_BIT(CE_FORMAT_OUT) == FO_PRESENT) - { - if (NET_URL_Type(cur_entry->URL_s->address) == NEWS_TYPE_URL) - { -#ifdef MOZILLA_CLIENT -#ifdef OLD_MOZ_MAIL_NEWS - /* #### DISGUSTING KLUDGE to make cacheing work for news articles. */ - CE_STATUS = net_InitializeNewsFeData (cur_entry); - if (CE_STATUS < 0) - { - /* #### what error message? */ - return CE_STATUS; - } -#endif /* OLD_MOZ_MAIL_NEWS */ -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } - else if (!PL_strncmp(cur_entry->URL_s->address, "IMAP://", 7)) - { -#ifdef MOZILLA_CLIENT -#ifdef OLD_MOZ_MAIL_NEWS - /* #### DISGUSTING KLUDGE to make cacheing work for imap articles. */ - CE_STATUS = IMAP_InitializeImapFeData (cur_entry); - if (CE_STATUS < 0) - { - /* #### what error message? */ - return CE_STATUS; - } -#endif /* OLD_MOZ_MAIL_NEWS */ -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } - } - - con_data->stream = NET_StreamBuilder(CE_FORMAT_OUT, cur_entry->URL_s, CE_WINDOW_ID); - - if(!con_data->stream) - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return(MK_UNABLE_TO_CONVERT); - } - -#ifdef MOZILLA_CLIENT - GH_UpdateGlobalHistory(cur_entry->URL_s); -#endif /* MOZILLA_CLIENT */ - - /* seek back to the beginning so that - * we are not forced to write out this - * first block without calling is_write_ready - * - * this also seeks to the beginning of the range that we - * are going to send - */ - NET_XP_FileSeek(con_data->file_ptr, cur_entry->URL_s->low_range, SEEK_SET); - - con_data->next_state = NET_READ_FILE_CHUNK; - con_data->pause_for_read = TRUE; - - return(CE_STATUS); /* ok */ -} - -PRIVATE int -net_open_directory (ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; -#ifdef XP_WIN - char *tmpDirName = NULL; -#endif - - TRACEMSG(("Trying to open directory: %s", con_data->filename)); - -#ifdef XP_WIN - /* nspr doesn't like our preceeding slash. */ - tmpDirName = (char*) PR_Malloc(PL_strlen(con_data->filename)); - if (!tmpDirName) - return MK_UNABLE_TO_OPEN_FILE; - PL_strcpy(tmpDirName, con_data->filename + 1); - - if((con_data->dir_ptr = PR_OpenDir (tmpDirName)) != NULL) -#else - if((con_data->dir_ptr = PR_OpenDir (con_data->filename)) != NULL) -#endif - { - con_data->next_state = NET_READ_DIRECTORY_CHUNK; - } - else - { -#ifdef XP_WIN - PR_Free(tmpDirName); -#endif - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_OPEN_FILE, - con_data->filename); - return(MK_UNABLE_TO_OPEN_FILE); - } -#ifdef XP_WIN - PR_Free(tmpDirName); -#endif - - con_data->is_dir = TRUE; - -#if defined(SMOOTH_PROGRESS) - PM_Progress(cur_entry->window_id, - cur_entry->URL_s, - 0, - cur_entry->URL_s->content_length); - - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_PROGRESS_READDIR)); -#else - FE_GraphProgressInit(CE_WINDOW_ID, cur_entry->URL_s, cur_entry->URL_s->content_length); - CD_DESTROY_GRAPH_PROGRESS = TRUE; /* we will need to destroy it */ - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_READDIR)); -#endif - CD_ORIGINAL_CONTENT_LENGTH = cur_entry->URL_s->content_length; - - /* make sure the last character isn't a slash - */ - if(con_data->filename[PL_strlen(con_data->filename)-1] == '/') - con_data->filename[PL_strlen(con_data->filename)-1] = '\0'; - - return(0); /* ok */ -} - -/* read part of a file and push it out the stream - */ -PRIVATE int -net_read_file_chunk(ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - int count; - int32 read_size = IS_WRITE_READY; - - /* If the stream sink doesn't want any data yet, do nothing. */ - if (read_size == 0) - { - con_data->pause_for_read = TRUE; - return NET_READ_FILE_CHUNK; - } - - read_size = MIN(read_size, NET_Socket_Buffer_Size); - - if(CD_RANGE_LENGTH) - read_size = MIN(read_size, CD_RANGE_LENGTH-CE_BYTES_RECEIVED); - - count = NET_XP_FileRead(NET_Socket_Buffer, read_size, con_data->file_ptr); - - if(count < 1 || (CD_RANGE_LENGTH && CE_BYTES_RECEIVED >= CD_RANGE_LENGTH)) - { - if(cur_entry->URL_s->real_content_length > cur_entry->URL_s->content_length) - { - /* this is a case of a partial cache file. - * we need to fall out of here and - * get the rest of the file from the - * network - */ - cur_entry->save_stream = con_data->stream; - con_data->stream = NULL; - NET_ClearFileReadSelect(CE_WINDOW_ID, NET_XP_Fileno(con_data->file_ptr)); -#if defined(SMOOTH_PROGRESS) - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_PROGRESS_FILEDONE)); -#else - if (!cur_entry->URL_s->load_background) - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_FILEDONE)); -#endif - NET_XP_FileClose(con_data->file_ptr); - CE_SOCK = NULL; - con_data->file_ptr = 0; - con_data->next_state = NET_FILE_FREE; - return(MK_GET_REST_OF_PARTIAL_FILE_FROM_NETWORK); - } - else if(CD_BYTERANGE_STRING && *CD_BYTERANGE_STRING) - { - /* go get more byte ranges */ - COMPLETE_STREAM; - con_data->next_state = NET_SETUP_FILE_STREAM; -#if defined(SMOOTH_PROGRESS) - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_READING_SEGMENT)); -#else - if (!cur_entry->URL_s->load_background) - NET_Progress(CE_WINDOW_ID, XP_GetString( XP_READING_SEGMENT ) ); -#endif - return(0); - } - - NET_ClearFileReadSelect(CE_WINDOW_ID, NET_XP_Fileno(con_data->file_ptr)); -#if defined(SMOOTH_PROGRESS) - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_PROGRESS_FILEDONE)); -#else - if (!cur_entry->URL_s->load_background) - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_FILEDONE)); -#endif - NET_XP_FileClose(con_data->file_ptr); - CE_SOCK = NULL; - con_data->file_ptr = 0; - con_data->next_state = NET_FILE_DONE; - return(MK_DATA_LOADED); - } - - CE_BYTES_RECEIVED += count; - - CE_STATUS = PUTB(NET_Socket_Buffer, count); - -#if defined(SMOOTH_PROGRESS) - PM_Progress(cur_entry->window_id, - cur_entry->URL_s, - cur_entry->bytes_received, - cur_entry->URL_s->content_length); -#else - if (!cur_entry->URL_s->load_background) - FE_GraphProgress(CE_WINDOW_ID, cur_entry->URL_s, CE_BYTES_RECEIVED, count, - cur_entry->URL_s->content_length); -#endif - - con_data->pause_for_read = TRUE; - - return(CE_STATUS); -} - -PRIVATE int -net_read_directory_chunk (ActiveEntry * cur_entry) -{ - - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - NET_FileEntryInfo * file_entry; - PRDirEntry * dir_entry; - PRFileInfo stat_entry; - char *full_path=0; - int32 len; - - con_data->sort_base = NET_SortInit(); - - while((dir_entry = PR_ReadDir(con_data->dir_ptr, PR_SKIP_BOTH)) != 0) - { - file_entry = NET_CreateFileEntryInfoStruct(); - if(!file_entry) - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - /* escape and copy - */ - file_entry->filename = NET_Escape(dir_entry->name, URL_PATH); - - /* make a full path */ - len = PL_strlen(con_data->filename) + PL_strlen(dir_entry->name) + 30; - PR_FREEIF(full_path); - full_path = (char *)PR_Malloc(len*sizeof(char)); - - if(!full_path) - return(MK_OUT_OF_MEMORY); - - PL_strcpy(full_path, con_data->filename + 1); - PL_strcat(full_path, "/"); - PL_strcat(full_path, dir_entry->name); - memset(&stat_entry, 0, sizeof(PRFileInfo)); /* paranoia */ - - if(PR_GetFileInfo(full_path, &stat_entry) == PR_SUCCESS) - { - PRInt64 r, u; - TRACEMSG(("Found stat info for file %s\n",full_path)); - - if(PR_FILE_DIRECTORY == stat_entry.type) - { -#if 0 /* Hoping this is not an issue with PR routines :). */ -#ifdef XP_MAC - stat_entry.st_size = 0; /* Mac stat gives spurious size data for folders */ -#endif -#endif - file_entry->special_type = NET_DIRECTORY; - StrAllocCat(file_entry->filename, "/"); - } - else - { - file_entry->cinfo = NET_cinfo_find_type(file_entry->filename); - } - - file_entry->size = (int32) stat_entry.size; - - /* Convert the PRTime (64-bit int) into a time_t (32 bit int) */ - LL_I2L(u, PR_USEC_PER_SEC); - LL_DIV(r, stat_entry.modifyTime, u); - LL_L2I(file_entry->date, r); - - if (file_entry->date < 0) { - file_entry->date = 0; - } - - TRACEMSG(("Got file: %s, %ld",file_entry->filename, file_entry->size)); - - NET_SortAdd(con_data->sort_base, file_entry); - } - } - - PR_FREEIF(full_path); - -#if defined(SMOOTH_PROGRESS) - PM_Status(cur_entry->window_id, - cur_entry->URL_s, - XP_GetString(XP_PROGRESS_DIRDONE)); -#else - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_DIRDONE)); -#endif - - PR_CloseDir(con_data->dir_ptr); - con_data->dir_ptr = 0; - - con_data->next_state = NET_BEGIN_PRINT_DIRECTORY; - - return(0); -} - -/* emit application/http-index-format */ -PRIVATE int -net_BeginPrintDirectory(ActiveEntry * ce) -{ - FILEConData * cd = (FILEConData *) ce->con_data; - - cd->next_state = NET_PRINT_DIRECTORY; - - return(ce->status); -} - -/* if the url is a local file this function returns - * the portion of the url that represents the - * file path as a malloc'd string. If the - * url is not a local file url this function - * returns NULL - */ -PRIVATE char * -net_return_local_file_part_from_url(char *address) -{ - char *host; -#ifdef XP_WIN - char *new_address; - char *rv; -#endif - - if (address == NULL) - return NULL; - - /* imap urls are never local */ - if (!PL_strncasecmp(address,"IMAP://",7)) - return NULL; - - /* mailbox url's are always local, but don't always point to a file */ - if(!PL_strncasecmp(address, "mailbox:", 8)) - { - char *filename = NET_ParseURL(address, GET_PATH_PART); - if (!filename) - filename = PL_strdup(""); - return filename; - } - - if(PL_strncasecmp(address, "file:", 5)) - return(NULL); - - host = NET_ParseURL(address, GET_HOST_PART); - - if(!host || *host == '\0' || !PL_strcasecmp(host, "LOCALHOST")) - { - PR_FREEIF(host); - return(NET_UnEscape(NET_ParseURL(address, GET_PATH_PART))); - } - -#ifdef XP_WIN - /* get the address minus the search and hash data */ - new_address = NET_ParseURL(address, - GET_PROTOCOL_PART | GET_HOST_PART | GET_PATH_PART); - NET_UnEscape(new_address); - - /* check for local drives as hostnames - */ - if(PL_strlen(host) == 2 - && isalpha(host[0]) - && (host[1] == '|' || host[1] == ':')) - { - PR_Free(host); - /* skip "file:/" */ - rv = PL_strdup(new_address+6); - PR_Free(new_address); - return(rv); - } - - if(1) - { - XP_StatStruct stat_entry; - /* try stating the url just in case since - * the local file system can - * have url's of the form \\prydain\dist - */ - if(-1 != NET_XP_Stat(address+5, &stat_entry, xpURL)) - { - PR_Free(host); - /* skip "file:" */ - rv = PL_strdup(address+5); - PR_Free(new_address); - return(rv); - } - } -#endif /* XP_WIN */ - - PR_Free(host); - - return(NULL); -} - -/* load local files and - * display directories - * - * if cache_file is not null then we this module is being used to - * read a localy cached url. Use the passed in cache_file variable - * as the location of the file and use the URL->address as the - * URL for StreamBuilding etc. - */ -PRIVATE int32 -net_FileLoad (ActiveEntry * cur_entry) -{ - char * cp; - FILEConData * con_data; - - NET_SetCallNetlibAllTheTime(CE_WINDOW_ID, "mkfile"); - - /* make space for the connection data */ - cur_entry->con_data = PR_NEW(FILEConData); - if(!cur_entry->con_data) - { - FE_Alert(CE_WINDOW_ID, XP_GetString(XP_ALERT_OUTMEMORY)); - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - CE_STATUS = MK_OUT_OF_MEMORY; - return(CE_STATUS); - } - - /* zero out the structure - */ - memset(cur_entry->con_data, 0, sizeof(FILEConData)); - - /* set this to make the CD_ macros work */ - con_data = cur_entry->con_data; - - if(!cur_entry->URL_s->cache_file) - { - char *path; - - if(!(path = net_return_local_file_part_from_url(cur_entry->URL_s->address))) - { - PR_Free(cur_entry->con_data); - cur_entry->con_data = 0; - return(MK_USE_FTP_INSTEAD); /* use ftp */ - } - - con_data->filename = path; - } - else - { - StrAllocCopy(con_data->filename, cur_entry->URL_s->cache_file); - con_data->is_cache_file = TRUE; - } - - TRACEMSG(("Load File: looking for file: %s\n",con_data->filename)); - - /* don't cache local files or local directory listings - * if we are only looking to cache this file fail now - */ - if(cur_entry->format_out == FO_CACHE_ONLY) - return -1; - cur_entry->format_out = CLEAR_CACHE_BIT(cur_entry->format_out); - - /* all non-cache filenames must begin with slash - */ - if(!con_data->is_cache_file == TRUE && *con_data->filename != '/') - { - cur_entry->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_LOCATE_FILE, - *con_data->filename ? con_data->filename : "/"); - CE_STATUS = MK_UNABLE_TO_LOCATE_FILE; - return(MK_UNABLE_TO_LOCATE_FILE); - } - -#define BYTERANGE_TOKEN "bytes=" - -#ifdef URL_BYTERANGE_METHOD - /* if the URL has ";bytes=" in it then it - * is a special partial byterange url. - * Parse out the byterange part and store it - * away - */ -#define URL_BYTERANGE_TOKEN ";"BYTERANGE_TOKEN - if (con_data->is_cache_file && (cp = PL_strcasestr(cur_entry->URL_s->address, URL_BYTERANGE_TOKEN)) != NULL) - { - StrAllocCopy(CD_BYTERANGE_STRING, cp+PL_strlen(URL_BYTERANGE_TOKEN)); - strtok(CD_BYTERANGE_STRING, ";"); - } - else if ((cp = PL_strcasestr(con_data->filename, URL_BYTERANGE_TOKEN)) != NULL) - { - *cp = '\0'; - /* remove any other weird ; stuff */ - strtok(cp+1, ";"); - StrAllocCopy(CD_BYTERANGE_STRING, cp+PL_strlen(URL_BYTERANGE_TOKEN)); - } -#endif /* URL_BYTERANGE_METHOD */ - - /* this is the byterange header method. - * both the URL byterange and the header - * byterange methods can coexist peacefully - */ - if(cur_entry->URL_s->range_header && !PL_strncmp(cur_entry->URL_s->range_header, BYTERANGE_TOKEN, PL_strlen(BYTERANGE_TOKEN))) - { - StrAllocCopy(CD_BYTERANGE_STRING, cur_entry->URL_s->range_header+PL_strlen(BYTERANGE_TOKEN)); - } - - /* lets do a local file read - */ - cur_entry->local_file = TRUE; /* se we don't select on the socket id */ - - con_data->next_state = NET_CHECK_FILE_TYPE; - - return(net_ProcessFile(cur_entry)); -} - -PRIVATE int32 -net_ProcessFile (ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *) cur_entry->con_data; - - TRACEMSG(("Entering ProcessFile with state #%d\n",con_data->next_state)); - - con_data->pause_for_read = FALSE; - - while(!con_data->pause_for_read) - { - - switch (con_data->next_state) - { - case NET_CHECK_FILE_TYPE: - CE_STATUS = net_check_file_type(cur_entry); - break; - - case NET_DELETE_FILE: - CE_STATUS = net_delete_file(cur_entry); - break; - - case NET_PUT_FILE: - CE_STATUS = net_put_file(cur_entry); - break; - - case NET_MOVE_FILE: - CE_STATUS = net_move_file(cur_entry); - break; - - case NET_MAKE_DIRECTORY: - CE_STATUS = net_make_directory(cur_entry); - break; - - case NET_FILE_SETUP_STREAM: - CE_STATUS = net_file_setup_stream(cur_entry); - break; - - case NET_OPEN_FILE: - CE_STATUS = net_open_file(cur_entry); - break; - - case NET_SETUP_FILE_STREAM: - CE_STATUS = net_setup_file_stream(cur_entry); - break; - - case NET_OPEN_DIRECTORY: - CE_STATUS = net_open_directory(cur_entry); - break; - - case NET_READ_FILE_CHUNK: - CE_STATUS = net_read_file_chunk(cur_entry); - break; - - case NET_READ_DIRECTORY_CHUNK: - CE_STATUS = net_read_directory_chunk(cur_entry); - break; - - case NET_BEGIN_PRINT_DIRECTORY: - CE_STATUS = net_BeginPrintDirectory(cur_entry); - break; - - case NET_PRINT_DIRECTORY: - if((*con_data->stream->is_write_ready)(con_data->stream)) - { - CE_STATUS = NET_PrintDirectory(&con_data->sort_base, con_data->stream, con_data->filename, cur_entry->URL_s); - con_data->next_state = NET_FILE_DONE; - } - else - { - /* come back into this state */ - if(!con_data->calling_netlib_all_the_time) - { - con_data->calling_netlib_all_the_time = TRUE; - NET_SetCallNetlibAllTheTime(CE_WINDOW_ID, "mkfile"); - } - cur_entry->memory_file = TRUE; - cur_entry->socket = NULL; - con_data->pause_for_read = TRUE; - } - break; - - case NET_FILE_DONE: - if(con_data->stream) - COMPLETE_STREAM; -#if defined(SMOOTH_PROGRESS) - PM_StopBinding(cur_entry->window_id, cur_entry->URL_s, 0, NULL); -#endif - con_data->next_state = NET_FILE_FREE; -#ifdef TRUST_LABELS - ProcessCookiesAndTrustLabels( cur_entry ); -#endif - break; - - case NET_FILE_ERROR_DONE: - if(con_data->stream) - ABORT_STREAM(CE_STATUS); - if(con_data->dir_ptr) - PR_CloseDir(con_data->dir_ptr); - if(con_data->file_ptr) - { - CE_SOCK = NULL; - NET_ClearFileReadSelect(CE_WINDOW_ID, NET_XP_Fileno(con_data->file_ptr)); - NET_XP_FileClose(con_data->file_ptr); - } -#if defined(SMOOTH_PROGRESS) - PM_StopBinding(cur_entry->window_id, cur_entry->URL_s, -1, NULL); -#endif - con_data->next_state = NET_FILE_FREE; - break; - - case NET_FILE_FREE: - if(con_data->calling_netlib_all_the_time) - { - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkfile"); - con_data->calling_netlib_all_the_time = FALSE; - } - -#if !defined(SMOOTH_PROGRESS) - if(CD_DESTROY_GRAPH_PROGRESS) - FE_GraphProgressDestroy(CE_WINDOW_ID, - cur_entry->URL_s, - CD_ORIGINAL_CONTENT_LENGTH, - CE_BYTES_RECEIVED); -#endif - PR_Free(con_data->filename); - PR_FREEIF(con_data->stream); - PR_Free(cur_entry->con_data); - - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mkfile"); - - return(-1); /* done */ - } - - if(CE_STATUS < 0 && con_data->next_state != NET_FILE_FREE) - { - con_data->pause_for_read = FALSE; - con_data->next_state = NET_FILE_ERROR_DONE; - } - - } - - return(0); /* keep going */ -} - -PRIVATE int32 -net_InterruptFile(ActiveEntry * cur_entry) -{ - FILEConData * con_data = (FILEConData *)cur_entry->con_data; - - con_data->next_state = NET_FILE_ERROR_DONE; - CE_STATUS = MK_INTERRUPTED; - - return(net_ProcessFile(cur_entry)); -} - -PRIVATE void -net_CleanupFile(void) -{ - return; -} - -typedef struct { - HTTPIndexParserData *parse_data; - MWContext *context; - int format_out; - URL_Struct *URL_s; -} index_format_conv_data_object; - -PRIVATE int net_IdxConvPut(NET_StreamClass *stream, char *s, int32 l) -{ - index_format_conv_data_object *obj=stream->data_object; - return(NET_HTTPIndexParserPut(obj->parse_data, s, l)); -} - -PRIVATE int net_IdxConvWriteReady(NET_StreamClass *stream) -{ - return(MAX_WRITE_READY); -} - -#define PD_PUTS(s) \ -do { \ -if(status > -1) \ - status = (*stream->put_block)(stream, s, PL_strlen(s)); \ -} while(0) - -/* take the parsed data and generate HTML */ -PRIVATE void net_IdxConvComplete(NET_StreamClass *inputStream) -{ - index_format_conv_data_object *obj=inputStream->data_object; - int32 num_files = NET_HTTPIndexParserGetTotalFiles(obj->parse_data); - NET_FileEntryInfo * file_entry; - int32 max_name_length, i, status = 0, window_width, len; - char out_buf[3096], *name, *date, *ptr; - NET_StreamClass *stream; - NET_cinfo * cinfo; - char *base_url=NULL, *path=NULL; - - /* direct the stream to the html parser */ - StrAllocCopy(obj->URL_s->content_type, TEXT_HTML); - - stream = NET_StreamBuilder(obj->format_out, - obj->URL_s, - obj->context); - if(!stream) - goto cleanup; - - /* Ask layout how wide the window is in the <PRE> font, to decide - how much space we should allocate for the file name column. */ -# define LISTING_OVERHEAD 51 -#ifdef MOZILLA_CLIENT - window_width = LO_WindowWidthInFixedChars (obj->context); -#else - window_width = 80; -#endif /* MOZILLA_CLIENT */ - - max_name_length = (window_width - LISTING_OVERHEAD); - if (max_name_length < 12) /* 8.3 */ - max_name_length = 12; - else if (max_name_length > 50) - max_name_length = 50; - - /* the the base url and path */ - if((base_url = NET_HTTPIndexParserGetBaseURL(obj->parse_data)) != NULL) - { - path = NET_ParseURL(base_url, GET_PATH_PART); - - if (path && path != '\0') /* Not Empty path: */ - { - int end; - NET_UnEscape(path); - - end = PL_strlen(path)-1; - /* if the path ends with a slash kill it. - * that includes the path "/" - */ - if(path[end] == '/') - { - path[end] = 0; /* kill the last slash */ - } - - /* output "directory of ..." message */ - PR_snprintf(out_buf, sizeof(out_buf), - XP_GetString( XP_TITLE_DIRECTORY_OF_ETC ), - *path ? path : "/", *path ? path : "/"); - PD_PUTS(out_buf); - } - } - - if(NET_HTTPIndexParserGetHTMLMessage(obj->parse_data)) - { - PL_strcpy(out_buf, CRLF"<HR>"CRLF); - PD_PUTS(out_buf); - - PD_PUTS(NET_HTTPIndexParserGetHTMLMessage(obj->parse_data)); - - if(!NET_HTTPIndexParserGetTextMessage(obj->parse_data)) - { - PL_strcpy(out_buf, CRLF"<HR>"CRLF); - PD_PUTS(out_buf); - } - } - - if(NET_HTTPIndexParserGetTextMessage(obj->parse_data)) - { - char *msg; - - PL_strcpy(out_buf, "<HR>"); - PD_PUTS(out_buf); - - msg = NET_HTTPIndexParserGetTextMessage(obj->parse_data); - - status = NET_ScanForURLs (NULL, msg, - PL_strlen(msg), - out_buf, sizeof(out_buf), - TRUE); - PD_PUTS(out_buf); - - PL_strcpy(out_buf, "<HR>"); - PD_PUTS(out_buf); - } - - /* allow the user to go up if path is not empty - */ - if(path && *path != '\0') - { - char *cp = PL_strrchr(path, '/'); - PL_strcpy(out_buf, "<A HREF=\""); - PD_PUTS(out_buf); - if(cp) - { - *cp = '\0'; - PD_PUTS(path); - *cp = '/'; - PL_strcpy(out_buf, "/"); - PD_PUTS(out_buf); - } - PL_strncpyz(out_buf, - XP_GetString(XP_UPTO_HIGHER_LEVEL_DIRECTORY), - sizeof(out_buf)); - PD_PUTS(out_buf); - } - - for(i=0; i < num_files; i++) - { - - file_entry = NET_HTTPIndexParserGetFileNum(obj->parse_data, i); - - if(!file_entry) - continue; - - if(!file_entry->date) - { - PR_snprintf(out_buf, sizeof(out_buf), " <A HREF=\"%s\">", - file_entry->filename); - PD_PUTS(out_buf); /* output the line */ - - PR_snprintf(out_buf, sizeof(out_buf), "%s</A>\n", - NET_UnEscape(file_entry->filename)); - PD_PUTS(out_buf); /* output the line */ - } - else - { - int max_size_for_this_name; - - date = ctime(&file_entry->date); - if(date) - date[24] = '\0'; /* strip return */ - else - date = ""; - - PR_snprintf(out_buf, sizeof(out_buf), " <A HREF=\"%s\">", - file_entry->filename); - PD_PUTS(out_buf); /* output the line */ - - /* do content_type icon stuff here */ - cinfo = NET_cinfo_find_info_by_type(file_entry->content_type); - - if(file_entry->special_type == NET_DIRECTORY - || file_entry->special_type == NET_SYM_LINK - || file_entry->special_type == NET_SYM_LINK_TO_DIR - || file_entry->special_type == NET_SYM_LINK_TO_FILE) - { - PR_snprintf(out_buf, - sizeof(out_buf), - "<IMG ALIGN=absbottom " - "BORDER=0 SRC=\"resource:/res/network/gopher-menu.gif\">"); - } - else if(cinfo && cinfo->icon) - { - PR_snprintf(out_buf, sizeof(out_buf), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"%.512s\">", - cinfo->icon); - } - else - { - PR_snprintf(out_buf, - sizeof(out_buf), - "<IMG ALIGN=absbottom BORDER=0 " - "SRC=\"resource:/res/network/gopher-unknown.gif\">"); - } - - PD_PUTS(out_buf); /* output the line */ - -#define SIZE_LISTING_OVERHEAD 9 - - /* print the filename - */ - name = NET_UnEscape (file_entry->filename); - len = PL_strlen (name); - max_size_for_this_name = max_name_length; - if(!file_entry->size) - max_size_for_this_name += SIZE_LISTING_OVERHEAD; - - if(len > max_size_for_this_name) - { - PL_strcpy (out_buf, " "); - memcpy (out_buf + 1, name, max_name_length - 3); - PL_strcpy (out_buf + 1 + max_name_length - 3, "...</A>"); - } - else - { - PL_strcpy (out_buf, " "); - PL_strcat (out_buf, name); - PL_strcat (out_buf, "</A>"); - } - PD_PUTS(out_buf); /* output the line */ - - /* put a standard number of spaces between the name and date - */ - for(ptr = out_buf; len < max_size_for_this_name; len++) - { - *ptr++ = ' '; - } - *ptr = '\0'; - - /* start from the end of out_buf - * - * note: add 4 to the date to get rid of the day of the week - */ - if(file_entry->size -#ifdef XP_MAC - || file_entry->special_type == NET_FILE_TYPE /* show size for zero-length files */ -#endif - ) - { - PR_snprintf(&out_buf[PL_strlen(out_buf)], - sizeof(out_buf) - PL_strlen(out_buf), - " %5ld %s %s ", - file_entry->size > 1024 ? - file_entry->size/1024 : file_entry->size, - file_entry->size > 1024 ? "Kb" : " b", - date+4); - } - else - { - PR_snprintf(&out_buf[PL_strlen(out_buf)], - sizeof(out_buf) - PL_strlen(out_buf), - " %s ", date+4); - } - - PD_PUTS(out_buf); /* output the line */ - - if(file_entry->special_type == NET_SYM_LINK - || file_entry->special_type == NET_SYM_LINK_TO_DIR - || file_entry->special_type == NET_SYM_LINK_TO_FILE) - { - PR_snprintf(out_buf, sizeof(out_buf), "Symbolic link\n"); - } - else if(file_entry->special_type == NET_DIRECTORY) - { - PR_snprintf(out_buf, sizeof(out_buf), "Directory\n"); - } - else if(cinfo && cinfo->desc) - { - PR_snprintf(out_buf, - sizeof(out_buf)-1, - "%s", - cinfo->desc); - PL_strcat(out_buf, "\n"); - } - else - { - PL_strcpy(out_buf, "\n"); - } - - PD_PUTS(out_buf); - } - } - - PL_strcpy(out_buf, "\n</PRE>"); - PD_PUTS(out_buf); - -cleanup: - NET_HTTPIndexParserFree(obj->parse_data); - PR_FREEIF(path); - (stream->complete)(stream); -} - -PRIVATE void net_IdxConvAbort(NET_StreamClass *stream, int32 status) -{ - index_format_conv_data_object *obj=stream->data_object; - NET_HTTPIndexParserFree(obj->parse_data); -} - -PUBLIC NET_StreamClass * -NET_HTTPIndexFormatToHTMLConverter(int format_out, - void *data_object, - URL_Struct *URL_s, - MWContext *window_id) -{ - index_format_conv_data_object* obj; - NET_StreamClass* stream; - - TRACEMSG(("Setting up display stream. Have URL: %s\n", URL_s->address)); - - stream = PR_NEW(NET_StreamClass); - if(stream == NULL) - return(NULL); - - obj = PR_NEW(index_format_conv_data_object); - if (obj == NULL) - { - PR_Free(stream); - return(NULL); - } - - memset(obj, 0, sizeof(index_format_conv_data_object)); - - obj->parse_data = NET_HTTPIndexParserInit(); - - if(!obj->parse_data) - { - PR_Free(stream); - PR_Free(obj); - } - - obj->context = window_id; - obj->URL_s = URL_s; - obj->format_out = format_out; - - stream->name = "HTTP index format converter"; - stream->complete = (MKStreamCompleteFunc) net_IdxConvComplete; - stream->abort = (MKStreamAbortFunc) net_IdxConvAbort; - stream->put_block = (MKStreamWriteFunc) net_IdxConvPut; - stream->is_write_ready = (MKStreamWriteReadyFunc) net_IdxConvWriteReady; - stream->data_object = obj; /* document info object */ - stream->window_id = window_id; - - return(stream); -} - -#include "libmocha.h" - -#define SANE_BUFLEN 1024 - -NET_StreamClass * -net_CloneWysiwygLocalFile(MWContext *window_id, URL_Struct *URL_s, - uint32 nbytes, const char * wysiwyg_url, - const char * base_href) -{ - char *filename; - XP_File fromfp; - NET_StreamClass *stream; - int32 buflen, len; - char *buf; - - filename = net_return_local_file_part_from_url(URL_s->address); - if (!filename) - return NULL; - fromfp = NET_XP_FileOpen(filename, xpURL, XP_FILE_READ_BIN); - PR_Free(filename); - if (!fromfp) - return NULL; - stream = LM_WysiwygCacheConverter(window_id, URL_s, wysiwyg_url, - base_href); - if (!stream) - { - NET_XP_FileClose(fromfp); - return 0; - } - buflen = stream->is_write_ready(stream); - if (buflen > SANE_BUFLEN) - buflen = SANE_BUFLEN; - buf = (char *)PR_Malloc(buflen * sizeof(char)); - if (!buf) - { - NET_XP_FileClose(fromfp); - return 0; - } - while (nbytes != 0) - { - len = buflen; - if ((uint32)len > nbytes) - len = (int32)nbytes; - len = NET_XP_FileRead(buf, len, fromfp); - if (len <= 0) - break; - if (stream->put_block(stream, buf, len) < 0) - break; - nbytes -= len; - } - PR_Free(buf); - NET_XP_FileClose(fromfp); - if (nbytes != 0) - { - /* NB: Our caller must clear top_state->mocha_write_stream. */ - stream->abort(stream, MK_UNABLE_TO_CONVERT); - PR_Free(stream); - return 0; - } - return stream; -} - -void -NET_InitFileProtocol(void) -{ - static NET_ProtoImpl file_proto_impl; - - file_proto_impl.init = net_FileLoad; - file_proto_impl.process = net_ProcessFile; - file_proto_impl.interrupt = net_InterruptFile; - file_proto_impl.resume = NULL; - file_proto_impl.cleanup = net_CleanupFile; - - NET_RegisterProtocolImplementation(&file_proto_impl, FILE_TYPE_URL); - NET_RegisterProtocolImplementation(&file_proto_impl, FILE_CACHE_TYPE_URL); -} diff --git a/mozilla/network/protocol/file/mkfile.h b/mozilla/network/protocol/file/mkfile.h deleted file mode 100644 index 3d488f500f7..00000000000 --- a/mozilla/network/protocol/file/mkfile.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKFILE_H -#define MKFILE_H - -#include "mkfsort.h" -#include "fileurl.h" - -#endif /* MKFILE_H */ diff --git a/mozilla/network/protocol/ftp/MANIFEST b/mozilla/network/protocol/ftp/MANIFEST deleted file mode 100644 index f87eb7f7b5d..00000000000 --- a/mozilla/network/protocol/ftp/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -ftpurl.h diff --git a/mozilla/network/protocol/ftp/Makefile.in b/mozilla/network/protocol/ftp/Makefile.in deleted file mode 100644 index d61fb44f92d..00000000000 --- a/mozilla/network/protocol/ftp/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = ftpurl -LIBRARY_NAME = ftpurl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl mimetype progress - -CSRCS = mkftp.c - -EXPORTS = $(srcdir)/ftpurl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/ftp/ftpurl.h b/mozilla/network/protocol/ftp/ftpurl.h deleted file mode 100644 index ba174e6f3b4..00000000000 --- a/mozilla/network/protocol/ftp/ftpurl.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKFTP_H -#define MKFTP_H - -#include "mkgeturl.h" - -extern void NET_InitFTPProtocol(void); - -#endif /* HTFTP_H */ diff --git a/mozilla/network/protocol/ftp/makefile.win b/mozilla/network/protocol/ftp/makefile.win deleted file mode 100644 index 06a551982df..00000000000 --- a/mozilla/network/protocol/ftp/makefile.win +++ /dev/null @@ -1,87 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkftp.obj \ - $(NULL) - - -CSRCS = \ - mkftp.c \ - $(NULL) - - -LIBRARY_NAME=ftpurl -MODULE=ftpurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= ftpurl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\mimetype \ - -I$(PUBLIC)\progress \ - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/ftp/mkftp.c b/mozilla/network/protocol/ftp/mkftp.c deleted file mode 100644 index 98280310fab..00000000000 --- a/mozilla/network/protocol/ftp/mkftp.c +++ /dev/null @@ -1,4886 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* state machine to read FTP sites - * - * Designed and originally implemented by Lou Montulli '94 - * - * State machine to implement File Transfer Protocol, - * all the protocol state machines work basically the same way. - */ - -#include "rosetta.h" -#include "xp.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "net_xp_file.h" -#include "prerror.h" -#include "prmem.h" -#include "plstr.h" - -#define FTP_PORT 21 - -#define FTP_MODE_UNKNOWN 0 -#define FTP_MODE_ASCII 1 -#define FTP_MODE_BINARY 2 - -#include "ftpurl.h" -#include "glhist.h" -#include "mkgeturl.h" -#include "mkparse.h" -#include "mktcp.h" -#include "mksort.h" -#include "mkfsort.h" /* file sorting */ -#include "mkformat.h" -#include "mkfsort.h" -#include "merrors.h" -#include "shist.h" -#include HG27229 -#include "prtime.h" -#include "pwcacapi.h" -#include "secnav.h" - -#if defined(SMOOTH_PROGRESS) -#include "progress.h" -#endif - -#ifdef XP_OS2 /* DSR072196 */ -#include "os2sock.h" -#endif /* XP_OS2 */ - -#ifdef XP_UNIX -#if defined(HAVE_SYS_FILIO_H) -#include <sys/filio.h> -#endif -#endif /* XP_UNIX */ - -#include "prefapi.h" - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_HTML_FTPERROR_NOLOGIN; -extern int XP_HTML_FTPERROR_TRANSFER; -extern int XP_PROGRESS_RECEIVE_FTPDIR; -extern int XP_PROGRESS_RECEIVE_FTPFILE; -extern int XP_PROGRESS_READFILE; -extern int XP_PROGRESS_FILEDONE; -extern int XP_PROMPT_ENTER_PASSWORD; -extern int MK_COULD_NOT_PUT_FILE; -extern int MK_TCP_READ_ERROR; -extern int MK_TCP_WRITE_ERROR; -extern int MK_UNABLE_TO_ACCEPT_SOCKET; -extern int MK_UNABLE_TO_CHANGE_FTP_MODE; -extern int MK_UNABLE_TO_CREATE_SOCKET; -extern int MK_UNABLE_TO_LOCATE_FILE; -extern int MK_UNABLE_TO_OPEN_FILE; -extern int MK_UNABLE_TO_SEND_PORT_COMMAND; -extern int MK_UNABLE_TO_DELETE_DIRECTORY; -extern int MK_COULD_NOT_CREATE_DIRECTORY; -extern int XP_ERRNO_EWOULDBLOCK; -extern int MK_OUT_OF_MEMORY; -extern int MK_DISK_FULL; -extern int XP_COULD_NOT_LOGIN_TO_FTP_SERVER; -extern int XP_ERROR_COULD_NOT_MAKE_CONNECTION_NON_BLOCKING; -extern int XP_POSTING_FILE; -extern int XP_TITLE_DIRECTORY_OF_ETC; -extern int XP_UPTO_HIGHER_LEVEL_DIRECTORY ; - - -#define PUTSTRING(s) (*cd->stream->put_block) \ - (cd->stream, s, PL_strlen(s)) -#define PUTBLOCK(b,l) (*cd->stream->put_block) \ - (cd->stream, b, l) -#define COMPLETE_STREAM (*cd->stream->complete) \ - (cd->stream) -#define ABORT_STREAM(s) (*cd->stream->abort) \ - (cd->stream, s) - - -#define FTP_GENERIC_TYPE 0 -#define FTP_UNIX_TYPE 1 -#define FTP_DCTS_TYPE 2 -#define FTP_NCSA_TYPE 3 -#define FTP_PETER_LEWIS_TYPE 4 -#define FTP_MACHTEN_TYPE 5 -#define FTP_CMS_TYPE 6 -#define FTP_TCPC_TYPE 7 -#define FTP_VMS_TYPE 8 -#define FTP_NT_TYPE 9 -/* bug # 309043 */ -#define FTP_WEBSTAR_TYPE 10 - - -#define OUTPUT_BUFFER_SIZE 2048 - -PRIVATE XP_List * connection_list=0; /* a pointer to a list of open connections */ - -PRIVATE Bool net_use_pasv=TRUE; -PRIVATE char * ftp_last_password=0; -PRIVATE char * ftp_last_password_host=0; -PRIVATE PRBool net_send_email_address_as_password=FALSE; - -#define PC_FTP_PASSWORD_KEY "pass" -#define PC_FTP_MODULE_KEY "ftp" - -typedef struct _FTPConnection { - char *hostname; /* hostname string (may contain :port) */ - PRFileDesc *csock; /* control socket */ - int server_type; /* type of server */ - int cur_mode; /* ascii, binary, unknown */ - Bool use_list; /* use LIST? (or NLST) */ - Bool busy; /* is the connection in use already? */ - Bool no_pasv; /* should we NOT use pasv mode since is doesn't work? */ - Bool prev_cache; /* did this connection come from the cache? */ - Bool no_restart; /* do we know that restarts don't work? */ -} FTPConnection; - -/* define the states of the machine - */ -typedef enum _FTPStates { -FTP_WAIT_FOR_RESPONSE, -FTP_WAIT_FOR_AUTH, -FTP_CONTROL_CONNECT, -FTP_CONTROL_CONNECT_WAIT, -FTP_SEND_USERNAME, -FTP_SEND_USERNAME_RESPONSE, -FTP_GET_PASSWORD, -FTP_GET_PASSWORD_RESPONSE, -FTP_SEND_PASSWORD, -FTP_SEND_PASSWORD_RESPONSE, -FTP_SEND_ACCT, -FTP_SEND_ACCT_RESPONSE, -FTP_SEND_REST_ZERO, -FTP_SEND_REST_ZERO_RESPONSE, -FTP_SEND_SYST, -FTP_SEND_SYST_RESPONSE, -FTP_SEND_MAC_BIN, -FTP_SEND_MAC_BIN_RESPONSE, -FTP_SEND_PWD, -FTP_SEND_PWD_RESPONSE, -FTP_SEND_PASV, -FTP_SEND_PASV_RESPONSE, -FTP_PASV_DATA_CONNECT, -FTP_PASV_DATA_CONNECT_WAIT, -FTP_FIGURE_OUT_WHAT_TO_DO, -FTP_SEND_DELETE_FILE, -FTP_SEND_DELETE_FILE_RESPONSE, -FTP_SEND_DELETE_DIR, -FTP_SEND_DELETE_DIR_RESPONSE, -FTP_SEND_MKDIR, -FTP_SEND_MKDIR_RESPONSE, -FTP_SEND_PORT, -FTP_SEND_PORT_RESPONSE, -FTP_GET_FILE_TYPE, -FTP_SEND_BIN, -FTP_SEND_BIN_RESPONSE, -FTP_SEND_ASCII, -FTP_SEND_ASCII_RESPONSE, -FTP_GET_FILE_SIZE, -FTP_GET_FILE_SIZE_RESPONSE, -FTP_GET_FILE_MDTM, -FTP_GET_FILE_MDTM_RESPONSE, -FTP_GET_FILE, -FTP_BEGIN_PUT, -FTP_BEGIN_PUT_RESPONSE, -FTP_DO_PUT, -FTP_SEND_REST, -FTP_SEND_REST_RESPONSE, -FTP_SEND_RETR, -FTP_SEND_RETR_RESPONSE, -FTP_SEND_CWD, -FTP_SEND_CWD_RESPONSE, -FTP_SEND_LIST_OR_NLST, -FTP_SEND_LIST_OR_NLST_RESPONSE, -FTP_SETUP_STREAM, -FTP_WAIT_FOR_ACCEPT, -FTP_START_READ_FILE, -FTP_READ_CACHE, -FTP_READ_FILE, -FTP_START_READ_DIRECTORY, -FTP_READ_DIRECTORY, -FTP_PRINT_DIR, -FTP_DONE, -FTP_ERROR_DONE, -FTP_FREE_DATA -} FTPStates; - -typedef struct _FTPConData { - FTPStates next_state; /* the next state of the machine */ - Bool pause_for_read; /* should we pause (return) for read? */ - - NET_StreamClass *stream; /* the outgoing data stream */ - - FTPConnection *cc; /* information about the control connection */ - - PRFileDesc *dsock; /* data socket */ - PRFileDesc *listen_sock; /* socket to listen on */ - Bool restart; /* is this a restarted fetch? */ - Bool use_list; /* use LIST or NLST */ - Bool pasv_mode; /* using pasv mode? */ - Bool is_directory; /* is the url a directory? */ - Bool retr_already_failed; /* did RETR fail? */ - Bool store_password; /* cache password? */ - char *data_buf; /* unprocessed data from the socket */ - int32 data_buf_size; /* size of the unprocesed data */ - - Bool use_default_path; /* set if we should use PWD to figure out - * current path and use that - */ - - /* used by response */ - FTPStates next_state_after_response; /* the next state after - * full response recieved */ - int response_code; /* code returned in response */ - char *return_msg; /* message from response */ - int cont_response; /* a continuation code */ - - char *data_con_address; /* address and port for PASV data connection*/ - char *filename; /* name of the file we are getting */ - char *file_to_post; /* local filename to put */ - XP_File file_to_post_fp; /* filepointer */ - char *post_file_to; /* If non-NULL, specifies the destination of - the source file, file_to_post. If NULL, - generate the destination name automatically - from file_to_post. */ - int32 total_size_of_files_to_post; /* total bytes */ - char *path; /* path as returned by MKParse */ - int type; /* a type indicator for the file */ - char *username; /* the username if not anonymous */ - char *password; /* the password if not anonymous */ - - char *cwd_message_buffer; /* used to print out server help messages */ - char *login_message_buffer; /* used to print out server help messages */ - - char *output_buffer; /* buffer before sending to PUTSTRING */ - - SortStruct *sort_base; /* base pointer to Qsorting list */ - - Bool destroy_graph_progress; /* do we need to destroy graph progress? */ - Bool destroy_file_upload_progress_dialog; /* do we need to destroy the dialog? */ - Bool calling_netlib_all_the_time; /* is SetCallNetlibAllTheTime set? */ - int32 original_content_length; /* the content length at the time of - * calling graph progress - */ - - TCP_ConData *tcp_con_data; /* Data pointer for tcp connect - * state machine */ - - int32 buff_size; /* used by ftp_send_file */ - int32 amt_of_buff_wrt; /* amount of data already written - * used by ftp_send_file() - */ - void *write_post_data_data; - XP_File partial_cache_fp; /* pointer to partial cache file */ -} FTPConData; - -/* forward decls */ -static const char *pref_email_as_ftp_password = "security.email_as_ftp_password"; -PRIVATE int32 net_ProcessFTP(ActiveEntry * ce); -PUBLIC PRBool stub_PromptPassword(MWContext *context, - char *prompt, - XP_Bool *remember, - XP_Bool is_secure, - void *closure); - -/* function prototypes - */ -PRIVATE NET_FileEntryInfo * net_parse_dir_entry (char *entry, int server_type); - -/* call this to enable/disable FTP PASV mode. - * Note: PASV mode is on by default - */ -PUBLIC void -NET_UsePASV(Bool do_it) -{ - net_use_pasv = do_it; -} - -/* callback routine invoked by prefapi when the pref value changes */ -/* fix Mac missing prototype warnings */ -MODULE_PRIVATE int PR_CALLBACK -net_ftp_pref_changed(const char * newpref, void * data); - -MODULE_PRIVATE int PR_CALLBACK -net_ftp_pref_changed(const char * newpref, void * data) -{ - PREF_GetBoolPref(pref_email_as_ftp_password, &net_send_email_address_as_password); - return PREF_NOERROR; -} - -PRIVATE XP_Bool -net_get_send_email_address_as_password(void) -{ -#ifdef XP_WIN - static XP_Bool net_read_FTP_password_pref = FALSE; - - if (!net_read_FTP_password_pref) { - if ( (PREF_OK != PREF_GetBoolPref(pref_email_as_ftp_password, &net_send_email_address_as_password)) ) { - net_send_email_address_as_password = FALSE; - } - PREF_RegisterCallback(pref_email_as_ftp_password, net_ftp_pref_changed, NULL); - net_read_FTP_password_pref = TRUE; - } -#endif - - return net_send_email_address_as_password; -} - -#if defined(XP_MAC) || defined(XP_UNIX) -/* call this with TRUE to enable the sending of the email - * address as the default user "anonymous" password. - * The default is OFF. - */ -PUBLIC void -NET_SendEmailAddressAsFTPPassword(Bool do_it) -{ - net_send_email_address_as_password = (XP_Bool)do_it; -} -#endif - -PRIVATE NET_StreamClass * -net_ftp_make_stream(FO_Present_Types format_out, - URL_Struct *URL_s, - MWContext *window_id) -{ - MWContext *stream_context; - -#ifdef MOZILLA_CLIENT - /* if the context can't handle HTML then we - * need to generate an HTML dialog to handle - * the message - */ - if(URL_s->files_to_post && EDT_IS_EDITOR(window_id)) - { - Chrome chrome_struct; - memset(&chrome_struct, 0, sizeof(Chrome)); - chrome_struct.is_modal = TRUE; - chrome_struct.allow_close = TRUE; - chrome_struct.allow_resize = TRUE; - chrome_struct.show_scrollbar = TRUE; - chrome_struct.w_hint = 400; - chrome_struct.h_hint = 300; -#ifdef XP_MAC - /* on Mac, topmost windows are floating windows not dialogs */ - chrome_struct.topmost = FALSE; - /* disable commands to change to minimal menu bar; */ - /* avoids confusion about which commands are present */ - chrome_struct.disable_commands = TRUE; -#else - chrome_struct.topmost = TRUE; -#endif - - stream_context = FE_MakeNewWindow(window_id, - NULL, - NULL, - &chrome_struct); - if(!stream_context) - return (NULL); - } - else -#endif /* MOZILLA_CLIENT */ - { - stream_context = window_id; - } - - return(NET_StreamBuilder(format_out, URL_s, stream_context)); - -} - -PRIVATE int -net_ftp_show_error(ActiveEntry *ce, char *line) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - /* show the error - */ - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - ce->URL_s->expires = 1; /* immediate expire date */ - cd->stream = net_ftp_make_stream(ce->format_out, ce->URL_s, ce->window_id); - - if(cd->stream) - { - PL_strcpy(cd->output_buffer, XP_GetString(XP_HTML_FTPERROR_TRANSFER)); - if(ce->status > -1) - ce->status = PUTSTRING(cd->output_buffer); - if(line && ce->status > -1) - ce->status = PUTSTRING(cd->return_msg); - PL_strcpy(cd->output_buffer, "</PRE>"); - if(ce->status > -1) - ce->status = PUTSTRING(cd->output_buffer); - } - - cd->next_state = FTP_ERROR_DONE; - return MK_INTERRUPTED; -} - -/* get a reply from the server - */ -PRIVATE int -net_ftp_response (ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - int result_code; /* numerical result code from server */ - int status; - char cont_char; - char * line; - - status = NET_BufferedReadLine(cd->cc->csock, &line, &cd->data_buf, - &cd->data_buf_size, &cd->pause_for_read); - - if (status > 0 && !line && cd->next_state_after_response == FTP_DONE) - { - /* This is wierd. I have been seeing this consistently when the ftp directory - * listing has ended. The condition is that there is no data on the socket, - * and we are waiting to gobble the final bytes from the ftp server for - * completing a ftp directory listing. NET_BufferedReadLine() seems to indicate - * that the call would block and no data is available now by returning a - * status of 1 and line set to NULL. - * - * For the end of ftp directory, next_state_after_response will be FTP_DONE. - * We will use that to fix this. How we are fixing it is by turning status to 0. - * This will make it adopt the following if condition of status==0 and set next_state to - * next_state_after_response which would be done. - * - * If we dont do this, ftp directory doesnt end and we have our ftp waiting indefinitely - * for some thing from the ftp server while there aint any more data showing up. - * - * XXX The right thing however would be to see why we are getting a non-zero status - * XXX but no data from NET_BufferedReadLine(). The smarted question to ask would - * XXX be "if no data is available, then why was this socket selected for read again ?" - */ - TRACEMSG(("Wierd state. status > 0 but no data and next_state_after_response = %d. Fixing up...\n", cd->next_state_after_response)); - status = 0; - } - - if(status == 0) - { - /* this shouldn't really happen, but... - */ - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - return(0); - } - else if(status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - /* Login messages or CWD messages - * Their so handy, those help messages are :) - */ - if(cd->cc->server_type == FTP_UNIX_TYPE && !PL_strncmp(line, "250-",4)) - { - StrAllocCat(cd->cwd_message_buffer, line+4); - StrAllocCat(cd->cwd_message_buffer, "\n"); /* nasty */ - } - else if(!PL_strncmp(line,"230-",4) || !PL_strncmp(line,"220-",4)) - { - StrAllocCat(cd->login_message_buffer, line+4); - StrAllocCat(cd->login_message_buffer, "\n"); /* nasty */ - } - else if(cd->cont_response == 230) - { - /* this does the same thing as the one directly above it - * but it checks for 230 response code instead - * this is to fix buggy ftp servers that don't follow specs - */ - if(PL_strncmp(line, "230", 3)) - { - /* make sure it's not "230 Guest login ok... - */ - StrAllocCat(cd->login_message_buffer, line); - StrAllocCat(cd->login_message_buffer, "\n"); /* nasty */ - } - } - - result_code = 0; /* defualts */ - cont_char = ' '; /* defualts */ - sscanf(line, "%d%c", &result_code, &cont_char); - - if(cd->cont_response == -1) - { - if (cont_char == '-') /* start continuation */ - cd->cont_response = result_code; - - StrAllocCopy(cd->return_msg, line+4); - } - else - { /* continuing */ - if (cd->cont_response == result_code && cont_char == ' ') - cd->cont_response = -1; /* ended */ - - StrAllocCat(cd->return_msg, "\n"); - if(PL_strlen(line) > 3) - { - if(isdigit(line[0])) - StrAllocCat(cd->return_msg, line+4); - else - StrAllocCat(cd->return_msg, line); - } - else - { - StrAllocCat(cd->return_msg, line); - } - } - - if(cd->cont_response == -1) /* all done with this response? */ - { - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - } - if(result_code == 551) - { - return net_ftp_show_error(ce, line + 4); - } - - cd->response_code = result_code/100; - - return(1); /* everything ok */ -} - -PRIVATE int -net_send_username(FTPConData * cd) -{ - - /* look for the word UNIX in the hello message - * if it is there assume a unix server that can - * use the LIST command - */ - if(cd->return_msg && PL_strcasestr(cd->return_msg, "UNIX")) - { - cd->cc->server_type = FTP_UNIX_TYPE; - cd->cc->use_list = TRUE; - } - - if (cd->username) - { - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "USER %.256s%c%c", cd->username, CR, LF); - } - else - { - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "USER anonymous%c%c", CR, LF); - } - - TRACEMSG(("FTP Rx: %.256s", cd->output_buffer)); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_USERNAME_RESPONSE; - cd->pause_for_read = TRUE; - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_username_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if (cd->response_code == 3) /* Send password */ - { - if(!cd->password) - cd->next_state = FTP_GET_PASSWORD; - else - cd->next_state = FTP_SEND_PASSWORD; - } - else if (cd->response_code == 2) /* Logged in */ - { - if( cd->cc->no_restart ) - cd->next_state = FTP_SEND_SYST; - else - cd->next_state = FTP_SEND_REST_ZERO; - } - else - { - /* show the error - */ - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - ce->URL_s->expires = 1; /* immediate expire date */ - cd->stream = net_ftp_make_stream(ce->format_out, ce->URL_s, ce->window_id); - - if(cd->stream) - { - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, XP_GetString(XP_HTML_FTPERROR_NOLOGIN)) ; - if(ce->status > -1) - ce->status = PUTSTRING(cd->output_buffer); - if(cd->return_msg && ce->status > -1) - ce->status = PUTSTRING(cd->return_msg); - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "</PRE>"); - if(ce->status > -1) - ce->status = PUTSTRING(cd->output_buffer); - - if(ce->status > -1) - COMPLETE_STREAM; - else - ABORT_STREAM(ce->status); - - PR_Free(cd->stream); - cd->stream = NULL; - } - - cd->next_state = FTP_ERROR_DONE; - - /* make sure error_msg is empty */ - PR_FREEIF(ce->URL_s->error_msg); - ce->URL_s->error_msg = NULL; - - return MK_UNABLE_TO_LOGIN; - - } - - return(0); /* good */ -} - - -PRIVATE int -net_send_password(FTPConData * cd) -{ - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, - "PASS %.256s%c%c", - NET_UnEscape(cd->password), - CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_PASSWORD_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE char * -gen_ftp_password_key(char *address, char *username) -{ - char *rv=NULL; - - if(!address || !username) - return NULL; - - StrAllocCopy(rv, address); - StrAllocCat(rv, "\t"); - StrAllocCat(rv, username); - - return rv; -} - -PRIVATE int -net_send_password_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if (cd->response_code == 3) - { - cd->next_state = FTP_SEND_ACCT; - } - else if (cd->response_code == 2) /* logged in */ - { - if(cd->store_password && cd->username) - { - /* store the password in the cache */ - char *key = gen_ftp_password_key(ce->URL_s->address, cd->username); - - if(key) - { - PCNameValueArray * array = PC_NewNameValueArray(); - - PC_AddToNameValueArray(array, PC_FTP_PASSWORD_KEY, cd->password); - - PC_StorePasswordNameValueArray(PC_FTP_MODULE_KEY, key, array); - - PR_Free(key); - - PC_FreeNameValueArray(array); - } - } - - if( cd->cc->no_restart ) - cd->next_state = FTP_SEND_SYST; - else - cd->next_state = FTP_SEND_REST_ZERO; - } - else - { - PR_FREEIF(ftp_last_password_host); - PR_FREEIF(ftp_last_password); - - cd->next_state = FTP_ERROR_DONE; -#if defined(SingleSignon) - if (cd->cc) { /* just for safety, probably cd->cc can never be null */ - SI_RemoveUser(cd->cc->hostname, cd->username, TRUE); - } -#endif - FE_Alert(ce->window_id, cd->return_msg ? cd->return_msg : - XP_GetString( XP_COULD_NOT_LOGIN_TO_FTP_SERVER ) ); - /* no error status message in this case - */ - return MK_UNABLE_TO_LOGIN; /* negative return code */ - } - - return(0); /* good */ -} - - -PRIVATE int -net_send_acct(FTPConData * cd) -{ - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "ACCT noaccount%c%c", CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_ACCT_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_acct_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if (cd->response_code == 2) - { - if( cd->cc->no_restart ) - cd->next_state = FTP_SEND_SYST; - else - cd->next_state = FTP_SEND_REST_ZERO; - } - else - { - cd->next_state = FTP_ERROR_DONE; - FE_Alert(ce->window_id, cd->return_msg ? cd->return_msg : - XP_GetString( XP_COULD_NOT_LOGIN_TO_FTP_SERVER ) ); - /* no error status message in this case - */ - return MK_UNABLE_TO_LOGIN; /* negative return code */ - } - - return(0); /* good */ -} - -PRIVATE int -net_send_rest_zero(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "REST 0%c%c", CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_REST_ZERO_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_rest_zero_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if( cd->response_code == 3 ) - { - TRACEMSG(("Server can do restarts!")); - ce->URL_s->server_can_do_restart = TRUE; - cd->cc->no_restart = FALSE; - } - else - { - TRACEMSG(("Server can NOT do restarts!")); - ce->URL_s->server_can_do_restart = FALSE; - cd->cc->no_restart = TRUE; - } - - cd->next_state = FTP_SEND_SYST; - return 0; -} - -PRIVATE int -net_send_syst(FTPConData * cd) -{ - - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "SYST%c%c", CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_SYST_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - - -PRIVATE int -net_send_syst_response(FTPConData * cd) -{ - if (cd->response_code == 2) - { - TRACEMSG(("SYST response: %s",cd->return_msg)); - - /* default next state will be to try PASV mode - * - * TEST: set this default next state to FTP_SEND_PORT - * to test the non-pasv mode ftp - */ - if(cd->use_default_path) - cd->next_state = FTP_SEND_PWD; - else - cd->next_state = FTP_FIGURE_OUT_WHAT_TO_DO; - - /* we got a line -- what kind of server are we talking to? */ - if (!PL_strncmp(cd->return_msg, "UNIX Type: L8 MAC-OS MachTen", 28)) - { - cd->cc->server_type = FTP_MACHTEN_TYPE; - cd->cc->use_list = TRUE; - } - else if (PL_strstr(cd->return_msg, "UNIX") != NULL) - { - cd->cc->server_type = FTP_UNIX_TYPE; - cd->cc->use_list = TRUE; - } - else if (PL_strstr(cd->return_msg, "Windows_NT") != NULL) - { - cd->cc->server_type = FTP_NT_TYPE; - cd->cc->use_list = TRUE; - } - else if (PL_strncmp(cd->return_msg, "VMS", 3) == 0) - { - cd->cc->server_type = FTP_VMS_TYPE; - cd->cc->use_list = TRUE; - } - else if ((PL_strncmp(cd->return_msg, "VM/CMS", 6) == 0) - || (PL_strncmp(cd->return_msg, "VM ", 3) == 0)) - { - cd->cc->server_type = FTP_CMS_TYPE; - } - else if (PL_strncmp(cd->return_msg, "DCTS", 4) == 0) - { - cd->cc->server_type = FTP_DCTS_TYPE; - } - else if (PL_strstr(cd->return_msg, "MAC-OS TCP/Connect II") != NULL) - { - cd->cc->server_type = FTP_TCPC_TYPE; - cd->next_state = FTP_SEND_PWD; - } - else if (PL_strncmp(cd->return_msg, "MACOS Peter's Server", 20) == 0) - { - cd->cc->server_type = FTP_PETER_LEWIS_TYPE; - cd->cc->use_list = TRUE; - cd->next_state = FTP_SEND_MAC_BIN; - } - else if (PL_strncmp(cd->return_msg, "MACOS WebSTAR FTP", 17) == 0) - { - cd->cc->server_type = FTP_WEBSTAR_TYPE; - cd->cc->use_list = TRUE; - cd->next_state = FTP_SEND_MAC_BIN; - } - else if(cd->cc->server_type == FTP_GENERIC_TYPE) - { - cd->next_state = FTP_SEND_PWD; - } - } - else - { - cd->next_state = FTP_SEND_PWD; - } - - TRACEMSG(("Set server type to: %d\n",cd->cc->server_type)); - - return(0); /* good */ - -} - -PRIVATE int -net_send_mac_bin(FTPConData * cd) -{ - /* Check bug # 323918 for MACB details */ - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "MACB ENABLE%c%c", CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_MAC_BIN_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - - -PRIVATE int -net_send_mac_bin_response(FTPConData * cd) -{ - if(cd->response_code == 2) - { /* succesfully set mac binary */ - if(cd->cc->server_type == FTP_UNIX_TYPE) - cd->cc->server_type = FTP_NCSA_TYPE; /* we were unsure here */ - } - - cd->next_state = FTP_FIGURE_OUT_WHAT_TO_DO; - - return(0); /* continue */ -} - -PRIVATE -int -net_figure_out_what_to_do(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - switch(ce->URL_s->method) - { - case URL_MKDIR_METHOD: - cd->next_state = FTP_SEND_MKDIR; - break; - - case URL_DELETE_METHOD: - cd->next_state = FTP_SEND_DELETE_FILE; - break; - - case URL_PUT_METHOD: - /* trim the path to the last slash */ - { - char * slash = PL_strrchr(cd->path, '/'); - if(slash) - *slash = '\0'; - } - /* fall through */ - goto get_method_case; - - case URL_POST_METHOD: - /* we support POST if files_to_post - * is filed in - */ - PR_ASSERT(ce->URL_s->files_to_post); - /* fall through */ - - case URL_GET_METHOD: -get_method_case: /* ack! goto alert */ - - /* don't send PASV if the server cant do it */ - if(cd->cc->no_pasv || !net_use_pasv) - cd->next_state = FTP_SEND_PORT; - else - cd->next_state = FTP_SEND_PASV; - break; - - default: - PR_ASSERT(0); - } - - return(0); -} - -PRIVATE int -net_send_mkdir(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "MKD %s"CRLF, - cd->path); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_MKDIR_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_mkdir_response(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if (cd->response_code !=2) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_COULD_NOT_CREATE_DIRECTORY, - cd->path); - return(MK_COULD_NOT_CREATE_DIRECTORY); - } - - /* success */ - - cd->next_state = FTP_DONE; - - return(0); -} - - -PRIVATE int -net_send_delete_file(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "DELE %s"CRLF, - cd->path); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_DELETE_FILE_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_delete_file_response(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if (cd->response_code !=2) - { - /* error */ - /* try and delete it as a file */ - cd->next_state = FTP_SEND_DELETE_DIR; - return(0); - } - - /* success */ - - cd->next_state = FTP_DONE; - - return(0); -} - -PRIVATE int -net_send_delete_dir(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "RMD %s"CRLF, - cd->path); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_DELETE_DIR_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_delete_dir_response(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if (cd->response_code !=2) - { - /* error */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_DELETE_DIRECTORY, - cd->path); - return(MK_UNABLE_TO_DELETE_DIRECTORY); - } - - /* success */ - - cd->next_state = FTP_DONE; - - return(0); -} - -PRIVATE int -net_send_pwd(FTPConData * cd) -{ - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "PWD%c%c", CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_PWD_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_pwd_response(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - char *cp = PL_strchr(cd->return_msg+5,'"'); - - if(cp) - *cp = '\0'; - - /* default next state */ - /* don't send PASV if the server cant do it */ - cd->next_state = FTP_FIGURE_OUT_WHAT_TO_DO; - - if (cd->cc->server_type == FTP_TCPC_TYPE) - { - cd->cc->server_type = (cd->return_msg[1] == '/' ? - FTP_NCSA_TYPE : FTP_TCPC_TYPE); - } - else if(cd->cc->server_type == FTP_GENERIC_TYPE) - { - if (cd->return_msg[1] == '/') - { - /* path names beginning with / imply Unix, - * right? - */ - cd->cc->server_type = FTP_UNIX_TYPE; - cd->cc->use_list = TRUE; - cd->next_state = FTP_SEND_MAC_BIN; /* see if it's a mac */ - } - else if (cd->return_msg[PL_strlen(cd->return_msg)-1] == ']') - { - /* path names ending with ] imply VMS, right? */ - cd->cc->server_type = FTP_VMS_TYPE; - cd->cc->use_list = TRUE; - } - } - - /* use the path returned by PWD if use_default_path is set - * don't do this for vms hosts - */ - if(cd->use_default_path && cd->cc->server_type != FTP_VMS_TYPE) - { - char *path = strtok(&cd->return_msg[1], "\""); - char *ptr; - char *existing_path = cd->path; - - /* NT can return a drive letter. We can't - * deal with a drive letter right now - * so we need to just strip the drive letter - */ - if(*path != '/') { - ptr = PL_strchr(path, '/'); - /* If that didn't work, look for a backslash (e.g., OS/2) */ - if( ptr == (char *)0 ) { - ptr = PL_strchr(path, '\\'); - /* If that worked, then go flip the slashes so the URL is legal */ - if( ptr != (char *)0 ) { - char *p; - for( p = ptr; *p != '\0'; p++ ){ - if( *p == '\\' ) { - *p = '/'; - } - } - } - } - } - else - ptr = path; - - if(ptr) - { - char * new_url; - - cd->path = NULL; - StrAllocCopy(cd->path, ptr); - - if(existing_path && existing_path[0] != '\0') - { - /* if the new path has a / on the - * end remove it since the - * existing path already has - * a slash at the beginning - */ - if(cd->path[0] != '\0') - { - char *end = &cd->path[PL_strlen(cd->path)-1]; - if(*end == '/') - *end = '\0'; - } - StrAllocCat(cd->path, existing_path); - } - - /* strip the path part from the URL - * and add the new path - */ - new_url = NET_ParseURL(ce->URL_s->address, - GET_PROTOCOL_PART | GET_USERNAME_PART | GET_HOST_PART); - - StrAllocCat(new_url, cd->path); - - PR_Free(ce->URL_s->address); - - ce->URL_s->address = new_url; - } - - - /* make sure we don't do this again for some reason */ - cd->use_default_path = FALSE; - } - - if (cd->cc->server_type == FTP_NCSA_TYPE || - cd->cc->server_type == FTP_TCPC_TYPE || - cd->cc->server_type == FTP_WEBSTAR_TYPE || - cd->cc->server_type == FTP_PETER_LEWIS_TYPE) - cd->next_state = FTP_SEND_MAC_BIN; - - return(0); /* good */ -} - - -PRIVATE int -net_send_pasv(FTPConData * cd) -{ - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "PASV%c%c", CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_PASV_RESPONSE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - - -PRIVATE int -net_send_pasv_response(FTPConData * cd) -{ - int h0, h1, h2, h3; - int32 p0, p1; - int32 pasv_port; - char *cp; - int status; - - if (cd->response_code !=2) - { - cd->next_state = FTP_SEND_PORT; /* default next state */ - cd->pasv_mode = FALSE; - cd->cc->no_pasv = TRUE; /* pasv doesn't work don't try it again */ - return(0); /* continue */ - } - - cd->cc->no_pasv = FALSE; /* pasv does work */ - - TRACEMSG(("PASV response: %s\n",cd->return_msg)); - - /* find first comma or end of line */ - for(cp=cd->return_msg; *cp && *cp != ','; cp++) - ; /* null body */ - - /* find the begining of digits */ - while (--cp > cd->return_msg && '0' <= *cp && *cp <= '9') - ; /* null body */ - - /* go past the '(' when the return is of the - * form (128,234,563,356,356) - */ - if(*cp < '0' || *cp > '9') - cp++; - - status = sscanf(cp, -#ifdef __alpha - "%d,%d,%d,%d,%d,%d", -#else - "%d,%d,%d,%d,%ld,%ld", -#endif - &h0, &h1, &h2, &h3, &p0, &p1); - if (status<6) - { - TRACEMSG(("FTP: PASV reply has no inet address!\n")); - cd->next_state = FTP_SEND_PORT; /* default next state */ - cd->pasv_mode = FALSE; - return(0); /* continue */ - } - - pasv_port = ((int32) (p0<<8)) + p1; - TRACEMSG(("FTP: Server is listening on port %d\n", pasv_port)); - - /* Open connection for data: - */ - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "%d.%d.%d.%d:%ld",h0,h1,h2,h3,pasv_port); - StrAllocCopy(cd->data_con_address, cd->output_buffer); - - cd->next_state = FTP_PASV_DATA_CONNECT; - - return(0); /* OK */ -} - - -PRIVATE int -net_send_port(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - int status; - PRNetAddr pr_addr; - PRSocketOptionData opt; - PRStatus sock_status; - - TRACEMSG(("Entering get_listen_socket with control socket: %d\n", cd->cc->csock)); - - cd->pasv_mode = FALSE; /* not using pasv mode if we get here */ - - /* Create internet socket - */ - cd->listen_sock = PR_NewTCPSocket(); - - if(cd->listen_sock == NULL) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CREATE_SOCKET); - return MK_UNABLE_TO_CREATE_SOCKET; - } - -#if defined(XP_WIN16) || (defined(XP_OS2) && !defined(XP_OS2_DOUGSOCK)) - opt.option = PR_SockOpt_Linger; - opt.value.linger.polarity = PR_TRUE; - opt.value.linger.linger = PR_INTERVAL_NO_WAIT; - PR_SetSocketOption(cd->listen_sock, &opt); -#endif - /* lets try to set the socket non blocking - * so that we can do multi threading - */ - opt.option = PR_SockOpt_Nonblocking; - opt.value.non_blocking = PR_TRUE; - sock_status = PR_SetSocketOption(cd->listen_sock, &opt); - if (sock_status != PR_SUCCESS) -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, - XP_GetString(XP_ERROR_COULD_NOT_MAKE_CONNECTION_NON_BLOCKING)); -#else - NET_Progress(ce->window_id, - XP_GetString( XP_ERROR_COULD_NOT_MAKE_CONNECTION_NON_BLOCKING ) ); -#endif - -HG31456 - - /* init the addr, leave port zero to let bind allocate one */ - PR_InitializeNetAddr(PR_IpAddrAny, 0, &pr_addr); - - status = PR_GetSockName(cd->cc->csock, &pr_addr); - if (status != PR_SUCCESS) - { - TRACEMSG(("Failure in getsockname for control connection: %d\n", - cd->cc->csock)); - return -1; - } - - status=PR_Bind(cd->listen_sock, &pr_addr); - if (status != PR_SUCCESS) - { - TRACEMSG(("Failure in bind for listen socket: %d\n", cd->listen_sock)); - return -1; - } - - /* TRACEMSG(("FTP: This host is %s\n", PR_NetAddrToString(&pr_addr))); */ - - /* get the name again to find out the port */ - status = PR_GetSockName(cd->listen_sock, &pr_addr); - if (status != PR_SUCCESS) - return -1; - - /* TRACEMSG(("FTP: bound to %s\n",PR_NetAddrToString(&pr_addr))); */ - - /* Now we must tell the other side where to connect - */ - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "PORT %d,%d,%d,%d,%d,%d%c%c", - (int)* ((unsigned char*) (&pr_addr.inet.ip)+0), - (int)* ((unsigned char*) (&pr_addr.inet.ip)+1), - (int)* ((unsigned char*) (&pr_addr.inet.ip)+2), - (int)* ((unsigned char*) (&pr_addr.inet.ip)+3), - (int)* ((unsigned char*) (&pr_addr.inet.port)+0), - (int)* ((unsigned char*) (&pr_addr.inet.port)+1), - CR, LF); - - /* Inform TCP that we will accept connections - */ - if (PR_Listen(cd->listen_sock, 1) < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LISTEN_ON_SOCKET); - return MK_UNABLE_TO_LISTEN_ON_SOCKET; - } - - TRACEMSG(("TCP: listen socket(), bind() and listen() all OK.\n")); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_PORT_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - /* Inform the server of the port number we will listen on - * The port_command came from above - */ - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); - -} /* get_listen */ - -PRIVATE int -net_send_port_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if (cd->response_code !=2) - { - TRACEMSG(("FTP: Bad response (port_command: %s)\n",cd->return_msg)); - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_SEND_PORT_COMMAND); - - return MK_UNABLE_TO_SEND_PORT_COMMAND; - } - - /* else */ - - cd->next_state = FTP_GET_FILE_TYPE; - return(0); /* good */ -} - -/* figure out what file transfer type to use - * and set the next state to set it if it needs - * set or else begin the transfer if it's already - * set correctly - */ -PRIVATE int -net_get_ftp_file_type(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - NET_cinfo * cinfo_struct; - - /* figure out if we are puttting a file - * and if we are figure out which - * file we are doing now - */ - if(ce->URL_s->files_to_post && - ce->URL_s->files_to_post[0] != 0) - { - /* files_to_post is an array of filename pointers - * find the last one in the list and - * remove it once done. - */ - char **array = ce->URL_s->files_to_post; - int i; - - if(!cd->total_size_of_files_to_post) - { - /* If we don't know the total size - * of all the files we are posting - * figure it out now - */ - XP_StatStruct stat_entry; - - for(i=0; array[i]; i++) - { - if(NET_XP_Stat(array[i], - &stat_entry, xpFileToPost) != -1) - cd->total_size_of_files_to_post += stat_entry.st_size; - } - - /* start the graph progress now since we know the size - */ - ce->URL_s->content_length = cd->total_size_of_files_to_post; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, ce->URL_s, 0, ce->URL_s->content_length); -#else - FE_GraphProgressInit(ce->window_id, ce->URL_s, ce->URL_s->content_length); - cd->destroy_graph_progress = TRUE; -#endif - cd->original_content_length = ce->URL_s->content_length; - -#ifdef EDITOR - /* Don't show the dialog if the data is being delivered to a plug-in */ - if (CLEAR_CACHE_BIT(ce->format_out) != FO_PLUGIN) - { - FE_SaveDialogCreate(ce->window_id, i, ED_SAVE_DLG_PUBLISH ); - cd->destroy_file_upload_progress_dialog = TRUE; - } -#endif /* EDITOR */ - } - - /* posting files is started as a POST METHOD - * eventually though, after posting the files - * we end up with a directory listing which - * should be treated as a GET METHOD. Change - * the method now so that the cache doesn't - * get confused about the method as it caches - * the directory listing at the end - */ - if(ce->URL_s->method == URL_POST_METHOD) - ce->URL_s->method = URL_GET_METHOD; - - for(i=0; array[i] != 0; i++) - ; /* null body */ - - if(i < 1) - { - /* no files left to post - * quit - */ - cd->next_state = FTP_DONE; - return(0); - } - - PR_FREEIF(cd->file_to_post); - cd->file_to_post = array[i-1]; - array[i-1] = 0; - - /* Use post_to data if specified in the URL struct. */ - if (ce->URL_s->post_to && ce->URL_s->post_to[i-1]) { - PR_FREEIF(cd->post_file_to); - cd->post_file_to = ce->URL_s->post_to[i-1]; - ce->URL_s->post_to[i-1] = 0; - } - - - cinfo_struct = NET_cinfo_find_type(cd->file_to_post); - - /* use binary mode always except for "text" types - * don't use ASCII for default types - */ - if(!cinfo_struct->is_default - && !PL_strncasecmp(cinfo_struct->type, "text",4)) - { - if(cd->cc->cur_mode != FTP_MODE_ASCII) - cd->next_state = FTP_SEND_ASCII; - else - cd->next_state = FTP_SEND_CWD; - } - else - { - if(cd->cc->cur_mode != FTP_MODE_BINARY) - cd->next_state = FTP_SEND_BIN; - else - cd->next_state = FTP_SEND_CWD; - } - - return(0); /* continue */ - } - else if(ce->URL_s->method == URL_PUT_METHOD) - { - cd->next_state = FTP_SEND_BIN; - return(0); - } - - if(cd->type == FTP_MODE_UNKNOWN) - { /* use extensions to determine the type */ - - NET_cinfo * enc = NET_cinfo_find_enc(cd->filename); - cinfo_struct = NET_cinfo_find_type(cd->filename); - - TRACEMSG(("%s", cinfo_struct->is_default ? - "Default cinfo type found" : "")); - - TRACEMSG(("Current FTP transfer mode is: %d", cd->cc->cur_mode)); - - /* use binary mode always except for "text" types - * don't use ASCII for default types - * - * if it has an encoding value, transfer as binary - */ - if(!cinfo_struct->is_default - && !PL_strncasecmp(cinfo_struct->type, "text",4) - && (!enc || !enc->encoding)) - { - if(cd->cc->cur_mode != FTP_MODE_ASCII) - cd->next_state = FTP_SEND_ASCII; - else - cd->next_state = FTP_GET_FILE_SIZE; - } - else - { - if(cd->cc->cur_mode != FTP_MODE_BINARY) - cd->next_state = FTP_SEND_BIN; - else - cd->next_state = FTP_GET_FILE_SIZE; - } - } - else - { /* use the specified type */ - if(cd->cc->cur_mode == cd->type) - { - cd->next_state = FTP_GET_FILE_SIZE; - } - else - { - if(cd->type == FTP_MODE_ASCII) - cd->next_state = FTP_SEND_ASCII; - else - cd->next_state = FTP_SEND_BIN; - } - } - - - return(0); /* continue */ -} - -PRIVATE int -net_send_bin(FTPConData * cd) -{ - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "TYPE I%c%c", CR, LF); - cd->cc->cur_mode = FTP_MODE_BINARY; - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_BIN_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - - -PRIVATE int -net_send_ascii(FTPConData * cd) -{ - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "TYPE A%c%c", CR, LF); - cd->cc->cur_mode = FTP_MODE_ASCII; - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_ASCII_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_bin_or_ascii_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if (cd->response_code != 2) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CHANGE_FTP_MODE); - return MK_UNABLE_TO_CHANGE_FTP_MODE; - } - - /* else */ - if(cd->file_to_post || ce->URL_s->method == URL_PUT_METHOD) - cd->next_state = FTP_SEND_CWD; - else - cd->next_state = FTP_GET_FILE_SIZE; - - return(0); /* good */ -} - -PRIVATE int -net_get_ftp_file_size(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if (cd->cc->server_type == FTP_VMS_TYPE) - { - /* skip this since I'm not sure how it should work on VMS - */ - cd->next_state = FTP_GET_FILE; /* we can skip the mdtm request, too */ - return(0); - } - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "SIZE %.1024s%c%c", cd->path, CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_GET_FILE_SIZE_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_get_ftp_file_size_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if(cd->response_code == 2 && cd->return_msg) - { - int32 cl = atol(cd->return_msg); - /* The response looks like "160452" - * where "160452" is the size in bytes. - */ - - if( cd->restart ) - { - TRACEMSG(("Verifying content length: was %ld, is %ld", ce->URL_s->real_content_length, cl)); - if( ce->URL_s->real_content_length != cl ) - { - TRACEMSG(("Doesn't match! Clearing restart flag.")); - cd->restart = FALSE; - ce->URL_s->content_length = cl; - ce->URL_s->real_content_length = cl; - } - else - { - TRACEMSG(("Length didn't change.")); - } - } - else - { - ce->URL_s->content_length = cl; - ce->URL_s->real_content_length = cl; - TRACEMSG(("Set content length: %ld", ce->URL_s->content_length)); - } - } - else - { - /* unknown length */ - ce->URL_s->content_length = 0; - ce->URL_s->real_content_length = 0; - cd->restart = FALSE; - } - - cd->next_state = FTP_GET_FILE_MDTM; - - return(0); -} - -PRIVATE int -net_get_ftp_file_mdtm(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if (cd->cc->server_type == FTP_VMS_TYPE) - { - /* skip this since I'm not sure how it should work on VMS - */ - cd->next_state = FTP_GET_FILE; - return(0); - } - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "MDTM %.1024s%c%c", cd->path, CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_GET_FILE_MDTM_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_get_ftp_file_mdtm_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if(cd->response_code == 2 && cd->return_msg) - { - /* - * The time is returned in ISO 3307 "Representation - * of the Time of Day" format. This format is YYYYMMDDHHmmSS or - * YYYYMMDDHHmmSS.xxx, where - * YYYY is the year - * MM is the month (01-12) - * DD is the day of the month (01-31) - * HH is the hour of the day (00-23) - * mm is the minute of the hour (00-59) - * SS is the second of the hour (00-59) - * xxx if present, is a fractional second and may be any length - * Time is expressed in UTC (GMT), not local time. - */ - - PRExplodedTime ts; - int64 s2us, st; - PRTime t; - time_t tt; - - TRACEMSG(("Parsing MDTM \"%.1024s\"", cd->return_msg, CR, LF)); - - ts.tm_year = (cd->return_msg[0] - '0') * 1000 + - (cd->return_msg[1] - '0') * 100 + - (cd->return_msg[2] - '0') * 10 + - (cd->return_msg[3] - '0'); - - ts.tm_month = ((cd->return_msg[4] - '0') * 10 + (cd->return_msg[5] - '0')) - 1; - ts.tm_mday = (cd->return_msg[6] - '0') * 10 + (cd->return_msg[7] - '0'); - ts.tm_hour = (cd->return_msg[8] - '0') * 10 + (cd->return_msg[9] - '0'); - ts.tm_min = (cd->return_msg[10] - '0') * 10 + (cd->return_msg[11] - '0'); - ts.tm_sec = (cd->return_msg[12] - '0') * 10 + (cd->return_msg[13] - '0'); - ts.tm_usec = 0; - - /* - * if( '.' == cd->return_msg[14] ) - * { - * long int i = 1000000; - * char *p = &cd->return_msg[15]; - * while( isdigit(*p) ) - * { - * ts.tm_usec += (*p - '0') * i; - * i /= 10; - * p++; - * } - * } - */ - - t = PR_ImplodeTime(&ts); - LL_I2L(s2us, PR_USEC_PER_SEC); - LL_DIV(st, t, s2us); - LL_L2I(tt, st); - -#ifdef DEBUG - { - char line[256]; - PRExplodedTime et; - PRTime t2; - LL_MUL(t2, st, s2us); - PR_ExplodeTime(t2, PR_GMTParameters, &et); - PR_FormatTimeUSEnglish(line, sizeof(line), "%Y%m%d%H%M%S", &et); - TRACEMSG(("Parse check: mdtm is \"%s\"", line)); - } -#endif - - if( cd->restart && (ce->URL_s->last_modified != 0) ) - { - TRACEMSG(("Verifying last modified date: was %ld, is %ld", - ce->URL_s->last_modified, tt)); - if( ce->URL_s->last_modified != tt ) - { - TRACEMSG(("Doesn't match! Clearing restart flag.")); - cd->restart = FALSE; - ce->URL_s->last_modified = tt; - } - else - { - TRACEMSG(("Time of last modification didn't change.")); - } - } - else - { - ce->URL_s->last_modified = tt; - TRACEMSG(("set last modified: %ld", ce->URL_s->last_modified)); - } - } - - cd->next_state = FTP_GET_FILE; - - return(0); -} - -PRIVATE int -net_get_ftp_file(FTPConData * cd) -{ - - /* if this is a VMS server then we need to - * do some special things to map a UNIX syntax - * ftp url to a VMS type file syntax - */ - if (cd->cc->server_type == FTP_VMS_TYPE) - { - cd->restart = FALSE; - /* If we want the VMS account's top directory speed to it - */ - if (cd->path[0] == '\0' || (cd->path[0] == '/' && cd->path[1]== '\0')) - { - cd->is_directory = YES; - cd->next_state = FTP_SEND_LIST_OR_NLST; - } - else if(!PL_strchr(cd->path, '/')) - { - /* if we want a file out of the top directory skip the PWD - */ - cd->next_state = FTP_SEND_RETR; - } - else - { - cd->next_state = FTP_SEND_CWD; - } - - } - else - { /* non VMS */ - /* if we have already done the RETR or - * if the path ends with a slash - */ - if(cd->retr_already_failed || - '/' == cd->path[PL_strlen(cd->path)-1]) - cd->next_state = FTP_SEND_CWD; - else - { - if( cd->restart ) cd->next_state = FTP_SEND_REST; - else cd->next_state = FTP_SEND_RETR; - } - } - - return(0); /* continue */ -} - -PRIVATE int -net_send_cwd(FTPConData * cd) -{ - - if (cd->cc->server_type == FTP_VMS_TYPE) - { - char *cp, *cp1; - /** Try to go to the appropriate directory and doctor filename **/ - if ((cp=PL_strrchr(cd->path, '/'))!=NULL) - { - *cp = '\0'; - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "CWD [%.1024s]" CRLF, - cd->path); - *cp = '/'; /* set it back so it is left unmodified */ - - /* turn slashes into '.' */ - while ((cp1=PL_strchr(cd->output_buffer, '/')) != NULL) - *cp1 = '.'; - } - else - { - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "CWD [.%.1024s]" CRLF, - cd->path); - } - } /* if FTP_VMS_TYPE */ - else - { /* non VMS server */ - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "CWD %.1024s" CRLF, cd->path); - } - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_CWD_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_cwd_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if (cd->response_code == 2) /* Successed : let's NAME LIST it */ - { - - if(cd->file_to_post) - { - cd->next_state = FTP_BEGIN_PUT; - return(0); /* good */ - } - else if(ce->URL_s->method == URL_PUT_METHOD) - { - cd->next_state = FTP_BEGIN_PUT; - return(0); /* good */ - } - - ce->URL_s->is_directory = TRUE; - cd->restart = FALSE; - - if (cd->cc->server_type == FTP_VMS_TYPE) - { - if(*cd->filename) - cd->next_state = FTP_SEND_RETR; - else - cd->next_state = FTP_SEND_LIST_OR_NLST; - return(0); /* good */ - } - - /* non VMS server */ - /* we are in the correct directory and we - * already failed on the RETR so lets - * LIST or NLST it - */ - cd->next_state = FTP_SEND_LIST_OR_NLST; - return(0); /* good */ - } - - /* else */ - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LOCATE_FILE, - *cd->path ? cd->path : "/"); - - return MK_UNABLE_TO_LOCATE_FILE; /* error */ -} - -PRIVATE int -net_begin_put(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - char *path, *filename; - - if(cd->file_to_post) - { - /* Use post_file_to as destination filename, if supplied. */ - /* All path info in post_file_to is thrown away. Assumed to - be in same directory. */ - if (cd->post_file_to) { - path = PL_strdup(cd->post_file_to); - if(!path) - return(MK_OUT_OF_MEMORY); - filename = PL_strrchr(path, '/'); - } - else { - path = PL_strdup(cd->file_to_post); - if(!path) - return(MK_OUT_OF_MEMORY); -#if defined(XP_WIN) || defined(XP_OS2) /* IBM - SAH */ - filename = PL_strrchr(path, '\\'); -#else - filename = PL_strrchr(path, '/'); -#endif - } - } - else - { - path = NET_ParseURL(ce->URL_s->address, GET_PATH_PART); - if(!path) - return(MK_OUT_OF_MEMORY); - filename = PL_strrchr(path, '/'); - } - - if(!filename) - filename = path; - else - filename++; /* go past delimiter */ - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "STOR %.1024s" CRLF, - filename); - -#ifdef EDITOR - if(cd->destroy_file_upload_progress_dialog) - FE_SaveDialogSetFilename(ce->window_id, filename); -#endif /* EDITOR */ - - PR_Free(path); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_BEGIN_PUT_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - - -PRIVATE int -net_begin_put_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if (cd->response_code != 1) - { - /* failed */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_COULD_NOT_PUT_FILE, - cd->file_to_post ? - cd->file_to_post : ce->URL_s->address, - cd->return_msg ? cd->return_msg : ""); - return(MK_COULD_NOT_PUT_FILE); - } - - NET_ClearReadSelect(ce->window_id, ce->socket); - ce->socket = cd->dsock; - ce->con_sock = cd->dsock; - -#if defined(XP_WIN16) || (defined(XP_OS2) && !defined(XP_OS2_DOUGSOCK)) /* stuff not for windows since setsockopt doesnt work */ - { - PRSocketOptionData opt; - /* turn the linger off so that we don't - * wait but we don't abort either - * since aborting will lose quede data - */ - opt.option = PR_SockOpt_Linger; - opt.value.linger.polarity = PR_FALSE; - opt.value.linger.linger = PR_INTERVAL_NO_WAIT; - PR_SetSocketOption(cd->listen_sock, &opt); - } -#endif /* XP_WIN16 */ - - /* set connect select because we are writting - * not reading - */ - if(cd->pasv_mode) - NET_SetConnectSelect(ce->window_id, ce->socket); -#ifdef XP_WIN - cd->calling_netlib_all_the_time = TRUE; - NET_SetCallNetlibAllTheTime(ce->window_id, "mkftp"); -#endif - - - /* Maybe should change string if cd->post_file_to */ - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - XP_GetString( XP_POSTING_FILE ), - cd->file_to_post); - -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, cd->output_buffer); -#else - NET_Progress(ce->window_id, cd->output_buffer); -#endif - - if(cd->pasv_mode) - { - cd->next_state = FTP_DO_PUT; - } - else - { /* non PASV */ - cd->next_state = FTP_WAIT_FOR_ACCEPT; - } - - return(0); - -} - -/* finally send the file - */ -PRIVATE int -net_do_put(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - /* Default to adding crlf if ftp ASCII mode. */ - XP_Bool add_crlf = (cd->cc->cur_mode == FTP_MODE_ASCII); - - - if(!cd->write_post_data_data) - { - /* first time through */ - - /* if file_to_post is filled in then - * throw the name into the post data - * so that we can use the WritePostData - * function - */ - if(cd->file_to_post) - { - ce->URL_s->post_data = cd->file_to_post; - ce->URL_s->post_data_is_file = TRUE; - } - } - - /* If the add_crlf field is set in the URL struct, find the - entry corresponding to the current file being posted. */ - if (ce->URL_s->files_to_post && ce->URL_s->add_crlf) { - int n = 0; - while (ce->URL_s->files_to_post[n]) { - n++; - } - /* n should now point after the last entry in files_to_post, - which is the current file being uploaded. */ - add_crlf = ce->URL_s->add_crlf[n]; - } - - /* returns 0 on done and negative on error - * positive if it needs to continue. - */ - ce->status = NET_WritePostData(ce->window_id, ce->URL_s, - ce->socket, - &cd->write_post_data_data, - add_crlf); - - cd->pause_for_read = TRUE; - - if(ce->status == 0) - { - /* normal done - */ - NET_ClearConnectSelect(ce->window_id, ce->socket); -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - { - cd->calling_netlib_all_the_time = FALSE; - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkftp"); - } -#endif - ce->socket = cd->cc->csock; - ce->con_sock = NULL; - NET_SetReadSelect(ce->window_id, ce->socket); - - PR_Close(cd->dsock); - cd->dsock = NULL; - -#if !defined(SMOOTH_PROGRESS) - if(cd->destroy_graph_progress) - { - FE_GraphProgressDestroy(ce->window_id, - ce->URL_s, - cd->original_content_length, - ce->bytes_received); - cd->destroy_graph_progress = FALSE; - } -#endif - - /* go read the response since we need to - * get the "226 sucessful transfer" message - * out of the read queue in order to cache - * connections properly - */ - cd->next_state = FTP_WAIT_FOR_RESPONSE; - - if(cd->file_to_post) - { - ce->URL_s->post_data = 0; - ce->URL_s->post_data_is_file = FALSE; - PR_FREEIF(cd->file_to_post); - cd->file_to_post = NULL; - } - - if (cd->post_file_to) - { - PR_FREEIF(cd->post_file_to); - cd->post_file_to = NULL; - } - - /* after getting the server response start - * over again if there are more - * files to send or to do a new directory - * listing... - */ - cd->next_state_after_response = FTP_DONE; - - - /* if this was the last file, check the history - * to see if the window is currently displaying an ftp - * listing. If it is update the listing. If it isnt - * quit. - */ - if(ce->URL_s->files_to_post) - { - if(ce->URL_s->files_to_post[0]) - { - /* more files, keep going */ - cd->next_state_after_response = FTP_FIGURE_OUT_WHAT_TO_DO; - } - /* Don't want to show a directory when remote editing a FTP page, bug 50942 */ - else if (!EDT_IS_EDITOR(ce->window_id)) - { - /* no more files, figure out if we should - * show an index - */ -#ifdef MOZILLA_CLIENT - History_entry * his = SHIST_GetCurrent(&ce->window_id->hist); -#else - History_entry * his = NULL; -#endif /* MOZILLA_CLIENT */ - - if(his && !PL_strncasecmp(his->address, "ftp:", 4)) - { - /* go get the index of the directory */ - cd->next_state_after_response = FTP_FIGURE_OUT_WHAT_TO_DO; - } - } - } - } - else if(ce->status > 0) - { - ce->bytes_received += ce->status; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, ce->URL_s, ce->bytes_received, ce->URL_s->content_length); -#else - FE_GraphProgress(ce->window_id, - ce->URL_s, - ce->bytes_received, - ce->status, - ce->URL_s->content_length); - FE_SetProgressBarPercent(ce->window_id, - (long)(((double)ce->bytes_received*100) / (double)(uint32)ce->URL_s->content_length) ); -#endif - } - - return(ce->status); -} - -PRIVATE int -net_send_rest(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "REST %ld%c%c", - ce->URL_s->content_length, CR, LF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_REST_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Rx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_rest_response(ActiveEntry *ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if(cd->response_code == 3 && cd->return_msg) - { - TRACEMSG(("Restarting! Yay!")); - } - else - { - TRACEMSG(("Didn't understand the REST command.")); - cd->cc->no_restart = TRUE; - cd->restart = FALSE; - } - - cd->next_state = FTP_SEND_RETR; - return(0); -} - - -PRIVATE int -net_send_retr(FTPConData * cd) -{ - - if(cd->cc->server_type == FTP_VMS_TYPE) - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "RETR %.1024s" CRLF, - cd->filename); - else - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "RETR %.1024s" CRLF, - cd->path); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_RETR_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - - -PRIVATE int -net_send_retr_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - if(cd->response_code != 1) - { - if(cd->cc->server_type == FTP_VMS_TYPE) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_LOCATE_FILE, - *cd->path ? cd->path : "/"); - return(MK_UNABLE_TO_LOCATE_FILE); - } - else - { /* non VMS */ - -#ifdef DOUBLE_PASV - /* this will use a new PASV connection - * for each command even if the one only - * failed and didn't transmit - */ - /* close the old pasv connection */ - NETCLOSE(cd->dsock); - /* invalidate the old pasv connection */ - cd->dsock = NULL; - - cd->next_state = FTP_SEND_PASV; /* send it again */ - cd->retr_already_failed = TRUE; -#else - /* we need to use this to make the mac FTPD work - */ - /* old way */ - cd->next_state = FTP_SEND_CWD; -#endif /* DOUBLE_PASV */ - } - } - else - { /* successful RETR */ - cd->next_state = FTP_SETUP_STREAM; - } - - return(0); /* continue */ -} - -PRIVATE int -net_send_list_or_nlst(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if(cd->cc->use_list) - PL_strcpy(cd->output_buffer, "LIST" CRLF); - else - PL_strcpy(cd->output_buffer, "NLST" CRLF); - - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_LIST_OR_NLST_RESPONSE; - cd->pause_for_read = TRUE; - - TRACEMSG(("FTP Tx: %s", cd->output_buffer)); - - return((int) NET_BlockingWrite(cd->cc->csock, - cd->output_buffer, - PL_strlen(cd->output_buffer))); -} - -PRIVATE int -net_send_list_or_nlst_response(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if(cd->response_code == 1) - { /* succesful list or nlst */ - cd->is_directory = TRUE; - cd->restart = FALSE; - cd->next_state = FTP_SETUP_STREAM; - - /* add a slash to the end of the uRL if it doesnt' have one now - */ - if(ce->URL_s->address[PL_strlen(ce->URL_s->address)-1] != '/') - { - /* update the global history before modification - */ -#ifdef MOZILLA_CLIENT - GH_UpdateGlobalHistory(ce->URL_s); -#endif /* MOZILLA_CLIENT */ - StrAllocCat(ce->URL_s->address, "/"); - ce->URL_s->address_modified = TRUE; - } - - return(0); /* good */ - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LOCATE_FILE, - *cd->path ? cd->path : "/"); - return(MK_UNABLE_TO_LOCATE_FILE); -} - - -PRIVATE int -net_setup_ftp_stream(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - /* set up the data stream now - */ - if(cd->is_directory) - { - char * pUrl ; - int status; - - status = PREF_CopyCharPref("protocol.mimefor.ftp",&pUrl); - - if (status >= 0 && pUrl) { - StrAllocCopy(ce->URL_s->content_type, pUrl); - PR_Free(pUrl); - } else { - StrAllocCopy(ce->URL_s->content_type, APPLICATION_HTTP_INDEX); - } - - cd->stream = net_ftp_make_stream(ce->format_out, ce->URL_s, ce->window_id); - } - else - { - if(!ce->URL_s->preset_content_type || !ce->URL_s->content_type ) - { - NET_cinfo * cinfo_struct = NET_cinfo_find_type(cd->filename); - StrAllocCopy(ce->URL_s->content_type, cinfo_struct->type); - - cinfo_struct = NET_cinfo_find_enc(cd->filename); - StrAllocCopy(ce->URL_s->content_encoding, cinfo_struct->encoding); - } - - cd->stream = net_ftp_make_stream(ce->format_out, ce->URL_s, ce->window_id); - } - - if (!cd->stream) - { - cd->next_state = FTP_ERROR_DONE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return(MK_UNABLE_TO_CONVERT); - } - -HG69136 - - if(cd->pasv_mode) - { - if(cd->is_directory) - cd->next_state = FTP_START_READ_DIRECTORY; - else - cd->next_state = FTP_START_READ_FILE; - } - else - { /* non PASV */ - cd->next_state = FTP_WAIT_FOR_ACCEPT; - } - - /* start the graph progress indicator - */ -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, ce->URL_s, 0, ce->URL_s->real_content_length); -#else - FE_GraphProgressInit(ce->window_id, ce->URL_s, ce->URL_s->real_content_length); - cd->destroy_graph_progress = TRUE; -#endif - cd->original_content_length = ce->URL_s->real_content_length; - - return(0); /* continue */ -} - -PRIVATE int -net_wait_for_ftp_accept(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - PRNetAddr pr_addr; - -/* make this non-blocking sometime */ - - /* Wait for the connection - */ -#define ACCEPT_TIMEOUT 20 - cd->dsock = PR_Accept(cd->listen_sock, &pr_addr, ACCEPT_TIMEOUT); - - if (cd->dsock == NULL) - { - if(PR_GetError() == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; /* pause */ - NET_ClearReadSelect(ce->window_id, ce->socket); - ce->socket = cd->listen_sock; - NET_SetReadSelect(ce->window_id, ce->socket); - return(0); - } - else - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_ACCEPT_SOCKET); - return MK_UNABLE_TO_ACCEPT_SOCKET; - } - } - - TRACEMSG(("FTP: Accepted new socket %d\n", cd->dsock)); - - if(cd->file_to_post || ce->URL_s->method == URL_POST_METHOD) - { - ce->socket = cd->dsock; - NET_SetConnectSelect(ce->window_id, ce->socket); - cd->next_state = FTP_DO_PUT; - } - else if (cd->is_directory) - { - cd->next_state = FTP_START_READ_DIRECTORY; - } - else - { - cd->next_state = FTP_START_READ_FILE; - } - - return(0); -} - -PRIVATE int -net_ftp_push_partial_cache_file(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - int32 write_ready, status; - - write_ready = (*cd->stream->is_write_ready)(cd->stream); - - if( 0 == write_ready ) - { - cd->pause_for_read = TRUE; - return(0); /* wait until we are ready to write */ - } - - write_ready = MIN(write_ready, NET_Socket_Buffer_Size); - - status = NET_XP_FileRead(NET_Socket_Buffer, write_ready, cd->partial_cache_fp); - - if( status < 0 ) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, - PR_GetOSError()); - return MK_TCP_READ_ERROR; - } - else if( status == 0 ) - { - /* All done, switch over to incoming data */ - TRACEMSG(("Closing FTP cache file")); -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, XP_GetString(XP_PROGRESS_FILEDONE)); -#else - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_FILEDONE)); -#endif - NET_ClearFileReadSelect(ce->window_id, XP_Fileno(cd->partial_cache_fp)); - NET_XP_FileClose(cd->partial_cache_fp); - cd->partial_cache_fp = NULL; - ce->socket = cd->dsock; - NET_SetReadSelect(ce->window_id, ce->socket); - ce->local_file = FALSE; - cd->next_state = FTP_READ_FILE; -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, XP_GetString(XP_PROGRESS_RECEIVE_FTPFILE)); -#else - NET_Progress (ce->window_id, XP_GetString(XP_PROGRESS_RECEIVE_FTPFILE)); -#endif - return 0; - } - else - { - /* write the data */ - TRACEMSG(("Transferring %ld bytes from cache file.", status)); - ce->bytes_received += status; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, ce->URL_s, ce->bytes_received, ce->URL_s->real_content_length); -#else - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, status, ce->URL_s->real_content_length); - FE_SetProgressBarPercent(ce->window_id, (long)(((double)ce->bytes_received*100) / (double)(uint32)ce->URL_s->real_content_length) ); -#endif - status = (*cd->stream->put_block)(cd->stream, NET_Socket_Buffer, status); - cd->pause_for_read = TRUE; - return status; - } -} - -PRIVATE int -net_start_ftp_read_file(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if( cd->restart ) - { - char *cache_file = ce->URL_s->cache_file; - XP_File fp; - - TRACEMSG(("Opening FTP cache file")); - - if( (NULL == cache_file) || (NULL == (fp = NET_XP_FileOpen(cache_file, xpCache, XP_FILE_READ_BIN))) ) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_OPEN_FILE, cache_file); - return MK_UNABLE_TO_OPEN_FILE; - } - - NET_ClearReadSelect(ce->window_id, ce->socket); - /* ce->socket = XP_Fileno(fp); */ - ce->socket = NULL; - NET_SetFileReadSelect(ce->window_id, XP_Fileno(fp)); - ce->local_file = TRUE; - cd->next_state = FTP_READ_CACHE; - cd->partial_cache_fp = fp; -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, XP_GetString(XP_PROGRESS_READFILE)); -#else - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_READFILE)); -#endif - return net_ftp_push_partial_cache_file(ce); - } - - /* nothing much to be done */ - cd->next_state = FTP_READ_FILE; - cd->pause_for_read = TRUE; - - NET_ClearReadSelect(ce->window_id, ce->socket); - ce->socket = cd->dsock; - NET_SetReadSelect(ce->window_id, ce->socket); - -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, XP_GetString(XP_PROGRESS_RECEIVE_FTPFILE)); -#else - NET_Progress (ce->window_id, XP_GetString(XP_PROGRESS_RECEIVE_FTPFILE)); -#endif - - return(0); /* continue */ -} - -PRIVATE int -net_ftp_read_file(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - int status; - unsigned int write_ready, read_size; - - /* check to see if the stream is ready for writing - */ - write_ready = (*cd->stream->is_write_ready)(cd->stream); - - if(!write_ready) - { - cd->pause_for_read = TRUE; - return(0); /* wait until we are ready to write */ - } - else if(write_ready < (unsigned int) NET_Socket_Buffer_Size) - { - read_size = write_ready; - } - else - { - read_size = NET_Socket_Buffer_Size; - } - - status = PR_Read(cd->dsock, NET_Socket_Buffer, read_size); - - if(status > 0) - { - ce->bytes_received += status; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, ce->URL_s, ce->bytes_received, ce->URL_s->real_content_length); -#else - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, status, ce->URL_s->real_content_length); - if (ce->URL_s->real_content_length == 0) - FE_SetProgressBarPercent(ce->window_id, 0); - else - FE_SetProgressBarPercent(ce->window_id, (long)(((double)ce->bytes_received*100) / (double)(uint32)ce->URL_s->real_content_length) ); -#endif - status = PUTBLOCK(NET_Socket_Buffer, status); - cd->pause_for_read = TRUE; - } - else if(status == 0) - { - /* go read the response since we need to - * get the "226 sucessful transfer" message - * out of the read queue in order to cache - * connections properly - */ - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_DONE; - - if(cd->dsock != NULL) - { - NET_ClearReadSelect(ce->window_id, cd->dsock); - PR_Close(cd->dsock); - cd->dsock = NULL; - } - - /* set select on the control socket */ - ce->socket = cd->cc->csock; - NET_SetReadSelect(ce->window_id, ce->socket); - /* try and read the response immediately, - * so don't pause for read - * - * cd->pause_for_read = TRUE; - */ - - return(MK_DATA_LOADED); - } - else - { - /* status less than zero - */ - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return 0; - } - status = (rv < 0) ? rv : (-rv); - } - - return(status); -} - -PRIVATE int -net_start_ftp_read_dir(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - char buf[512]; - char *line; - - cd->sort_base = NET_SortInit(); - -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, XP_GetString(XP_PROGRESS_RECEIVE_FTPDIR)); -#else - NET_Progress (ce->window_id, XP_GetString(XP_PROGRESS_RECEIVE_FTPDIR)); -#endif - - if (*cd->path != '\0') /* Not Empty path: */ - { - int end; - - end = PL_strlen(cd->path)-1; - /* if the path ends with a slash kill it. - * that includes the path "/" - */ - if(cd->path[end] == '/') - { - cd->path[end] = 0; /* kill the last slash */ - } - } - - if(cd->login_message_buffer) /* Don't check !(*cd->path) here or this - message never shows up. It's supposed to - be shown the first time you connect to - this server, whether you started at the - root or not. */ - { - - /* print it out like so: 101: message line 1 - * 101: message line 2, etc... - */ - line = strtok(cd->login_message_buffer, "\n"); - while(ce->status >= 0 && line) - { - PL_strcpy(buf, "101: "); - PL_strcatn (buf, sizeof(buf)-8, line); - PL_strcat (buf, CRLF); - - ce->status = PUTSTRING(buf); - - line = strtok(NULL, "\n"); - } - - /* if there is also a cwd message add a blank line */ - if(ce->status >= 0 && cd->cwd_message_buffer) - { - PL_strcpy(buf, "101: "CRLF); - ce->status = PUTSTRING(buf); - } - } - - if(cd->cwd_message_buffer) - { - /* print it out like so: 101: message line 1 - * 101: message line 2, etc... - */ - char *end_line = PL_strchr(cd->cwd_message_buffer, '\n'); - if(end_line) - *end_line = '\0'; - line = cd->cwd_message_buffer; - - while(ce->status >= 0 && line) - { - PL_strcpy(buf, "101: "); - PL_strcatn (buf, sizeof(buf)-8, line); - PL_strcat (buf, CRLF); - - ce->status = PUTSTRING(buf); - - if(end_line) - { - line = end_line+1; - end_line = PL_strchr(line, '\n'); - if(end_line) - *end_line = '\0'; - } - else - { - line = NULL; - } - } - } - - /* clear the buffer so we can use it on the data sock */ - PR_FREEIF(cd->data_buf); - cd->data_buf = NULL; - cd->data_buf_size = 0; - - cd->next_state = FTP_READ_DIRECTORY; - - /* clear the select on the control socket - */ - NET_ClearReadSelect(ce->window_id, ce->socket); - ce->socket = cd->dsock; - NET_SetReadSelect(ce->window_id, ce->socket); - - return(0); /* continue */ -} - -PRIVATE int -net_ftp_read_dir(ActiveEntry * ce) -{ - - char * line; - NET_FileEntryInfo * entry_info; - FTPConData * cd = (FTPConData *)ce->con_data; - - ce->status = NET_BufferedReadLine(cd->dsock, &line, &cd->data_buf, - &cd->data_buf_size, &cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = FTP_PRINT_DIR; -#ifdef XP_MAC - cd->pause_for_read = FALSE; /* rjc: fix FTP for Mac */ -#endif - return(ce->status); - } - else if(ce->status < 0) - { - if(cd->stream && (*cd->stream->is_write_ready)(cd->stream)) - NET_PrintDirectory(&cd->sort_base, cd->stream, cd->path, ce->URL_s); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, ce->status); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - /* not exactly right but really close - */ - if(ce->status > 1) - { - ce->bytes_received += ce->status; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, ce->URL_s, ce->bytes_received, ce->URL_s->content_length); -#else - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, ce->status, ce->URL_s->content_length); -#endif - } - - if(!line) - return(0); /* no line ready */ - - TRACEMSG(("MKFTP: Line in %s is %s\n", cd->path, line)); - - entry_info = net_parse_dir_entry(line, cd->cc->server_type); - - if(!entry_info) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - if(entry_info->display) - { - TRACEMSG(("Adding file to sort list: %s\n", entry_info->filename)); - NET_SortAdd(cd->sort_base, (void *)entry_info); - } - else - { - NET_FreeEntryInfoStruct(entry_info); - } - - return(ce->status); -} - -PRIVATE int -net_ftp_print_dir(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - if(!cd->calling_netlib_all_the_time) - { - - cd->calling_netlib_all_the_time = TRUE; - NET_SetCallNetlibAllTheTime(ce->window_id, "mkftp"); - } - - if(cd->stream - && (ce->status = (*cd->stream->is_write_ready)(cd->stream)) != 0) - { - ce->status = NET_PrintDirectory(&cd->sort_base, cd->stream, cd->path, ce->URL_s); - - /* go read the response since we need to - * get the "226 sucessful transfer" message - * out of the read queue in order to cache - * connections properly - */ - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_DONE; - - /* clear select on the data sock and set select on the control sock - */ - if(cd->dsock != NULL) - { - NET_ClearReadSelect(ce->window_id, cd->dsock); - PR_Close(cd->dsock); - cd->dsock = NULL; - } - - ce->socket = cd->cc->csock; - NET_SetReadSelect(ce->window_id, cd->cc->csock); - - return(ce->status); - } - else - { - /* come back into this state and try again later */ - /* @@@ busy wait */ - cd->pause_for_read = TRUE; - return(0); - } -} - -/* - * is_ls_date() -- - * Return 1 if the ptr points to a string of the form: - * "Sep 1 1990 " or - * "Sep 11 11:59 " or - * "Dec 12 1989 " or - * "FCv 23 1990 " ... - */ -PRIVATE Bool -net_is_ls_date (char *s) -{ - /* must start with three alpha characters */ - if (!isalpha(*s++) || !isalpha(*s++) || !isalpha(*s++)) - return FALSE; - - /* space */ - if (*s++ != ' ') - return FALSE; - - /* space or digit */ - if ((*s != ' ') && !isdigit(*s)) - return FALSE; - s++; - - /* digit */ - if (!isdigit(*s++)) - return FALSE; - - /* space */ - if (*s++ != ' ') - return FALSE; - - /* space or digit */ - if ((*s != ' ') && !isdigit(*s)) - return FALSE; - s++; - - /* digit */ - if (!isdigit(*s++)) - return FALSE; - - /* colon or digit */ - if ((*s != ':') && !isdigit(*s)) - return FALSE; - s++; - - /* digit */ - if (!isdigit(*s++)) - return FALSE; - - /* space or digit */ - if ((*s != ' ') && !isdigit(*s)) - return FALSE; - s++; - - /* space */ - if (*s++ != ' ') - return FALSE; - - return TRUE; -} /* is_ls_date() */ - -/* - * Converts a date string from 'ls -l' to a time_t number - * - * "Sep 1 1990 " or - * "Sep 11 11:59 " or - * "Dec 12 1989 " or - * "FCv 23 1990 " ... - * - * Returns 0 on error. - */ -PRIVATE time_t net_convert_unix_date (char * datestr) -{ - struct tm *time_info; /* Points to static tm structure */ - char *bcol = datestr; /* Column begin */ - char *ecol; /* Column end */ - long tval; - int cnt; - time_t curtime = time(NULL); - - if ((time_info = gmtime(&curtime)) == NULL) - { - return (time_t) 0; - } - - time_info->tm_isdst = -1; /* Disable summer time */ - for (cnt=0; cnt<3; cnt++) /* Month */ - *bcol++ = toupper(*bcol); - - if ((time_info->tm_mon = NET_MonthNo(datestr)) < 0) - return (time_t) 0; - - ecol = bcol; /* Day */ - while (*ecol++ == ' ') ; /* Spool to other side of day */ - while (*ecol++ != ' ') ; - *--ecol = '\0'; - - time_info->tm_mday = atoi(bcol); - time_info->tm_wday = 0; - time_info->tm_yday = 0; - bcol = ++ecol; /* Year */ - if ((ecol = PL_strchr(bcol, ':')) == NULL) - { - time_info->tm_year = atoi(bcol)-1900; - time_info->tm_sec = 0; - time_info->tm_min = 0; - time_info->tm_hour = 0; - } - else - { /* Time */ - /* If the time is given as hh:mm, then the file is less than 1 year - * old, but we might shift calandar year. This is avoided by checking - * if the date parsed is future or not. - */ - *ecol = '\0'; - time_info->tm_sec = 0; - time_info->tm_min = atoi(++ecol); /* Right side of ':' */ - time_info->tm_hour = atoi(bcol); /* Left side of ':' */ - if (mktime(time_info) > curtime) - --time_info->tm_year; - } - return ((tval = mktime(time_info)) == -1 ? (time_t) 0 : tval); -} - -/* a dos date/time string looks like this - * 04-06-95 02:03PM - * 07-13-95 11:39AM - */ -PRIVATE time_t -net_parse_dos_date_time (char * datestr) -{ - struct tm *time_info; /* Points to static tm structure */ - long tval; - time_t curtime = time(NULL); - - if ((time_info = gmtime(&curtime)) == NULL) - { - return (time_t) 0; - } - - time_info->tm_isdst = -1; /* Disable summer time */ - - time_info->tm_mon = (datestr[1]-'0')-1; - - time_info->tm_mday = (((datestr[3]-'0')*10) + datestr[4]-'0'); - time_info->tm_year = (((datestr[6]-'0')*10) + datestr[7]-'0'); - time_info->tm_hour = (((datestr[10]-'0')*10) + datestr[11]-'0'); - if(datestr[15] == 'P') - time_info->tm_hour += 12; - time_info->tm_min = (((datestr[13]-'0')*10) + datestr[14]-'0'); - - time_info->tm_wday = 0; - time_info->tm_yday = 0; - time_info->tm_sec = 0; - - return ((tval = mktime(time_info)) == -1 ? (time_t) 0 : tval); -} - -/* - * Converts a date string from vms to a time_t number - * This is needed in order to put out the date using the same format - * for all directory listings. - * - * Returns 0 on error - */ -PRIVATE time_t net_convert_vms_date (char * datestr) -{ - struct tm *time_info; /* Points to static tm structure */ - char *col; - long tval; - time_t curtime = time(NULL); - - if ((time_info = gmtime(&curtime)) == NULL) - return (time_t) 0; - - time_info->tm_isdst = -1; /* Disable summer time */ - - if ((col = strtok(datestr, "-")) == NULL) - return (time_t) 0; - - time_info->tm_mday = atoi(col); /* Day */ - time_info->tm_wday = 0; - time_info->tm_yday = 0; - - if ((col = strtok(NULL, "-")) == NULL || (time_info->tm_mon = NET_MonthNo(col)) < 0) - return (time_t) 0; - - if ((col = strtok(NULL, " ")) == NULL) /* Year */ - return (time_t) 0; - - time_info->tm_year = atoi(col)-1900; - - if ((col = strtok(NULL, ":")) == NULL) /* Hour */ - return (time_t) 0; - - time_info->tm_hour = atoi(col); - - if ((col = strtok(NULL, " ")) == NULL) /* Mins */ - return (time_t) 0; - - time_info->tm_min = atoi(col); - time_info->tm_sec = 0; - - return ((tval = mktime(time_info)) < 0 ? (time_t) 0 : tval); -} - - -/* - * parse_ls_line() -- - * Extract the name, size, and date from an ls -l line. - * - * ls -l listing - * - * drwxr-xr-x 2 montulli eng 512 Nov 8 23:23 CVS - * -rw-r--r-- 1 montulli eng 2244 Nov 8 23:23 Imakefile - * -rw-r--r-- 1 montulli eng 14615 Nov 9 17:03 Makefile - * - * or a dl listing - * - * cs.news/ = ICSI Computing Systems Newsletter - * dash/ - DASH group documents and software - * elisp/ - Emacs lisp code - * - */ -PRIVATE void -net_parse_ls_line (char *line, NET_FileEntryInfo *entry_info) -{ - int32 base=1; - int32 size_num=0; - char save_char; - char *ptr; - - for (ptr = &line[PL_strlen(line) - 1]; - (ptr > line+13) && (!NET_IS_SPACE(*ptr) || !net_is_ls_date(ptr-12)); ptr--) - ; /* null body */ - save_char = *ptr; - *ptr = '\0'; - if (ptr > line+13) - { - entry_info->date = net_convert_unix_date(ptr-12); - } - else - { - /* must be a dl listing - */ - /* unterminate the line */ - *ptr = save_char; - /* find the first whitespace and terminate - */ - for(ptr=line; *ptr != '\0'; ptr++) - if(NET_IS_SPACE(*ptr)) - { - *ptr = '\0'; - break; - } - entry_info->filename = NET_Escape(line, URL_PATH); - - return; - } - - /* escape and copy - */ - entry_info->filename = NET_Escape(ptr+1, URL_PATH); - - /* parse size - */ - if(ptr > line+15) - { - ptr -= 14; - while (isdigit(*ptr)) - { - size_num += ((int32) (*ptr - '0')) * base; - base *= 10; - ptr--; - } - - entry_info->size = size_num; - } - -} /* parse_ls_line() */ - -/* - * net_parse_vms_dir_entry() - * Format the name, date, and size from a VMS LIST line - * into the EntryInfo structure - */ -PRIVATE void -net_parse_vms_dir_entry (char *line, NET_FileEntryInfo *entry_info) -{ - int i, j; - int32 ialloc; - char *cp, *cpd, *cps, date[64], *sp = " "; - time_t NowTime; - static char ThisYear[32]; - static Bool HaveYear = FALSE; - - /** Get rid of blank lines, and information lines. **/ - /** Valid lines have the ';' version number token. **/ - if (!PL_strlen(line) || (cp=PL_strchr(line, ';')) == NULL) - { - entry_info->display = FALSE; - return; - } - - /** Cut out file or directory name at VMS version number. **/ - *cp++ ='\0'; - /* escape and copy - */ - entry_info->filename = NET_Escape(line, URL_PATH); - - /** Cast VMS file and directory names to lowercase. **/ - for (i=0; entry_info->filename[i]; i++) - entry_info->filename[i] = tolower(entry_info->filename[i]); - - /** Uppercase terminal .z's or _z's. **/ - if ((--i > 2) && entry_info->filename[i] == 'z' && - (entry_info->filename[i-1] == '.' || entry_info->filename[i-1] == '_')) - entry_info->filename[i] = 'Z'; - - /** Convert any tabs in rest of line to spaces. **/ - cps = cp-1; - while ((cps=PL_strchr(cps+1, '\t')) != NULL) - *cps = ' '; - - /** Collapse serial spaces. **/ - i = 0; j = 1; - cps = cp; - while (cps[j] != '\0') - { - if (cps[i] == ' ' && cps[j] == ' ') - j++; - else - cps[++i] = cps[j++]; - } - cps[++i] = '\0'; - - /* Save the current year. - * It could be wrong on New Year's Eve. - */ - if (!HaveYear) - { - NowTime = time(NULL); - PL_strcpy(ThisYear, (char *)ctime(&NowTime)+20); - ThisYear[4] = '\0'; - HaveYear = TRUE; - } - - /* get the date. - */ - if ((cpd=PL_strchr(cp, '-')) != NULL && - PL_strlen(cpd) > 9 && isdigit(*(cpd-1)) && - isalpha(*(cpd+1)) && *(cpd+4) == '-') - { - - /* Month - */ - *(cpd+4) = '\0'; - *(cpd+2) = tolower(*(cpd+2)); - *(cpd+3) = tolower(*(cpd+3)); - sprintf(date, "%.32s ", cpd+1); - *(cpd+4) = '-'; - - /** Day **/ - *cpd = '\0'; - if (isdigit(*(cpd-2))) - sprintf(date+4, "%.32s ", cpd-2); - else - sprintf(date+4, " %.32s ", cpd-1); - *cpd = '-'; - - /** Time or Year **/ - if (!PL_strncmp(ThisYear, cpd+5, 4) && PL_strlen(cpd) > 15 && *(cpd+12) == ':') - { - *(cpd+15) = '\0'; - sprintf(date+7, "%.32s", cpd+10); - *(cpd+15) = ' '; - } - else - { - *(cpd+9) = '\0'; - sprintf(date+7, " %.32s", cpd+5); - *(cpd+9) = ' '; - } - - entry_info->date = net_convert_vms_date(date); - } - - /* get the size - */ - if ((cpd=PL_strchr(cp, '/')) != NULL) - { - /* Appears be in used/allocated format */ - cps = cpd; - while (isdigit(*(cps-1))) - cps--; - if (cps < cpd) - *cpd = '\0'; - entry_info->size = atol(cps); - cps = cpd+1; - while (isdigit(*cps)) - cps++; - *cps = '\0'; - ialloc = atoi(cpd+1); - /* Check if used is in blocks or bytes */ - if (entry_info->size <= ialloc) - entry_info->size *= 512; - } - else if ((cps=strtok(cp, sp)) != NULL) - { - /* We just initialized on the version number - * Now let's find a lone, size number - */ - while ((cps=strtok(NULL, sp)) != NULL) - { - cpd = cps; - while (isdigit(*cpd)) - cpd++; - if (*cpd == '\0') - { - /* Assume it's blocks */ - entry_info->size = atol(cps) * 512; - break; - } - } - } - - /** Wrap it up **/ - TRACEMSG(("MKFTP: VMS filename: %s date: %d size: %ld\n", - entry_info->filename, entry_info->date, entry_info->size)); - return; - -} /* net_parse_vms_dir_entry() */ - -/* - * parse_dir_entry() - * Given a line of LIST/NLST output in entry, return results - * and a file/dir name in entry_info struct - * - */ -PRIVATE NET_FileEntryInfo * -net_parse_dir_entry (char *entry, int server_type) -{ - NET_FileEntryInfo *entry_info; - int i; - int len; - Bool remove_size=FALSE; - - entry_info = NET_CreateFileEntryInfoStruct(); - if(!entry_info) - return(NULL); - - entry_info->display = TRUE; - - /* do special case for ambiguous NT servers - * - * ftp.microsoft.com is an NT server with UNIX ls -l - * syntax. But most NT servers use the DOS dir syntax. - * If there is a space at position 8 then it's a DOS dir syntax - */ - if(server_type == FTP_NT_TYPE && !NET_IS_SPACE(entry[8])) - server_type = FTP_UNIX_TYPE; - - switch (server_type) - { - case FTP_UNIX_TYPE: - case FTP_PETER_LEWIS_TYPE: - case FTP_WEBSTAR_TYPE: - case FTP_MACHTEN_TYPE: - /* interpret and edit LIST output from Unix server */ - - if(!PL_strncmp(entry, "total ", 6) - || (PL_strstr(entry, "Permission denied") != NULL) - || (PL_strstr(entry, "not available") != NULL)) - { - entry_info->display=FALSE; - return(entry_info); - } - - len = PL_strlen(entry); - - if( '+' == entry[0] ) - { - /* - * EPLF: see http://pobox.com/~djb/proto/eplf.txt - * "+i8388621.29609,m824255902,/,\tdev" - * "+i8388621.44468,m839956783,r,s10376,\tRFCEPLF" - * - * A plus, a bunch of comma-separated facts, a tab, - * and then the name. Facts include m for mdtm (as - * seconds since the Unix epoch), s for size, r for - * (readable) file, and / for (listable) directory. - */ - char *tab = PL_strchr(entry, '\t'); - char *begin, *end; - remove_size = TRUE; /* It'll be put back if we have data */ - if( (char *)0 == tab ) break; - for( begin = &entry[1]; begin < tab; begin = &end[1]) - { - end = PL_strchr(begin, ','); - if( (char *)0 == end ) break; - switch( *begin ) - { - case 'm': - *end = '\0'; - entry_info->date = XP_ATOI(&begin[1]); - *end = ','; - break; - case 's': - *end = '\0'; - entry_info->size = XP_ATOI(&begin[1]); - *end = ','; - remove_size = FALSE; - break; - case 'r': - entry_info->special_type = NET_FILE_TYPE; - break; - case '/': - entry_info->special_type = NET_DIRECTORY; - break; - default: - break; - } - } - - entry_info->filename = NET_Escape(&tab[1], URL_PATH); - break; - } - else - /* check first character of ls -l output */ - if (toupper(entry[0]) == 'D') - { - /* it's a directory */ - entry_info->special_type = NET_DIRECTORY; - remove_size=TRUE; /* size is not useful */ - } - else if (entry[0] == 'l') - { - /* it's a symbolic link, does the user care about - * knowing if it is symbolic? I think so since - * it might be a directory - */ - entry_info->special_type = NET_SYM_LINK; - remove_size=TRUE; /* size is not useful */ - - /* strip off " -> pathname" */ - for (i = len - 1; (i > 3) && (!NET_IS_SPACE(entry[i]) - || (entry[i-1] != '>') - || (entry[i-2] != '-') - || (entry[i-3] != ' ')); i--) - ; /* null body */ - if (i > 3) - { - entry[i-3] = '\0'; - len = i - 3; - } - } /* link */ - - net_parse_ls_line(entry, entry_info); - - if(!PL_strcmp(entry_info->filename,"..") || !PL_strcmp(entry_info->filename,".")) - entry_info->display=FALSE; - - /* add a trailing slash to all directories */ - if(entry_info->special_type == NET_DIRECTORY) - StrAllocCat(entry_info->filename, "/"); - - /* goto the bottom and get real type */ - break; - - case FTP_VMS_TYPE: - /* Interpret and edit LIST output from VMS server */ - /* and convert information lines to zero length. */ - net_parse_vms_dir_entry(entry, entry_info); - - /* Get rid of any junk lines */ - if(!entry_info->display) - return(entry_info); - - /** Trim off VMS directory extensions **/ - len = PL_strlen(entry_info->filename); - if ((len > 4) && !PL_strcmp(&entry_info->filename[len-4], ".dir")) - { - entry_info->filename[len-4] = '\0'; - entry_info->special_type = NET_DIRECTORY; - remove_size=TRUE; /* size is not useful */ - /* add trailing slash to directories - */ - StrAllocCat(entry_info->filename, "/"); - } - /* goto the bottom and get real type */ - break; - - case FTP_CMS_TYPE: - /* can't be directory... */ - /* - * "entry" already equals the correct filename - */ - /* escape and copy - */ - entry_info->filename = NET_Escape(entry, URL_PATH); - /* goto the bottom and get real type */ - break; - - case FTP_NCSA_TYPE: - case FTP_TCPC_TYPE: - /* directories identified by trailing "/" characters */ - /* escape and copy - */ - entry_info->filename = NET_Escape(entry, URL_PATH); - len = PL_strlen(entry); - if (entry[len-1] == '/') - { - entry_info->special_type = NET_DIRECTORY; - remove_size=TRUE; /* size is not useful */ - } - /* goto the bottom and get real type */ - break; - - case FTP_NT_TYPE: - /* windows NT DOS dir syntax. - * looks like: - * 1 2 3 4 5 - * 012345678901234567890123456789012345678901234567890 - * 06-29-95 03:05PM <DIR> muntemp - * 05-02-95 10:03AM 961590 naxp11e.zip - * - * The date time directory indicator and filename - * are always in a fixed position. The file - * size always ends at position 37. - */ - { - char *date, *size_s, *name; - - if(PL_strlen(entry) > 37) - { - date = entry; - entry[17] = '\0'; - size_s = &entry[18]; - entry[38] = '\0'; - name = &entry[39]; - - if(PL_strstr(size_s, "<DIR>")) - entry_info->special_type = NET_DIRECTORY; - else - entry_info->size = atol(XP_StripLine(size_s)); - - entry_info->date = net_parse_dos_date_time(date); - - StrAllocCopy(entry_info->filename, name); - } - else - { - StrAllocCopy(entry_info->filename, entry); - } - } - break; - - default: - /* we cant tell if it is a directory since we only - * did an NLST - */ - /* escape and copy - */ - entry_info->filename = NET_Escape(entry, URL_PATH); - return(entry_info); /* mostly empty info */ - /* break; Not needed */ - - } /* switch (server_type) */ - - - if(remove_size && entry_info->size) - { - entry_info->size = 0; - } - - /* get real types eventually */ - if(!entry_info->special_type) - { - entry_info->cinfo = NET_cinfo_find_type(entry_info->filename); - } - - return(entry_info); - -} /* net_parse_dir_entry */ - - -PRIVATE int -net_get_ftp_password(ActiveEntry *ce) -{ - FTPConData *cd = (FTPConData *) ce->con_data; - - if(!cd->password) - { - char * host_string = NET_ParseURL(ce->URL_s->address, (GET_USERNAME_PART | GET_HOST_PART) ); - -#ifndef MCC_PROXY - if(ftp_last_password - && ftp_last_password_host - && !PL_strcmp(ftp_last_password_host, host_string)) - { - StrAllocCopy(cd->password, ftp_last_password); - } - else -#endif - { - /* check for cached password */ - char *key = gen_ftp_password_key(ce->URL_s->address, cd->username); - - if(key) - { - PCNameValueArray * array = PC_CheckForStoredPasswordArray(PC_FTP_MODULE_KEY, key); - - if(array) - cd->password = PC_FindInNameValueArray(array, PC_FTP_PASSWORD_KEY); - - PC_FreeNameValueArray(array); - - PR_Free(key); - } - - if(!cd->password) - { - PRBool status; - NET_AuthClosure * auth_closure = PR_NEWZAP (NET_AuthClosure); - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, - XP_GetString(XP_PROMPT_ENTER_PASSWORD), - host_string); - - /* the new multi-threaded case -- we return asynchronously */ - if (!auth_closure) { - return(MK_INTERRUPTED); - } - - auth_closure->_private = (void *) ce; - auth_closure->user = NULL; - auth_closure->pass = NULL; - auth_closure->msg = PL_strdup (cd->output_buffer); - - status = stub_PromptPassword(ce->window_id, - cd->output_buffer, - &cd->store_password, - FALSE /* not secure */, - (void *) auth_closure); - - PR_Free(host_string); - /* this no longer a user cancel - password prompting is async */ - return(FTP_WAIT_FOR_AUTH); - } - } - } - - cd->next_state = FTP_SEND_PASSWORD; - - return 0; -} - - -PRIVATE int -net_get_ftp_password_response(FTPConData *cd) -{ - /* not used yet - */ - return 0; /* #### what should return value be? */ -} - -/* the load initializeation routine for FTP. - * - * this sets up all the data structures and begin's the - * connection by calling processFTP - */ -PRIVATE int32 -net_FTPLoad (ActiveEntry * ce) -{ - char * host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - char * unamePwd = NET_ParseURL(ce->URL_s->address, GET_USERNAME_PART | GET_PASSWORD_PART); - char *username,*colon,*password=NULL; - char * filename; - char * semi_colon; - FTPConData * cd = PR_NEW(FTPConData); - - if(!cd) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - ce->status = MK_OUT_OF_MEMORY; - return(MK_OUT_OF_MEMORY); - } - - /* get the username & password out of the combo string */ - if( (colon = PL_strchr(unamePwd, ':')) != NULL ) { - *colon='\0'; - username=PL_strdup(unamePwd); - password=PL_strdup(colon+1); - *colon=':'; - PR_Free(unamePwd); - } else { - username=unamePwd; - } - - ce->con_data = (FTPConData *)cd; - - /* init the connection data struct - */ - memset(cd, 0, sizeof(FTPConData)); - cd->dsock = NULL; - cd->listen_sock = NULL; - cd->pasv_mode = TRUE; - cd->is_directory = FALSE; - cd->next_state_after_response = FTP_ERROR_DONE; - cd->cont_response = -1; - - /* @@@@ hope we never need a buffer larger than this - */ - cd->output_buffer = (char *) PR_Malloc(OUTPUT_BUFFER_SIZE); - if(!cd->output_buffer) - { - PR_Free(cd); - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - ce->status = MK_OUT_OF_MEMORY; - return(MK_OUT_OF_MEMORY); - } - - if (username && *username) { - StrAllocCopy(cd->username, username); - if (password && *password) - StrAllocCopy(cd->password, password); - } else { - const char * user = NULL; - PR_FREEIF(username); - username = NULL; - PR_FREEIF(password); - password = NULL; - -#ifdef OLD_MOZ_MAIL_NEWS -#ifdef MOZILLA_CLIENT - if(net_get_send_email_address_as_password()) - user = FE_UsersMailAddress(); -#endif -#endif /* OLD_MOZ_MAIL_NEWS */ - - if(user && *user) - { - StrAllocCopy(cd->password, user); - - /* make sure it has an @ sign in it or else the ftp - * server won't like it - */ - if(!PL_strchr(cd->password, '@')) - StrAllocCat(cd->password, "@"); - } - else - { - StrAllocCopy(cd->password, "mozilla@"); - } - } - - /* get the path */ - cd->path = NET_ParseURL(ce->URL_s->address, GET_PATH_PART); - - if(!cd->path) - { - PR_Free(ce->con_data); - PR_Free(cd->output_buffer); - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - ce->status = MK_OUT_OF_MEMORY; - return(MK_OUT_OF_MEMORY); - } - - NET_UnEscape(cd->path); - - if(*cd->path == '\0') - { - TRACEMSG(("Found ftp url with NO PATH")); - - cd->use_default_path = TRUE; - } - else - { - /* terminate at an "\r" or "\n" in the string - * this prevents URL's of the form "foo\nDELE foo" - */ - strtok(cd->path, "\r"); - strtok(cd->path, "\n"); - } - - /* if the path begins with /./ - * use pwd to get the sub path - * and append the end to it - */ - if(!PL_strncmp(cd->path, "/./", 3) || !PL_strcmp(cd->path, "/.")) - { - char * tmp = cd->path; - - cd->use_default_path = TRUE; - - /* skip the "/." and leave a slash at the beginning */ - cd->path = PL_strdup(cd->path+2); - PR_Free(tmp); - - if(!cd->path) - { - PR_Free(ce->con_data); - PR_Free(cd->output_buffer); - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - ce->status = MK_OUT_OF_MEMORY; - return(MK_OUT_OF_MEMORY); - } - } - - /* set the default type for use later - */ - cd->type = FTP_MODE_UNKNOWN; - - TRACEMSG(("content length: %d, real content length: %d", - ce->URL_s->content_length, ce->URL_s->real_content_length)); - if( (ce->URL_s->real_content_length > ce->URL_s->content_length) && - (NULL != ce->URL_s->cache_file) ) - { - cd->restart = TRUE; - TRACEMSG(("Considering a restart.")); - } - - /* look for the extra type information at the end per - * the RFC 1630. It will be delimited by a ';' - */ - if((semi_colon = PL_strrchr(cd->path, ';')) != NULL) - { - /* just switch on the character at the end of this whole - * thing since it must be the type to use - */ - switch(semi_colon[PL_strlen(semi_colon)-1]) - { - case 'a': - case 'A': - cd->type = FTP_MODE_ASCII; - TRACEMSG(("Explicitly setting type ASCII")); - break; - - case 'i': - case 'I': - cd->type = FTP_MODE_BINARY; - TRACEMSG(("Explicitly setting type BINARY")); - break; - } - - /* chop off the bits after the semi colon - */ - *semi_colon = '\0'; - - /* also chop of the semi colon from the real URL */ - strtok(ce->URL_s->address, ";"); - } - - /* find the filename in the path */ - filename = PL_strrchr(cd->path, '/'); - if(!filename) - filename = cd->path; - else - filename++; /* go past slash */ - - cd->filename = 0; - StrAllocCopy(cd->filename, filename); - - /* Try and find an open connection to this - * server that is not currently being used - */ - if(connection_list) - { - FTPConnection * tmp_con; - XP_List * list_entry = connection_list; - - while((tmp_con = (FTPConnection *)XP_ListNextObject(list_entry)) != NULL) - { - /* if the hostnames match up exactly and the connection - * is not busy at the moment then reuse this connection. - */ - if(!tmp_con->busy && !PL_strcmp(tmp_con->hostname, host)) - { - cd->cc = tmp_con; - ce->socket = cd->cc->csock; /* set select on the control socket */ - NET_SetReadSelect(ce->window_id, cd->cc->csock); - cd->cc->prev_cache = TRUE; /* this was from the cache */ - break; - } - } - } - else - { - /* initialize the connection list - */ - connection_list = XP_ListNew(); - } - - if(!cd->cc) - { - - TRACEMSG(("cached connection not found making new FTP connection")); - - /* build a control connection structure so we - * can store the data as we go along - */ - cd->cc = PR_NEW(FTPConnection); - if(!cd->cc) - { - PR_Free(host); /* free from way up above */ - PR_FREEIF(username); - PR_FREEIF(password); - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - cd->cc->hostname = 0; - StrAllocCopy(cd->cc->hostname, host); - /* set the mode of the control connection unknown - */ - cd->cc->cur_mode = FTP_MODE_UNKNOWN; - cd->cc->csock = NULL; - cd->cc->server_type = FTP_GENERIC_TYPE; - cd->cc->use_list = FALSE; - cd->cc->no_pasv = FALSE; - - cd->cc->prev_cache = FALSE; /* this wasn't from the cache */ - cd->cc->no_restart = FALSE; /* as far as we know so far */ - - /* add this structure to the connection list even - * though it's not really valid yet. - * we will fill it in as we go and if - * an error occurs will will remove it from the - * list. No one else will be able to use it since - * we will mark it busy. - */ - XP_ListAddObjectToEnd(connection_list, cd->cc); - - /* set this connection busy so no one else can use it - */ - cd->cc->busy = TRUE; - - /* gate the maximum number of cached connections - * to one - */ - if(XP_ListCount(connection_list) > 1) - { - XP_List * list_ptr = connection_list->next; - FTPConnection * con; - - while(list_ptr) - { - con = (FTPConnection *) list_ptr->object; - list_ptr = list_ptr->next; - if(!con->busy) - { - XP_ListRemoveObject(connection_list, con); - PR_Close(con->csock); - /* dont reduce the number of - * open connections since cached ones - * dont count as active - */ - PR_FREEIF(con->hostname); - PR_Free(con); - break; - } - } - } - - cd->next_state = FTP_CONTROL_CONNECT; - } - else - { - TRACEMSG(("Found cached FTP connection! YES!!! ")); - - /* don't send PASV if the server cant do it */ - if(cd->cc->no_pasv || !net_use_pasv) - cd->next_state = FTP_SEND_PORT; - else - cd->next_state = FTP_SEND_PASV; - - if( cd->cc->no_restart ) - ce->URL_s->server_can_do_restart = FALSE; - else - ce->URL_s->server_can_do_restart = TRUE; - - /* set this connection busy so no one else can use it - */ - cd->cc->busy = TRUE; - /* add this connection to the number that is open - * since it is now active - */ - NET_TotalNumberOfOpenConnections++; - } - - PR_Free(host); /* free from way up above */ - PR_FREEIF(username); - PR_FREEIF(password); - TRACEMSG(("Server can do restarts: %s", ce->URL_s->server_can_do_restart ? - "TRUE" : "FALSE")); - return(net_ProcessFTP(ce)); -} - - -PUBLIC void -net_ResumeFTP(ActiveEntry *ce, NET_AuthClosure *auth_closure, PRBool resume) -{ - FTPConData * cd = (FTPConData *) ce->con_data; - - TRACEMSG (("net_ResumeFTP: %s", ce->URL_s->address)); - - if (resume) { - char * host_string = NET_ParseURL(ce->URL_s->address, (GET_USERNAME_PART | GET_HOST_PART) ); - - cd->password = PL_strdup (auth_closure->pass); - cd->next_state = FTP_SEND_PASSWORD; - - StrAllocCopy(ftp_last_password_host, host_string); - StrAllocCopy(ftp_last_password, cd->password); - - PR_Free (host_string); - } else { - cd->next_state = FTP_DONE; - } - - return; -} - -/* the main state machine control routine. Calls - * the individual state processors - * - * returns -1 when all done or 0 or positive all other times - */ -PRIVATE int32 -net_ProcessFTP(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - cd->pause_for_read = FALSE; - - while(!cd->pause_for_read) - { - TRACEMSG(("In ProcessFTP switch loop with state: %d \n", cd->next_state)); - - switch(cd->next_state) { - - case FTP_WAIT_FOR_AUTH: - printf ("ProcessFTP: waiting for password\n"); - break; - - case FTP_WAIT_FOR_RESPONSE: - ce->status = net_ftp_response(ce); - break; - - /* begin login states */ - case FTP_CONTROL_CONNECT: - ce->status = NET_BeginConnect(ce->URL_s->address, - ce->URL_s->IPAddressString, - "FTP", - FTP_PORT, - &cd->cc->csock, - HG27230 - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - ce->socket = cd->cc->csock; - - if(cd->cc->csock != NULL) - NET_TotalNumberOfOpenConnections++; - - cd->pause_for_read = TRUE; - - if(ce->status == MK_CONNECTED) - { - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_USERNAME; - NET_SetReadSelect(ce->window_id, cd->cc->csock); - } - else if(ce->status > -1) - { - cd->next_state = FTP_CONTROL_CONNECT_WAIT; - ce->con_sock = cd->cc->csock; /* set con sock so we can select on it */ - NET_SetConnectSelect(ce->window_id, ce->con_sock); - - } - break; - - case FTP_CONTROL_CONNECT_WAIT: - ce->status = NET_FinishConnect(ce->URL_s->address, - "FTP", - FTP_PORT, - &cd->cc->csock, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - - cd->pause_for_read = TRUE; - - if(ce->status == MK_CONNECTED) - { - cd->next_state = FTP_WAIT_FOR_RESPONSE; - cd->next_state_after_response = FTP_SEND_USERNAME; - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = NULL; /* reset con sock so we don't select on it */ - NET_SetReadSelect(ce->window_id, ce->socket); - } - else - { - /* the not yet connected state */ - - /* unregister the old CE_SOCK from the select list - * and register the new value in the case that it changes - */ - if(ce->con_sock != cd->cc->csock) - { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = cd->cc->csock; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - } - break; - - case FTP_SEND_USERNAME: - ce->status = net_send_username((FTPConData *)ce->con_data); - break; - - case FTP_SEND_USERNAME_RESPONSE: - ce->status = net_send_username_response(ce); - break; - - case FTP_GET_PASSWORD: - ce->status = net_get_ftp_password(ce); - break; - - case FTP_GET_PASSWORD_RESPONSE: - /* currently skipped - */ - ce->status = net_get_ftp_password_response((FTPConData *)ce->con_data); - break; - - case FTP_SEND_PASSWORD: - ce->status = net_send_password((FTPConData *)ce->con_data); - break; - - case FTP_SEND_PASSWORD_RESPONSE: - ce->status = net_send_password_response(ce); - break; - - case FTP_SEND_ACCT: - ce->status = net_send_acct((FTPConData *)ce->con_data); - break; - - case FTP_SEND_ACCT_RESPONSE: - ce->status = net_send_acct_response(ce); - break; - - case FTP_SEND_REST_ZERO: - ce->status = net_send_rest_zero(ce); - break; - - case FTP_SEND_REST_ZERO_RESPONSE: - ce->status = net_send_rest_zero_response(ce); - break; - - case FTP_SEND_SYST: - ce->status = net_send_syst((FTPConData *)ce->con_data); - break; - - case FTP_SEND_SYST_RESPONSE: - ce->status = net_send_syst_response((FTPConData *)ce->con_data); - break; - - case FTP_SEND_MAC_BIN: - ce->status = net_send_mac_bin((FTPConData *)ce->con_data); - break; - - case FTP_SEND_MAC_BIN_RESPONSE: - ce->status = net_send_mac_bin_response((FTPConData *)ce->con_data); - break; - - case FTP_SEND_PWD: - ce->status = net_send_pwd((FTPConData *)ce->con_data); - break; - - case FTP_SEND_PWD_RESPONSE: - ce->status = net_send_pwd_response(ce); - break; - /* end login states */ - - case FTP_FIGURE_OUT_WHAT_TO_DO: - ce->status = net_figure_out_what_to_do(ce); - break; - - case FTP_SEND_MKDIR: - ce->status = net_send_mkdir(ce); - break; - - case FTP_SEND_MKDIR_RESPONSE: - ce->status = net_send_mkdir_response(ce); - break; - - case FTP_SEND_DELETE_FILE: - ce->status = net_send_delete_file(ce); - break; - - case FTP_SEND_DELETE_FILE_RESPONSE: - ce->status = net_send_delete_file_response(ce); - break; - - case FTP_SEND_DELETE_DIR: - ce->status = net_send_delete_dir(ce); - break; - - case FTP_SEND_DELETE_DIR_RESPONSE: - ce->status = net_send_delete_dir_response(ce); - break; - - case FTP_SEND_PASV: - ce->status = net_send_pasv((FTPConData *)ce->con_data); - break; - - case FTP_SEND_PASV_RESPONSE: - ce->status = net_send_pasv_response((FTPConData *)ce->con_data); - break; - - case FTP_PASV_DATA_CONNECT: - ce->status = NET_BeginConnect(cd->data_con_address, - NULL, - "FTP Data Connection", - FTP_PORT, - &cd->dsock, - HG27230 - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - - if(ce->status == MK_CONNECTED) - { - cd->next_state = FTP_GET_FILE_TYPE; - } - else if(ce->status > -1) - { - cd->pause_for_read = TRUE; - cd->next_state = FTP_PASV_DATA_CONNECT_WAIT; - ce->con_sock = cd->dsock; /* set con sock so we can select on it */ - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - break; - - case FTP_PASV_DATA_CONNECT_WAIT: - ce->status = NET_FinishConnect(cd->data_con_address, - "FTP Data Connection", - FTP_PORT, - &cd->dsock, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - TRACEMSG(("FTP: got pasv data connection on port #%d\n",cd->cc->csock)); - - if(ce->status == MK_CONNECTED) - { - cd->next_state = FTP_GET_FILE_TYPE; - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = NULL; /* reset con sock so we don't select on it */ - } - else - { - ce->con_sock = cd->dsock; /* it might change */ - cd->pause_for_read = TRUE; - } - break; - - case FTP_SEND_PORT: - ce->status = net_send_port(ce); - break; - - case FTP_SEND_PORT_RESPONSE: - ce->status = net_send_port_response(ce); - break; - - /* This is the state that gets called after - * login and port/pasv are done - */ - case FTP_GET_FILE_TYPE: - ce->status = net_get_ftp_file_type(ce); - break; - - case FTP_SEND_BIN: - ce->status = net_send_bin((FTPConData *)ce->con_data); - break; - - case FTP_SEND_ASCII: - ce->status = net_send_ascii((FTPConData *)ce->con_data); - break; - - case FTP_SEND_BIN_RESPONSE: - case FTP_SEND_ASCII_RESPONSE: - ce->status = net_send_bin_or_ascii_response(ce); - break; - - case FTP_GET_FILE_SIZE: - ce->status = net_get_ftp_file_size(ce); - break; - - case FTP_GET_FILE_SIZE_RESPONSE: - ce->status = net_get_ftp_file_size_response(ce); - break; - - case FTP_GET_FILE_MDTM: - ce->status = net_get_ftp_file_mdtm(ce); - break; - - case FTP_GET_FILE_MDTM_RESPONSE: - ce->status = net_get_ftp_file_mdtm_response(ce); - break; - - case FTP_GET_FILE: - ce->status = net_get_ftp_file((FTPConData *)ce->con_data); - break; - - case FTP_SEND_REST: - ce->status = net_send_rest(ce); - break; - - case FTP_SEND_REST_RESPONSE: - ce->status = net_send_rest_response(ce); - break; - - case FTP_SEND_RETR: - ce->status = net_send_retr((FTPConData *)ce->con_data); - break; - - case FTP_SEND_RETR_RESPONSE: - ce->status = net_send_retr_response(ce); - break; - - case FTP_SEND_CWD: - ce->status = net_send_cwd((FTPConData *)ce->con_data); - break; - - case FTP_SEND_CWD_RESPONSE: - ce->status = net_send_cwd_response(ce); - break; - - case FTP_BEGIN_PUT: - ce->status = net_begin_put(ce); - break; - - case FTP_BEGIN_PUT_RESPONSE: - ce->status = net_begin_put_response(ce); - break; - - case FTP_DO_PUT: - ce->status = net_do_put(ce); - break; - - case FTP_SEND_LIST_OR_NLST: - ce->status = net_send_list_or_nlst(ce); - break; - - case FTP_SEND_LIST_OR_NLST_RESPONSE: - ce->status = net_send_list_or_nlst_response(ce); - break; - - case FTP_SETUP_STREAM: - ce->status = net_setup_ftp_stream(ce); - break; - - case FTP_WAIT_FOR_ACCEPT: - ce->status = net_wait_for_ftp_accept(ce); - break; - - case FTP_READ_CACHE: - ce->status = net_ftp_push_partial_cache_file(ce); - break; - - case FTP_START_READ_FILE: - ce->status = net_start_ftp_read_file(ce); - break; - - case FTP_READ_FILE: - ce->status = net_ftp_read_file(ce); - break; - - case FTP_START_READ_DIRECTORY: - ce->status = net_start_ftp_read_dir(ce); - break; - - case FTP_READ_DIRECTORY: - - ce->status = net_ftp_read_dir(ce); - break; - - case FTP_PRINT_DIR: - ce->status = net_ftp_print_dir(ce); - break; - - case FTP_DONE: - if(cd->stream) - COMPLETE_STREAM; - - /* Make sure that any previous cache entry is not locked anymore */ -#ifndef NU_CACHE - NET_ChangeCacheFileLock(ce->URL_s, FALSE); -#endif /* NU_CACHE */ - - /* don't close the control sock since we need - * it for connection caching - */ - if(cd->dsock != NULL) - { - NET_ClearReadSelect(ce->window_id, cd->dsock); - TRACEMSG(("Closing and clearing sock cd->dsock: %d", cd->dsock)); - PR_Close(cd->dsock); - cd->dsock = NULL; - } - - if(cd->listen_sock != NULL) - { - TRACEMSG(("Closing and clearing sock cd->listen_sock: %d", cd->listen_sock)); - NET_ClearReadSelect(ce->window_id, cd->listen_sock); - PR_Close(cd->listen_sock); - /* not counted as a connection */ - } - - cd->next_state = FTP_FREE_DATA; - - cd->cc->busy = FALSE; /* we are no longer using the connection */ - NET_ClearReadSelect(ce->window_id, cd->cc->csock); - - /* we can't reuse VMS control connections since they are screwed up - */ - if(cd->cc->server_type == FTP_VMS_TYPE) - { - /* remove the connection from the cache list - * and free the data - */ - XP_ListRemoveObject(connection_list, cd->cc); - PR_FREEIF(cd->cc->hostname); - if(cd->cc->csock != NULL) - { - TRACEMSG(("Closing and clearing sock cd->cc->csock: %d", cd->cc->csock)); - PR_Close(cd->cc->csock); - cd->cc->csock = NULL; - } - PR_Free(cd->cc); - cd->cc = 0; - } - - /* remove the cached connection from the total number - * counted, since it is no longer active - */ - NET_TotalNumberOfOpenConnections--; - - break; - - case FTP_ERROR_DONE: - if(cd->sort_base) - { - /* we have to do this to get it free'd - */ - if(cd->stream && (*cd->stream->is_write_ready)(cd->stream)) - NET_PrintDirectory(&cd->sort_base, cd->stream, cd->path, ce->URL_s); - } - - if(cd->stream && cd->stream->data_object) - { - ABORT_STREAM(ce->status); - /* (ABORT_STREAM frees cd->stream->data_object:) */ - cd->stream->data_object = NULL; - } - - /* lock the object in cache if we can restart it */ - /* This way even if it's huge, we can restart. */ - TRACEMSG(("FTP aborting! content_length = %ld, real_content_length = %ld\n", - ce->URL_s->content_length, ce->URL_s->real_content_length)); - TRACEMSG((" bytes_received = %ld\n", ce->bytes_received)); -#ifndef NU_CACHE - if(ce->URL_s->server_can_do_restart) - NET_ChangeCacheFileLock(ce->URL_s, TRUE); -#endif /* NU_CACHE */ - - if(cd->dsock != NULL) - { - NET_ClearConnectSelect(ce->window_id, cd->dsock); - NET_ClearReadSelect(ce->window_id, cd->dsock); - NET_ClearDNSSelect(ce->window_id, cd->dsock); - -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - { - cd->calling_netlib_all_the_time = FALSE; - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkftp"); - } -#endif /* XP_WIN */ - - TRACEMSG(("Closing and clearing sock cd->dsock: %d", cd->dsock)); - PR_Close(cd->dsock); - cd->dsock = NULL; - } - - if(cd->file_to_post_fp) - { - NET_XP_FileClose(cd->file_to_post_fp); - cd->file_to_post_fp = 0; - } - - if(cd->cc->csock != NULL) - { - NET_ClearConnectSelect(ce->window_id, cd->cc->csock); - NET_ClearReadSelect(ce->window_id, cd->cc->csock); - NET_ClearDNSSelect(ce->window_id, cd->cc->csock); - TRACEMSG(("Closing and clearing sock cd->cc->csock: %d", cd->cc->csock)); - PR_Close(cd->cc->csock); - cd->cc->csock = NULL; - NET_TotalNumberOfOpenConnections--; - } - - if(cd->listen_sock != NULL) - { - TRACEMSG(("Closing and clearing sock cd->listen_sock: %d", cd->listen_sock)); - NET_ClearReadSelect(ce->window_id, cd->listen_sock); - PR_Close(cd->listen_sock); - /* not counted as a connection */ - } - - - /* check if this connection came from the cache or if it was - * a new connection. If it was new lets start it over again - */ - if(cd->cc->prev_cache - && ce->status != MK_INTERRUPTED - && ce->status != MK_UNABLE_TO_CONVERT - && ce->status != MK_OUT_OF_MEMORY - && ce->status != MK_DISK_FULL) - { - cd->cc->prev_cache = NO; - cd->next_state = FTP_CONTROL_CONNECT; - cd->pasv_mode = TRUE; /* until we learn otherwise */ - cd->pause_for_read = FALSE; - ce->status = 0; /* keep going */ - cd->cc->cur_mode = FTP_MODE_UNKNOWN; - } - else - { - cd->next_state = FTP_FREE_DATA; - - /* remove the connection from the cache list - * and free the data - */ - XP_ListRemoveObject(connection_list, cd->cc); - PR_FREEIF(cd->cc->hostname); - PR_Free(cd->cc); - } - - break; - - case FTP_FREE_DATA: - if(cd->calling_netlib_all_the_time) - { - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkftp"); - cd->calling_netlib_all_the_time = FALSE; - } - -#if !defined(SMOOTH_PROGRESS) - if(cd->destroy_graph_progress) - FE_GraphProgressDestroy(ce->window_id, - ce->URL_s, - cd->original_content_length, - ce->bytes_received); -#endif - -#ifdef EDITOR - if(cd->destroy_file_upload_progress_dialog) { - /* Convert from netlib errors to editor errors. */ - ED_FileError error = ED_ERROR_NONE; - if ( ce->status < 0 ) - error = ED_ERROR_PUBLISHING; - FE_SaveDialogDestroy(ce->window_id, error, ce->URL_s->post_data); - /* FE_SaveDialogDestroy(ce->window_id, ce->status, cd->file_to_post); */ - } -#endif /* EDITOR */ - PR_FREEIF(cd->cwd_message_buffer); - PR_FREEIF(cd->login_message_buffer); - PR_FREEIF(cd->data_buf); - PR_FREEIF(cd->return_msg); - PR_FREEIF(cd->data_con_address); - PR_FREEIF(cd->filename); - PR_FREEIF(cd->path); - PR_FREEIF(cd->username); - PR_FREEIF(cd->password); - PR_FREEIF(cd->stream); /* don't forget the stream */ - PR_FREEIF(cd->output_buffer); - if(cd->tcp_con_data) - NET_FreeTCPConData(cd->tcp_con_data); - - - PR_Free(cd); - - /* gate the maximum number of cached connections - * to one - */ - if(XP_ListCount(connection_list) > 1) - { - XP_List * list_ptr = connection_list->next; - FTPConnection * con; - - while(list_ptr) - { - con = (FTPConnection *) list_ptr->object; - list_ptr = list_ptr->next; - if(!con->busy) - { - XP_ListRemoveObject(connection_list, con); - - if(con->csock != NULL) - { - PR_Close(con->csock); - /* dont reduce the number of - * open connections since cached ones - * dont count as active - */ - } - PR_FREEIF(con->hostname); - PR_Free(con); - break; - } - } - } - - return(-1); - - default: - TRACEMSG(("Bad state in ProcessFTP\n")); - return(-1); - } /* end switch */ - - if(ce->status < 0 && cd->next_state != FTP_FREE_DATA) - { - cd->pause_for_read = FALSE; - cd->next_state = FTP_ERROR_DONE; - } - } /* end while */ - - return(ce->status); -} - -/* abort the connection in progress - */ -PRIVATE int32 -net_InterruptFTP(ActiveEntry * ce) -{ - FTPConData * cd = (FTPConData *)ce->con_data; - - cd->next_state = FTP_ERROR_DONE; - ce->status = MK_INTERRUPTED; - cd->cc->prev_cache = FALSE; /* to keep it from reconnecting */ - - return(net_ProcessFTP(ce)); -} - -/* Free any connections or memory that are cached - */ -PRIVATE void -net_CleanupFTP(void) -{ - if(connection_list) - { - FTPConnection * tmp_con; - - while((tmp_con = (FTPConnection *)XP_ListRemoveTopObject(connection_list)) != NULL) - { - if(!tmp_con->busy) - { - PR_Free(tmp_con->hostname); /* hostname string */ - if(tmp_con->csock != NULL) - { - PR_Close(tmp_con->csock); /* control socket */ - tmp_con->csock = NULL; - /* don't count cached connections as open ones - */ - } - PR_Free(tmp_con); - } - } - } - - return; -} - - -MODULE_PRIVATE void -NET_InitFTPProtocol(void) -{ - static NET_ProtoImpl ftp_proto_impl; - - ftp_proto_impl.init = net_FTPLoad; - ftp_proto_impl.process = net_ProcessFTP; - ftp_proto_impl.interrupt = net_InterruptFTP; - ftp_proto_impl.resume = net_ResumeFTP; - ftp_proto_impl.cleanup = net_CleanupFTP; - - NET_RegisterProtocolImplementation(&ftp_proto_impl, FTP_TYPE_URL); -} diff --git a/mozilla/network/protocol/gopher/MANIFEST b/mozilla/network/protocol/gopher/MANIFEST deleted file mode 100644 index c49eaaa9fd2..00000000000 --- a/mozilla/network/protocol/gopher/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -gophurl.h diff --git a/mozilla/network/protocol/gopher/Makefile.in b/mozilla/network/protocol/gopher/Makefile.in deleted file mode 100644 index 011406bb2ba..00000000000 --- a/mozilla/network/protocol/gopher/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = gophurl -LIBRARY_NAME = gophurl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl remoturl mimetype - -CSRCS = mkgopher.c - -EXPORTS = $(srcdir)/gophurl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/gopher/gophurl.h b/mozilla/network/protocol/gopher/gophurl.h deleted file mode 100644 index a78d9499644..00000000000 --- a/mozilla/network/protocol/gopher/gophurl.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKGOPHER_H -#define MKGOPHER_H - -extern void NET_InitGopherProtocol(void); - -#endif /* MKGOPHER_H */ - diff --git a/mozilla/network/protocol/gopher/makefile.win b/mozilla/network/protocol/gopher/makefile.win deleted file mode 100644 index e3c3ba31c71..00000000000 --- a/mozilla/network/protocol/gopher/makefile.win +++ /dev/null @@ -1,86 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkgopher.obj \ - $(NULL) - -CSRCS = \ - mkgopher.c \ - $(NULL) - - -LIBRARY_NAME=gophurl -MODULE=gophurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= gophurl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\remoturl \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\mimetype \ - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/gopher/mkgopher.c b/mozilla/network/protocol/gopher/mkgopher.c deleted file mode 100644 index d5138d612e8..00000000000 --- a/mozilla/network/protocol/gopher/mkgopher.c +++ /dev/null @@ -1,1180 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* A state machine to implement the Gopher protocol - * Designed and Implemented by Lou Montulli circa '94 - */ - -#include "rosetta.h" -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "prerror.h" - -/* Gopher types: - */ -#define GTYPE_TEXT '0' /* text/plain */ -#define GTYPE_MENU '1' /* menu - becomes text/html */ -#define GTYPE_CSO '2' /* cso search - becomes text/html */ -#define GTYPE_ERROR '3' /* some sort of error */ -#define GTYPE_MACBINHEX '4' /* application/binhex */ -#define GTYPE_PCBINARY '5' /* application/octet-stream */ -#define GTYPE_UUENCODED '6' /* application/uuencoded */ -#define GTYPE_INDEX '7' /* search - becomes text/html */ -#define GTYPE_TELNET '8' /* maps to telnet URL */ -#define GTYPE_BINARY '9' /* application/octet-stream */ -#define GTYPE_GIF 'g' /* image/gif */ -#define GTYPE_HTML 'h' /* HTML URL */ -#define GTYPE_HTMLCAPS 'H' /* HTML URL Capitalized */ -#define GTYPE_INFO 'i' /* unselectable info */ -#define GTYPE_IMAGE 'I' /* image/gif */ -#define GTYPE_MIME 'm' /* not used */ -#define GTYPE_SOUND 's' /* audio/(wildcard) */ -#define GTYPE_TN3270 'T' /* maps to tn3270 program (url) */ -#define GTYPE_WWW 'w' /* W3 address */ -#define GTYPE_MPEG ';' /* video/mpeg */ - -#include "mkgeturl.h" /* URL Struct */ -#include "mkstream.h" -#include "mkformat.h" /* for File Format stuff (cinfo) */ -#include "gophurl.h" /* function prototypes */ -#include "mktcp.h" /* connect, read, etc. */ -#include "mkparse.h" /* NET_ParseURL() */ -#include "remoturl.h" /* NET_RemoteHostLoad */ - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_HTML_GOPHER_INDEX; -extern int XP_HTML_CSO_SEARCH; -extern int XP_PROGRESS_WAITREPLY_GOTHER; -extern int MK_OUT_OF_MEMORY; -extern int MK_SERVER_DISCONNECTED; -extern int MK_TCP_READ_ERROR; -extern int MK_TCP_WRITE_ERROR; -extern int XP_ERRNO_EWOULDBLOCK; -extern int XP_SERVER_RETURNED_NO_DATA; -extern int MK_MALFORMED_URL_ERROR; - -#include "merrors.h" - -#define CD_OUTPUT_BUFFER_SIZE 4*1024 - -typedef struct _GopherConData { - int next_state; /* the next state or action to be taken */ - char *data_buf; /* temporary string storage */ - int32 data_buf_size; /* current size of the line buffer */ - char gopher_type; /* the gopher type */ - char *command; /* the request command */ - char *output_buf; /* temporary output buffer */ - NET_StreamClass *stream; /* The output stream */ - Bool pause_for_read; /* Pause now for next read? */ - Bool destroy_graph_progress; /* do we need to destroy graph progress? */ - int32 original_content_length; /* the content length at the time of - * calling graph progress - */ - char cso_last_char; - TCP_ConData *tcp_con_data; -} GopherConData; - -#define PUTSTRING(s) (*connection_data->stream->put_block) \ - (connection_data->stream, s, PL_strlen(s)) -#define PUTBLOCK(b, l) (*connection_data->stream->put_block) \ - (connection_data->stream, b, l) -#define COMPLETE_STREAM (*connection_data->stream->complete) \ - (connection_data->stream) -#define ABORT_STREAM(s) (*connection_data->stream->abort) \ - (connection_data->stream, s) - -/* helpful shortcut names - */ -#define CD_NEXT_STATE connection_data->next_state -#define CD_DATA_BUF connection_data->data_buf -#define CD_DATA_BUF_SIZE connection_data->data_buf_size -#define CD_STREAM connection_data->stream -#define CD_GOPHER_TYPE connection_data->gopher_type -#define CD_COMMAND connection_data->command -#define CD_OUTPUT_BUF connection_data->output_buf -#define CD_PAUSE_FOR_READ connection_data->pause_for_read -#define CD_DESTROY_GRAPH_PROGRESS connection_data->destroy_graph_progress -#define CD_ORIGINAL_CONTENT_LENGTH connection_data->original_content_length -#define CD_CSO_LAST_CHAR connection_data->cso_last_char -#define CD_TCP_CON_DATA connection_data->tcp_con_data - - -#define CE_WINDOW_ID cur_entry->window_id -#define CE_URL_S cur_entry->URL_s -#define CE_STATUS cur_entry->status -#define CE_SOCK cur_entry->socket -#define CE_CON_SOCK cur_entry->con_sock -#define CE_BYTES_RECEIVED cur_entry->bytes_received - -/* states for the state machine - */ -#define GOPHER_BEGIN_CONNECT 1 -#define GOPHER_FINISH_CONNECT 2 -#define GOPHER_SEND_REQUEST 3 -#define GOPHER_BEGIN_TRANSFER 4 -#define GOPHER_TRANSFER_MENU 5 -#define GOPHER_TRANSFER_CSO 6 -#define GOPHER_TRANSFER_BINARY 7 -#define GOPHER_DONE 8 -#define GOPHER_ERROR_DONE 9 -#define GOPHER_FREE 10 - - -/* forward decl */ -PRIVATE int32 net_ProcessGopher(ActiveEntry * cur_entry); - -/* net_begin_gopher_menu - * - * adds little bits to the begining of the document so that is looks nice - */ - -PRIVATE int -net_begin_gopher_menu(GopherConData * connection_data) -{ - - CD_NEXT_STATE = GOPHER_TRANSFER_MENU; - - PL_strcpy(CD_OUTPUT_BUF, "<H1>Gopher Menu</H1>\n<PRE>"); - return(PUTSTRING(CD_OUTPUT_BUF)); - -} - -/* parse the gopher menu type - */ -PRIVATE int -net_parse_menu (ActiveEntry * cur_entry) -{ - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - char gopher_type; - char *name=NULL; - char *gopher_path=0; - char *port; - char *ptr; - char *line; - char *host=NULL; - - CE_STATUS = NET_BufferedReadLine(CE_SOCK, &line, &CD_DATA_BUF, - &CD_DATA_BUF_SIZE, &CD_PAUSE_FOR_READ); - - if(CE_STATUS == 0) - { - CD_NEXT_STATE = GOPHER_DONE; - CD_PAUSE_FOR_READ = FALSE; - if(CE_BYTES_RECEIVED < 4) - { - PL_strcpy(CD_OUTPUT_BUF, XP_GetString( XP_SERVER_RETURNED_NO_DATA ) ); - PUTSTRING(CD_OUTPUT_BUF); - } - - return(MK_DATA_LOADED); - } - - /* if TCP error of if there is not a full line yet return - */ - if(!line) - { - return CE_STATUS; - } - else if(CE_STATUS < 0) - { - NET_ExplainErrorDetails(MK_TCP_READ_ERROR, PR_GetOSError()); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - if(CE_STATUS > 1) - { - CE_BYTES_RECEIVED += CE_STATUS; - FE_GraphProgress(CE_WINDOW_ID, CE_URL_S, CE_BYTES_RECEIVED, CE_STATUS, CE_URL_S->content_length); - } - - gopher_type = *line; - - if(gopher_type != '\0') - ptr = line+1; - else - return(0); - - /* remove trailing spaces */ - XP_StripLine(line); - - TRACEMSG(("gopher_parse_menu: parsing line: %s\n",line)); - - /* quit when just a dot is found on a line by itself - */ - if(!PL_strcmp(line,".")) - { - CD_NEXT_STATE = GOPHER_DONE; - CD_PAUSE_FOR_READ = FALSE; - - if(CE_BYTES_RECEIVED < 4) - { - PL_strcpy(CD_OUTPUT_BUF, XP_GetString( XP_SERVER_RETURNED_NO_DATA ) ); - PUTSTRING(CD_OUTPUT_BUF); - } - - return(MK_DATA_LOADED); - } - - if (gopher_type && *ptr) - { - name = ptr; - gopher_path = PL_strchr(name, '\t'); - if (gopher_path) - { - *gopher_path++ = 0; - host = PL_strchr(gopher_path, '\t'); - if (host) - { - *host++ = 0; - port = PL_strchr(host, '\t'); - if (port) - { - char *tab; - - port[0] = ':'; /* fake the port no */ - tab = PL_strchr(port, '\t'); - if (tab) - *tab++ = '\0'; - - if (port[1]=='0' && port[2]=='\0') - port[0] = 0; - } - } - } - } - - if(!gopher_path) - { - return(PUTSTRING(ptr)); /* keep going bad data */ - } - - /* Nameless files are a separator line */ - if (gopher_type == GTYPE_TEXT) - { - int i=0; - while(NET_IS_SPACE(name[i])) i++; - if(!PL_strlen(name)) - gopher_type = GTYPE_INFO; - } - - /* these first few are grouped together with an - * if else because they each have special needs - * the rest of them fit nicely in the switch - */ - if(gopher_type == GTYPE_ERROR) - { - /* ignore it */ - } - else if(gopher_type == GTYPE_WWW) - { - /* points to URL */ - PL_strcpy(CD_OUTPUT_BUF, "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-text\">"); - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - - if(CE_STATUS < 0) - return(CE_STATUS); - - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<A HREF=\"%s\">%s</A>\n", gopher_path, name); - return(PUTSTRING(CD_OUTPUT_BUF)); - - } - else if(gopher_type == GTYPE_INFO) - { - /* Information or separator line */ - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, " %s\n", name); - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - } - else if(gopher_type == GTYPE_TELNET) - { - if (*gopher_path) - { - char * temp = NET_Escape(gopher_path, URL_XALPHAS); - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<A HREF=\"telnet://%s@%s/\"><IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-telnet\"> %s</A>\n", temp, host, name); - PR_Free(temp); - } - else - { - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<A HREF=\"telnet://%s/\"><IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-telnet\"> %s</A>\n", host, name); - } - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - } - else if(gopher_type == GTYPE_TN3270) - { - if (gopher_path && *gopher_path) - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<A HREF=\"tn3270://%s@%s/\"><IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-telnet\"> %s</A>\n", gopher_path, host, name); - else - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<A HREF=\"tn3270://%s/\"><IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-telnet\"> %s</A>\n", host, name); - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - } - else - { - if(host && gopher_path) - { - if(!PL_strcmp(host, "error.host:70")) - { - - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "Error: %s", name); - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - - } - else - { - char * newpath = NET_Escape(gopher_path, URL_PATH); - - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<A HREF=\"gopher://%s/%c%s\">", host, gopher_type, newpath); - - switch(gopher_type) { - case GTYPE_TEXT: - case GTYPE_HTML: - case GTYPE_HTMLCAPS: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 " - "SRC=\"internal-gopher-text\">"); - break; - case GTYPE_MENU: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-menu\">"); - break; - case GTYPE_CSO: - case GTYPE_INDEX: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-index\">"); - break; - case GTYPE_PCBINARY: - case GTYPE_UUENCODED: - case GTYPE_BINARY: - case GTYPE_MACBINHEX: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-binary\">"); - break; - case GTYPE_IMAGE: - case GTYPE_GIF: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-image\">"); - break; - case GTYPE_SOUND: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-sound\">"); - break; - case GTYPE_MPEG: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-movie\">"); - break; - - case GTYPE_MIME: - default: - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - "<IMG ALIGN=absbottom BORDER=0 SRC=\"internal-gopher-unknown\">"); - break; - } - - PR_snprintf(&CD_OUTPUT_BUF[PL_strlen(CD_OUTPUT_BUF)], - CD_OUTPUT_BUFFER_SIZE - - PL_strlen(CD_OUTPUT_BUF), - " %s</A>\n", name); - PR_Free(newpath); - - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - } - } - } - - return(CE_STATUS); /* keep going */ - -} - -/* net_begin_gopher_cso - * - * adds formatting to the front of the document to make - * it look pretty - */ -PRIVATE int -net_begin_gopher_cso(GopherConData * connection_data) -{ - PL_strcpy(CD_OUTPUT_BUF, "<H1>CSO Search Results</H1>\n<PRE>"); - - CD_NEXT_STATE = GOPHER_TRANSFER_CSO; - - return(PUTSTRING(CD_OUTPUT_BUF)); -} - -/* - * parse cso output - * - * receives date from the cso server and turns it into HTML - */ -PRIVATE int -net_parse_cso (ActiveEntry * cur_entry) -{ - char *line; - char *colon1, *colon2; - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - - CE_STATUS = NET_BufferedReadLine(CE_SOCK, &line, &CD_DATA_BUF, - &CD_DATA_BUF_SIZE, &CD_PAUSE_FOR_READ); - - if(CE_STATUS == 0) - CE_STATUS = MK_SERVER_DISCONNECTED; - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_SERVER_DISCONNECTED); - - /* if TCP error of if there is not a full line yet return - */ - if(CE_STATUS < 0) - { - NET_ExplainErrorDetails(MK_TCP_READ_ERROR, PR_GetOSError()); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return CE_STATUS; - } - - if(CE_STATUS > 1) - { - CE_BYTES_RECEIVED += CE_STATUS; - FE_GraphProgress(CE_WINDOW_ID, CE_URL_S, CE_BYTES_RECEIVED, CE_STATUS, CE_URL_S->content_length); - } - - /* a line beginning with a 2 means the end of data - */ - if (*line == '2') - { - CD_NEXT_STATE = GOPHER_DONE; - CD_PAUSE_FOR_READ = FALSE; - return(MK_DATA_LOADED); - } - - /* if it starts with a 5 something went wrong, print - * out the error message - */ - if (*line == '5') - { - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, "<H2>%s</H2>", line+4); - PUTSTRING(CD_OUTPUT_BUF); - CD_NEXT_STATE = GOPHER_DONE; - CD_PAUSE_FOR_READ = FALSE; - return(MK_DATA_LOADED); - } - - if(*line == '-') - { - colon1 = PL_strchr(line,':'); - if(colon1) - colon2 = PL_strchr(colon1+1, ':'); - else - colon2 = NULL; - - if(colon2 != NULL) - { - if (*(colon2-1) != CD_CSO_LAST_CHAR) - { /* print seperator */ - PL_strcpy(CD_OUTPUT_BUF, "</PRE><H2>"); - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - } - - if(CE_STATUS > -1) - CE_STATUS = PUTSTRING(colon2+1); - PL_strcpy(CD_OUTPUT_BUF, "\n"); - if(CE_STATUS > -1) - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - - if (*(colon2-1) != CD_CSO_LAST_CHAR) - { - /* end seperator */ - PL_strcpy(CD_OUTPUT_BUF, "</H2><PRE>"); - if(CE_STATUS > -1) - CE_STATUS = PUTSTRING(CD_OUTPUT_BUF); - } - - /* remember the last char so that we can - * tell when the sequence number changes - */ - CD_CSO_LAST_CHAR = *(colon2-1); - - } /* end if colon2 */ - } /* end if *line == '-' */ - - return(1); /* keep going */ - -} /* end of procedure */ - -/* display the page that allows searching of a gopher index - */ -PRIVATE int -net_display_index_splash_screen (ActiveEntry * cur_entry) -{ - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - char *address_copy = 0; - - StrAllocCopy(address_copy, CE_URL_S->address); - NET_UnEscape(address_copy); - - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, XP_GetString(XP_HTML_GOPHER_INDEX), address_copy, address_copy); - PUTSTRING(CD_OUTPUT_BUF); - - COMPLETE_STREAM; - - PR_Free(address_copy); - - return(0); -} - - -/* parse CSO server output -*/ -PRIVATE int -net_display_cso_splash_screen (ActiveEntry * cur_entry) -{ - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - char *address_copy = 0; - - StrAllocCopy(address_copy, CE_URL_S->address); - NET_UnEscape(address_copy); - - PR_snprintf(CD_OUTPUT_BUF, CD_OUTPUT_BUFFER_SIZE, XP_GetString(XP_HTML_CSO_SEARCH), address_copy, address_copy); - - PUTSTRING(CD_OUTPUT_BUF); - - COMPLETE_STREAM; - - PR_Free(address_copy); - - return(0); -} - -/* send the request to get the data - */ -PRIVATE int -net_send_gopher_request (ActiveEntry * cur_entry) -{ - - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - - TRACEMSG(("MKGopher: Connected, writing command `%s' to socket %d\n", - CD_COMMAND, CE_SOCK)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, CD_COMMAND, PL_strlen(CD_COMMAND)); - - NET_Progress (CE_WINDOW_ID, XP_GetString(XP_PROGRESS_WAITREPLY_GOTHER)); - - /* start the graph progress indicator - */ - FE_GraphProgressInit(CE_WINDOW_ID, CE_URL_S, CE_URL_S->content_length); - CD_DESTROY_GRAPH_PROGRESS = TRUE; /* we will need to destroy it */ - CD_ORIGINAL_CONTENT_LENGTH = CE_URL_S->content_length; - - CD_NEXT_STATE = GOPHER_BEGIN_TRANSFER; - CD_PAUSE_FOR_READ = TRUE; - - if(CE_STATUS < 0) - CE_STATUS = MK_TCP_WRITE_ERROR; - - return(CE_STATUS); /* everything OK */ - -} /* end GopherLoad */ - - -/* pull down data in binary mode - */ -PRIVATE int -net_pull_gopher_data(ActiveEntry * cur_entry) -{ - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - unsigned int write_ready, read_size; - - /* check to see if the stream is ready for writing - */ - write_ready = (*CD_STREAM->is_write_ready)(CD_STREAM); - - if(write_ready < 1) - { - CD_PAUSE_FOR_READ = TRUE; - return(0); /* wait until we are ready to write */ - } - else if(write_ready < (unsigned int) NET_Socket_Buffer_Size) - { - read_size = write_ready; - } - else - { - read_size = NET_Socket_Buffer_Size; - } - - CE_STATUS = PR_Read(CE_SOCK, NET_Socket_Buffer, read_size); - - if(CE_STATUS == 0) - { /* all done */ - CD_NEXT_STATE = GOPHER_DONE; - CE_STATUS = MK_DATA_LOADED; - } - else if(CE_STATUS > 0) - { - CE_BYTES_RECEIVED += CE_STATUS; - FE_GraphProgress(CE_WINDOW_ID, - CE_URL_S, - CE_BYTES_RECEIVED, - CE_STATUS, - CE_URL_S->content_length); - CE_STATUS = PUTBLOCK(NET_Socket_Buffer, CE_STATUS); - CD_PAUSE_FOR_READ = TRUE; - } - else - { - /* status less than zero - */ - int rv = PR_GetError(); - if(rv == PR_WOULD_BLOCK_ERROR) - { - CD_PAUSE_FOR_READ = TRUE; - return 0; - } - CE_STATUS = (rv < 0) ? rv : (-rv); - } - - return(CE_STATUS); - -} - -/* a list of dis-allowed ports for gopher - * connections - */ -PRIVATE int bad_ports_table[] = { -1, 7, 9, 11 , 13, 15, 17, 19, 20, -21, 23, 25, 37, 42, 43, 53, 77, 79, 87, 95, 101, 102, -103, 104, 109, 110, 111, 113, 115, 117, 119, -135, 143, 512, 513, 514, 515, 526, 530, 531, 532, -540, 556, 601, 6000, 0 }; - -/* begin the load by initializing data structures and calling Process Gopher - */ -PRIVATE int32 -net_GopherLoad (ActiveEntry * cur_entry) -{ - char gopher_type; /* type */ - char * path; /* the URL path */ - char * gopher_path; /* the gopher path */ - char * gopher_host; - char * query; /* holds the '?' query string */ - char *ptr; - GopherConData * connection_data; /* state data for this connection */ - - /* check for illegal gopher port numbers and - * return invalid URL for those - */ - gopher_host = NET_ParseURL(CE_URL_S->address, GET_HOST_PART); - if(gopher_host) - { - int port_number; - int i; - char *colon = PL_strchr(gopher_host, ':'); - - if(colon) - { - colon++; /* now it points to a port number */ - - port_number = XP_ATOI(colon); - - /* disallow well known ports */ - for(i=0; bad_ports_table[i]; i++) - if(port_number == bad_ports_table[i]) - { - char *error_msg = NET_ExplainErrorDetails( - MK_MALFORMED_URL_ERROR, - CE_URL_S->address); - if(error_msg) - FE_Alert(CE_WINDOW_ID, error_msg); - PR_Free(gopher_host); - return(MK_MALFORMED_URL_ERROR); - } - } - PR_Free(gopher_host); - } - - - /* malloc space for connection data - */ - connection_data = PR_NEW(GopherConData); - if(!connection_data) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - memset(connection_data, 0, sizeof(GopherConData)); /* zero it */ - - CE_SOCK = NULL; - - cur_entry->con_data = connection_data; - - CD_OUTPUT_BUF = (char*) PR_Malloc(CD_OUTPUT_BUFFER_SIZE); - if(!CD_OUTPUT_BUF) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - - /* Get entity type, and gopher_path string. - */ - path = NET_ParseURL(CE_URL_S->address, GET_PATH_PART); - - TRACEMSG(("GopherLoad: Got path: %s\n",path)); - - if(*path && *path != '/') - { - gopher_type = *path; - gopher_path = path+1; - } - else if ((*path=='/') && (*(path+1))) /* past first slash slash */ - { - gopher_type = *(path+1); /* get gopher_type */ - gopher_path = path+2; /* go past slash and gopher_type */ - } - else /* no path or just slash */ - { - /* special case!!! - * if the URL looks like gopher://host/?search term - * treat it as a text file and append the search term - */ - if(PL_strchr(CE_URL_S->address, '?')) - { - gopher_type = '0'; - } - else - { - gopher_type = '1'; /* menus are the default */ - } - if(*path == '\0') - gopher_path = path; - else - gopher_path = path+1; - } - - CD_GOPHER_TYPE = gopher_type; /* set for later use */ - - TRACEMSG(("URL: %s\ngopher_type: %c\nGopher_Path: %s\n", - CE_URL_S->address, gopher_type, gopher_path)); - - /* We now have the gopher type so we can safely set up - * the Stream stack since we know what type will be - * returned ahead of time - */ - switch(gopher_type) { - case GTYPE_HTML: /* all HTML types */ - case GTYPE_HTMLCAPS: - case GTYPE_MENU: - case GTYPE_CSO: - case GTYPE_INDEX: - StrAllocCopy(CE_URL_S->content_type, TEXT_HTML); - break; - case GTYPE_TEXT: - StrAllocCopy(CE_URL_S->content_type, TEXT_PLAIN); - break; - case GTYPE_MACBINHEX: - StrAllocCopy(CE_URL_S->content_type, APPLICATION_BINHEX); - break; - case GTYPE_PCBINARY: - case GTYPE_BINARY: - case GTYPE_MIME: - StrAllocCopy(CE_URL_S->content_type, APPLICATION_OCTET_STREAM); - break; - case GTYPE_UUENCODED: - StrAllocCopy(CE_URL_S->content_type, APPLICATION_UUENCODE); - break; - case GTYPE_TELNET: - case GTYPE_TN3270: -#ifdef MOZILLA_CLIENT - /* do the telnet and return */ - return(NET_RemoteHostLoad(cur_entry)); -#else - PR_ASSERT(0); - break; -#endif /* MOZILLA_CLIENT */ - case GTYPE_GIF: - case GTYPE_IMAGE: - StrAllocCopy(CE_URL_S->content_type, IMAGE_GIF); - break; - case GTYPE_SOUND: - StrAllocCopy(CE_URL_S->content_type, AUDIO_BASIC); - break; - case GTYPE_MPEG: - StrAllocCopy(CE_URL_S->content_type, VIDEO_MPEG); - break; - default: - StrAllocCopy(CE_URL_S->content_type, TEXT_PLAIN); - break; - } - - CD_STREAM = NET_StreamBuilder(cur_entry->format_out, CE_URL_S, CE_WINDOW_ID); - - if (!CD_STREAM) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return(MK_UNABLE_TO_CONVERT); - } - - TRACEMSG(("MKGopher: Stream now set up \n")); - - /* now do all the special handling of each type that - * doesn't involve just a direct get - */ - switch(gopher_type) { - case GTYPE_INDEX: - /* Search is allowed */ - query = PL_strchr(CE_URL_S->address, '?'); /* Look for search string */ - - if (!query || !query[1]) { /* No search defined */ - /* Display "cover page" */ - net_display_index_splash_screen(cur_entry); - CD_NEXT_STATE = GOPHER_DONE; - return -1; /* Local function only */ - } - - *query++ = 0; /* Go past '?' */ - - StrAllocCopy(CD_COMMAND, NET_UnEscape(gopher_path)); - - StrAllocCat(CD_COMMAND, "\t"); - - /* Remove plus signs */ - for (ptr=query; *ptr; ptr++) - if (*ptr == '+') - *ptr = ' '; - - StrAllocCat(CD_COMMAND, NET_UnEscape(query)); - - *(query-1) = '?'; /* set it back to the way it was */ - break; - - case GTYPE_CSO: - /* Search is allowed */ - query = PL_strchr(CE_URL_S->address, '?'); /* Look for search string */ - - if (!query || !query[1]) /* No search required */ - { - /* Display "cover page" */ - net_display_cso_splash_screen(cur_entry); - CE_STATUS = MK_DATA_LOADED; - return -1; /* Local function only */ - } - *query++ = 0; /* Go past '?' */ - - StrAllocCopy(CD_COMMAND, "query "); - - /* Remove plus signs */ - for (ptr=query; *ptr; ptr++) - if (*ptr == '+') - *ptr = ' '; - - StrAllocCat(CD_COMMAND, (char *)NET_UnEscape(query)); - - *(query-1) = '?'; /* set it back to the way it was */ - - break; - - case GTYPE_TEXT: - /* Look for search string */ - query = PL_strchr(CE_URL_S->address, '?'); - - /* special case!!! - * if a query exist treat it special, send - * the query instead - */ - if(query) - { - *query++ = 0; /* Go past '?' */ - - /* Remove plus signs */ - for (ptr=query; *ptr; ptr++) - if (*ptr == '+') - *ptr = ' '; - - StrAllocCopy(CD_COMMAND, (char *)NET_UnEscape(query)); - - *(query-1) = '?'; /* set it back to the way it was */ - } - else if(*path != '\0') - { - StrAllocCopy(CD_COMMAND, (char*)NET_UnEscape(gopher_path)); - } - else - { - StrAllocCopy(CD_COMMAND, "/"); - } - break; - - default: /* all other types besides index and CSO */ - if(*path == '\0') - StrAllocCopy(CD_COMMAND, "/"); - else - StrAllocCopy(CD_COMMAND, (char*)NET_UnEscape(gopher_path)); - } - - PR_FREEIF(path); /* NET_Parse malloc'd the path string */ - path = NULL; - - /* protect against other protocol attacks by limiting - * the command to a single line. Terminate the command - * at any \n or \r - */ - if(PL_strchr(CD_COMMAND, '\n') || PL_strchr(CD_COMMAND, '\r')) - { - char *error_msg = NET_ExplainErrorDetails(MK_MALFORMED_URL_ERROR, - CE_URL_S->address); - if(error_msg) - FE_Alert(CE_WINDOW_ID, error_msg); - return(MK_MALFORMED_URL_ERROR); - } - - StrAllocCat(CD_COMMAND, CRLF); /* finish off the command */ - - CD_NEXT_STATE = GOPHER_BEGIN_CONNECT; - - return(net_ProcessGopher(cur_entry)); -} - -/* NET_ProcessGopher - * completes the data transfer; is called from NET_ProcessNet() - * - * returns negative when complete - */ -PRIVATE int32 -net_ProcessGopher(ActiveEntry * cur_entry) -{ - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - - TRACEMSG(("Entered ProcessGopher: gopher_type=%c\n",CD_GOPHER_TYPE)); - - CD_PAUSE_FOR_READ = FALSE; - - while(!CD_PAUSE_FOR_READ) - { - TRACEMSG(("ProcessGopher: in switch with state: #%d\n",CD_NEXT_STATE)); - - switch(CD_NEXT_STATE) { - - case GOPHER_BEGIN_CONNECT: - /* Set up a socket to the server for the data: - */ - TRACEMSG(("MKGopher: Setting up net connection\n")); - - CE_STATUS = NET_BeginConnect(CE_URL_S->address, - CE_URL_S->IPAddressString, - "Gopher", - 70, - &CE_SOCK, - HG10300 - &CD_TCP_CON_DATA, - CE_WINDOW_ID, - &CE_URL_S->error_msg, - cur_entry->socks_host, - cur_entry->socks_port, - cur_entry->URL_s->localIP); - - if(CE_SOCK != NULL) - NET_TotalNumberOfOpenConnections++; - - if(CE_STATUS == MK_CONNECTED) - { - CD_NEXT_STATE = GOPHER_SEND_REQUEST; - NET_SetReadSelect(CE_WINDOW_ID, CE_SOCK); - } - else if(CE_STATUS > -1) - { - CD_NEXT_STATE = GOPHER_FINISH_CONNECT; - CD_PAUSE_FOR_READ = TRUE; - CE_CON_SOCK = CE_SOCK; /* set so we select on it */ - NET_SetConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - } - break; - - case GOPHER_FINISH_CONNECT: - CE_STATUS = NET_FinishConnect(CE_URL_S->address, - "Gopher", - 70, - &CE_SOCK, - &CD_TCP_CON_DATA, - CE_WINDOW_ID, - &CE_URL_S->error_msg, - cur_entry->URL_s->localIP); - if(CE_STATUS == MK_CONNECTED) - { - CD_NEXT_STATE = GOPHER_SEND_REQUEST; - NET_ClearConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - CE_CON_SOCK = NULL; /* reset so we don't select on it */ - NET_SetReadSelect(CE_WINDOW_ID, CE_SOCK); - } - else - { - - /* unregister the old CE_SOCK from the select list - * and register the new value in the case that it changes - */ - if(CE_CON_SOCK != CE_SOCK) - { - NET_ClearConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - CE_CON_SOCK = CE_SOCK; - NET_SetConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - } - - CD_PAUSE_FOR_READ = TRUE; - } - break; - - case GOPHER_SEND_REQUEST: - CE_STATUS = net_send_gopher_request(cur_entry); - break; - - case GOPHER_BEGIN_TRANSFER: - if(CD_GOPHER_TYPE == GTYPE_MENU || CD_GOPHER_TYPE == GTYPE_INDEX) - CE_STATUS = net_begin_gopher_menu(connection_data); - else if(CD_GOPHER_TYPE == GTYPE_CSO) - CE_STATUS = net_begin_gopher_cso(connection_data); - else - CD_NEXT_STATE = GOPHER_TRANSFER_BINARY; - break; - - case GOPHER_TRANSFER_MENU: - CE_STATUS = net_parse_menu(cur_entry); - break; - - case GOPHER_TRANSFER_CSO: - CE_STATUS = net_parse_cso(cur_entry); - break; - - case GOPHER_TRANSFER_BINARY: - CE_STATUS = net_pull_gopher_data(cur_entry); - break; - - case GOPHER_DONE: - NET_ClearReadSelect(CE_WINDOW_ID, CE_SOCK); - PR_Close(CE_SOCK); - NET_TotalNumberOfOpenConnections--; - COMPLETE_STREAM; - CD_NEXT_STATE = GOPHER_FREE; - break; - - case GOPHER_ERROR_DONE: - if(CE_SOCK != NULL) - { - NET_ClearReadSelect(CE_WINDOW_ID, CE_SOCK); - NET_ClearConnectSelect(CE_WINDOW_ID, CE_SOCK); - NET_ClearDNSSelect(CE_WINDOW_ID, CE_SOCK); - PR_Close(CE_SOCK); - NET_TotalNumberOfOpenConnections--; - } - if(CD_STREAM) - ABORT_STREAM(CE_STATUS); - CD_NEXT_STATE = GOPHER_FREE; - break; - - case GOPHER_FREE: - if(CD_DESTROY_GRAPH_PROGRESS) - FE_GraphProgressDestroy(CE_WINDOW_ID, - CE_URL_S, - CD_ORIGINAL_CONTENT_LENGTH, - CE_BYTES_RECEIVED); - PR_FREEIF(CD_COMMAND); - PR_FREEIF(CD_STREAM); /* don't forget the stream */ - PR_FREEIF(CD_OUTPUT_BUF); - PR_FREEIF(CD_DATA_BUF); - if(CD_TCP_CON_DATA) - NET_FreeTCPConData(CD_TCP_CON_DATA); - - PR_Free(connection_data); - return(-1); /* all done */ - - } /* end switch(NEXT_STATE) */ - - - if(CE_STATUS < 0 && CD_NEXT_STATE != GOPHER_DONE && - CD_NEXT_STATE != GOPHER_ERROR_DONE && - CD_NEXT_STATE != GOPHER_FREE) - { - CD_NEXT_STATE = GOPHER_ERROR_DONE; - CD_PAUSE_FOR_READ = FALSE; - } - - } /* end while */ - - return(CE_STATUS); -} - -/* abort the connection in progress - */ -PRIVATE int32 -net_InterruptGopher(ActiveEntry * cur_entry) -{ - GopherConData * connection_data = (GopherConData *)cur_entry->con_data; - - CD_NEXT_STATE = GOPHER_ERROR_DONE; - CE_STATUS = MK_INTERRUPTED; - - return(net_ProcessGopher(cur_entry)); -} - -/* Free any memory - */ -PRIVATE void -net_CleanupGopher(void) -{ - /* nothing to free */ - return; -} - -MODULE_PRIVATE void -NET_InitGopherProtocol(void) -{ - static NET_ProtoImpl gopher_proto_impl; - - gopher_proto_impl.init = net_GopherLoad; - gopher_proto_impl.process = net_ProcessGopher; - gopher_proto_impl.interrupt = net_InterruptGopher; - gopher_proto_impl.resume = NULL; - gopher_proto_impl.cleanup = net_CleanupGopher; - - NET_RegisterProtocolImplementation(&gopher_proto_impl, GOPHER_TYPE_URL); -} diff --git a/mozilla/network/protocol/http/MANIFEST b/mozilla/network/protocol/http/MANIFEST deleted file mode 100644 index ac12a9a67d8..00000000000 --- a/mozilla/network/protocol/http/MANIFEST +++ /dev/null @@ -1,8 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -httpurl.h -cookies.h -httpauth.h -mkaccess.h diff --git a/mozilla/network/protocol/http/Makefile.in b/mozilla/network/protocol/http/Makefile.in deleted file mode 100644 index 346f2d367e7..00000000000 --- a/mozilla/network/protocol/http/Makefile.in +++ /dev/null @@ -1,48 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = httpurl -LIBRARY_NAME = httpurl - -CSRCS = \ - mkhttp.c \ - mkaccess.c \ - $(NULL) - -CPPSRCS = nsCookie.cpp - -ifdef MOZ_BRPROF -CPPSRCS += nsGetBrowsingProfile.cpp -endif - -EXPORTS = mkaccess.h httpurl.h httpauth.h cookies.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/http/cookies.h b/mozilla/network/protocol/http/cookies.h deleted file mode 100644 index 56eab0afe5e..00000000000 --- a/mozilla/network/protocol/http/cookies.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef COOKIES_H -#define COOKIES_H - -#include "mkgeturl.h" - -PR_BEGIN_EXTERN_C - -/* removes all cookies structs from the cookie list */ -extern void -NET_RemoveAllCookies(void); - -extern char * -NET_GetCookie(MWContext * context, char * address); - -extern void -NET_SetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header); - -/* saves out the HTTP cookies to disk - * - * on entry pass in the name of the file to save - * - * returns 0 on success -1 on failure. - * - */ -extern int NET_SaveCookies(char * filename); - -/* reads HTTP cookies from disk - * - * on entry pass in the name of the file to read - * - * returns 0 on success -1 on failure. - * - */ -extern int NET_ReadCookies(char * filename); - -/* wrapper of NET_SetCookieString for netlib use. We need outformat and url_struct to determine - * whether we're dealing with inline cookies - */ -extern void -NET_SetCookieStringFromHttp(FO_Present_Types outputFormat, - URL_Struct * URL_s, - MWContext * context, - char * cur_url, - char * set_cookie_header); - -PR_END_EXTERN_C - -#endif /* COOKIES_H */ diff --git a/mozilla/network/protocol/http/htmldlgs.h b/mozilla/network/protocol/http/htmldlgs.h deleted file mode 100644 index 7f8b79f72ce..00000000000 --- a/mozilla/network/protocol/http/htmldlgs.h +++ /dev/null @@ -1,377 +0,0 @@ -#define XP_STRSTR strstr -#define XP_STRTOUL strtoul - -#include "platform.h" -#include "xp_core.h" -#include "xp_mem.h" -#include "xp_str.h" -#include "xp_list.h" -#include "prprf.h" -#include <string.h> - -#include "xp_file.h" -#include "jsotypes.h" -#include "plstr.h" -#include "seccomon.h" -#include "xpgetstr.h" - -#define PORT_Strlen(s) strlen(s) - -#define HTML_DLGS_URL "file:///y|/htmldlgs.html" -#define XP_DIALOG_CANCEL_BUTTON (1<<0) -#define XP_DIALOG_OK_BUTTON (1<<2) -#define XP_STRINGS_CHUNKSIZE 512 -typedef struct _XPDialogState XPDialogState; -typedef struct _XPDialogInfo XPDialogInfo; -typedef struct _XPDialogStrings XPDialogStrings; -typedef PRBool (* XP_HTMLDialogHandler) - (XPDialogState *state, char **argv, int argc, unsigned int button); - -/* SACopy and SACat should really be defined elsewhere */ -#include "plstr.h" -#include "prmem.h" -#define LocalStrAllocCopy(dest, src) Local_SACopy (&(dest), src) -#define LocalStrAllocCat(dest, src) Local_SACat (&(dest), src) - -struct _XPDialogState { - PRArenaPool *arena; - void *window; - void *proto_win; - XPDialogInfo *dialogInfo; - void *arg; - void (* deleteCallback)(void *arg); - void *cbarg; - PRBool deleted; -}; - -struct _XPDialogInfo { - unsigned int buttonFlags; - XP_HTMLDialogHandler handler; - int width; - int height; -}; - -struct _XPDialogStrings -{ - PRArenaPool *arena; - int basestringnum; - int nargs; - char **args; - char *contents; -}; - -#ifdef InSingleSignon - -char * -Local_SACopy(char **destination, const char *source); - -char * -Local_SACat(char **destination, const char *source); - -XPDialogState * -XP_MakeHTMLDialog( - void *proto_win, - XPDialogInfo *dialogInfo, - int titlenum, - XPDialogStrings *strings, - void *arg, - PRBool utf8CharSet); - -void -XP_MakeHTMLDialog2(XPDialogInfo *dialogInfo); - -XPDialogStrings * -XP_GetDialogStrings(int stringnum); - -void -XP_SetDialogString(XPDialogStrings *strings, int argNum, char *string); - -void -XP_CopyDialogString(XPDialogStrings *strings, int argNum, const char *string); - -char * -XP_FindValueInArgs(const char *name, char **av, int ac); - -#else - -char * -Local_SACopy(char **destination, const char *source) -{ - if(*destination) { - PL_strfree(*destination); - *destination = 0; - } - *destination = PL_strdup(source); - return *destination; -} - -char * -Local_SACat(char **destination, const char *source) -{ - if (source && *source) { - if (*destination) { - int length = PL_strlen (*destination); - *destination = (char *) PR_Realloc(*destination, length + PL_strlen(source) + 1); - if (*destination == NULL) { - return(NULL); - } - PL_strcpy (*destination + length, source); - } else { - *destination = PL_strdup(source); - } - } - return *destination; -} - -XPDialogState * -XP_MakeHTMLDialog( - void *proto_win, - XPDialogInfo *dialogInfo, - int titlenum, - XPDialogStrings *strings, - void *arg, - PRBool utf8CharSet) -{ - /* write out html dialog to /htmldlgs.htm */ - XP_File f = fopen("/htmldlgs.htm","w"); - int i; - for (i=0; i<strings->nargs; i++) { - if (strings->args[i]) { - fprintf(f, "%s", (char *)(strings->args[i])); - } - } - fclose(f); - fflush(f); - - /* write out dialog info to /index.htm */ - f = fopen("/index.htm","w"); - fprintf(f, "<HTML> \n"); - fprintf(f, " <BODY \n"); - fprintf(f, " onload=\"msgWindow=window.open(\n"); - fprintf(f, " 'htmldlgs.htm', \n"); - fprintf(f, " 'window2', \n"); - fprintf(f, " 'resizable=no, titlebar=no, width=%d, height=%d')\">\n", - dialogInfo->width, dialogInfo->height); - fprintf(f, " </BODY> \n"); - fprintf(f, "</HTML> \n"); - fclose(f); - fflush(f); - - return NULL; -} - -#ifdef junk -void -XP_MakeHTMLDialog2(XPDialogInfo *dialogInfo) { - char* argv[] = {NULL, NULL, NULL, NULL, NULL, NULL}; - int argc = 0; - char* button = NULL; - - nsAutoString * nsCookie = new nsAutoString(""); - nsIURI* url; - char* separator; - - nsINetService *netservice; - nsresult res; - res = nsServiceManager::GetService(kNetServiceCID, - kINetServiceIID, - (nsISupports **)&netservice); - if ((NS_OK == res) && (nsnull != netservice)) { - const nsAutoString html_dlgs = nsAutoString(HTML_DLGS_URL); - if (!NS_FAILED(NS_NewURL(&url, html_dlgs))) { - res = netservice->GetCookieString(url, *nsCookie); - - /* convert cookie to a C string */ - - char *cookies = nsCookie->ToNewCString(); - char *cookie = PL_strstr(cookies, "htmldlgs=|"); /* get to htmldlgs=| */ - if (cookie) { - cookie = cookie + PL_strlen("htmldlgs=|"); /* get passed htmldlgs=| */ - - /* button name is first item in cookie (up to next verical bar) */ - - separator = strchr(cookie, '|'); - *separator = '\0'; - LocalStrAllocCopy(button, cookie); - cookie = separator+1; - *separator = '|'; - - /* remainder of cookie string are the args, separated by vertical bars */ - for (int i=0; ((*cookie != '\0') && (*cookie != ';')); i++) { - separator = strchr(cookie, '|'); - *separator = '\0'; - LocalStrAllocCopy(argv[i], cookie); - cookie = separator+1; - *separator = '|'; - argc++; - } - - /* call the callback routine */ - if (!PORT_Strcmp(button,"OK")) { - (dialogInfo->handler)(NULL, argv, argc, XP_DIALOG_OK_BUTTON); - } else { - (dialogInfo->handler)(NULL, argv, argc, XP_DIALOG_CANCEL_BUTTON); - } - - /* free up the allocated strings */ - XP_FREE(button); - for (int j=0; j<argc; j++) { - XP_FREE(argv[j]); - } - } - delete[] cookies; - } - NS_RELEASE(netservice); - } -} -#endif - -XPDialogStrings * -XP_GetDialogStrings(int stringnum) -{ - XPDialogStrings *header = NULL; - PRArenaPool *arena = NULL; - char *dst, *src; - int n, size, len, done = 0; - - /* get a new arena */ - arena = PORT_NewArena(XP_STRINGS_CHUNKSIZE); - if ( arena == NULL ) { - return(NULL); - } - - /* allocate the header structure */ - header = (XPDialogStrings *)PORT_ArenaAlloc(arena, sizeof(XPDialogStrings)); - if ( header == NULL ) { - goto loser; - } - - /* init the header */ - header->arena = arena; - header->basestringnum = stringnum; - -#ifdef XP_MAC - goto loser; -#else - src = XP_GetString(stringnum); - -#endif - len = PORT_Strlen(src); - size = len + 1; - dst = header->contents = - (char *)PORT_ArenaAlloc(arena, sizeof(char) * size); - if (dst == NULL) { - goto loser; - } - - while (!done) { /* Concatenate pieces to form message */ - PORT_Memcpy(dst, src, len+1); - done = 1; - if (XP_STRSTR(src, "%-cont-%")) { /* Continuation */ - src = XP_GetString(++stringnum); - len = PORT_Strlen(src); - header->contents = - (char *)PORT_ArenaGrow(arena, - header->contents, size, size + len); - if (header->contents == NULL) { - goto loser; - } - dst = header->contents + size - 1; - size += len; - done = 0; - } - } - - /* At this point we should have the complete message in - header->contents, including like %-cont-%, which will be - ignored later. */ - - /* Count the arguments in the message */ - header->nargs = -1; /* Support %0% as lowest token */ - src = header->contents; - while ((src = PORT_Strchr(src, '%'))) { - src++; - n = (int)XP_STRTOUL(src, &dst, 10); - if (dst == src) { /* Integer not found... */ - src = PORT_Strchr(src, '%') + 1; /* so skip this %..% */ - PORT_Assert(NULL != src-1); /* Unclosed %..% ? */ - continue; - } - - if (header->nargs < n) { - header->nargs = n; - } - src = dst + 1; - } - - if (++(header->nargs) > 0) { /* Allocate space for arguments */ - header->args = - (char **)PORT_ArenaZAlloc(arena, sizeof(char *) * header->nargs); - } - - return(header); - -loser: - PORT_FreeArena(arena, PR_FALSE); - return(NULL); -} - - - -void -XP_SetDialogString(XPDialogStrings *strings, int argNum, char *string) -{ - /* make sure we are doing it right */ - PORT_Assert(argNum < strings->nargs); - PORT_Assert(argNum >= 0); - PORT_Assert(strings->args[argNum] == NULL); - - /* set the string */ - strings->args[argNum] = string; - - return; -} - -void -XP_CopyDialogString(XPDialogStrings *strings, int argNum, const char *string) -{ - int len; - - /* make sure we are doing it right */ - PORT_Assert(argNum < strings->nargs); - PORT_Assert(argNum >= 0); - PORT_Assert(strings->args[argNum] == NULL); - - /* copy the string */ - len = PORT_Strlen(string) + 1; - strings->args[argNum] = (char *)PORT_ArenaAlloc(strings->arena, len); - if ( strings->args[argNum] != NULL ) { - PORT_Memcpy(strings->args[argNum], string, len); - } - - return; -} - -char * -XP_FindValueInArgs(const char *name, char **av, int ac) -{ - for( ;ac > 0; ac -= 2, av += 2 ) { - if ( PORT_Strcmp(name, av[0]) == 0 ) { - return(av[1]); - } - } - return(0); -} - -#endif - -#define BUFLEN 5000 - -#define FLUSH_BUFFER \ - if (buffer) { \ - LocalStrAllocCat(buffer2, buffer); \ - buffer[0] = '\0'; \ - g = 0; \ - } - -extern int XP_EMPTY_STRINGS; diff --git a/mozilla/network/protocol/http/httpauth.h b/mozilla/network/protocol/http/httpauth.h deleted file mode 100644 index d882ac46afe..00000000000 --- a/mozilla/network/protocol/http/httpauth.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef HTTPAUTH_H -#define HTTPAUTH_H - -#ifndef MKGETURL_H -#include "mkgeturl.h" -#endif - -/* removes all authorization structs from the auth list */ -extern void -NET_RemoveAllAuthorizations(void); - -/* - * Figure out better of two {WWW,Proxy}-Authenticate headers; - * SimpleMD5 is better than Basic. Uses the order of AuthType - * enum values. - * - */ -extern PRBool -net_IsBetterAuth(char *new_auth, char *old_auth); - -#endif /* HTTPAUTH_H */ diff --git a/mozilla/network/protocol/http/httpurl.h b/mozilla/network/protocol/http/httpurl.h deleted file mode 100644 index e4d7f972dc4..00000000000 --- a/mozilla/network/protocol/http/httpurl.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKHTTP_H -#define MKHTTP_H - -#ifndef MKGETURL_H -#include "mkgeturl.h" -#endif /* MKGETURL_H */ - -#define DEF_HTTP_PORT 80 -#define DEF_HTTPS_PORT 443 - -typedef enum { - POINT_NINE, - ONE_POINT_O, - ONE_POINT_ONE -} HTTP_Version; - -extern void -NET_SetSendRefererHeader(Bool b); - -extern void -NET_InitHTTPProtocol(void); - -extern void -NET_getInternetKeyword(const URL_Struct *inURL, char *outKeyword, - int16 inMaxLength); - -#endif /* MKHTTP_H */ diff --git a/mozilla/network/protocol/http/makefile.win b/mozilla/network/protocol/http/makefile.win deleted file mode 100644 index 29771b7cadf..00000000000 --- a/mozilla/network/protocol/http/makefile.win +++ /dev/null @@ -1,110 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT -DMOZ_BRPROF - -LCFLAGS = $(LCFLAGS) - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -LLIBS= \ - $(NULL) -OBJS= \ - .\$(OBJDIR)\mkhttp.obj \ - .\$(OBJDIR)\mkaccess.obj \ - $(NULL) - -CPP_OBJS= \ - .\$(OBJDIR)\nsGetBrowsingProfile.obj \ - .\$(OBJDIR)\nsCookie.obj \ - $(NULL) - -CSRCS = \ - mkhttp.c \ - mkaccess.c \ - $(NULL) - -CPPSRCS = \ - nsGetBrowsingProfile.cpp \ - nsCookie.cpp \ - $(NULL) - -LIBRARY_NAME=httpurl -MODULE=httpurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= mkaccess.h httpurl.h cookies.h httpauth.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\mimetype \ -!ifdef MOZ_SMOOTH_PROGRESS - -I$(PUBLIC)\progress \ -!endif - -I$(PUBLIC)\xpcom \ - -I$(PUBLIC)\brprof \ - -I$(PUBLIC)\raptor \ - -I$(PUBLIC)\netlib \ - -I$(PUBLIC)\intl \ - -I$(PUBLIC)\locale \ - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/http/mkaccess.c b/mozilla/network/protocol/http/mkaccess.c deleted file mode 100644 index aecc07b25d5..00000000000 --- a/mozilla/network/protocol/http/mkaccess.c +++ /dev/null @@ -1,5456 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * - * Designed and Implemented by Lou Montulli '94 - * Heavily modified by Judson Valeski '97 - * Yada yada yada... Gagan Saksena '98 - * - * This file implements HTTP access authorization - * and HTTP cookies - */ - -#if defined(CookieManagement) -/* #define TRUST_LABELS */ -#endif - -#if defined(SingleSignon) -#define EDITOR 1 -#endif - -#define alphabetize 1 -#include "rosetta.h" -#include "xp.h" -#include "mkprefs.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "mkparse.h" -#include "mkaccess.h" -#include "net_xp_file.h" -/*#include "cookies.h" */ -#include "httpauth.h" -#include "prefapi.h" -#include "shist.h" -#include "jscookie.h" -#include "prmon.h" -#include "edt.h" /* for EDT_SavePublishUsernameAndPassword */ - -#ifdef XP_MAC -#include "prpriv.h" /* for NewNamedMonitor */ -#else -#include "private/prpriv.h" -#endif - -#include "secnav.h" -#include "sechash.h" -#include "libevent.h" -#include "pwcacapi.h" - -/* for XP_GetString() */ -#include "xpgetstr.h" - -extern int XP_CONFIRM_AUTHORIZATION_FAIL; -extern int XP_ACCESS_ENTER_USERNAME; -extern int XP_CONFIRM_PROXYAUTHOR_FAIL; -extern int XP_CONNECT_PLEASE_ENTER_PASSWORD_FOR_HOST; -extern int XP_PROXY_REQUIRES_UNSUPPORTED_AUTH_SCHEME; -extern int XP_LOOPING_OLD_NONCES; -extern int XP_UNIDENTIFIED_PROXY_SERVER; -extern int XP_PROXY_AUTH_REQUIRED_FOR; -extern int XP_CONNECT_PLEASE_ENTER_PASSWORD_FOR_PROXY; -extern int XP_FORTEZZA_PROXY_AUTH; -/* -extern int MK_ACCESS_COOKIES_THE_SERVER; -extern int MK_ACCESS_COOKIES_WISHES; -#if defined(CookieManagement) -extern int MK_ACCESS_COOKIES_WISHES0; -extern int MK_ACCESS_COOKIES_WISHES1; -extern int MK_ACCESS_COOKIES_WISHESN; -extern int MK_ACCESS_COOKIES_WISHES_MODIFY; -extern int MK_ACCESS_COOKIES_REMEMBER; -extern int MK_ACCESS_COOKIES_ACCEPTED; -extern int MK_ACCESS_SITE_COOKIES_ACCEPTED; -extern int MK_ACCESS_COOKIES_PERMISSION; -#else -extern int MK_ACCESS_COOKIES_TOANYSERV; -extern int MK_ACCESS_COOKIES_TOSELF; -extern int MK_ACCESS_COOKIES_NAME_AND_VAL; -extern int MK_ACCESS_COOKIES_COOKIE_WILL_PERSIST; -#endif -extern int MK_ACCESS_COOKIES_SET_IT; -extern int MK_ACCESS_YOUR_COOKIES; -extern int MK_ACCESS_NAME; -extern int MK_ACCESS_VALUE; -extern int MK_ACCESS_HOST; -extern int MK_ACCESS_DOMAIN; -extern int MK_ACCESS_PATH; -extern int MK_ACCESS_YES; -extern int MK_ACCESS_NO; -extern int MK_ACCESS_SECURE; -extern int MK_ACCESS_EXPIRES; -extern int MK_ACCESS_END_OF_SESSION; -extern int MK_ACCESS_VIEW_COOKIES; -extern int MK_ACCESS_VIEW_SITES; - -#ifdef TRUST_LABELS -extern int MK_ACCESS_TL_PUR1; -extern int MK_ACCESS_TL_PUR2; -extern int MK_ACCESS_TL_PUR3; -extern int MK_ACCESS_TL_PUR4; -extern int MK_ACCESS_TL_PUR5; -extern int MK_ACCESS_TL_PUR6; -extern int MK_ACCESS_TL_PPH0; -extern int MK_ACCESS_TL_PPH1; -extern int MK_ACCESS_TL_PPH2; -extern int MK_ACCESS_TL_PPH3; -extern int MK_ACCESS_TL_PPH4; -extern int MK_ACCESS_TL_PPH5; -extern int MK_ACCESS_TL_ID1; -extern int MK_ACCESS_TL_ID0; -extern int MK_ACCESS_TL_BY; -extern int MK_ACCESS_TL_RECP1; -extern int MK_ACCESS_TL_RECP2; -extern int MK_ACCESS_TL_RECP3; -extern int MK_ACCESS_TL_RPH0; -extern int MK_ACCESS_TL_RPH1; -extern int MK_ACCESS_TL_RPH2; -extern int MK_ACCESS_TL_RPH3; - -#endif - - -#define MAX_NUMBER_OF_COOKIES 300 -#define MAX_COOKIES_PER_SERVER 20 -#define MAX_BYTES_PER_COOKIE 4096 // must be at least 1 -*/ -/* - * Authentication information for servers and proxies is kept - * on separate lists, but both lists consist of net_AuthStruct's. - */ - -HG73943 - -PRIVATE XP_List * net_auth_list = NULL; -PRIVATE XP_List * net_proxy_auth_list = NULL; -/* -PRIVATE Bool cookies_changed = FALSE; -#if defined(CookieManagement) -PRIVATE Bool cookie_permissions_changed = FALSE; -PRIVATE Bool cookie_remember_checked = FALSE; -#endif - -PRIVATE NET_CookieBehaviorEnum net_CookieBehavior = NET_Accept; -PRIVATE Bool net_WarnAboutCookies = FALSE; -PRIVATE char *net_scriptName = (char *)0; -*/ -/* - * Different schemes supported by the client. - * Order means the order of preference between authentication schemes. - * - */ -typedef enum _net_AuthType { - AUTH_INVALID = 0, - AUTH_BASIC = 1 -#ifdef SIMPLE_MD5 - HG72621 -#endif /* SIMPLE_MD5 */ - ,AUTH_FORTEZZA = 3 -} net_AuthType; - - -/* - * This struct describes both Basic authentication stuff, - * for both HTTP servers and proxies. - * - */ -HG10828 - - -typedef struct _net_AuthStruct { - net_AuthType auth_type; - char * path; /* For normal authentication only */ - char * proxy_addr; /* For proxy authentication only */ - char * username; /* Obvious */ - char * password; /* Not too cryptic either */ - char * auth_string; /* Storage for latest Authorization str */ - char * realm; /* For all auth schemes */ -#ifdef SIMPLE_MD5 - HG82727 -#endif - char * challenge; - HG26250 - char * signature; - char * clientRan; - PRBool oldChallenge; - int oldChallenge_retries; -} net_AuthStruct; - - - -/*----------------- Normal client-server authentication ------------------ */ - -PRIVATE net_AuthStruct * -net_CheckForAuthorization(char * address, Bool exact_match) -{ - - char *atSign, *fSlash, *afterProto, *newAddress=NULL; - char tmp; - XP_List * list_ptr = net_auth_list; - net_AuthStruct * auth_s; - - TRACEMSG(("net_CheckForAuthorization: checking for auth on: %s", address)); - - /* Auth struct->path doesn't contain username/password info (such as - * http://uname:pwd@host.com, so make sure we don't compare an address - * passed in with one with an auth struct->path until we remove/reduce the - * address passed in. */ - if( (afterProto=PL_strstr(address, "://")) != 0 ) { - afterProto=afterProto+3; - tmp=*afterProto; - *afterProto='\0'; - StrAllocCopy(newAddress, address); - *afterProto=tmp; - - /* temporarily truncate after first slash, if any. */ - if( (fSlash=PL_strchr(afterProto, '/')) != 0) - *fSlash='\0'; - atSign=PL_strchr(afterProto, '@'); - if(fSlash) - *fSlash='/'; - if(atSign) - StrAllocCat(newAddress, atSign+1); - else - StrAllocCat(newAddress, afterProto); - } - - while((auth_s = (net_AuthStruct *) XP_ListNextObject(list_ptr))!=0) - { - XP_ASSERT(newAddress); - if(!newAddress) - return NULL; - - if(exact_match) - { - if(!PL_strcmp(address, auth_s->path)) { - XP_FREE(newAddress); - return(auth_s); - } - } - else - { - /* shorter strings always come last so there can be no - * ambiquity - */ - if(!PL_strncasecmp(address, auth_s->path, PL_strlen(auth_s->path))) { - XP_FREE(newAddress); - return(auth_s); - } - } - } - XP_FREE(newAddress); - HG25262 - - return(NULL); -} - -/* returns TRUE if authorization is required - */ -PUBLIC Bool -NET_AuthorizationRequired(char * address) -{ - net_AuthStruct * rv; - char * last_slash = PL_strrchr(address, '/'); - - if(last_slash) - *last_slash = '\0'; - - rv = net_CheckForAuthorization(address, FALSE); - - HG17993 - if(last_slash) - *last_slash = '/'; - - if(!rv) - return(FALSE); - else - return(TRUE); -} - -/* returns a authorization string if one is required, otherwise - * returns NULL - */ -PUBLIC char * -NET_BuildAuthString(MWContext * context, URL_Struct *URL_s) -{ - char * address = URL_s->address; - net_AuthStruct * auth_s = net_CheckForAuthorization(address, FALSE); - - if(!auth_s) -#if defined(XP_WIN) && defined(MOZILLA_CLIENT) - return(WFE_BuildCompuserveAuthString(URL_s)); -#else - return(NULL); -#endif - else - { - static char * auth_header = 0; - - if(auth_header) - PR_Free(auth_header); - auth_header = PR_smprintf("Authorization: Basic %s"CRLF, auth_s->auth_string); - return(auth_header); - } -} - -PRIVATE net_AuthStruct * -net_ScanForHostnameRealmMatch(char * address, char * realm) -{ - char * proto_host = NET_ParseURL(address, GET_HOST_PART | GET_PROTOCOL_PART); - XP_List * list_ptr = net_auth_list; - net_AuthStruct * auth_s; - - while((auth_s = (net_AuthStruct *) XP_ListNextObject(list_ptr))!=0) - { - /* shorter strings always come last so there can be no - * ambiquity - */ - if(!PL_strncasecmp(proto_host, auth_s->path, PL_strlen(proto_host)) - && !PL_strcasecmp(realm, auth_s->realm)) - { - PR_Free(proto_host); - return(auth_s); - } - } - PR_Free(proto_host); - return(NULL); -} - -PRIVATE void -net_free_auth_struct(net_AuthStruct *auth) -{ - PR_Free(auth->path); - PR_Free(auth->proxy_addr); - PR_Free(auth->username); - PR_Free(auth->password); - PR_Free(auth->auth_string); - PR_Free(auth->realm); - /*FORTEZZA related stuff */ - PR_FREEIF(auth->challenge); - HG26763 - PR_FREEIF(auth->signature); - PR_FREEIF(auth->clientRan); - /*End FORTEZZA related stuff*/ - PR_Free(auth); -} - -/* blows away all authorization structs currently in the list, and the list itself. - * frees and nulls the list pointer itself (net_auth_list) - */ -PUBLIC void -NET_RemoveAllAuthorizations() -{ - net_AuthStruct * victim; - if(XP_ListIsEmpty(net_auth_list)) /* XP_ListIsEmpty handles null list */ - return; - - while((victim = (net_AuthStruct *) XP_ListNextObject(net_auth_list)) != 0) - net_free_auth_struct(victim); - XP_ListDestroy(net_auth_list); - net_auth_list = NULL; -} - -PRIVATE void -net_remove_exact_auth_match_on_cancel(net_AuthStruct *prev_auth, char *cur_path) -{ - if(!prev_auth || !cur_path) - return; - - if(!PL_strcmp(prev_auth->path, cur_path)) - { - /* if the paths are exact and the user cancels - * remove the mapping - */ - XP_ListRemoveObject(net_auth_list, prev_auth); - net_free_auth_struct(prev_auth); - } -} - -#define HTTP_PW_MODULE_NAME "http_pw" -#define HTTP_PW_NAME_TOKEN "name" -#define HTTP_PW_PASSWORD_TOKEN "pass" - -PRIVATE char * -gen_http_key(char *address, char *realm) -{ - char *rv=NULL; - - StrAllocCopy(rv, address); - StrAllocCat(rv, "\t"); - StrAllocCat(rv, realm); - - return rv; -} - -PRIVATE void -separate_http_key(char *key, char **address, char **realm) -{ - char *tab; - - HG72294 - - *address = NULL; - *realm = NULL; - - if(!key) - return; - - tab = PL_strchr(key, '\t'); - - if(!tab) - return; - - *address = key; - *realm = tab+1; -} - -PRIVATE void -net_store_http_password(char *address, char *realm, char *username, char *password) -{ - char *key; - PCNameValueArray *array = PC_NewNameValueArray(); - - if(!array) - return; - - PC_AddToNameValueArray(array, HTTP_PW_NAME_TOKEN, username); - PC_AddToNameValueArray(array, HTTP_PW_PASSWORD_TOKEN, password); - - key = gen_http_key(address, realm); - - if(!key) - return; - - PC_StorePasswordNameValueArray(HTTP_PW_MODULE_NAME, key, array); - - PR_Free(key); - -} - -PRIVATE void -net_remove_stored_http_password(char *url) -{ - PC_DeleteStoredPassword(HTTP_PW_MODULE_NAME, url); -} - -MODULE_PRIVATE void -net_http_password_data_interp( - char *module, - char *key, - char *data, int32 data_len, - char *type_buffer, int32 type_buffer_size, - char *url_buffer, int32 url_buffer_size, - char *username_buffer, int32 username_buffer_size, - char *password_buffer, int32 password_buffer_size) -{ - PCNameValueArray * array; - char *username, *password; - char *address, *realm; - - array = PC_CharToNameValueArray(data, data_len); - - if(!array) - return; - - username = PC_FindInNameValueArray(array, HTTP_PW_NAME_TOKEN); - password = PC_FindInNameValueArray(array, HTTP_PW_PASSWORD_TOKEN); - - PL_strncpyz(type_buffer, "HTTP basic authorization", type_buffer_size); - - separate_http_key(key, &address, &realm); - - if(address) - { - PL_strncpyz(url_buffer, address, url_buffer_size); - } - - if(username) - { - PL_strncpyz(username_buffer, username, username_buffer_size); - PR_Free(username); - } - - if(password) - { - PL_strncpyz(password_buffer, password, password_buffer_size); - PR_Free(password); - } -} - -PRIVATE void -net_initialize_http_access(void) -{ - /* register PW cache interp function */ - - PC_RegisterDataInterpretFunc(HTTP_PW_MODULE_NAME, - net_http_password_data_interp); - HG21522 -} - -/* forward declaration */ -PUBLIC XP_Bool -stub_PromptUsernameAndPassword(MWContext *context, - const char *msg, - char **username, - char **password, - void *closure); - -/* returns false if the user wishes to cancel authorization - * and TRUE if the user wants to continue with a new authorization - * string - */ -/* HARDTS: I took a whack at fixing up some of the strings leaked in this - * function. All the PR_FREEIF()s are new. - */ -PUBLIC Bool -NET_AskForAuthString(MWContext *context, - URL_Struct * URL_s, - char * authenticate, - char * prot_template, - Bool already_sent_auth, - void *closure) -{ - static PRBool first_time=TRUE; - net_AuthStruct *prev_auth; - char *address=URL_s->address; - char *host=NET_ParseURL(address, GET_HOST_PART); - char *new_address=NULL; - char *username=NULL,*colon=NULL,*password=NULL,*unamePwd=NULL; - char *u_pass_string=NULL; - char *auth_string=NULL; - char *realm; - char *slash; - char *authenticate_header_value; - char *buf=NULL; - int32 len=0; - int status; - PRBool re_authorize=FALSE; - - TRACEMSG(("Entering NET_AskForAuthString")); - - if(first_time) - { - net_initialize_http_access(); - first_time = FALSE; - } - - if(authenticate) - { - /* check for the compuserve Remote-Passphrase type of - * authentication - */ - authenticate_header_value = XP_StripLine(authenticate); - HG03937 - -#define COMPUSERVE_HEADER_NAME "Remote-Passphrase" - - if(!PL_strncasecmp(authenticate_header_value, - COMPUSERVE_HEADER_NAME, - sizeof(COMPUSERVE_HEADER_NAME) - 1)) - { - /* This is a compuserv style header - */ - - PR_FREEIF(host); -#if defined(XP_WIN) && defined(MOZILLA_CLIENT) - return(WFE_DoCompuserveAuthenticate(context, URL_s, authenticate_header_value)); -#else - return(NET_AUTH_FAILED_DISPLAY_DOCUMENT); -#endif - } -#define HTTP_BASIC_AUTH_TOKEN "BASIC" - else if(PL_strncasecmp(authenticate_header_value, - HTTP_BASIC_AUTH_TOKEN, - sizeof(HTTP_BASIC_AUTH_TOKEN) - 1)) - { - HG21632 - /* unsupported auth type */ - return(NET_AUTH_FAILED_DISPLAY_DOCUMENT); - } - } - - new_address = NET_ParseURL(address, GET_PROTOCOL_PART | GET_HOST_PART | GET_PATH_PART); - if(!new_address) { - PR_FREEIF(host); - return NET_AUTH_FAILED_DISPLAY_DOCUMENT; - } - - /* get the username and password from the URL struct */ - if( URL_s->password && *URL_s->password ) { - password = PL_strdup(URL_s->password); - } - - if( URL_s->username && *URL_s->username ) { - username = PL_strdup(URL_s->username); - } else { - /* See if username and password are still in the address */ - unamePwd=NET_ParseURL(address, GET_USERNAME_PART | GET_PASSWORD_PART); - /* get the username & password out of the combo string */ - if( (colon = PL_strchr(unamePwd, ':')) != NULL ) { - *colon='\0'; - username=PL_strdup(unamePwd); - /* Use password we found above? */ - if( password == NULL ) { - password=PL_strdup(colon+1); - } - - *colon=':'; - PR_Free(unamePwd); - } else { - username=unamePwd; - } - } - - - /*if last char is not a slash then */ - if (new_address[PL_strlen(new_address)-1] != '/') - { - /* remove everything after the last slash */ - slash = PL_strrchr(new_address, '/'); - if(++slash) - *slash = '\0'; - } - - if(!authenticate) - { - realm = "unknown"; - } - else - { - realm = PL_strchr(authenticate, '"'); - - if(realm) - { - realm++; - - /* terminate at next quote */ - strtok(realm, "\""); - -#define MAX_REALM_SIZE 128 - if(PL_strlen(realm) > MAX_REALM_SIZE) - realm[MAX_REALM_SIZE] = '\0'; - - } - else - { - realm = "unknown"; - } - - } - - /* no hostname/realm match search for exact match */ - prev_auth = net_CheckForAuthorization(new_address, FALSE); - - if(prev_auth && !already_sent_auth) - { - /* somehow the mapping changed since the time we sent - * the authorization. - * This happens sometimes because of the parrallel - * nature of the requests. - * In this case we want to just retry the connection - * since it will probably succede now. - */ - HG22220 - PR_FREEIF(host); - PR_FREEIF(new_address); - PR_FREEIF(username); - PR_FREEIF(password); - return(NET_RETRY_WITH_AUTH); - } - else if(prev_auth) - { - /* we sent the authorization string and it was wrong - */ - if(!FE_Confirm(context, XP_GetString(XP_CONFIRM_AUTHORIZATION_FAIL))) - { - TRACEMSG(("User canceled login!!!")); - - if(!PL_strcmp(prev_auth->path, new_address)) - { - /* if the paths are exact and the user cancels - * remove the mapping - */ - net_remove_exact_auth_match_on_cancel(prev_auth, new_address); - PR_FREEIF(host); - PR_FREEIF(new_address); - PR_FREEIF(username); - PR_FREEIF(password); - return(NET_AUTH_FAILED_DISPLAY_DOCUMENT); - } - } - - if (!username) - username = PL_strdup(prev_auth->username); - if (!password) - password = PL_strdup(prev_auth->password); - re_authorize = TRUE; - } - else - { - char *ptr1, *ptr2; - - /* scan all the authorization strings to see if we - * can find a hostname and realm match. If we find - * a match then reduce the authorization path to include - * the current path as well. - */ - prev_auth = net_ScanForHostnameRealmMatch(address, realm); - - if(prev_auth) - { - char *tmp; - int skipProtoHost; - - net_remove_stored_http_password(prev_auth->path); - - tmp = NET_ParseURL(prev_auth->path, GET_HOST_PART | GET_PROTOCOL_PART); - skipProtoHost = PL_strlen(tmp); - PR_ASSERT(!PL_strncasecmp( - tmp, - NET_ParseURL(new_address, GET_HOST_PART | GET_PROTOCOL_PART), - skipProtoHost)); - PR_Free(tmp); - - /* compare the two url paths until they deviate - * once they deviate truncate. - * skip ptr1, ptr2 past the host names - * which we have already compared - */ - for(ptr1 = prev_auth->path + skipProtoHost, ptr2 = new_address + skipProtoHost; *ptr1 && *ptr2; ptr1++, ptr2++) - { - if(*ptr1 != *ptr2) - { - break; /* end for */ - } - } - /* truncate at *ptr1 now since the new address may - * be just a subpath of the original address and - * the compare above will not handle the subpath correctly - */ - *ptr1 = '\0'; /* truncate */ - - if(*(ptr1-1) == '/') - *(ptr1-1) = '\0'; /* strip a trailing slash */ - - /* make sure a path always has at least a slash - * at the end. - * If the slash isn't there then - * the password will be sent to ports on the - * same host since we use a first part match - */ - tmp = NET_ParseURL(prev_auth->path, GET_PATH_PART); - if(!*tmp) - StrAllocCat(prev_auth->path, "/"); - PR_Free(tmp); - - TRACEMSG(("Truncated new auth path to be: %s", prev_auth->path)); - - net_store_http_password(prev_auth->path, prev_auth->realm, prev_auth->username, prev_auth->password); - - PR_Free(host); - PR_Free(new_address); - return(NET_RETRY_WITH_AUTH); - } - } - - /* Use username and/or password specified in URL_struct if exists. */ - if (!username && URL_s->username && *URL_s->username) { - username = PL_strdup(URL_s->username); - } - if (!password && URL_s->password && *URL_s->password) { - password = PL_strdup(URL_s->password); - } - - if(!username && !password) - { - /* look for a previously stored password in the pw cache */ - PCNameValueArray *array; - - array = PC_CheckForStoredPasswordArray(HTTP_PW_MODULE_NAME, URL_s->address); - - if(array) - { - username = PC_FindInNameValueArray(array, HTTP_PW_NAME_TOKEN); - password = PC_FindInNameValueArray(array, HTTP_PW_PASSWORD_TOKEN); - - if(!username) - { - PR_FREEIF(password); - password = NULL; - } - } - } - - /* if the password is filled in then the username must - * be filled in already. - */ - /* 4/6/99 -- with the new async dialogs, we will only enter this - statement the first time through; afterward, we will have the - user and pass via NET_ResumeWithAuth() - */ - if(!password || re_authorize) - { - XP_Bool remember_password = FALSE; - char *loginString=XP_GetString(XP_ACCESS_ENTER_USERNAME); - host = NET_ParseURL(address, GET_HOST_PART); - - /* malloc memory here to prevent buffer overflow */ - len = XP_STRLEN(loginString) + XP_STRLEN(realm) + XP_STRLEN(host) + 10; - buf = (char *)PR_Malloc(len*sizeof(char)); - - if(buf) { - PR_snprintf( buf, len*sizeof(char), loginString, realm, host); - - - NET_Progress(context, XP_GetString( XP_CONNECT_PLEASE_ENTER_PASSWORD_FOR_HOST) ); -#if 0 -#if defined(SingleSignon) - /* prefill prompt with previous username/passwords if any - * this returns 1 if user pressed OK, or 0 if they Canceled - */ - status = SI_PromptUsernameAndPassword - (context, buf, &username, &password, URL_s->address); - - /* Tell the Editor the correct username */ - if( status > 0 ) { - EDT_SavePublishUsername(context, address, username); - } -#else - status = PC_PromptUsernameAndPassword - (context, buf, &username, &password, - &remember_password, NET_IsURLSecure(URL_s->address)); -#endif -#else - { - NET_AuthClosure * authclosure = (NET_AuthClosure *) closure; - - /* the new multi-threaded case -- we return asynchronously */ - authclosure->msg = PL_strdup (buf); - status = stub_PromptUsernameAndPassword - (context, buf, &username, &password, closure); - } -#endif - - PR_Free(buf); - } else { - status = 0; - } - - PR_Free(host); - - if(!status) { - /* XXX now we have FALSE == WAIT_FOR_AUTH */ - return(NET_WAIT_FOR_AUTH); - -#ifdef notused /* with async dialogs, we never have a user/pass here */ - TRACEMSG(("User canceled login!!!")); - - /* if the paths are exact and the user cancels - * remove the mapping - */ - net_remove_exact_auth_match_on_cancel(prev_auth, new_address); - - PR_FREEIF(username); - PR_FREEIF(password); - PR_FREEIF(new_address); - return(NET_AUTH_FAILED_DISPLAY_DOCUMENT); -#endif /* notused */ - } - else if(!username || !password) - { - PR_FREEIF(username); - PR_FREEIF(password); - PR_FREEIF(new_address); - return(NET_AUTH_FAILED_DISPLAY_DOCUMENT); - } - else if(remember_password) - { - net_store_http_password(URL_s->address, realm, username, password); - } - } - - StrAllocCopy(u_pass_string, username); - StrAllocCat(u_pass_string, ":"); - StrAllocCat(u_pass_string, password); - - len = PL_strlen(u_pass_string); - auth_string = (char*) PR_Malloc((((len+1)*4)/3)+10); - - if(!auth_string) - { - PR_FREEIF(username); - PR_FREEIF(password); - PR_FREEIF(u_pass_string); - PR_Free(new_address); - return(NET_RETRY_WITH_AUTH); - } - - HG38932 - NET_UUEncode((unsigned char *)u_pass_string, (unsigned char*) auth_string, len); - - PR_Free(u_pass_string); - - if(prev_auth) - { - PR_FREEIF(prev_auth->auth_string); - prev_auth->auth_string = auth_string; - PR_FREEIF(prev_auth->username); - prev_auth->username = username; - PR_FREEIF(prev_auth->password); - prev_auth->password = password; - } - else - { - char *atSign, *host, *fSlash; - XP_List * list_ptr = net_auth_list; - net_AuthStruct * tmp_auth_ptr; - size_t new_len; - - /* construct a new auth_struct - */ - prev_auth = PR_NEWZAP(net_AuthStruct); - if(!prev_auth) - { - PR_FREEIF(auth_string); - PR_FREEIF(username); - PR_FREEIF(password); - PR_Free(new_address); - return(NET_RETRY_WITH_AUTH); - } - - prev_auth->auth_string = auth_string; - prev_auth->username = username; - prev_auth->password = password; - prev_auth->path = 0; - /* Don't save username/password info in the auth struct path. */ - if( (atSign=PL_strchr(new_address, '@')) != 0) { - if( (host=PL_strstr(new_address, "://")) != 0) { - char tmp; - host+=3; - tmp=*host; - *host='\0'; - StrAllocCopy(prev_auth->path, new_address); - *host=tmp; - - fSlash=PL_strchr(host, '/'); - if(fSlash) - *fSlash='\0'; - /* Do the atSign check again so we're sure to get one between the - * protocol part and the first slash. */ - atSign=PL_strchr(host, '@'); - if(fSlash) - *fSlash='/'; - - if(atSign) { - StrAllocCat(prev_auth->path, atSign+1); - } else { - StrAllocCat(prev_auth->path, host); - } - } - } else { - StrAllocCopy(prev_auth->path, new_address); - } - - prev_auth->realm = 0; - StrAllocCopy(prev_auth->realm, realm); - - if(!net_auth_list) - { - net_auth_list = XP_ListNew(); - if(!net_auth_list) - { - /* Maybe should free prev_auth here. */ - PR_Free(new_address); - return(NET_RETRY_WITH_AUTH); - } - } - - /* add it to the list so that it is before any strings of - * smaller length - */ - new_len = PL_strlen(prev_auth->path); - while((tmp_auth_ptr = (net_AuthStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(new_len > PL_strlen(tmp_auth_ptr->path)) - { - XP_ListInsertObject(net_auth_list, tmp_auth_ptr, prev_auth); - PR_Free(new_address); - return(NET_RETRY_WITH_AUTH); - } - } - /* no shorter strings found in list */ - XP_ListAddObjectToEnd(net_auth_list, prev_auth); - } - - PR_Free(new_address); - return(NET_RETRY_WITH_AUTH); -} - -/*-------------------------------------------------- - * The following routines support the - * Set-Cookie: / Cookie: headers - */ -/* -PRIVATE XP_List * net_cookie_list=0; -#if defined(CookieManagement) -PRIVATE XP_List * net_cookie_permission_list=0; -PRIVATE XP_List * net_defer_cookie_list=0; -#endif - -typedef struct _net_CookieStruct { - char * path; - char * host; - char * name; - char * cookie; - time_t expires; - time_t last_accessed; - HG26237 - Bool is_domain; // is it a domain instead of an absolute host? -} net_CookieStruct; -*/ - -/* -#if defined(CookieManagement) -typedef struct _net_CookiePermissionStruct { - char * host; - Bool permission; -#ifdef TRUST_LABELS - XP_List * TrustList; // a list of trust label entries -#endif -} net_CookiePermissionStruct; -*/ -/* -typedef struct _net_DeferCookieStruct { - MWContext * context; - char * cur_url; - char * set_cookie_header; - time_t timeToExpire; -} net_DeferCookieStruct; -*/ -/* -#ifdef TRUST_LABELS -void ParseTrustLabelInfo - (char *Buf, net_CookiePermissionStruct * cookie_permission); -void SaveTrustLabelData - ( net_CookiePermissionStruct * cookie_permission, XP_File fp ); -void DeleteCookieFromPermissions( char *CookieHost, char *CookieName ); -void AddTrustLabelInfo( char *CookieName, TrustLabel *trustlabel ); - -typedef struct { - char * CookieName; - int purpose; // the purpose rating has a series of bits set - int recipient; // the recipient value - Bool bIdentifiable; // true if the related cookie puts to identifiable information - char * by; // the by field from the trust label - char * CookieSet; // when the cookie was set into cookies.txt -} TrustEntry; -#endif - -#endif -*/ -/* Routines and data to protect the cookie list so it -** can be accessed by mulitple threads -*/ -/* -#include "prthread.h" -#include "prmon.h" - -static PRMonitor * cookie_lock_monitor = NULL; -static PRThread * cookie_lock_owner = NULL; -static int cookie_lock_count = 0; - -PRIVATE void -net_lock_cookie_list(void) -{ - if(!cookie_lock_monitor) - cookie_lock_monitor = PR_NewNamedMonitor("cookie-lock"); - - PR_EnterMonitor(cookie_lock_monitor); - - while(TRUE) { - - // no current owner or owned by this thread - PRThread * t = PR_CurrentThread(); - if(cookie_lock_owner == NULL || cookie_lock_owner == t) { - cookie_lock_owner = t; - cookie_lock_count++; - - PR_ExitMonitor(cookie_lock_monitor); - return; - } - - // owned by someone else -- wait till we can get it - PR_Wait(cookie_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} -*/ - -/* -PRIVATE void -net_unlock_cookie_list(void) -{ - PR_EnterMonitor(cookie_lock_monitor); - -#ifdef DEBUG - // make sure someone doesn't try to free a lock they don't own - PR_ASSERT(cookie_lock_owner == PR_CurrentThread()); -#endif - - cookie_lock_count--; - - if(cookie_lock_count == 0) { - cookie_lock_owner = NULL; - PR_Notify(cookie_lock_monitor); - } - PR_ExitMonitor(cookie_lock_monitor); - -} -*/ - -/* -#if defined(CookieManagement) -static PRMonitor * defer_cookie_lock_monitor = NULL; -static PRThread * defer_cookie_lock_owner = NULL; -static int defer_cookie_lock_count = 0; - -PRIVATE void -net_lock_defer_cookie_list(void) -{ - if(!defer_cookie_lock_monitor) - defer_cookie_lock_monitor = - PR_NewNamedMonitor("defer_cookie-lock"); - - PR_EnterMonitor(defer_cookie_lock_monitor); - - while(TRUE) { - - // no current owner or owned by this thread - PRThread * t = PR_CurrentThread(); - if(defer_cookie_lock_owner == NULL || defer_cookie_lock_owner == t) { - defer_cookie_lock_owner = t; - defer_cookie_lock_count++; - - PR_ExitMonitor(defer_cookie_lock_monitor); - return; - } - - // owned by someone else -- wait till we can get it - PR_Wait(defer_cookie_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} -*/ -/* -PRIVATE void -net_unlock_defer_cookie_list(void) -{ - PR_EnterMonitor(defer_cookie_lock_monitor); - -#ifdef DEBUG - // make sure someone doesn't try to free a lock they don't own - PR_ASSERT(defer_cookie_lock_owner == PR_CurrentThread()); -#endif - - defer_cookie_lock_count--; - - if(defer_cookie_lock_count == 0) { - defer_cookie_lock_owner = NULL; - PR_Notify(defer_cookie_lock_monitor); - } - PR_ExitMonitor(defer_cookie_lock_monitor); - -} -*/ - -/* -static PRMonitor * cookie_permission_lock_monitor = NULL; -static PRThread * cookie_permission_lock_owner = NULL; -static int cookie_permission_lock_count = 0; - -PRIVATE void -net_lock_cookie_permission_list(void) -{ - if(!cookie_permission_lock_monitor) - cookie_permission_lock_monitor = - PR_NewNamedMonitor("cookie_permission-lock"); - - PR_EnterMonitor(cookie_permission_lock_monitor); - - while(TRUE) { - - // no current owner or owned by this thread - PRThread * t = PR_CurrentThread(); - if(cookie_permission_lock_owner == NULL || cookie_permission_lock_owner == t) { - cookie_permission_lock_owner = t; - cookie_permission_lock_count++; - - PR_ExitMonitor(cookie_permission_lock_monitor); - return; - } - - // owned by someone else -- wait till we can get it - PR_Wait(cookie_permission_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} -*/ - -/* -PRIVATE void -net_unlock_cookie_permission_list(void) -{ - PR_EnterMonitor(cookie_permission_lock_monitor); - -#ifdef DEBUG - // make sure someone doesn't try to free a lock they don't own - PR_ASSERT(cookie_permission_lock_owner == PR_CurrentThread()); -#endif - - cookie_permission_lock_count--; - - if(cookie_permission_lock_count == 0) { - cookie_permission_lock_owner = NULL; - PR_Notify(cookie_permission_lock_monitor); - } - PR_ExitMonitor(cookie_permission_lock_monitor); - -} -*/ - -/* -PRIVATE int -net_SaveCookiePermissions(char * filename); - -PRIVATE void -net_FreeCookiePermission - (net_CookiePermissionStruct * cookie_permission, Bool save) -{ - - // This routine should only be called while holding the - // cookie permission list lock - - - if(!cookie_permission) { - return; - } - XP_ListRemoveObject(net_cookie_permission_list, cookie_permission); - PR_FREEIF(cookie_permission->host); - -#ifdef TRUST_LABELS - // free the entries on the trust list - if ( cookie_permission->TrustList ) { - TrustEntry * TEntry; - XP_List *Tptr = cookie_permission->TrustList; - while( (TEntry = (TrustEntry *)XP_ListNextObject( Tptr )) ) { - PR_FREEIF(TEntry->CookieName); - PR_FREEIF(TEntry->by); - PR_FREEIF(TEntry->CookieSet); - // before removing the current entry get the ptr to the next one - Tptr = Tptr->prev; - XP_ListRemoveObject(cookie_permission->TrustList, TEntry); - } - XP_ListDestroy(cookie_permission->TrustList); - } -#endif - - PR_Free(cookie_permission); - if (save) { - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(NULL); - } -} -*/ -/* blows away all cookie permissions currently in the list */ -/* -PRIVATE void -net_RemoveAllCookiePermissions() -{ - net_CookiePermissionStruct * victim; - XP_List * cookiePermissionList; - - // check for NULL or empty list - net_lock_cookie_permission_list(); - cookiePermissionList = net_cookie_permission_list; - - if(XP_ListIsEmpty(cookiePermissionList)) { - net_unlock_cookie_permission_list(); - return; - } - while((victim = - (net_CookiePermissionStruct *) - XP_ListNextObject(cookiePermissionList)) != 0) { - net_FreeCookiePermission(victim, FALSE); - cookiePermissionList = net_cookie_permission_list; - } - XP_ListDestroy(net_cookie_permission_list); - net_cookie_permission_list = NULL; - net_unlock_cookie_permission_list(); -} -#endif -*/ - -/* This should only get called while holding the cookie-lock -** -*/ -/* -PRIVATE void -net_FreeCookie(net_CookieStruct * cookie) -{ - - if(!cookie) - return; -#ifdef TRUST_LABELS - // delete the reference to the cookie in the cookie permission list - //which contains the trust label for the cookie - - DeleteCookieFromPermissions(cookie->host, cookie->name ); -#endif - XP_ListRemoveObject(net_cookie_list, cookie); - - PR_FREEIF(cookie->path); - PR_FREEIF(cookie->host); - PR_FREEIF(cookie->name); - PR_FREEIF(cookie->cookie); - - PR_Free(cookie); - - cookies_changed = TRUE; -} -*/ -/* -PUBLIC void -NET_DeleteCookie(char* cookieURL) -{ - net_CookieStruct * cookie; - XP_List * list_ptr; - char * cookieURL2 = 0; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - while((cookie = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - StrAllocCopy(cookieURL2, "cookie:"); - StrAllocCat(cookieURL2, cookie->host); - StrAllocCat(cookieURL2, "!"); - StrAllocCat(cookieURL2, cookie->path); - StrAllocCat(cookieURL2, "!"); - StrAllocCat(cookieURL2, cookie->name); - if (PL_strcmp(cookieURL, cookieURL2)==0) { - net_FreeCookie(cookie); - break; - } - } - PR_FREEIF(cookieURL2); - net_unlock_cookie_list(); -} -*/ - -/* blows away all cookies currently in the list, then blows away the list itself - * nulling it after it's free'd - */ -/* -PRIVATE void -net_RemoveAllCookies() -{ - net_CookieStruct * victim; - XP_List * cookieList; - - // check for NULL or empty list - net_lock_cookie_list(); - cookieList = net_cookie_list; - if(XP_ListIsEmpty(cookieList)) { - net_unlock_cookie_list(); - return; - } - - while((victim = (net_CookieStruct *) XP_ListNextObject(cookieList)) != 0) { - net_FreeCookie(victim); - cookieList=net_cookie_list; - } - XP_ListDestroy(net_cookie_list); - net_cookie_list = NULL; - net_unlock_cookie_list(); -} -*/ - -/* -PUBLIC void -NET_RemoveAllCookies() -{ - -#if defined(CookieManagement) - net_RemoveAllCookiePermissions(); -#endif - net_RemoveAllCookies(); -} - -PRIVATE void -net_remove_oldest_cookie(void) -{ - XP_List * list_ptr; - net_CookieStruct * cookie_s; - net_CookieStruct * oldest_cookie; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - - if(XP_ListIsEmpty(list_ptr)) { - net_unlock_cookie_list(); - return; - } - - oldest_cookie = (net_CookieStruct*) list_ptr->next->object; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(cookie_s->last_accessed < oldest_cookie->last_accessed) - oldest_cookie = cookie_s; - } - - if(oldest_cookie) - { - TRACEMSG(("Freeing cookie because global max cookies has been exceeded")); - net_FreeCookie(oldest_cookie); - } - net_unlock_cookie_list(); -} -*/ - -/* Remove any expired cookies from memory -** This routine should only be called while holding the cookie list lock -*/ -/* -PRIVATE void -net_remove_expired_cookies(void) -{ - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * cookie_s; - time_t cur_time = time(NULL); - - if(XP_ListIsEmpty(list_ptr)) - return; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - // Don't get rid of expire time 0 because these need to last for - // the entire session. They'll get cleared on exit. - // - if( cookie_s->expires && (cookie_s->expires < cur_time) ) { - net_FreeCookie(cookie_s); - // Reset the list_ptr to the beginning of the list. - // Do this because list_ptr's object was just freed - // by the call to net_FreeCookie struct, even - // though it's inefficient. - - list_ptr = net_cookie_list; - } - } -} -*/ - -/* -PRIVATE XP_List * net_dormant_cookie_list=0; -Bool net_anonymous = FALSE; - -PUBLIC void -NET_AnonymizeCookies() -{ - if (!net_anonymous) { - net_lock_cookie_list(); - net_dormant_cookie_list = net_cookie_list; - net_cookie_list = XP_ListNew(); - net_unlock_cookie_list(); - net_anonymous = TRUE; - } -} - - - -PUBLIC void -NET_UnanonymizeCookies() -{ - if (net_anonymous) { - net_RemoveAllCookies(); - net_lock_cookie_list(); - net_cookie_list = net_dormant_cookie_list; - net_unlock_cookie_list(); - net_dormant_cookie_list = 0; - net_anonymous = FALSE; - } -} -*/ -/* - * Determine whether or not to suppress the referer field for anonymity. - * The first time this function is called on behalf of a given window - * after a mode change (into or out of anonymous mode), the returned value is - * true. - */ - -PUBLIC Bool -NET_SupressRefererForAnonymity(MWContext *window_id) { - return FALSE; -} - -/* checks to see if the maximum number of cookies per host - * is being exceeded and deletes the oldest one in that - * case - * This routine should only be called while holding the cookie lock - */ -/* -PRIVATE void -net_CheckForMaxCookiesFromHost(const char * cur_host) -{ - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * cookie_s; - net_CookieStruct * oldest_cookie = 0; - int cookie_count = 0; - - if(XP_ListIsEmpty(list_ptr)) - return; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(!PL_strcasecmp(cookie_s->host, cur_host)) - { - cookie_count++; - if(!oldest_cookie - || oldest_cookie->last_accessed > cookie_s->last_accessed) - oldest_cookie = cookie_s; - } - } - - if(cookie_count >= MAX_COOKIES_PER_SERVER && oldest_cookie) - { - TRACEMSG(("Freeing cookie because max cookies per server has been exceeded")); - net_FreeCookie(oldest_cookie); - } -} -*/ - -/* search for previous exact match -** This routine should only be called while holding the cookie lock -*/ -/* -PRIVATE net_CookieStruct * -net_CheckForPrevCookie(char * path, - char * hostname, - char * name) -{ - - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * cookie_s; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - if(path && hostname && cookie_s->path && cookie_s->host && cookie_s->name - && !PL_strcmp(name, cookie_s->name) - && !PL_strcmp(path, cookie_s->path) - && !PL_strcasecmp(hostname, cookie_s->host)) - return(cookie_s); - } - return(NULL); -} -*/ -/* cookie utility functions */ -/* -PRIVATE void -NET_SetCookieBehaviorPref(NET_CookieBehaviorEnum x) -{ - net_CookieBehavior = x; - - HG83330 - if(net_CookieBehavior == NET_DontUse) { - NET_XP_FileRemove("", xpHTTPCookie); -#if defined(CookieManagement) - NET_XP_FileRemove("", xpHTTPCookiePermission); -#endif - } -} -*/ -/* -PRIVATE void -NET_SetCookieWarningPref(Bool x) -{ - net_WarnAboutCookies = x; -} - -PRIVATE void -NET_SetCookieScriptPref(const char *name) -{ - PR_FREEIF(net_scriptName); - if( name && *name ) - net_scriptName=PL_strdup(name); - else - net_scriptName=NULL; -} - -PRIVATE NET_CookieBehaviorEnum -NET_GetCookieBehaviorPref(void) -{ - return net_CookieBehavior; -} - -PRIVATE Bool -NET_GetCookieWarningPref(void) -{ - return net_WarnAboutCookies; -} - -PRIVATE const char * -NET_GetCookieScriptPref(void) -{ - return (const char *)net_scriptName; -} - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieBehaviorPrefChanged(const char * newpref, void * data) -{ - PRInt32 n; - if ( (PREF_OK != PREF_GetIntPref(pref_cookieBehavior, &n)) ) { - n = DEF_COOKIE_BEHAVIOR; - } - NET_SetCookieBehaviorPref((NET_CookieBehaviorEnum)n); - return PREF_NOERROR; -} - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieWarningPrefChanged(const char * newpref, void * data) -{ - PRBool x; - if ( (PREF_OK != PREF_GetBoolPref(pref_warnAboutCookies, &x)) ) { - x = FALSE; - } - NET_SetCookieWarningPref(x); - return PREF_NOERROR; -} - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieScriptPrefChanged(const char * newpref, void * data) -{ - char s[64]; - int len = sizeof(s); - *s='\0'; - PREF_GetCharPref(pref_scriptName, s, &len); - NET_SetCookieScriptPref(s); - return PREF_NOERROR; -} -*/ -/* -#if defined(CookieManagement) - - // search if permission already exists - -PRIVATE net_CookiePermissionStruct * -net_CheckForCookiePermission(char * hostname) { - XP_List * list_ptr; - net_CookiePermissionStruct * cookie_s; - - // ignore leading period in host name - while (hostname && (*hostname == '.')) { - hostname++; - } - - net_lock_cookie_permission_list(); - list_ptr = net_cookie_permission_list; - while((cookie_s = (net_CookiePermissionStruct *) XP_ListNextObject(list_ptr))!=0) { - if(hostname && cookie_s->host - && !PL_strcasecmp(hostname, cookie_s->host)) { - net_unlock_cookie_permission_list(); - return(cookie_s); - } - } - net_unlock_cookie_permission_list(); - return(NULL); -} -*/ - -/* - * return: - * +1 if cookie permission exists for host and indicates host can set cookies - * 0 if cookie permission does not exist for host - * -1 if cookie permission exists for host and indicates host can't set cookies - */ -/* -PUBLIC int -NET_CookiePermission(char* URLName) { - net_CookiePermissionStruct * cookiePermission; - char * host; - char * colon; - - if (!URLName || !(*URLName)) { - return 0; - } - - // remove protocol from URL name - host = NET_ParseURL(URLName, GET_HOST_PART); - - // remove port number from URL name - colon = PL_strchr(host, ':'); - if(colon) { - *colon = '\0'; - } - cookiePermission = net_CheckForCookiePermission(host); - if(colon) { - *colon = ':'; - } - PR_Free(host); - if (cookiePermission == NULL) { - return 0; - } - if (cookiePermission->permission) { - return 1; - } - return -1; -} - -#endif -*/ -/* called from mkgeturl.c, NET_InitNetLib(). This sets the module local cookie pref variables - and registers the callbacks */ -/* -PUBLIC void -NET_RegisterCookiePrefCallbacks(void) -{ - PRInt32 n; - PRBool x; - char s[64]; - int len = sizeof(s); - *s = '\0'; - - if ( (PREF_OK != PREF_GetIntPref(pref_cookieBehavior, &n)) ) { - n = DEF_COOKIE_BEHAVIOR; - } - NET_SetCookieBehaviorPref((NET_CookieBehaviorEnum)n); - PREF_RegisterCallback(pref_cookieBehavior, NET_CookieBehaviorPrefChanged, NULL); - - if ( (PREF_OK != PREF_GetBoolPref(pref_warnAboutCookies, &x)) ) { - x = FALSE; - } - NET_SetCookieWarningPref(x); - PREF_RegisterCallback(pref_warnAboutCookies, NET_CookieWarningPrefChanged, NULL); - - *s='\0'; - PREF_GetCharPref(pref_scriptName, s, &len); - NET_SetCookieScriptPref(s); - PREF_RegisterCallback(pref_scriptName, NET_CookieScriptPrefChanged, NULL); -} -*/ -/* returns TRUE if authorization is required -** -** -** IMPORTANT: Now that this routine is mutli-threaded it is up -** to the caller to free any returned string -*/ -/* -PUBLIC char * -NET_GetCookie(MWContext * context, char * address) -{ - char *name=0; - char *host = NET_ParseURL(address, GET_HOST_PART); - char *path = NET_ParseURL(address, GET_PATH_PART); - XP_List * list_ptr; - net_CookieStruct * cookie_s; - Bool first=TRUE; - HG26748 - time_t cur_time = time(NULL); - int host_length; - int domain_length; - - // return string to build - char * rv=0; - - // disable cookie's if the user's prefs say so - - if(NET_GetCookieBehaviorPref() == NET_DontUse) - return NULL; - - HG98476 - - // search for all cookies - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(!cookie_s->host) - continue; - - // check the host or domain first - - if(cookie_s->is_domain) - { - char *cp; - domain_length = PL_strlen(cookie_s->host); - - // calculate the host length by looking at all characters up to - // a colon or '\0'. That way we won't include port numbers - //in domains - - for(cp=host; *cp != '\0' && *cp != ':'; cp++) - ; // null body - - host_length = cp - host; - if(domain_length > host_length - || PL_strncasecmp(cookie_s->host, - &host[host_length - domain_length], - domain_length)) - { - HG20476 - //no match. FAIL - - continue; - } - - } - else if(PL_strcasecmp(host, cookie_s->host)) - { - //hostname matchup failed. FAIL - - continue; - } - - // shorter strings always come last so there can be no - // ambiquity - - if(cookie_s->path && !PL_strncmp(path, - cookie_s->path, - PL_strlen(cookie_s->path))) - { - - // if the cookie is secure and the path isn't - // dont send it - - HG83764 - - // check for expired cookies - // - if( cookie_s->expires && (cookie_s->expires < cur_time) ) - { - //expire and remove the cookie - - net_FreeCookie(cookie_s); - - // start the list parsing over :( - //we must also start the string over - - PR_FREEIF(rv); - rv = NULL; - list_ptr = net_cookie_list; - first = TRUE; // reset first - continue; - } - - if(first) - first = FALSE; - else - StrAllocCat(rv, "; "); - - if(cookie_s->name && *cookie_s->name != '\0') - { - cookie_s->last_accessed = cur_time; - StrAllocCopy(name, cookie_s->name); - StrAllocCat(name, "="); - -#ifdef PREVENT_DUPLICATE_NAMES - // make sure we don't have a previous - // name mapping already in the string - // - if(!rv || !PL_strstr(rv, name)) - { - StrAllocCat(rv, name); - StrAllocCat(rv, cookie_s->cookie); - } -#else - StrAllocCat(rv, name); - StrAllocCat(rv, cookie_s->cookie); -#endif // PREVENT_DUPLICATE_NAMES - } - else - { - StrAllocCat(rv, cookie_s->cookie); - } - } - } - -#if defined(MOZ_BRPROF) - - // Okay, this is a horrible hack. It looks for a URL with - // 'iiop/BRPROF' in it (our little browsing profile reader), and - //if it finds it, it uploads the browsing profile cookie. - // - // The _real_ way to do this would be to - // - // 1) See if the user has enabled the preference to even allow us - // to send out the cookie to _anyone_. - // - // 2) See if the specific site has asked for and received - // permission to be sent the cookie. - // - if (PL_strstr(address, "iiop/BRPROF")) { - extern PRBool BP_GetProfile(char* *aProfileCookie); - char* profile; - if (BP_GetProfile(&profile)) { - if (! first) - StrAllocCat(rv, "; "); - StrAllocCat(rv, "BP="); - StrAllocCat(rv, profile); - PL_strfree(profile); - } - } -#endif - - net_unlock_cookie_list(); - PR_FREEIF(name); - PR_Free(path); - PR_Free(host); - - // may be NULL - return(rv); -} -*/ -/* -#if defined(CookieManagement) -void -net_AddCookiePermission - (net_CookiePermissionStruct * cookie_permission, Bool save ) { - - // This routine should only be called while holding the - // cookie permission list lock - // - if (cookie_permission) { - XP_List * list_ptr = net_cookie_permission_list; - if(!net_cookie_permission_list) { - net_cookie_permission_list = XP_ListNew(); - if(!net_cookie_permission_list) { - PR_Free(cookie_permission->host); - PR_Free(cookie_permission); - return; - } - list_ptr = net_cookie_permission_list; - } - -#ifdef alphabetize - // add it to the list in alphabetical order - { - net_CookiePermissionStruct * tmp_cookie_permission; - Bool permissionAdded = FALSE; - while((tmp_cookie_permission = (net_CookiePermissionStruct *) - XP_ListNextObject(list_ptr))!=0) { - if (PL_strcasecmp - (cookie_permission->host,tmp_cookie_permission->host)<0) { - XP_ListInsertObject - (net_cookie_permission_list, - tmp_cookie_permission, - cookie_permission); - permissionAdded = TRUE; - break; - } - } - if (!permissionAdded) { - XP_ListAddObjectToEnd - (net_cookie_permission_list, cookie_permission); - } - } -#else - // add it to the end of the list - XP_ListAddObjectToEnd (net_cookie_permission_list, cookie_permission); -#endif - - if (save) { - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(NULL); - } - } -} -*/ - -/* -MODULE_PRIVATE PRBool -net_CookieIsFromHost(net_CookieStruct *cookie_s, char *host) { - if (!cookie_s || !(cookie_s->host)) { - return FALSE; - } - if (cookie_s->is_domain) { - char *cp; - int domain_length, host_length; - - domain_length = PL_strlen(cookie_s->host); - - // calculate the host length by looking at all characters up to - // a colon or '\0'. That way we won't include port numbers - // in domains - // - for(cp=host; *cp != '\0' && *cp != ':'; cp++) { - ; // null body - } - host_length = cp - host; - - // compare the tail end of host to cook_s->host - return (domain_length <= host_length && - PL_strncasecmp(cookie_s->host, - &host[host_length - domain_length], - domain_length) == 0); - } else { - return PL_strcasecmp(host, cookie_s->host) == 0; - } -} -*/ - -/* find out how many cookies this host has already set */ -/* -PRIVATE int -net_CookieCount(char * host) { - int count = 0; - XP_List * list_ptr; - net_CookieStruct * cookie; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - while((cookie = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - if (host && net_CookieIsFromHost(cookie, host)) { - count++; - } - } - net_unlock_cookie_list(); - - return count; -} -*/ -/* -PUBLIC int -NET_CookieCount(char * URLName) { - char * host; - char * colon; - int count = 0; - - if (!URLName || !(*URLName)) { - return 0; - } - - // remove protocol from URL name - host = NET_ParseURL(URLName, GET_HOST_PART); - - // remove port number from URL name - colon = PL_strchr(host, ':'); - if(colon) { - *colon = '\0'; - } - - // get count - count = net_CookieCount(host); - - // free up allocated string and return - if(colon) { - *colon = ':'; - } - PR_Free(host); - return count; -} -*/ -/* -PRBool net_IntSetCookieStringInUse = FALSE; - -PRIVATE void -net_DeferCookie( - MWContext * context, - char * cur_url, - char * set_cookie_header, - time_t timeToExpire) { - net_DeferCookieStruct * defer_cookie = PR_NEW(net_DeferCookieStruct); - defer_cookie->context = context; - defer_cookie->cur_url = NULL; - StrAllocCopy(defer_cookie->cur_url, cur_url); - defer_cookie->set_cookie_header = NULL; - StrAllocCopy(defer_cookie->set_cookie_header, set_cookie_header); - defer_cookie->timeToExpire = timeToExpire; - net_lock_defer_cookie_list(); - if (!net_defer_cookie_list) { - net_defer_cookie_list = XP_ListNew(); - if (!net_cookie_list) { - PR_FREEIF(defer_cookie->cur_url); - PR_FREEIF(defer_cookie->set_cookie_header); - PR_Free(defer_cookie); - } - } - XP_ListAddObject(net_defer_cookie_list, defer_cookie); - net_unlock_defer_cookie_list(); -} -*/ -/* -PRIVATE void -net_IntSetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header, - time_t timeToExpire ); - -PRIVATE void -net_UndeferCookies() { - net_DeferCookieStruct * defer_cookie; - net_lock_defer_cookie_list(); - if(XP_ListIsEmpty(net_defer_cookie_list)) { - net_unlock_defer_cookie_list(); - return; - } - defer_cookie = XP_ListRemoveEndObject(net_defer_cookie_list); - net_unlock_defer_cookie_list(); - net_IntSetCookieString ( - defer_cookie->context, - defer_cookie->cur_url, - defer_cookie->set_cookie_header, - defer_cookie->timeToExpire); - PR_FREEIF(defer_cookie->cur_url); - PR_FREEIF(defer_cookie->set_cookie_header); - PR_Free(defer_cookie); -} -#endif -*/ -/* Java script is calling NET_SetCookieString, netlib is calling -** this via NET_SetCookieStringFromHttp. -*/ -/* -PRIVATE void -net_IntSetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header, - time_t timeToExpire ) -{ - net_CookieStruct * prev_cookie; - char *path_from_header=NULL, *host_from_header=NULL; - char *host_from_header2=NULL; - char *name_from_header=NULL, *cookie_from_header=NULL; - time_t expires=0; - char *cur_path = NET_ParseURL(cur_url, GET_PATH_PART); - char *cur_host = NET_ParseURL(cur_url, GET_HOST_PART); - char *semi_colon, *ptr, *equal; - const char *script_name; - PRBool HG83744 is_domain=FALSE, ask=FALSE, accept=FALSE; - MWContextType type; - Bool bCookieAdded; - - if(!context) { - PR_Free(cur_path); - PR_Free(cur_host); - return; - } - - // Only allow cookies to be set in the listed contexts. We - // don't want cookies being set in html mail. - - type = context->type; - if(!( (type == MWContextBrowser) - || (type == MWContextHTMLHelp) - || (type == MWContextPane) )) { - PR_Free(cur_path); - PR_Free(cur_host); - return; - } - - if(NET_GetCookieBehaviorPref() == NET_DontUse) { - PR_Free(cur_path); - PR_Free(cur_host); - return; - } - -#if defined(CookieManagement) - // Don't enter this routine if it is already in use by another - // thread. Otherwise the "remember this decision" result of the - // other cookie (which came first) won't get applied to this cookie. - - if (net_IntSetCookieStringInUse) { - PR_Free(cur_path); - PR_Free(cur_host); - net_DeferCookie(context, cur_url, set_cookie_header, timeToExpire); - return; - } - net_IntSetCookieStringInUse = TRUE; -#endif - - HG87358 - // terminate at any carriage return or linefeed - for(ptr=set_cookie_header; *ptr; ptr++) - if(*ptr == LF || *ptr == CR) { - *ptr = '\0'; - break; - } - - // parse path and expires attributes from header if - //present - // - semi_colon = PL_strchr(set_cookie_header, ';'); - - if(semi_colon) - { - // truncate at semi-colon and advance - // - *semi_colon++ = '\0'; - - // there must be some attributes. (hopefully) - // - HG83476 - - // look for the path attribute - // - ptr = PL_strcasestr(semi_colon, "path="); - - if(ptr) { - // allocate more than we need - StrAllocCopy(path_from_header, XP_StripLine(ptr+5)); - // terminate at first space or semi-colon - // - for(ptr=path_from_header; *ptr != '\0'; ptr++) - if(NET_IS_SPACE(*ptr) || *ptr == ';' || *ptr == ',') { - *ptr = '\0'; - break; - } - } - - // look for the URI or URL attribute - - // This might be a security hole so I'm removing - // it for now. - - - // look for a domain - ptr = PL_strcasestr(semi_colon, "domain="); - - if(ptr) { - char *domain_from_header=NULL; - char *dot, *colon; - int domain_length, cur_host_length; - - // allocate more than we need - StrAllocCopy(domain_from_header, XP_StripLine(ptr+7)); - - // terminate at first space or semi-colon - // - for(ptr=domain_from_header; *ptr != '\0'; ptr++) - if(NET_IS_SPACE(*ptr) || *ptr == ';' || *ptr == ',') { - *ptr = '\0'; - break; - } - - // verify that this host has the authority to set for - // this domain. We do this by making sure that the - // host is in the domain - // We also require that a domain have at least two - // periods to prevent domains of the form ".com" - // and ".edu" - // - // Also make sure that there is more stuff after - // the second dot to prevent ".com." - - dot = PL_strchr(domain_from_header, '.'); - if(dot) - dot = PL_strchr(dot+1, '.'); - - if(!dot || *(dot+1) == '\0') { - // did not pass two dot test. FAIL - - PR_Free(domain_from_header); - PR_Free(cur_path); - PR_Free(cur_host); - TRACEMSG(("DOMAIN failed two dot test")); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - - // strip port numbers from the current host - // for the domain test - - colon = PL_strchr(cur_host, ':'); - if(colon) - *colon = '\0'; - - domain_length = PL_strlen(domain_from_header); - cur_host_length = PL_strlen(cur_host); - - // check to see if the host is in the domain - // - if(domain_length > cur_host_length - || PL_strcasecmp(domain_from_header, - &cur_host[cur_host_length-domain_length])) - { - TRACEMSG(("DOMAIN failed host within domain test." - " Domain: %s, Host: %s", domain_from_header, cur_host)); - PR_Free(domain_from_header); - PR_Free(cur_path); - PR_Free(cur_host); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - - - // check that portion of host not in domain does not contain a dot - // This satisfies the fourth requirement in section 4.3.2 of the cookie - // spec rfc 2109 (see www.cis.ohio-state.edu/htbin/rfc/rfc2109.html). - // It prevents host of the form x.y.co.nz from setting cookies in the - // entire .co.nz domain. Note that this doesn't really solve the problem, - // it justs makes it more unlikely. Sites such as y.co.nz can still set - // cookies for the entire .co.nz domain. - // - - cur_host[cur_host_length-domain_length] = '\0'; - dot = XP_STRCHR(cur_host, '.'); - cur_host[cur_host_length-domain_length] = '.'; - if (dot) { - TRACEMSG(("host minus domain failed no-dot test." - " Domain: %s, Host: %s", domain_from_header, cur_host)); - PR_Free(domain_from_header); - PR_Free(cur_path); - PR_Free(cur_host); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - - // all tests passed, copy in domain to hostname field - - StrAllocCopy(host_from_header, domain_from_header); - is_domain = TRUE; - - TRACEMSG(("Accepted domain: %s", host_from_header)); - - PR_Free(domain_from_header); - } - - // now search for the expires header - // NOTE: that this part of the parsing - // destroys the original part of the string - // - ptr = PL_strcasestr(semi_colon, "expires="); - - if(ptr) { - char *date = ptr+8; - // terminate the string at the next semi-colon - - for(ptr=date; *ptr != '\0'; ptr++) - if(*ptr == ';') { - *ptr = '\0'; - break; - } - if(timeToExpire) - expires = timeToExpire; - else - expires = NET_ParseDate(date); - - TRACEMSG(("Have expires date: %ld", expires)); - } - } - - if(!path_from_header) { - // strip down everything after the last slash - // to get the path. - - char * slash = PL_strrchr(cur_path, '/'); - if(slash) - *slash = '\0'; - - path_from_header = cur_path; - } else { - PR_Free(cur_path); - } - - if(!host_from_header) - host_from_header = cur_host; - else - PR_Free(cur_host); - - // keep cookies under the max bytes limit - if(PL_strlen(set_cookie_header) > MAX_BYTES_PER_COOKIE) - set_cookie_header[MAX_BYTES_PER_COOKIE-1] = '\0'; - - // separate the name from the cookie - equal = PL_strchr(set_cookie_header, '='); - - if(equal) { - *equal = '\0'; - StrAllocCopy(name_from_header, XP_StripLine(set_cookie_header)); - StrAllocCopy(cookie_from_header, XP_StripLine(equal+1)); - } else { - TRACEMSG(("Warning: no name found for cookie")); - StrAllocCopy(cookie_from_header, XP_StripLine(set_cookie_header)); - StrAllocCopy(name_from_header, ""); - } - - // If there's a script, call it now - script_name = NET_GetCookieScriptPref(); - if( (const char *)0 != script_name ) { - JSCFCookieData *cd; - Bool changed = FALSE; - JSCFResult result; - - cd = PR_NEWZAP(JSCFCookieData); - if( (JSCFCookieData *)0 == cd ) { - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - // FREEIF(cur_path); - // FREEIF(cur_host); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - - cd->path_from_header = path_from_header; - cd->host_from_header = host_from_header; - cd->name_from_header = name_from_header; - cd->cookie_from_header = cookie_from_header; - cd->expires = expires; - cd->url = cur_url; - HG84777 - cd->domain = is_domain; - cd->prompt = NET_GetCookieWarningPref(); - cd->preference = NET_GetCookieBehaviorPref(); - - //This is only safe to do from the mozilla thread - // since it might do file I/O and uses the preferences - // global context + objects. - // - // XXX: This is probably not correct, but it will fix the build for now... - result= JSCF_Execute(context, script_name, cd, &changed); - if( result != JSCF_error) { - if( changed ) { - if( cd->path_from_header != path_from_header ) { - PR_FREEIF(path_from_header); - path_from_header = PL_strdup(cd->path_from_header); - } - if( cd->host_from_header != host_from_header ) { - PR_FREEIF(host_from_header); - host_from_header = PL_strdup(cd->host_from_header); - } - if( cd->name_from_header != name_from_header ) { - PR_FREEIF(name_from_header); - name_from_header = PL_strdup(cd->name_from_header); - } - if( cd->cookie_from_header != cookie_from_header ) { - PR_FREEIF(cookie_from_header); - cookie_from_header = PL_strdup(cd->cookie_from_header); - } - if( cd->expires != expires ) - expires = cd->expires; - if( cd->domain != is_domain ) - //lets hope the luser remembered to change the domain field - is_domain = cd->domain; - HG27398 - } - switch( result ) { - case JSCF_reject: - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - PR_Free(cd); - // FREEIF(cur_path); - // FREEIF(cur_host); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - case JSCF_accept: - accept=TRUE; - case JSCF_error: - case JSCF_ask: - ask=TRUE; - case JSCF_whatever: - break; - } - } - PR_Free(cd); -#if defined(CookieManagement) - } else { - net_CookiePermissionStruct * cookie_permission; - cookie_permission = net_CheckForCookiePermission(host_from_header); - if (cookie_permission != NULL) { - if (cookie_permission->permission == FALSE) { - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } else { - accept = TRUE; - } - } -#endif - } - - - if( (NET_GetCookieWarningPref() || ask) && !accept ) { - // the user wants to know about cookies so let them - // know about every one that is set and give them - //the choice to accept it or not - // - char * new_string=0; -#if defined(CookieManagement) - int count; - char * remember_string = 0; - StrAllocCopy - (remember_string, XP_GetString(MK_ACCESS_COOKIES_REMEMBER)); - - // find out how many cookies this host has already set - count = net_CookieCount(host_from_header); - net_lock_cookie_list(); - prev_cookie = net_CheckForPrevCookie - (path_from_header, host_from_header, name_from_header); - net_unlock_cookie_list(); - if (prev_cookie) { - new_string = PR_smprintf( - XP_GetString(MK_ACCESS_COOKIES_WISHES_MODIFY), - host_from_header ? host_from_header : ""); - } else if (count>1) { - new_string = PR_smprintf( - XP_GetString(MK_ACCESS_COOKIES_WISHESN), - host_from_header ? host_from_header : "", - count); - } else if (count==1){ - new_string = PR_smprintf( - XP_GetString(MK_ACCESS_COOKIES_WISHES1), - host_from_header ? host_from_header : ""); - } else { - new_string = PR_smprintf( - XP_GetString(MK_ACCESS_COOKIES_WISHES0), - host_from_header ? host_from_header : ""); - } -#else - char * tmp_host = NET_ParseURL(cur_url, GET_HOST_PART); - StrAllocCopy(new_string, XP_GetString(MK_ACCESS_COOKIES_THE_SERVER)); - StrAllocCat(new_string, tmp_host ? tmp_host : ""); - StrAllocCat(new_string, XP_GetString(MK_ACCESS_COOKIES_WISHES)); - PR_Free(tmp_host); - - if(is_domain) { - StrAllocCat(new_string, XP_GetString(MK_ACCESS_COOKIES_TOANYSERV)); - StrAllocCat(new_string, host_from_header); - } else { - StrAllocCat(new_string, XP_GetString(MK_ACCESS_COOKIES_TOSELF)); - } - - StrAllocCat(new_string, XP_GetString(MK_ACCESS_COOKIES_NAME_AND_VAL)); - - StrAllocCat(new_string, name_from_header); - StrAllocCat(new_string, "="); - StrAllocCat(new_string, cookie_from_header); - StrAllocCat(new_string, "\n"); - - if(expires) { - StrAllocCat(new_string, XP_GetString(MK_ACCESS_COOKIES_COOKIE_WILL_PERSIST)); - StrAllocCat(new_string, ctime(&expires)); - } - - StrAllocCat(new_string, XP_GetString(MK_ACCESS_COOKIES_SET_IT)); -#endif - - // - // Who knows what thread we are on. Only the mozilla thread - // is allowed to post dialogs so, if need be, go over there - // -#if defined(CookieManagement) - - { - Bool old_cookie_remember_checked = cookie_remember_checked; - XP_Bool userHasAccepted = ET_PostCheckConfirmBox - (context, - new_string, - remember_string, - 0,0, - &cookie_remember_checked); - PR_FREEIF(new_string); - PR_FREEIF(remember_string); - if (cookie_remember_checked) { - net_CookiePermissionStruct * cookie_permission; - cookie_permission = PR_NEW(net_CookiePermissionStruct); - if (cookie_permission) { - net_lock_cookie_permission_list(); - StrAllocCopy(host_from_header2, host_from_header); - //ignore leading periods in host name - while (host_from_header2 && (*host_from_header2 == '.')) { - host_from_header2++; - } - cookie_permission->host = host_from_header2; // set host string - cookie_permission->permission = userHasAccepted; -#ifdef TRUST_LABELS - cookie_permission->TrustList = NULL; -#endif - net_AddCookiePermission(cookie_permission, TRUE); - net_unlock_cookie_permission_list(); - } - } - - if (old_cookie_remember_checked != cookie_remember_checked) { - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(NULL); - } - - - if (!userHasAccepted) { -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - } -#else - if(!ET_PostMessageBox(context, new_string, TRUE)) { - PR_FREEIF(new_string); - return; - } - PR_FREEIF(new_string); -#endif - } - - TRACEMSG(("mkaccess.c: Setting cookie: %s for host: %s for path: %s", - cookie_from_header, host_from_header, path_from_header)); - - // We have decided we are going to insert a cookie into the list - // Get the cookie lock so that we can munge on the list - // - net_lock_cookie_list(); - - // limit the number of cookies from a specific host or domain - net_CheckForMaxCookiesFromHost(host_from_header); - - if(XP_ListCount(net_cookie_list) > MAX_NUMBER_OF_COOKIES-1) - net_remove_oldest_cookie(); - - - prev_cookie = net_CheckForPrevCookie - (path_from_header, host_from_header, name_from_header); - - if(prev_cookie) { - prev_cookie->expires = expires; - PR_FREEIF(prev_cookie->cookie); - PR_FREEIF(prev_cookie->path); - PR_FREEIF(prev_cookie->host); - PR_FREEIF(prev_cookie->name); - prev_cookie->cookie = cookie_from_header; - prev_cookie->path = path_from_header; - prev_cookie->host = host_from_header; - prev_cookie->name = name_from_header; - HG83263 - prev_cookie->is_domain = is_domain; - prev_cookie->last_accessed = time(NULL); - } else { - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * tmp_cookie_ptr; - size_t new_len; - - // construct a new cookie_struct - // - prev_cookie = PR_NEW(net_CookieStruct); - if(!prev_cookie) { - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - net_unlock_cookie_list(); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - - //copy - // - prev_cookie->cookie = cookie_from_header; - prev_cookie->name = name_from_header; - prev_cookie->path = path_from_header; - prev_cookie->host = host_from_header; - prev_cookie->expires = expires; - HG22730 - prev_cookie->is_domain = is_domain; - prev_cookie->last_accessed = time(NULL); - - if(!net_cookie_list) { - net_cookie_list = XP_ListNew(); - if(!net_cookie_list) { - PR_FREEIF(path_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(cookie_from_header); - PR_Free(prev_cookie); - net_unlock_cookie_list(); -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; - } - } - - // add it to the list so that it is before any strings of - // smaller length - // - bCookieAdded = FALSE; - new_len = PL_strlen(prev_cookie->path); - while((tmp_cookie_ptr = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - if(new_len > PL_strlen(tmp_cookie_ptr->path)) { - XP_ListInsertObject(net_cookie_list, tmp_cookie_ptr, prev_cookie); - bCookieAdded = TRUE; - break; - } - } - if ( !bCookieAdded ) { - // no shorter strings found in list - XP_ListAddObjectToEnd(net_cookie_list, prev_cookie); - } - } - - //At this point we know a cookie has changed. Write the cookies to file. - cookies_changed = TRUE; - NET_SaveCookies(NULL); - net_unlock_cookie_list(); -#ifdef TRUST_LABELS - { - TrustLabel *trustlabel; - // At this point the cookie was added to - // the cookie list. So see if there is a trust label that - // matches the cookie and if so add the trust label to the - // cookie permission list. Existing trust label entries in - // the permission list replaced with this latest entry. - // - if ( MatchCookieToLabel2( - cur_url, prev_cookie->name, - prev_cookie->path, prev_cookie->host, &trustlabel ) ) { - // found a match - add the trust info to the proper - // entry in the cookie permission list - // - AddTrustLabelInfo( prev_cookie->name, trustlabel ); - // update the disk file // - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(NULL); - } - } -#endif -#if defined(CookieManagement) - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); -#endif - return; -} -*/ - -/* -PUBLIC void -NET_SetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header) { - net_IntSetCookieString(context, cur_url, set_cookie_header, 0); -} -*/ - -/* Determines whether the inlineHost is in the same domain as the currentHost. For use with rfc 2109 - * compliance/non-compliance. */ -/* -#ifdef TRUST_LABELS -PUBLIC int -#else -PRIVATE int -#endif -*/ -/* -NET_SameDomain(char * currentHost, char * inlineHost) -{ - char * dot = 0; - char * currentDomain = 0; - char * inlineDomain = 0; - - if(!currentHost || !inlineHost) - return 0; - - // case insensitive compare - if(PL_strcasecmp(currentHost, inlineHost) == 0) - return 1; - - currentDomain = PL_strchr(currentHost, '.'); - inlineDomain = PL_strchr(inlineHost, '.'); - - if(!currentDomain || !inlineDomain) - return 0; - - // check for at least two dots before continuing, if there are - // not two dots we don't have enough information to determine - // whether or not the inlineDomain is within the currentDomain - dot = PL_strchr(inlineDomain, '.'); - if(dot) - dot = PL_strchr(dot+1, '.'); - else - return 0; - - // handle .com. case - if(!dot || (*(dot+1) == '\0') ) - return 0; - - if(!PL_strcasecmp(inlineDomain, currentDomain)) - return 1; - return 0; -} -*/ -/* This function wrapper wraps NET_SetCookieString for the purposes of -** determining whether or not a cookie is inline (we need the URL struct, -** and outputFormat to do so). this is called from NET_ParseMimeHeaders -** in mkhttp.c -** This routine does not need to worry about the cookie lock since all of -** the work is handled by sub-routines -*/ -/* -PUBLIC void -NET_SetCookieStringFromHttp(FO_Present_Types outputFormat, - URL_Struct * URL_s, - MWContext * context, - char * cur_url, - char * set_cookie_header) -{ - // If the outputFormat is not PRESENT (the url is not going to the screen), and not - // SAVE AS (shift-click) then - // the cookie being set is defined as inline so we need to do what the user wants us - // to based on his preference to deal with foreign cookies. If it's not inline, just set - // the cookie. - char *ptr=NULL, *date=NULL; - time_t gmtCookieExpires=0, expires=0; - - if(CLEAR_CACHE_BIT(outputFormat) != FO_PRESENT && CLEAR_CACHE_BIT(outputFormat) != FO_SAVE_AS) - { - if (NET_GetCookieBehaviorPref() == NET_DontAcceptForeign) - { - // the user doesn't want foreign cookies, check to see if its foreign - char * curSessionHistHost = 0; - char * theColon = 0; - char * curHost = NET_ParseURL(cur_url, GET_HOST_PART); - History_entry * shistEntry = SHIST_GetCurrent(&context->hist); - if (shistEntry) { - curSessionHistHost = NET_ParseURL(shistEntry->address, GET_HOST_PART); - } - if(!curHost || !curSessionHistHost) - { - PR_FREEIF(curHost); - PR_FREEIF(curSessionHistHost); - return; - } - - // strip ports - theColon = PL_strchr(curHost, ':'); - if(theColon) - *theColon = '\0'; - theColon = PL_strchr(curSessionHistHost, ':'); - if(theColon) - *theColon = '\0'; - - // if it's foreign, get out of here after a little clean up - if(!NET_SameDomain(curHost, curSessionHistHost)) - { - PR_FREEIF(curHost); - PR_FREEIF(curSessionHistHost); - return; - } - PR_FREEIF(curHost); - PR_FREEIF(curSessionHistHost); - } - } - - //Determine when the cookie should expire. This is done by taking the difference between - //the server time and the time the server wants the cookie to expire, and adding that - // difference to the client time. This localizes the client time regardless of whether or - // not the TZ environment variable was set on the client. - - // Get the time the cookie is supposed to expire according to the attribute - ptr = PL_strcasestr(set_cookie_header, "expires="); - if(ptr) - { - char *date = ptr+8; - char origLast = '\0'; - for(ptr=date; *ptr != '\0'; ptr++) - if(*ptr == ';') - { - origLast = ';'; - *ptr = '\0'; - break; - } - expires = NET_ParseDate(date); - *ptr=origLast; - } - if( URL_s->server_date && expires ) - { - if( expires < URL_s->server_date ) - { - gmtCookieExpires=1; - } - else - { - gmtCookieExpires = expires - URL_s->server_date + time(NULL); - // if overflow - if( gmtCookieExpires < time(NULL) ) - gmtCookieExpires = (((unsigned) (~0) << 1) >> 1); // max int - } - } - - net_IntSetCookieString(context, cur_url, set_cookie_header, gmtCookieExpires); -} -*/ - -#if defined(CookieManagement) -/* saves the HTTP cookies permissions to disk - * the parameter passed in on entry is ignored - * returns 0 on success -1 on failure. - */ -/* -PRIVATE int -net_SaveCookiePermissions(char * filename) -{ - XP_List * list_ptr; - net_CookiePermissionStruct * cookie_permission_s; - XP_File fp; - int32 len = 0; - - if(NET_GetCookieBehaviorPref() == NET_DontUse) { - return(-1); - } - - if(!cookie_permissions_changed) { - return(-1); - } - - net_lock_cookie_permission_list(); - list_ptr = net_cookie_permission_list; - - if(!(net_cookie_permission_list)) { - net_unlock_cookie_permission_list(); - return(-1); - } - - if(!(fp = NET_XP_FileOpen(filename, xpHTTPCookiePermission, XP_FILE_WRITE))) { - net_unlock_cookie_permission_list(); - return(-1); - } - len = NET_XP_FileWrite("# Netscape HTTP Cookie Permission File" LINEBREAK - "# http://www.netscape.com/newsref/std/cookie_spec.html" - LINEBREAK "# This is a generated file! Do not edit." - LINEBREAK LINEBREAK, -1, fp); - - if (len < 0) { - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return -1; - } - - // format shall be: - // host \t permission <optional trust label information > - // - while((cookie_permission_s = (net_CookiePermissionStruct *) - XP_ListNextObject(list_ptr)) != NULL) { - len = NET_XP_FileWrite(cookie_permission_s->host, -1, fp); - if (len < 0) { - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return -1; - } - - NET_XP_FileWrite("\t", 1, fp); - - if(cookie_permission_s->permission) { - NET_XP_FileWrite("TRUE", -1, fp); - } else { - NET_XP_FileWrite("FALSE", -1, fp); - } - -#ifdef TRUST_LABELS - // save the trust label information - SaveTrustLabelData( cookie_permission_s, fp ); -#endif - len = NET_XP_FileWrite(LINEBREAK, -1, fp); - if (len < 0) { - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return -1; - } - } - - // save current state of cookie nag-box's checkmark - NET_XP_FileWrite("@@@@", -1, fp); - NET_XP_FileWrite("\t", 1, fp); - if (cookie_remember_checked) { - NET_XP_FileWrite("TRUE", -1, fp); - } else { - NET_XP_FileWrite("FALSE", -1, fp); - } - NET_XP_FileWrite(LINEBREAK, -1, fp); - - cookie_permissions_changed = FALSE; - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return(0); -} -*/ -/* reads the HTTP cookies permission from disk - * the parameter passed in on entry is ignored - * returns 0 on success -1 on failure. - * - */ -/* #define PERMISSION_LINE_BUFFER_SIZE 4096 */ -/* -PRIVATE int -net_ReadCookiePermissions(char * filename) -{ - XP_File fp; - char buffer[PERMISSION_LINE_BUFFER_SIZE]; - char *host, *p; - Bool permission_value; - net_CookiePermissionStruct * cookie_permission; - char *host_from_header2; - - if(!(fp = NET_XP_FileOpen(filename, xpHTTPCookiePermission, XP_FILE_READ))) - return(-1); - - // format is: - // host \t permission <optional trust label information> - // if this format isn't respected we move onto the next line in the file. - // - - net_lock_cookie_permission_list(); - while(NET_XP_FileReadLine(buffer, PERMISSION_LINE_BUFFER_SIZE, fp)) { - if (*buffer == '#' || *buffer == CR || *buffer == LF || *buffer == 0) { - continue; - } - - XP_StripLine(buffer); // remove '\n' from end of the line - - host = buffer; - // isolate the host field which is the first field on the line - if( !(p = PL_strchr(host, '\t')) ) { - continue; / * no permission field * / - } - *p++ = '\0'; - if(*p == CR || *p == LF || *p == 0) { - continue; // no permission field - } - - // ignore leading periods in host name - while (host && (*host == '.')) { - host++; - } - - // the first part of the permission file is valid - - // allocate a new permission struct and fill it in - // - cookie_permission = PR_NEW(net_CookiePermissionStruct); - if (cookie_permission) { - host_from_header2 = PL_strdup(host); - cookie_permission->host = host_from_header2; - - // Now handle the permission field. - // a host value of "@@@@" is a special code designating the - // state of the cookie nag-box's checkmark - // - permission_value = (!PL_strncmp(p, "TRUE", sizeof("TRUE")-1)); - if (!PL_strcmp(host, "@@@@")) { - cookie_remember_checked = permission_value; - } else { - cookie_permission->permission = permission_value; - -#ifdef TRUST_LABELS - // pick up the trust label information from the line - // and add it to the permission struct - // - cookie_permission->TrustList = NULL; - ParseTrustLabelInfo(p, cookie_permission); -#endif - - // add the permission entry - net_AddCookiePermission( cookie_permission, FALSE ); - } - } // end if (cookie_permission) - } // while(NET_XP_FileReadLine( - - net_unlock_cookie_permission_list(); - NET_XP_FileClose(fp); - cookie_permissions_changed = FALSE; - return(0); -} -*/ -#endif - -/* saves out the HTTP cookies to disk - * - * on entry pass in the name of the file to save - * - * returns 0 on success -1 on failure. - * - */ - -/* -PUBLIC int -NET_SaveCookies(char * filename) -{ - XP_List * list_ptr; - net_CookieStruct * cookie_s; - time_t cur_date = time(NULL); - XP_File fp; - int32 len = 0; - char date_string[36]; - - if(NET_GetCookieBehaviorPref() == NET_DontUse) - return(-1); - - if(!cookies_changed) - return(-1); - - if(net_anonymous) { - return(-1); - } - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - if(!(list_ptr)) { - net_unlock_cookie_list(); - return(-1); - } - - if(!(fp = NET_XP_FileOpen(filename, xpHTTPCookie, XP_FILE_WRITE))) { - net_unlock_cookie_list(); - return(-1); - } - - len = NET_XP_FileWrite("# Netscape HTTP Cookie File" LINEBREAK - "# http://www.netscape.com/newsref/std/cookie_spec.html" - LINEBREAK "# This is a generated file! Do not edit." - LINEBREAK LINEBREAK, - -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return -1; - } - - // format shall be: - // host \t is_domain \t path \t secure \t expires \t name \t cookie - //is_domain is TRUE or FALSE - // secure is TRUE or FALSE - // expires is a time_t integer - // cookie can have tabs - // - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr)) != NULL) - { - if(cookie_s->expires < cur_date) - continue; // don't write entry if cookie has expired - // or has no expiration date - // - - len = NET_XP_FileWrite(cookie_s->host, -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return -1; - } - NET_XP_FileWrite("\t", 1, fp); - - if(cookie_s->is_domain) - NET_XP_FileWrite("TRUE", -1, fp); - else - NET_XP_FileWrite("FALSE", -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - NET_XP_FileWrite(cookie_s->path, -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - HG74640 - NET_XP_FileWrite("FALSE", -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - PR_snprintf(date_string, sizeof(date_string), "%lu", cookie_s->expires); - NET_XP_FileWrite(date_string, -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - NET_XP_FileWrite(cookie_s->name, -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - NET_XP_FileWrite(cookie_s->cookie, -1, fp); - len = NET_XP_FileWrite(LINEBREAK, -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return -1; - } - } - - cookies_changed = FALSE; - - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return(0); -} -*/ -/* This isn't needed any more */ -/* -PRIVATE void -NET_InitRDFCookieResources (void) -{ -} -*/ -/* reads HTTP cookies from disk - * - * on entry pass in the name of the file to read - * - * returns 0 on success -1 on failure. - * - * - */ -/*#define LINE_BUFFER_SIZE 4096 */ -/* -PUBLIC int -NET_ReadCookies(char * filename) -{ - XP_List * list_ptr; - net_CookieStruct *new_cookie, *tmp_cookie_ptr; - size_t new_len; - XP_File fp; - char buffer[LINE_BUFFER_SIZE]; - char *host, *is_domain, *path, *xxx, *expires, *name, *cookie; - Bool added_to_list; - -#if defined(CookieManagement) - net_ReadCookiePermissions(NULL); -#endif - - if(!(fp = NET_XP_FileOpen(filename, xpHTTPCookie, XP_FILE_READ))) - return(-1); - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - - // format is: - // - // host \t is_domain \t path \t xxx \t expires \t name \t cookie - // - // if this format isn't respected we move onto the next line in the file. - // is_domain is TRUE or FALSE -- defaulting to FALSE - // xxx is TRUE or FALSE -- should default to TRUE - // expires is a time_t integer - // cookie can have tabs - // - while(NET_XP_FileReadLine(buffer, LINE_BUFFER_SIZE, fp)) - { - added_to_list = FALSE; - - if (*buffer == '#' || *buffer == CR || *buffer == LF || *buffer == 0) - continue; - - host = buffer; - - if( !(is_domain = PL_strchr(host, '\t')) ) - continue; - *is_domain++ = '\0'; - if(*is_domain == CR || *is_domain == LF || *is_domain == 0) - continue; - - if( !(path = PL_strchr(is_domain, '\t')) ) - continue; - *path++ = '\0'; - if(*path == CR || *path == LF || *path == 0) - continue; - - if( !(xxx = PL_strchr(path, '\t')) ) - continue; - *xxx++ = '\0'; - if(*xxx == CR || *xxx == LF || *xxx == 0) - continue; - - if( !(expires = PL_strchr(xxx, '\t')) ) - continue; - *expires++ = '\0'; - if(*expires == CR || *expires == LF || *expires == 0) - continue; - - if( !(name = PL_strchr(expires, '\t')) ) - continue; - *name++ = '\0'; - if(*name == CR || *name == LF || *name == 0) - continue; - - if( !(cookie = PL_strchr(name, '\t')) ) - continue; - *cookie++ = '\0'; - if(*cookie == CR || *cookie == LF || *cookie == 0) - continue; - - // remove the '\n' from the end of the cookie - XP_StripLine(cookie); - - // construct a new cookie_struct - // - new_cookie = PR_NEW(net_CookieStruct); - if(!new_cookie) - { - net_unlock_cookie_list(); - return(-1); - } - - memset(new_cookie, 0, sizeof(net_CookieStruct)); - - //copy - // - StrAllocCopy(new_cookie->cookie, cookie); - StrAllocCopy(new_cookie->name, name); - StrAllocCopy(new_cookie->path, path); - StrAllocCopy(new_cookie->host, host); - new_cookie->expires = atol(expires); - - HG87365 - - if(!PL_strcmp(is_domain, "TRUE")) - new_cookie->is_domain = TRUE; - else - new_cookie->is_domain = FALSE; - - if(!net_cookie_list) - { - net_cookie_list = XP_ListNew(); - if(!net_cookie_list) - { - net_unlock_cookie_list(); - return(-1); - } - } - - // add it to the list so that it is before any strings of - // smaller length - // - new_len = PL_strlen(new_cookie->path); - while((tmp_cookie_ptr = (net_CookieStruct *) XP_ListNextObject(list_ptr)) != NULL) - { - if(new_len > PL_strlen(tmp_cookie_ptr->path)) - { - XP_ListInsertObject(net_cookie_list, tmp_cookie_ptr, new_cookie); - added_to_list = TRUE; - break; - } - } - - // no shorter strings found in list - if(!added_to_list) - XP_ListAddObjectToEnd(net_cookie_list, new_cookie); - } - - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - - cookies_changed = FALSE; - - return(0); -} -*/ - -/* --- New stuff: General auth utils (currently used only by proxy auth) --- */ - -/* - * Figure out the authentication scheme used; currently supported: - * - * * Basic - * - */ - HG73632 - -PRIVATE net_AuthType -net_auth_type(char *name) -{ - if (name) { - while (*name && NET_IS_SPACE(*name)) - name++; - if (!PL_strncasecmp(name, "basic", 5)) - return AUTH_BASIC; -#ifdef SIMPLE_MD5 - HG29383 -#endif - /*FORTEZZA checks*/ - else if (!PL_strncasecmp(name, "fortezzaproxy", 13)) - return AUTH_FORTEZZA; - } - return AUTH_INVALID; -} - - -/* - * Figure out better of two {WWW,Proxy}-Authenticate headers; - * SimpleMD5 is better than Basic. Uses the order of AuthType - * enum values. - * - */ -MODULE_PRIVATE PRBool -net_IsBetterAuth(char *new_auth, char *old_auth) -{ - if (!old_auth || net_auth_type(new_auth) >= net_auth_type(old_auth)) - return PR_TRUE; - else - return PR_FALSE; -} - - -/* - * Turns binary data of given lenght into a newly-allocated HEX string. - * - * - */ -PRIVATE char * -bin2hex(unsigned char *data, int len) -{ - char *buf = (char *)PR_Malloc(2 * len + 1); - char *p = buf; - - if(!buf) - return NULL; - - while (len-- > 0) { - sprintf(p, "%02x", *data); - p += 2; - data++; - } - *p = '\0'; - return buf; -} - - -/* - * Parse {WWW,Proxy}-Authenticate header parameters into a net_AuthStruct - * structure. - * - */ -#define SKIP_WS(p) while((*(p)) && NET_IS_SPACE(*(p))) p++ - -PRIVATE PRBool -next_params(char **pp, char **name, char **value) -{ - char *q, *p = *pp; - - SKIP_WS(p); - if (!p || !(*p) || !(q = strchr(p, '='))) - return FALSE; - *name = p; - *q++ = '\0'; - if (*q == '"') { - *value = q + 1; - q = strchr(*value, '"'); - if (q) - *q++ = '\0'; - } - else { - *value = q; - while (*q && !NET_IS_SPACE(*q)) q++; - if (*q) - *q++ = '\0'; - } - - *pp = q; - return TRUE; -} - -PRIVATE net_AuthStruct * -net_parse_authenticate_line(char *auth, net_AuthStruct *ret) -{ - char *name, *value, *p = auth; - - if (!auth || !*auth) - return NULL; - - if (!ret) - ret = PR_NEWZAP(net_AuthStruct); - - if(!ret) - return NULL; - - SKIP_WS(p); - ret->auth_type = net_auth_type(p); - while (*p && !NET_IS_SPACE(*p)) p++; - - while (next_params(&p, &name, &value)) { - if (!PL_strcasecmp(name, "realm")) - { - StrAllocCopy(ret->realm, value); - } -#ifdef SIMPLE_MD5 - else if (!PL_strcasecmp(name, "domain")) - { - StrAllocCopy(ret->domain, value); - } - else if (!PL_strcasecmp(name, "nonce")) - { - StrAllocCopy(ret->nonce, value); - } - else if (!PL_strcasecmp(name, "opaque")) - { - StrAllocCopy(ret->opaque, value); - } - else if (!PL_strcasecmp(name, "oldnonce")) - { - ret->oldNonce = (!PL_strcasecmp(value, "TRUE")) ? TRUE : FALSE; - } -#endif /* SIMPLE_MD5 */ - /* Some FORTEZZA checks */ - else if (!PL_strcasecmp(name, "challenge")) - { - StrAllocCopy(ret->challenge, value); - } - else if (!PL_strcasecmp(name, "oldchallenge")) - { - ret->oldChallenge = (!PL_strcasecmp(value, "TRUE")) ? TRUE : FALSE; - } - /* End FORTEZZA checks */ - } - -#ifdef SIMPLE_MD5 - if (!ret->oldNonce) - ret->oldNonce_retries = 0; -#endif /* SIMPLE_MD5 */ - /*Another FORTEZZA addition*/ - if (!ret->oldChallenge) - ret->oldChallenge_retries = 0; - /*End FORTEZZA addition */ - return ret; -} - - -#ifdef SIMPLE_MD5 -/* ---------- New stuff: SimpleMD5 Authentication for proxies -------------- */ - -PRIVATE void do_md5(unsigned char *stuff, unsigned char digest[16]) -{ - SECStatus rv; - - rv = HASH_HashBuf(HASH_AlgMD5, digest, stuff, strlen((char *)stuff)); - - return; -} - - -/* - * Generate a response for a SimpleMD5 challenge. - * - * HEX( MD5("challenge password method url")) - * - */ -char *net_generate_md5_challenge_response(char *challenge, - char *password, - int method, - char *url) -{ - unsigned char digest[16]; - unsigned char *cookie = - (unsigned char *)PR_Malloc(strlen(challenge) + strlen(password) + - strlen(url) + 10); - - if(!cookie) - return NULL; - - sprintf((char *)cookie, "%s %s %s %s", challenge, password, - (method==URL_POST_METHOD ? "POST" : - method==URL_HEAD_METHOD ? "HEAD" : "GET"), - url); - do_md5(cookie, digest); - return bin2hex(digest, 16); -} - - -#define SIMPLEMD5_AUTHORIZATION_FMT "SimpleMD5\ - username=\"%s\",\ - realm=\"%s\",\ - nonce=\"%s\",\ - response=\"%s\",\ - opaque=\"%s\"" - -#endif /* SIMPLE_MD5 */ - -PRIVATE -char *net_generate_auth_string(URL_Struct *url_s, - net_AuthStruct *auth_s) -{ - if (!auth_s) - return NULL; - - switch (auth_s->auth_type) { - - case AUTH_INVALID: - break; - - case AUTH_BASIC: - if (!auth_s->auth_string) { - int len; - char *u_pass_string = NULL; - - StrAllocCopy(u_pass_string, auth_s->username); - StrAllocCat (u_pass_string, ":"); - StrAllocCat (u_pass_string, auth_s->password); - - len = PL_strlen(u_pass_string); - if (!(auth_s->auth_string = (char*) PR_Malloc((((len+1)*4)/3)+20))) - { - return NULL; - } - - PL_strcpy(auth_s->auth_string, "Basic "); - NET_UUEncode((unsigned char *)u_pass_string, - (unsigned char *)&auth_s->auth_string[6], - len); - - PR_Free(u_pass_string); - } - break; - -#ifdef SIMPLE_MD5 - case AUTH_SIMPLEMD5: - if (auth_s->username && auth_s->password && - auth_s->nonce && auth_s->opaque && - url_s && url_s->address) - { - char *resp; - - PR_FREEIF(auth_s->auth_string); - auth_s->auth_string = NULL; - - if ((resp = net_generate_md5_challenge_response(auth_s->nonce, - auth_s->password, - url_s->method, - url_s->address))) - { - if ((auth_s->auth_string = - (char *)PR_Malloc(PL_strlen(auth_s->username) + - PL_strlen(auth_s->realm) + - PL_strlen(auth_s->nonce) + - PL_strlen(resp) + - PL_strlen(auth_s->opaque) + - 100))) - { - sprintf(auth_s->auth_string, - SIMPLEMD5_AUTHORIZATION_FMT, - auth_s->username, - auth_s->realm, - auth_s->nonce, - resp, - auth_s->opaque); - } - PR_Free(resp); - } - } - break; -#endif /* SIMPLE_MD5 */ - /* Handle the FORTEZZA case */ - case AUTH_FORTEZZA: - HG26251 - break; - /* Done Handling the FORTEZZA case */ - } - - return auth_s->auth_string; -} - - -/* --------------- New stuff: client-proxy authentication --------------- */ - -PRIVATE net_AuthStruct * -net_CheckForProxyAuth(char * proxy_addr) -{ - XP_List * lp = net_proxy_auth_list; - net_AuthStruct * s; - - while ((s = (net_AuthStruct *)XP_ListNextObject(lp)) != NULL) - { - if (!PL_strcasecmp(s->proxy_addr, proxy_addr)) - return s; - } - - return NULL; -} - - -/* - * returns a proxy authorization string if one is required, otherwise - * returns NULL - */ -PUBLIC char * -NET_BuildProxyAuthString(MWContext * context, - URL_Struct * url_s, - char * proxy_addr) -{ - net_AuthStruct * auth_s = net_CheckForProxyAuth(proxy_addr); - - return auth_s ? net_generate_auth_string(url_s, auth_s) : NULL; -} - - -/* - * Returns FALSE if the user wishes to cancel proxy authorization - * and TRUE if the user wants to continue with a new authorization - * string. - */ -#define INVALID_AUTH_HEADER XP_GetString( XP_PROXY_REQUIRES_UNSUPPORTED_AUTH_SCHEME ) - -#define LOOPING_OLD_NONCES XP_GetString( XP_LOOPING_OLD_NONCES ) - -PUBLIC PRBool -NET_AskForProxyAuth(MWContext * context, - char * proxy_addr, - char * pauth_params, - PRBool already_sent_auth, - void * closure) -{ - net_AuthStruct * prev; - PRBool new_entry = FALSE; - char * username = NULL; - char * password = NULL; - char * buf; - int32 len=0; - - TRACEMSG(("Entering NET_AskForProxyAuth")); - - if (!proxy_addr || !*proxy_addr || !pauth_params || !*pauth_params) - return FALSE; - - prev = net_CheckForProxyAuth(proxy_addr); - if (prev) { - new_entry = FALSE; - net_parse_authenticate_line(pauth_params, prev); - } - else { - new_entry = TRUE; - if (!(prev = net_parse_authenticate_line(pauth_params, NULL))) - { - FE_Alert(context, INVALID_AUTH_HEADER); - return FALSE; - } - StrAllocCopy(prev->proxy_addr, proxy_addr); - } - - if (!prev->realm || !*prev->realm) - StrAllocCopy(prev->realm, XP_GetString( XP_UNIDENTIFIED_PROXY_SERVER ) ); - - if (!new_entry) { - if (!already_sent_auth) - { - /* somehow the mapping changed since the time we sent - * the authorization. - * This happens sometimes because of the parrallel - * nature of the requests. - * In this case we want to just retry the connection - * since it will probably succeed now. - */ - return TRUE; - } -#ifdef SIMPLE_MD5 - else if (prev->oldNonce && prev->oldNonce_retries++ < 3) - { - /* - * We already sent the authorization string and the - * nonce was expired -- auto-retry. - */ - if (!FE_Confirm(context, LOOPING_OLD_NONCES)) - return FALSE; - } -#endif /* SIMPLE_MD5 */ - /* Do the good old FORTEZZA stuff */ - else if (prev->oldChallenge && (prev->oldChallenge_retries++ > 3)) - { - /* - * We already sent the authorization string and the - * nonce was expired -- auto-retry. - */ - if (!FE_Confirm(context, XP_GetString(XP_CONFIRM_PROXYAUTHOR_FAIL))) - return FALSE; - } - else if (prev->auth_type != AUTH_FORTEZZA) - { - /* - * We already sent the authorization string and it failed. - */ - if (!FE_Confirm(context, XP_GetString(XP_CONFIRM_PROXYAUTHOR_FAIL))) - return FALSE; - } - } - - - if (prev->auth_type == AUTH_FORTEZZA) { - SECStatus rv; - rv = HG26252 - if ( rv != SECSuccess ) { - return(FALSE); - } - } else - { - username = prev->username; - password = prev->password; - - len = PL_strlen(prev->realm) + PL_strlen(proxy_addr) + 50; - buf = (char*)PR_Malloc(len*sizeof(char)); - - if(buf) - { - PR_snprintf(buf, len*sizeof(char), XP_GetString( XP_PROXY_AUTH_REQUIRED_FOR ), prev->realm, proxy_addr); - - NET_Progress(context, XP_GetString( XP_CONNECT_PLEASE_ENTER_PASSWORD_FOR_PROXY ) ); -#if 1 -#if defined(SingleSignon) - /* prefill prompt with previous username/passwords if any */ - len = SI_PromptUsernameAndPassword - (context, buf, &username, &password, proxy_addr); -#else - len = FE_PromptUsernameAndPassword - (context, buf, &username, &password); -#endif -#else - /* the new multi-thread case -- we return with out user/pass */ - len = stub_PromptUsernameAndPassword - (context, buf, &username, &password, closure); -#endif - PR_Free(buf); - } - else - { - len = 0; - } - - if (!len) - { - TRACEMSG(("Waiting for user auth")); - return FALSE; -#if notused - TRACEMSG(("User canceled login!!!")); - return FALSE; -#endif /* notused */ - } - else if (!username || !password) - { - return FALSE; - } - - PR_FREEIF(prev->auth_string); - prev->auth_string = NULL; /* Generate a new one */ - PR_FREEIF(prev->username); - prev->username = username; - PR_FREEIF(prev->password); - prev->password = password; - } - - if (new_entry) - { - if (!net_proxy_auth_list) - { - net_proxy_auth_list = XP_ListNew(); - if (!net_proxy_auth_list) - { - return TRUE; - } - } - XP_ListAddObjectToEnd(net_proxy_auth_list, prev); - } - - return TRUE; -} - - -#if defined(CookieManagement) -/* -#include "htmldlgs.h" -extern int XP_CERT_PAGE_STRINGS; -extern int SA_REMOVE_BUTTON_LABEL; - -// return TRUE if "number" is in sequence of comma-separated numbers -Bool net_InSequence(char* sequence, int number) { - char* ptr; - char* endptr; - char* undo = NULL; - Bool retval = FALSE; - int i; - - // not necessary -- routine will work even with null sequence - if (!*sequence) { - return FALSE; - } - - for (ptr = sequence ; ptr ; ptr = endptr) { - - // get to next comma - endptr = PL_strchr(ptr, ','); - - // if comma found, process it - if (endptr) { - - // restore last comma-to-null back to comma - if (undo) { - *undo = ','; - } - - // set the comma to a null - undo = endptr; - *endptr++ = '\0'; - - // compare the number before the comma with "number" - if (*ptr) { - i = atoi(ptr); - if (i == number) { - - // "number" was in the sequence so return TRUE - retval = TRUE; - break; - } - } - } - } - - // restore last comma-to-null back to comma - if (undo) { - *undo = ','; - } - return retval; -} -*/ - -/* -PR_STATIC_CALLBACK(PRBool) -net_AboutCookiesDialogDone(XPDialogState* state, char** argv, int argc, - unsigned int button) -{ - XP_List *list; - net_CookieStruct *cookie; - net_CookiePermissionStruct *cookiePermission; - char *buttonName; - int cookieNumber; - net_CookieStruct *cookieToDelete = 0; - net_CookiePermissionStruct *cookiePermissionToDelete = 0; - - char* gone; - - buttonName = XP_FindValueInArgs("button", argv, argc); - if (button != XP_DIALOG_OK_BUTTON) { - // OK button not pressed (must be cancel button that was pressed) - return PR_FALSE; - } - - // OK was pressed, do the deletions - - // get the comma-separated sequence of cookies to be deleted - gone = XP_FindValueInArgs("goneC", argv, argc); - PR_ASSERT(gone); - if (!gone) { - return PR_FALSE; - } - - // walk through the cookie list, deleting the designated cookies - // Note: we can't delete cookie while "list" is pointing to it because - // that would destroy "list". So we do a lazy deletion - // - net_lock_cookie_list(); - list = net_cookie_list; - cookieNumber = 0; - while ( (cookie=(net_CookieStruct *) XP_ListNextObject(list)) ) { - if (net_InSequence(gone, cookieNumber)) { - if (cookieToDelete) { - net_FreeCookie(cookieToDelete); - } - cookieToDelete = cookie; - } - cookieNumber++; - } - - if (cookieToDelete) { - net_FreeCookie(cookieToDelete); - cookies_changed = TRUE; - NET_SaveCookies(NULL); - } - net_unlock_cookie_list(); - - // get the comma-separated sequence of permissions to be deleted - gone = XP_FindValueInArgs("goneP", argv, argc); - PR_ASSERT(gone); - if (!gone) { - return PR_FALSE; - } - - // walk through the cookie permission list, deleting the designated permissions - // Note: we can't delete permissions while "list" is pointing to it because - // that would destroy "list". So we do a lazy deletion - // - net_lock_cookie_permission_list(); - list = net_cookie_permission_list; - cookieNumber = 0; - while ( (cookiePermission=(net_CookiePermissionStruct *) XP_ListNextObject(list)) ) { - if (net_InSequence(gone, cookieNumber)) { - if (cookiePermissionToDelete) { - net_FreeCookiePermission(cookiePermissionToDelete, TRUE); - } - cookiePermissionToDelete = cookiePermission; - } - cookieNumber++; - } - - if (cookiePermissionToDelete) { - net_FreeCookiePermission(cookiePermissionToDelete, TRUE); - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(NULL); - } - - net_unlock_cookie_permission_list(); - return PR_FALSE; -} -*/ - -/* -PRIVATE Bool -CookieCompare (net_CookieStruct * cookie1, net_CookieStruct * cookie2) { - char * host1 = cookie1->host; - char * host2 = cookie2->host; - - // get rid of leading period on host name, if any - if (*host1 == '.') { - host1++; - } - if (*host2 == '.') { - host2++; - } - - // make decision based on host name if they are unequal - if (PL_strcmp (host1, host2) < 0) { - return -1; - } - if (PL_strcmp (host1, host2) > 0) { - return 1; - } - - // if host names are equal, make decision based on cookie name - return (PL_strcmp (cookie1->name, cookie2->name)); -} -*/ - -/* - * find the next cookie that is alphabetically after the specified cookie - * ordering is based on hostname and the cookie name - * if specified cookie is NULL, find the first cookie alphabetically - */ -/* -PRIVATE net_CookieStruct * -NextCookieAfter(net_CookieStruct * cookie, int * cookieNum) { - XP_List *cookie_list=net_cookie_list; - net_CookieStruct *cookie_ptr; - net_CookieStruct *lowestCookie = NULL; - int localCookieNum = 0; - int lowestCookieNum; - - while ( (cookie_ptr=(net_CookieStruct *) XP_ListNextObject(cookie_list)) ) { - if (!cookie || (CookieCompare(cookie_ptr, cookie) > 0)) { - if (!lowestCookie || - (CookieCompare(cookie_ptr, lowestCookie) < 0)) { - lowestCookie = cookie_ptr; - lowestCookieNum = localCookieNum; - } - } - localCookieNum++; - } - - *cookieNum = lowestCookieNum; - return lowestCookie; -} -*/ -/* -typedef struct _CookieViewerDialog CookieViewerDialog; - -struct _CookieViewerDialog { - void *window; - void *parent_window; - PRBool dialogUp; - XPDialogState *state; -}; -*/ -#ifdef TRUST_LABELS -/* Purpose: given a cookie name look in the list containing the cookperm.txt - * file and locate a matching trust label. If a matching trust label - * is found then format a simple text string that describes the trust label - * information in a user friendly manner. - * - * If a matching label is not found return a string with a single space. - * The caller must free the string. - * - * History: - * 9/9/98 Paul Chek - switch recipient from a range to a single value - */ -/* -char *GetTrustLabelString(char *CookieName) -{ - XP_List * list_ptr, *Tptr; - TrustEntry *TEntry; - net_CookiePermissionStruct *cookperm; - char *szTemp = NULL; - char *szPurpose = NULL; - char *szRecipient = NULL; - char *szBy = NULL; - int i, j; - -// here's how we would like to write the code but it doesn't compile on the mac - // -// int PurposeIds[] = {MK_ACCESS_TL_PPH0, MK_ACCESS_TL_PPH1, - // MK_ACCESS_TL_PPH2, MK_ACCESS_TL_PPH3, - // MK_ACCESS_TL_PPH4, MK_ACCESS_TL_PPH5}; - // int RecpIds[] = { MK_ACCESS_TL_RPH0, MK_ACCESS_TL_RPH1, - // MK_ACCESS_TL_RPH2, MK_ACCESS_TL_RPH3}; -// - -#define NumPurposeBits 6 // number of bits in the recipient value - int PurposeIds[NumPurposeBits]; - -#define NumRecpBits 4 // number of bits in the recipient value - // the list of msg Ids for the recipient value. - int RecpIds[NumRecpBits]; - -#if NumPurposeBits > NumRecpBits -#define NumStrs NumPurposeBits -#else -#define NumStrs NumRecpBits -#endif - // this array holds strings used in formatting the message - char *szTempStrs[ NumStrs ]; - - PurposeIds[0] = MK_ACCESS_TL_PPH0; - PurposeIds[1] = MK_ACCESS_TL_PPH1; - PurposeIds[2] = MK_ACCESS_TL_PPH2; - PurposeIds[3] = MK_ACCESS_TL_PPH3; - PurposeIds[4] = MK_ACCESS_TL_PPH4; - PurposeIds[5] = MK_ACCESS_TL_PPH5; - - RecpIds[0] = MK_ACCESS_TL_RPH0; - RecpIds[1] = MK_ACCESS_TL_RPH1; - RecpIds[2] = MK_ACCESS_TL_RPH2; - RecpIds[3] = MK_ACCESS_TL_RPH3; - - - - if( CookieName ) { - //look thru the cookie permission list for a matching trust label // - net_lock_cookie_permission_list(); - list_ptr = net_cookie_permission_list; - while( szTemp == NULL && - (cookperm = (net_CookiePermissionStruct *) XP_ListNextObject(list_ptr))!=0) { - //look thru the trust list for this cookie // - if (cookperm->TrustList ) { - Tptr = cookperm->TrustList; - while( (TEntry = (TrustEntry *)XP_ListNextObject(Tptr))) { - if( TEntry->CookieName - && !PL_strcmp(CookieName, TEntry->CookieName)) { - // this permission entry matches the given cookie// - szTemp = (char*)PR_Malloc(BUFLEN); - break; - } - } - } - } - net_unlock_cookie_permission_list(); - - // was a match found?? - if (szTemp) { - // yes convert the ratings info into user strings // - - for( j=0; j<NumStrs; j++) { - szTempStrs[j] = NULL; - } - - // count the number of purpose bits set AND - // make a list of the phrases to use - // - for (j=0,i=0; i<NumPurposeBits; i++) { - if ((TEntry->purpose>>i) & 1) { - //this bit is set get the associated phrase - szTempStrs[j++] = PL_strdup( XP_GetString( PurposeIds[i] ) ); - } - } - // build the purpose string - // For translation purposes I am using strings - // of the form "This information is used for %1$s, %2$s and %3$s." - // and inserting the additional phrases in the formating. - switch ( j ) { - case 1: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_PUR1 ), - szTempStrs[0] - ); - break; - case 2: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_PUR2 ), - szTempStrs[0], - szTempStrs[1] - ); - break; - - case 3: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_PUR3 ), - szTempStrs[0], - szTempStrs[1], - szTempStrs[2] - ); - break; - - case 4: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_PUR4 ), - szTempStrs[0], - szTempStrs[1], - szTempStrs[2], - szTempStrs[3] - ); - break; - - case 5: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_PUR5 ), - szTempStrs[0], - szTempStrs[1], - szTempStrs[2], - szTempStrs[3], - szTempStrs[4] - ); - break; - - case 6: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_PUR6 ), - szTempStrs[0], - szTempStrs[1], - szTempStrs[2], - szTempStrs[3], - szTempStrs[4], - szTempStrs[5] - ); - break; - - } // switch ( j ) - // I did things this way to avoid buffer overflow problems - szPurpose = PL_strdup( szTemp ); - // free the temporary strings - for( j=0; j<NumStrs; j++) { - PR_FREEIF(szTempStrs[j]); - szTempStrs[j] = NULL; - } - - // second, build the recipient phrase list. The recipients value as - // ossolated between allowing a range of values (0:2) and a single - // value, thats the reason for the ifdef'd code. -#ifndef RECIPIENT_RANGE - szTempStrs[0] = PL_strdup( XP_GetString( RecpIds[ TEntry->recipient] ) ); - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_RECP1 ), - szTempStrs[0] - ); - PR_FREEIF(szTempStrs[0]); - szRecipient = PL_strdup( szTemp ); -#else - // is just a single bit set and is that bit 0 ? - // if RECIPIENT_RANGE is defined you will need to - // include these lines in allxpstr.h - // ResDef(MK_ACCESS_TL_RECP2, (TRUST_LABEL_BASE + 17), - // "It is %1$s and %2$s." ) - // ResDef(MK_ACCESS_TL_RECP3, (TRUST_LABEL_BASE + 18), - // "It is %1$s, %2$s and %3$s." ) - /// - if ( TEntry->recipient == 1 ) { - szTempStrs[0] = PL_strdup( XP_GetString( MK_ACCESS_TL_RPH0 ) ); - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_RECP1 ), - szTempStrs[0] - ); - } else { - // if bits other than bit 0 are set then dont - // output the "used only by this site" text - // - // count the number of purpose bits set AND - // make a list of the phrases to use - /// - for (j=0,i=1; i<NumRecpBits; i++) { - if ((TEntry->recipient>>i) & 1) { - // this bit is set get the associated phrase - szTempStrs[j++] = PL_strdup( XP_GetString( RecpIds[i] ) ); - } - } - // format the recipient string according to the - // number of bits set - // - switch ( j ) { - case 1: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_RECP1 ), - szTempStrs[0] - ); - break; - - case 2: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_RECP2 ), - szTempStrs[0], - szTempStrs[1] - ); - break; - - case 3: - PR_snprintf(szTemp, BUFLEN, - XP_GetString( MK_ACCESS_TL_RECP3 ), - szTempStrs[0], - szTempStrs[1], - szTempStrs[2] - ); - break; - - } // switch ( j ) - } - // I did things this way to avoid buffer overflow problems - szRecipient = PL_strdup( szTemp ); - // free the temporary strings - for( j=0; j<NumStrs; j++) { - PR_FREEIF(szTempStrs[j]); - szTempStrs[j] = NULL; - } -#endif - - //construct the by string - if (TEntry->by) { - PR_snprintf(szTemp, BUFLEN, XP_GetString(MK_ACCESS_TL_BY), TEntry->by); - szBy = PL_strdup( szTemp ); - } else { - szBy = PL_strdup( " " ); - } - - // construct the entire trust label statement. - // WATCHOUT: you can only execute four XP_GetString calls - // in this format string. - // - PR_snprintf(szTemp, BUFLEN, - "%s " // identifiable text - "%s " // purpose string - "%s " /// receipent - "%s", // by string - (TEntry->bIdentifiable - ? XP_GetString(MK_ACCESS_TL_ID1) - : XP_GetString(MK_ACCESS_TL_ID0)), - szPurpose, szRecipient, szBy); - } - } - PR_FREEIF(szPurpose); - PR_FREEIF(szRecipient); - PR_FREEIF(szBy); - - return szTemp; -} -*/ -/* -#define STR_TRUST_LABEL "(TrustLabel" -// these structures describe the layout of the trust label information in - // the cookperm.txt. The structures are used for both reading and writing the -// file. -// -enum {TYPE_QUOTED_STRING, TYPE_INT}; -typedef struct { - char *szMatchStr; // the string to look for coming in - int ValueType; // what kind of thing the value is - int DataOffset; // where in the TrustEntry struct to store the value -} ParseItem; - -static ParseItem ParseData[] = { - {"cookie", TYPE_QUOTED_STRING, offsetof(TrustEntry, CookieName)}, - {"purpose", TYPE_INT, offsetof(TrustEntry, purpose)}, - {"id", TYPE_INT, offsetof(TrustEntry, bIdentifiable)}, - {"recipient", TYPE_INT, offsetof(TrustEntry, recipient)}, - {"by", TYPE_QUOTED_STRING, offsetof(TrustEntry, by)}, - //the timestamp is the date and time when the cookie was set. - // It is in the form "14 Apr 89 03:20 GMT". Use PR_ParseTimeString - // to parse it into a PR_Exploded time. - // - {"timestamp", TYPE_QUOTED_STRING, offsetof(TrustEntry, CookieSet)} -}; -#define NUM_ITEMS sizeof(ParseData) / sizeof( ParseItem) -*/ -/****************************************************** - * Purpose: parse all the trust label string from a line in - * cookperm.txt and store the result in a net_CookiePermissionStruct. - * - * This is a simple table driven parser. - ******************************************************/ -/* -PRIVATE -void ParseTrustLabelInfo - (char *Buf, net_CookiePermissionStruct * cookie_permission) -{ - char *pToken, *p, *pEnd, *pSub; - int i, k, len; - Bool Status = FALSE; - char *pChar, *szTemp; - char *pCopy = NULL; - TrustEntry *TEntry; - - // Look for the trust label information which is in the form - // "(TrustLabel" - must be the first token - // "cookie:"<cookie name> - // "purpose:"<purpose value> - // "id:"<"0"|"1"> - // "recipient:"<recipient value> - // "by:"<by value> - // "timestamp:"<timestamp> - // ")" - must be the last token - // purpose value == a hex value corresponding to the purpose value to set - // recipient value == a hex value corresponding to the recipient value to set - // by value == a text string enclosed in double quotes - // timestamp == time when the cookie was set: format is quoted string in any of the - // formats that PR_Time will accept. - // cookie name == the name of the cookie enclosed in quotes - // - // The middle tokens can be in any order. - /// - - // Do I have a well formed trust label string ?? - // - can I find a beginning and an end?? - // - p = Buf; - while ((p=strcasestr(p, (char *)STR_TRUST_LABEL)) && (pEnd=strchr(p,')'))) { - p += PL_strlen(STR_TRUST_LABEL); - - // Allocate a new trust Entry - TEntry = PR_NEW(TrustEntry); - if (TEntry) { - // init the elements - TEntry->CookieName = NULL; - TEntry->purpose = 0; - TEntry->recipient = 0; - TEntry->bIdentifiable = FALSE; - TEntry->by = NULL; - TEntry->CookieSet = NULL; - - // isolate this trust label string for parsing, I must make a copy - // of the incoming string because the tokenizer will add nulls to it. - // Also allocate one more byte than I really need so that the tokenizer - // can write an extra Null at the end. - // - len = pEnd-p+1; - pCopy = XP_ALLOC(len + 1); - if (!pCopy) return; - XP_MEMCPY(pCopy, p, len-1); - pCopy[len] = '\0'; - - // get the first token from the copy - pToken = XP_STRTOK_R(pCopy, " :", &pSub); - while (pToken) { - if (pToken != ")") { - for ( i=0; i<NUM_ITEMS; i++ ) { - // Is this token one that we are interested in ?? - if (PL_strcasecmp(pToken, ParseData[i].szMatchStr) == 0) { - // yes - extract its associated value and store it - switch(ParseData[i].ValueType) { - case TYPE_QUOTED_STRING: - /// since I allow white space INSIDE the - // quoted string, AND I want the next token - // to contain all the stuff inside the - // quoted string; I need to eat all the - // whitespace between the : and the - // next " - /// - while(*pSub == ' ' || *pSub == '\t') { - pSub++; - } - // get next token which should be " - pToken = XP_STRTOK_R(nil, "\"", &pSub ); - if (pToken) { - pChar = (char *)((void *)(TEntry)) - + ParseData[i].DataOffset; - szTemp = PL_strdup(pToken); - XP_MEMCPY((void *)pChar, - (void *)&szTemp, - sizeof(char *) ); - } - break; - case TYPE_INT: - // get the next token which should be some - // number - // - pToken = XP_STRTOK_R(nil, " ", &pSub ); - if (pToken) { - pChar = (char *)((void *)(TEntry)) - + ParseData[i].DataOffset; - k = XP_ATOI( pToken ); - XP_MEMCPY((void *)pChar, - (void *)&k, sizeof(int)); - } - break; - } - break; // break out of the for loop - } - } - } else { - // all done - break; - } - pToken = XP_STRTOK_R(nil, " :", &pSub ); // get the next token - } // end while - PR_FREEIF( pCopy ); - - // Does the trust list exist in this entry, if not create it - if(!cookie_permission->TrustList) { - cookie_permission->TrustList = XP_ListNew(); - if(!cookie_permission->TrustList) { - return; - } - } - - // add the entry to the list in the permission entry - XP_ListAddObjectToEnd( cookie_permission->TrustList, TEntry ); - - } //end if (TEntry) - // set up for the next entry - p = ++pEnd; - } // end while ((p=strcasestr( - return; -} -*/ - -/**************************************************************** -* Purpose: Write the trust label information from the permission -* list to cookperm.txt -* -* History: -* Paul Chek - initial creation -****************************************************************/ -/* -PRIVATE -void SaveTrustLabelData - ( net_CookiePermissionStruct * cookie_permission, XP_File fp ) -{ - XP_List *Tptr; - TrustEntry *TEntry; - char *szTemp; - char *szTemp2; - char **pChar; - int *pInt; - int T2Size = 50; - int len, i; - - // do an initial allocation for szTemp2. Whenever a quoted string - // is processed the size of szTemp2 is tested to make sure it is big enough, - // if it is not it is resized. - // - szTemp2 = XP_ALLOC( T2Size ); - if ( fp && cookie_permission && cookie_permission->TrustList && szTemp2 ) { - // there is trust label information, write it - Tptr = cookie_permission->TrustList; - while( (TEntry = (TrustEntry *)XP_ListNextObject(Tptr))) { - // build the string up one piece at a time, its slower but safer - szTemp = NULL; - StrAllocCopy( szTemp, " "STR_TRUST_LABEL); - // march thru the Parsing table and output the TrustLabel information - for ( i=0; i<NUM_ITEMS; i++ ) { - switch(ParseData[i].ValueType) { - case TYPE_QUOTED_STRING: - pChar = (char **)(((char *)TEntry)+ ParseData[i].DataOffset); - if ( PL_strlen( *pChar ) ) { - // make sure szTemp2 is big enough. - len = PL_strlen( ParseData[i].szMatchStr ) + PL_strlen(*pChar) + 3; - if ( T2Size <= len ) { - T2Size = len +50; - szTemp2 = XP_REALLOC( szTemp2, T2Size ); - } - if ( szTemp2 ) { - PR_snprintf( szTemp2, T2Size, " %s:\"%s\"", - ParseData[i].szMatchStr, *pChar ); - StrAllocCat( szTemp, szTemp2 ); - } else { - // error reallocating szTemp2, blast out - PR_FREEIF( szTemp ); - return; - } - } - break; - - case TYPE_INT: - pInt = (int *)(((char *)TEntry)+ ParseData[i].DataOffset); - PR_snprintf( szTemp2, T2Size, " %s:%d", - ParseData[i].szMatchStr, *pInt ); - StrAllocCat( szTemp, szTemp2 ); - break; - } - } // end for - StrAllocCat( szTemp, " )" ); // add the termination paren - - // write a single trust label string - NET_XP_FileWrite(szTemp, -1, fp); - PR_FREEIF( szTemp ); - } // end while( (TEntry = - PR_FREEIF( szTemp2 ); - } -} -*/ -/**************************************************************** -* Purpose: search for a TrustEntry in the trust list of a cookie -* permission entry. -* -* History: -* Paul Chek - initial creation -****************************************************************/ -/* -PRIVATE -Bool FindTrustEntry( char *CookieName, XP_List *TList, TrustEntry **TheEntry ) -{ - TrustEntry *TEntry; - XP_List *TPtr; - Bool Status = FALSE; - if ( TList && !XP_ListIsEmpty( TList ) ) { - TPtr = TList; - while( (TEntry = (TrustEntry *)XP_ListNextObject(TPtr))) { - if (PL_strcasecmp(CookieName, TEntry->CookieName) == 0) { - // the entry was found - *TheEntry = TEntry; - Status = TRUE; - break; - } - } - } - return Status; -} -*/ -/**************************************************************** -* Purpose: given a TrustLabel struct sat up the corresponding TrustEntry -* -* History: -* Paul Chek - initial creation -****************************************************************/ -/* -PRIVATE -void CopyTrustEntry( char *CookieName, TrustEntry *TEntry, TrustLabel *trustlabel ) -{ - PRExplodedTime now; - char line[100]; - - if ( TEntry && trustlabel ) { - PR_FREEIF(TEntry->CookieName); - PR_FREEIF(TEntry->by); - PR_FREEIF(TEntry->CookieSet); - TEntry->CookieName = PL_strdup( CookieName ); - TEntry->purpose = trustlabel->purpose; - TEntry->recipient = trustlabel->recipients; - TEntry->bIdentifiable = trustlabel->ID; - TEntry->by = PL_strdup( trustlabel->szBy ); - - // format an ASCII timestamp for when the cookie was set. Use a - //format that PR_ParseTimeString supports. "22-AUG-1993 10:59 PM" - // - PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &now); - PR_FormatTimeUSEnglish(line, 400, "%d-%b-%Y %I:%M %p", &now); - TEntry->CookieSet = PL_strdup( line ); - } -} -*/ -/**************************************************************** -* Purpose: look in the permissions list to see if there is -* trust label information for the cookie. If so delete it. -* -* History: -* Paul Chek - initial creation -****************************************************************/ -/* -PRIVATE -void DeleteCookieFromPermissions( char *CookieHost, char *CookieName ) -{ - XP_List *TmpList; - TrustEntry *TEntry; - net_CookiePermissionStruct * cookie_permission; - - // lock the permission list - TmpList=net_cookie_permission_list; - net_lock_cookie_permission_list(); - while ( (cookie_permission=(net_CookiePermissionStruct *)XP_ListNextObject(TmpList)) ) { - // is this the corect host for the cookie */ - if (PL_strcasecmp(CookieHost, cookie_permission->host) == 0) { - // yes - see if there is a trust label entry for the cookie - if ( FindTrustEntry( CookieName, cookie_permission->TrustList, &TEntry ) ) { - // yes there is - delete it */ - XP_ListRemoveObject( cookie_permission->TrustList, TEntry); - // free the strings in the entry - PR_FREEIF(TEntry->CookieName); - PR_FREEIF(TEntry->by); - PR_FREEIF(TEntry->CookieSet); - } - // dont need to look in the list anymore cause there is only one entry per host - break; - } - } - net_unlock_cookie_permission_list(); - -} -*/ -/**************************************************************** -* Purpose: given a TrustLabel struct containing the trust label -* info that matches a particular cookie add the trust -* label info to the cookie permission list -* -* History: -* Paul Chek - initial creation -****************************************************************/ -/* -PRIVATE -void AddTrustLabelInfo( char *CookieName, TrustLabel *trustlabel ) -{ - XP_List *TmpList; - TrustEntry *TEntry; - net_CookiePermissionStruct * cookie_permission; - // lock the permission list // - TmpList=net_cookie_permission_list; - net_lock_cookie_permission_list(); - while ( (cookie_permission=(net_CookiePermissionStruct *)XP_ListNextObject(TmpList)) ) { - // is this the corect host for the cookie - if (PL_strcasecmp(trustlabel->domainName, cookie_permission->host) == 0) { - // OK - we have found the entry for this host. Look thru the trust list - // to see if we have an existing entry for this cookie. If so replace it. - // If not add a new entry - // - if ( FindTrustEntry( CookieName, cookie_permission->TrustList, &TEntry ) ) { - //the entry exists modify it - CopyTrustEntry( CookieName, TEntry, trustlabel ); - } else { - // the entry does NOT exist - add a new one - TEntry = PR_NEWZAP( TrustEntry ); - if ( TEntry ) { - // yes - build the entry for the cookie - CopyTrustEntry( CookieName, TEntry, trustlabel ); - // Does the trust list exist in this entry, if not create it - if(!cookie_permission->TrustList) { - cookie_permission->TrustList = XP_ListNew(); - if(!cookie_permission->TrustList) { - return; - } - } - - // add it to the list - XP_ListAddObjectToEnd(cookie_permission->TrustList, TEntry); - break; // all done - } - } - } - } - net_unlock_cookie_permission_list(); -} -*/ -#endif - -/* - * return a string that has each " of the argument sting - * replaced with \" so it can be used inside a quoted string - */ - -PRIVATE char* -net_FixQuoted(char* s) { - char * result; - int count = PL_strlen(s); - char *quote = s; - unsigned int i, j; - while (quote = PL_strchr(quote, '"')) { - count = count++; - quote++; - } - result = XP_ALLOC(count + 1); - for (i=0, j=0; i<PL_strlen(s); i++) { - if (s[i] == '"') { - result[i+(j++)] = '\\'; - } - result[i+j] = s[i]; - } - result[i+j] = '\0'; - return result; -} - -#ifdef XP_MAC -/* pinkerton - if we don't do this, it won't compile because it runs out of registers */ -#pragma global_optimizer on -#endif -/* -PRIVATE void -net_DisplayCookieInfoAsHTML(MWContext *context, char* host) -{ - char *buffer = (char*)PR_Malloc(BUFLEN); - char *buffer2 = 0; - int g = 0, count, cookieNum; - XP_List *cookie_list; - XP_List *cookie_permission_list; - net_CookieStruct *cookie; - net_CookiePermissionStruct *cookperm; - CookieViewerDialog *dlg; - int i; - char * view_sites = NULL; - char * view_cookies = NULL; - char * heading = NULL; -#ifdef TRUST_LABELS - char * szTrustLabel = NULL; -#endif - - static XPDialogInfo dialogInfo = { - 0, - net_AboutCookiesDialogDone, - 600, - 400 - }; - - XPDialogStrings* strings; - strings = XP_GetDialogStrings(XP_CERT_PAGE_STRINGS); - if (!strings) { - return; - } - StrAllocCopy(buffer2, ""); - StrAllocCopy (view_cookies, XP_GetString(MK_ACCESS_VIEW_COOKIES)); - StrAllocCopy (view_sites, XP_GetString(MK_ACCESS_VIEW_SITES)); - - // generate initial section of html file - g += PR_snprintf(buffer+g, BUFLEN-g, -"<HTML>\n" -"<HEAD>\n" -" <TITLE>Cookies</TITLE>\n" -" <SCRIPT>\n" -" index_frame = 0;\n" -" title_frame = 1;\n" -" spacer1_frame = 2;\n" -" list_frame = 3;\n" -" spacer2_frame = 4;\n" -" prop_frame = 5;\n" -" spacer3_frame = 6;\n" -" button_frame = 7;\n" -"\n" -" var cookie_mode;\n" -" var goneC;\n" -" var goneP;\n" -" deleted_cookies = new Array (0" - ); - FLUSH_BUFFER - - - //fill in initial 0's for deleted_cookies and deleted_sites arrays - count = XP_ListCount(net_cookie_list); - for (i=1; i<count; i++) { - g += PR_snprintf(buffer+g, BUFLEN-g, -",0" - ); - if ((i%50) == 0) { - g += PR_snprintf(buffer+g, BUFLEN-g, -"\n " - ); - } - } - g += PR_snprintf(buffer+g, BUFLEN-g, -");\n" -" deleted_sites = new Array (0" - ); - count = XP_ListCount(net_cookie_permission_list); - for (i=1; i<count; i++) { - g += PR_snprintf(buffer+g, BUFLEN-g, -",0" - ); - if ((i%50) == 0) { - g += PR_snprintf(buffer+g, BUFLEN-g, -"\n " - ); - } - } - FLUSH_BUFFER - - g += PR_snprintf(buffer+g, BUFLEN-g, -");\n" -"\n" -" function DeleteItemSelected() {\n" -" if (cookie_mode) {\n" -" DeleteCookieSelected();\n" -" } else {\n" -" DeleteSiteSelected();\n" -" }\n" -" }\n" -"\n" -" function DeleteCookieSelected() {\n" -" selname = top.frames[list_frame].document.fSelectCookie.selname;\n" -" goneC = top.frames[button_frame].document.buttons.goneC;\n" -" var p;\n" -" var i;\n" -" for (i=selname.options.length; i>0; i--) {\n" -" if (selname.options[i-1].selected) {\n" -" selname.options[i-1].selected = 0;\n" -" goneC.value = goneC.value + selname.options[i-1].value + \",\";\n" -" deleted_cookies[selname.options[i-1].value] = 1;\n" -" for (j=i ; j<selname.options.length ; j++) {\n" -" selname.options[j-1] = selname.options[j];\n" -" }\n" -" selname.options[selname.options.length-1] = null;\n" -" }\n" -" }\n" -" top.frames[prop_frame].document.open();\n" -" top.frames[prop_frame].document.close();\n" -" }\n" -"\n" -" function DeleteSiteSelected() {\n" -" selname = top.frames[list_frame].document.fSelectSite.selname;\n" -" goneP = top.frames[button_frame].document.buttons.goneP;\n" -" var p;\n" -" var i;\n" -" for (i=selname.options.length; i>0; i--) {\n" -" if (selname.options[i-1].selected) {\n" -" selname.options[i-1].selected = 0;\n" -" goneP.value = goneP.value + selname.options[i-1].value + \",\";\n" -" deleted_sites[selname.options[i-1].value] = 1;\n" -" for (j=i; j < selname.options.length; j++) {\n" -" selname.options[j-1] = selname.options[j];\n" -" }\n" -" selname.options[selname.options.length-1] = null;\n" -" }\n" -" }\n" -" top.frames[prop_frame].document.open();\n" -" top.frames[prop_frame].document.close();\n" -" }\n" -"\n" -" function ViewCookieSelected(selCookie) {\n" -" selname = top.frames[list_frame].document.fSelectCookie.selname;\n" -" top.frames[prop_frame].document.open();\n" -" switch (selname.options[selCookie].value) {\n" - ); - FLUSH_BUFFER - - // Get rid of any expired cookies now so user doesn't - // think/see that we're keeping cookies in memory. - // - net_lock_cookie_list(); - net_remove_expired_cookies(); - - // Generate the html for the cookie properties (alphabetical order) - cookie_list=net_cookie_list; - cookie = NULL; - while (cookie = NextCookieAfter(cookie, &cookieNum)) { - char * name = NULL; - char * value = NULL; - char * domain_or_host = NULL; - char * path = NULL; - char * secure = NULL; - char * yes_or_no = NULL; - char * expires = NULL; - char * expireDate = NULL; - - char *fixed_name = net_FixQuoted(cookie->name); - char *fixed_value = net_FixQuoted(cookie->cookie); - char *fixed_domain_or_host = net_FixQuoted(cookie->host); - char *fixed_path = net_FixQuoted(cookie->path); - - StrAllocCopy (name, XP_GetString(MK_ACCESS_NAME)); - StrAllocCopy (value, XP_GetString(MK_ACCESS_VALUE)); - StrAllocCopy (domain_or_host, - cookie->is_domain - ? XP_GetString(MK_ACCESS_DOMAIN) - : XP_GetString(MK_ACCESS_HOST)); - StrAllocCopy (path, XP_GetString(MK_ACCESS_PATH)); - StrAllocCopy (secure, XP_GetString(MK_ACCESS_SECURE)); - StrAllocCopy (yes_or_no, - HG78111 - ? XP_GetString(MK_ACCESS_YES) - : XP_GetString(MK_ACCESS_NO)); - StrAllocCopy (expires, XP_GetString(MK_ACCESS_EXPIRES)); - StrAllocCopy (expireDate, - cookie->expires - ? ctime(&(cookie->expires)) - : XP_GetString(MK_ACCESS_END_OF_SESSION)); - - if (!expireDate) { - StrAllocCopy (expireDate, ""); - } else if (expireDate[PL_strlen(expireDate)-1] == '\n') { - expireDate[PL_strlen(expireDate)-1] = ' '; - } - - g += PR_snprintf(buffer+g, BUFLEN-g, -" case %d:\n" -" top.frames[prop_frame].document.write(\n" -" \"<NOBR><b>%s</b> %s</NOBR><BR>\" +\n" -" \"<NOBR><b>%s</b> %s</NOBR><BR>\" +\n" -" \"<NOBR><b>%s</b> %s</NOBR><BR>\" +\n" -" \"<NOBR><b>%s</b> %s</NOBR><BR>\" +\n" -" \"<NOBR><b>%s</b> %s</NOBR><BR>\" +\n" -" \"<NOBR><b>%s</b> %s</NOBR><BR>\" ", - cookieNum, - name, fixed_name, - value, fixed_value, - domain_or_host, fixed_domain_or_host, - path, fixed_path, - secure, yes_or_no, - expires, expireDate - ); - FLUSH_BUFFER - PR_FREEIF(fixed_name); - PR_FREEIF(fixed_value); - PR_FREEIF(fixed_domain_or_host); - PR_FREEIF(fixed_path); - PR_FREEIF(name); - PR_FREEIF(value); - PR_FREEIF(domain_or_host); - PR_FREEIF(path); - PR_FREEIF(secure); - PR_FREEIF(yes_or_no); - PR_FREEIF(expires); - PR_FREEIF(expireDate); - // caveat: It would have been simpler to not allocate and free the - // above strings but rather just use the XP_GetString(...) parameters - // in the call to PR_snprintf. However there are only four buffers - // that XP_GetString uses and it keeps recycling them. Since the - // above would require more than four parameters which are calls to - // XP_GetString, some of the returned buffers would be overwritten - // before they could be used. Hence the simpler approach wouldn't work - // - -#ifdef TRUST_LABELS - // add an entry that contains the trust label information - szTrustLabel = GetTrustLabelString( cookie->name ); - if ( szTrustLabel ) { - g += PR_snprintf(buffer+g, BUFLEN-g, -"+\n" -" \"<HR WIDTH=100%> <FONT SIZE=2> %s </FONT>\"", - szTrustLabel); - PR_FREEIF(szTrustLabel); - } -#endif - g += PR_snprintf(buffer+g, BUFLEN-g, -"\n" -" );\n" -" break;\n" - ); - FLUSH_BUFFER - } - - // generate next section of html file - g += PR_snprintf(buffer+g, BUFLEN-g, -" }\n" -" top.frames[prop_frame].document.close();\n" -" }\n" -"\n" -" function loadCookies(){\n" -" cookie_mode = 1;\n" - ); - FLUSH_BUFFER - - // generate index frame only if full viewer - - if (!host) { - g += PR_snprintf(buffer+g, BUFLEN-g, -" top.frames[index_frame].document.open();\n" -" top.frames[index_frame].document.write(\n" -" \"<BODY BGCOLOR=#C0C0C0>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100%>\" +\n" -" \"<TR>\" +\n" -" \"<TD> <SPACER TYPE=HORIZONTAL SIZE=10> </TD>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#FFFFFF>\" +\n" -" \"<FONT SIZE=2 COLOR=#666666>\" +\n" -" \"<B>%s</B>\" +\n" -" \"</FONT>\" +\n" -" \"</TD>\" +\n" -" \"<TD>&nbsp;&nbsp;&nbsp;</TD>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#C0C0C0>\" +\n" -" \"<A HREF=javascript:top.loadSites();>\" +\n" -" \"<FONT SIZE=2>%s</FONT>\" +\n" -" \"</A>\" +\n" -" \"</TD>\" +\n" -" \"<TD>&nbsp;&nbsp;&nbsp;</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</BODY>\"\n" -" );\n" -" top.frames[index_frame].document.close();\n" -"\n", - view_cookies, view_sites); - FLUSH_BUFFER - } - - // generate next section of html file - if (!host) { - StrAllocCopy (heading, XP_GetString(MK_ACCESS_COOKIES_ACCEPTED)); - } else { - StrAllocCopy (heading, XP_GetString(MK_ACCESS_SITE_COOKIES_ACCEPTED)); - } - g += PR_snprintf(buffer+g, BUFLEN-g, -" top.frames[title_frame].document.open();\n" -" top.frames[title_frame].document.write\n" -" (\"&nbsp;%s\");\n" -" top.frames[title_frame].document.close();\n" -"\n" -" top.frames[list_frame].document.open();\n" -" top.frames[list_frame].document.write(\n" -" \"<FORM name=fSelectCookie>\" +\n" -" \"<P>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100% HEIGHT=95%>\" +\n" -" \"<TR>\" +\n" -" \"<TD WIDTH=100% VALIGN=TOP>\" +\n" -" \"<CENTER>\" +\n" -" \"<P>\" +\n" -" \"<SELECT NAME=selname \" +\n" -" \"SIZE=15 \" +\n" -" \"MULTIPLE \" +\n" -" \"onchange=top.ViewCookieSelected(selname.selectedIndex);>\"\n" -" );\n", - heading); - FLUSH_BUFFER - PR_FREEIF(heading); - - // generate the html for the list of cookies in alphabetical order - cookie_list=net_cookie_list; - cookie = NULL; - while (cookie = NextCookieAfter(cookie, &cookieNum)) { - if (!host || net_CookieIsFromHost(cookie, host)) { - char *fixed_name = net_FixQuoted(cookie->name); - g += PR_snprintf(buffer+g, BUFLEN-g, -" if (!deleted_cookies[%d]) {\n" -" top.frames[list_frame].document.write(\n" -" \"<OPTION value=%d>\" +\n" -" \"%s:%s\" +\n" -" \"</OPTION>\"\n" -" );\n" -" }\n", - cookieNum, cookieNum, - (*(cookie->host)=='.') ? (cookie->host)+1: cookie->host, - fixed_name - ); - FLUSH_BUFFER - PR_FREEIF(fixed_name); - } - } - net_unlock_cookie_list(); - - // generate next section of html file - StrAllocCopy (heading, XP_GetString(MK_ACCESS_COOKIES_PERMISSION)); - g += PR_snprintf(buffer+g, BUFLEN-g, -" top.frames[list_frame].document.write(\n" -" \"</SELECT>\" +\n" -" \"</CENTER>\" +\n" -" \"</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</FORM>\"\n" -" );\n" -" top.frames[list_frame].document.close();\n" -"\n" -" top.frames[prop_frame].document.open();\n" -" top.frames[prop_frame].document.close();\n" -" }\n" -"\n" -" function loadSites(){\n" -" cookie_mode = 0;\n" -" top.frames[index_frame].document.open();\n" -" top.frames[index_frame].document.write(\n" -" \"<BODY BGCOLOR=#C0C0C0>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100%>\" +\n" -" \"<TR>\" +\n" -" \"<TD> <SPACER TYPE=HORIZONTAL SIZE=10> </TD>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#C0C0C0>\" +\n" -" \"<A HREF=javascript:top.loadCookies();>\" +\n" -" \"<FONT SIZE=2>%s</FONT>\" +\n" -" \"</A>\" +\n" -" \"</TD>\" +\n" -" \"<TD>&nbsp;&nbsp;&nbsp;</TD>\" +\n" -" \"<TD ALIGN=CENTER VALIGN=MIDDLE BGCOLOR=#FFFFFF>\" +\n" -" \"<FONT SIZE=2 COLOR=#666666>\" +\n" -" \"<B>%s</B>\" +\n" -" \"</FONT>\" +\n" -" \"</TD>\" +\n" -" \"<TD>&nbsp;&nbsp;&nbsp;</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</BODY>\"\n" -" );\n" -" top.frames[index_frame].document.close();\n" -"\n" -" top.frames[title_frame].document.open();\n" -" top.frames[title_frame].document.write\n" -" (\"&nbsp;%s\");\n" -" top.frames[title_frame].document.close();\n" -"\n" -" top.frames[list_frame].document.open();\n" -" top.frames[list_frame].document.write(\n" -" \"<FORM name=fSelectSite>\" +\n" -" \"<P>\" +\n" -" \"<TABLE BORDER=0 WIDTH=100% HEIGHT=95%>\" +\n" -" \"<TR>\" +\n" -" \"<TD WIDTH=100% VALIGN=TOP>\" +\n" -" \"<CENTER>\" +\n" -" \"<P>\" +\n" -" \"<SELECT NAME=selname SIZE=15 MULTIPLE> \"\n" -" );\n", - view_cookies, view_sites, heading); - FLUSH_BUFFER - PR_FREEIF(heading); - FLUSH_BUFFER - - // generate the html for the list of cookie permissions - cookieNum = 0; - cookie_permission_list=net_cookie_permission_list; - net_lock_cookie_permission_list(); - while ( (cookperm=(net_CookiePermissionStruct *) - XP_ListNextObject(cookie_permission_list)) ) { - g += PR_snprintf(buffer+g, BUFLEN-g, -" if (!deleted_sites[%d]) {\n" -" top.frames[list_frame].document.write(\n" -" \"<OPTION value=\" +\n" -" \"%d>\" +\n" -" \"%s %s\" +\n" -" \"</OPTION>\"\n" -" );\n" -" }\n", - cookieNum, cookieNum, - cookperm->permission ? "+" : "-", - cookperm->host); - FLUSH_BUFFER - cookieNum++; - } - net_unlock_cookie_permission_list(); - - // generate next section of html file - g += PR_snprintf(buffer+g, BUFLEN-g, -" top.frames[list_frame].document.write(\n" -" \"</SELECT>\" +\n" -" \"</CENTER>\" +\n" -" \"</TD>\" +\n" -" \"</TR>\" +\n" -" \"</TABLE>\" +\n" -" \"</FORM>\"\n" -" );\n" -" top.frames[list_frame].document.close();\n" -"\n" -" top.frames[prop_frame].document.open();\n" -" top.frames[prop_frame].document.close();\n" -" }\n" -"\n" -" function loadButtons(){\n" -" top.frames[button_frame].document.open();\n" -" top.frames[button_frame].document.write(\n" -" \"<FORM name=buttons action=internal-cookieViewer-handler method=post>\" +\n" -" \"<BR>\" +\n" -" \"&nbsp;\" +\n" -" \"<INPUT type=BUTTON \" +\n" -" \"value=Remove \" +\n" -" \"onclick=top.DeleteItemSelected();>\" +\n" -" \"<DIV align=right>\" +\n" -" \"<INPUT type=BUTTON value=OK width=80 onclick=parent.clicker(this,window.parent)>\" +\n" -" \" &nbsp;&nbsp;\" +\n" -" \"<INPUT type=BUTTON value=Cancel width=80 onclick=parent.clicker(this,window.parent)>\" +\n" -" \"</DIV>\" +\n" -" \"<INPUT type=HIDDEN name=xxxbuttonxxx>\" +\n" -" \"<INPUT type=HIDDEN name=handle value=" - ); - FLUSH_BUFFER - - // transfer what we have so far into strings->args[0] - if (buffer2) { - XP_SetDialogString(strings, 0, buffer2); - buffer2 = NULL; - } - - //Note: strings->args[1] will later be filled in with value of handle - - // generate remainder of html, it will go into strings->arg[2] - g += PR_snprintf(buffer+g, BUFLEN-g, -">\" +\n" -" \"<INPUT TYPE=HIDDEN NAME=goneC SIZE=-1>\" +\n" -" \"<INPUT TYPE=HIDDEN NAME=goneP SIZE=-1>\" +\n" -" \"</FORM>\"\n" -" );\n" -" top.frames[button_frame].document.close();\n" -" }\n" -"\n" -" function loadFrames(){\n" -" loadCookies();\n" -" loadButtons();\n" -" }\n" -"\n" -" function clicker(but,win){\n" -#ifndef HTMLDialogs -" var goneC = top.frames[button_frame].document.buttons.goneC;\n" -" var goneP = top.frames[button_frame].document.buttons.goneP;\n" -" var expires = new Date();\n" -" expires.setTime(expires.getTime() + 1000*60*60*24*365);\n" -" document.cookie = \"htmldlgs=|\" + but.value +\n" -" \"|goneC|\" + goneC.value + \"|goneP|\" + goneP.value + \"|\" +\n" -" \"; expires=\" + expires.toGMTString();\n" -#endif -" top.frames[button_frame].document.buttons.xxxbuttonxxx.value = but.value;\n" -" top.frames[button_frame].document.buttons.xxxbuttonxxx.name = 'button';\n" -" top.frames[button_frame].document.buttons.submit();\n" -" }\n" -"\n" -" </SCRIPT>\n" -"</HEAD>\n" -"<FRAMESET ROWS = 25,25,*,75\n" -" BORDER=0\n" -" FRAMESPACING=0\n" -" onLoad=loadFrames()>\n" -" <FRAME SRC=about:blank\n" -" NAME=index_frame\n" -" SCROLLING=NO\n" -" MARGINWIDTH=1\n" -" MARGINHEIGHT=1\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=title_frame\n" -" SCROLLING=NO\n" -" MARGINWIDTH=1\n" -" MARGINHEIGHT=1\n" -" NORESIZE>\n" -" <FRAMESET COLS=5,*,10,*,5\n" -" BORDER=0\n" -" FRAMESPACING=0>\n" -" <FRAME SRC=about:blank\n" -" NAME=spacer1_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=list_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=spacer2_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=prop_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" <FRAME SRC=about:blank\n" -" NAME=spacer3_frame\n" -" SCROLLING=AUTO\n" -" MARGINWIDTH=0\n" -" MARGINHEIGHT=0\n" -" NORESIZE>\n" -" </FRAMESET>\n" -" <FRAME SRC=about:blank\n" -" NAME=button_frame\n" -" SCROLLING=NO\n" -" MARGINWIDTH=1\n" -" MARGINHEIGHT=1\n" -" NORESIZE>\n" -"</FRAMESET>\n" -"\n" -"<NOFRAMES>\n" -" <BODY> <P> </BODY>\n" -"</NOFRAMES>\n" -"</HTML>\n" - ); - FLUSH_BUFFER - - // free some strings that are no longer needed // - PR_FREEIF(view_cookies); - PR_FREEIF(view_sites); - PR_FREEIF(buffer); - - // put html just generated into strings->arg[2] and invoke HTML dialog // - if (buffer2) { - XP_SetDialogString(strings, 2, buffer2); - buffer2 = NULL; - } - dlg = PORT_ZAlloc(sizeof(CookieViewerDialog)); - if ( dlg == NULL ) { - return; - } - dlg->parent_window = (void *)context; - dlg->dialogUp = PR_TRUE; - dlg->state =XP_MakeHTMLDialog(NULL, &dialogInfo, MK_ACCESS_YOUR_COOKIES, - strings, (void *)dlg, PR_FALSE); - - return; -} -*/ -/* -PUBLIC void -NET_CookieViewerReturn() { -} -*/ -/* -PUBLIC void -NET_DisplayCookieInfoOfSiteAsHTML(MWContext * context, char * URLName) -{ - char * host; - char * colon; - - // remove protocol from URL name - host = NET_ParseURL(URLName, GET_HOST_PART); - - // remove port number from URL name - colon = PL_strchr(host, ':'); - if(colon) { - *colon = '\0'; - } - - net_DisplayCookieInfoAsHTML(context, host); - - // free up allocated string and return - if(colon) { - *colon = ':'; - } - PR_Free(host); -} -*/ - -PUBLIC void -NET_DisplayCookieInfoAsHTML(MWContext * context) -{ -} - - -#ifdef XP_MAC -/* pinkerton - reset optimization state (see above) */ -#pragma global_optimizer reset -#endif - -#else -/* -PUBLIC void -NET_DisplayCookieInfoAsHTML(MWContext * context) -{ -} -*/ -#endif - diff --git a/mozilla/network/protocol/http/mkaccess.h b/mozilla/network/protocol/http/mkaccess.h deleted file mode 100644 index e2a52217661..00000000000 --- a/mozilla/network/protocol/http/mkaccess.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKACCESS_H -#define MKACCESS_H - -#ifndef MKGETURL_H -#include "mkgeturl.h" -#endif -/* returns TRUE if authorization is required - */ -extern Bool NET_AuthorizationRequired(char * address); - -/* returns false if the user wishes to cancel authorization - * and TRUE if the user wants to continue with a new authorization - * string - */ -extern Bool NET_AskForAuthString(MWContext * context, - URL_Struct *URL_s, - char * authenticate, - char * prot_template, - Bool already_sent_auth, - void * closure); - -/* returns a authorization string if one is required, otherwise - * returns NULL - */ -extern char * NET_BuildAuthString(MWContext * context, URL_Struct *URL_s); - -/* - * Builds the Proxy-authorization string - */ -extern char * -NET_BuildProxyAuthString(MWContext * context, - URL_Struct * url_s, - char * proxy_addr); - -/* - * Returns FALSE if the user wishes to cancel proxy authorization - * and TRUE if the user wants to continue with a new authorization - * string. - */ -PUBLIC PRBool -NET_AskForProxyAuth(MWContext * context, - char * proxy_addr, - char * pauth_params, - PRBool already_sent_auth, - void * closure); - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieBehaviorPrefChanged(const char * newpref, void * data); - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieWarningPrefChanged(const char * newpref, void * data); - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieScriptPrefChanged(const char * newpref, void * data); - -MODULE_PRIVATE void -net_http_password_data_interp( - char *module, - char *key, - char *data, int32 data_len, - char *type_buffer, int32 type_buffer_size, - char *url_buffer, int32 url_buffer_size, - char *username_buffer, int32 username_buffer_size, - char *password_buffer, int32 password_buffer_size); - -PUBLIC void NET_DeleteCookie(char* cookieURL); -PUBLIC void NET_DisplayCookieInfoAsHTML(MWContext * context); -PUBLIC void NET_CookieViewerReturn(); - - -/*============================================================================================ - THIS IS THE BEGINNING OF TRUST.H WHICH IDEALLY SHOULD BE A SEPERATE FILE - ============================================================================================*/ -#ifndef TRUSTLABEL_H -/* #define TRUSTLABEL_H 1 */ -#ifdef TRUST_LABELS - -/* the structure that the iterators use to pass back the processed trust label - * associated with this struct is a constructor and destructor and some methods */ -typedef struct { - short purpose; /* the purpose range encoded in bits 0-5 */ - short ID; /* the id value */ - short recipients; /* the Recipients value */ - PRBool isGeneric; /* true if this is a generic label i.e. applies to all cookies */ - PRBool isSigned; /* true if this label was signed and the signature verified */ - PRTime ExpDate; /* the expiration date in local time */ - char *signatory; /* who signed the label if it was signed */ - char *domainName; /* the applicable domain for the label */ - char *path; /* the path for the label */ - char *szTrustAuthority; /* the trust authority rating service */ - XP_List *nameList; /* the list of names of the specific cookies that this label is for */ - char *szBy; /* the by field from the PICS label */ -} TrustLabel; - -TrustLabel *TL_Construct(); -void TL_Destruct( TrustLabel *ALabel ); -void TL_ProcessForAttrib( TrustLabel *ALabel, char *szFor); -void TL_SetSignatory( TrustLabel *ALabel, char *Signatory ); -void TL_SetTrustAuthority( TrustLabel *ALabel, char *TrustAuthority ); -void TL_SetByField( TrustLabel *ALabel, char *ByField ); - -/* utility function that use TrustLabel */ -void PICS_ExtractTrustLabel( URL_Struct *URL_s, char *value ); -PRBool IsTrustLabelsEnabled(void); -PUBLIC PRBool MatchCookieToLabel2( char *TargetURL, char *CookieName, - char *CookiePath, char *CookieHost, - TrustLabel **TheLabel ); - -#endif - -#endif - - - - -#endif /* MKACCESS_H */ diff --git a/mozilla/network/protocol/http/mkhttp.c b/mozilla/network/protocol/http/mkhttp.c deleted file mode 100644 index 62f667373c6..00000000000 --- a/mozilla/network/protocol/http/mkhttp.c +++ /dev/null @@ -1,3934 +0,0 @@ - -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * state machine to speak HTTP - * - * Designed and implemented by Lou Montulli '94 - * Additions/Changes by Judson Valeski, Gagan Saksena 1997 - */ - -#if defined(CookieManagement) -/* #define TRUST_LABELS 1 */ -#endif - -#include "rosetta.h" -#include "xp.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkpadpac.h" -#include "prerror.h" -#include "net_xp_file.h" -#include "mkprefs.h" - -#include "merrors.h" - -#include "mkgeturl.h" -#include "httpurl.h" -#include "shist.h" -#include "glhist.h" -#include "mkparse.h" -#include "netstream.h" -#include "mkformat.h" -#include "mkaccess.h" -#include "cookies.h" -#include "netcache.h" -#include "mkautocf.h" -#include "secnav.h" -#include "ssl.h" -#include "jscookie.h" -#include "prefapi.h" -#include "libi18n.h" -#include "prtime.h" -#include "prmem.h" -#include "plstr.h" -#include "timing.h" - -#include "xp_error.h" - -#if defined(SMOOTH_PROGRESS) -#include "progress.h" -#endif - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int MK_REDIRECT_ATTEMPT_NOT_ALLOWED; -extern int MK_HTTP_TYPE_CONFLICT; -extern int MK_OUT_OF_MEMORY; -extern int MK_TCP_READ_ERROR; -extern int MK_TCP_WRITE_ERROR; -extern int MK_CONNECTION_REFUSED; -extern int MK_CONNECTION_TIMED_OUT; -extern int MK_UNABLE_TO_CONNECT; -extern int MK_UNABLE_TO_CONNECT_TO_PROXY; -extern int MK_UNABLE_TO_LOCATE_HOST; -extern int MK_UNABLE_TO_LOCATE_FILE; -extern int MK_UNABLE_TO_OPEN_FILE; -extern int MK_ZERO_LENGTH_FILE; -extern int MK_COMPUSERVE_AUTH_FAILED; -extern int XP_ALERT_UNKNOWN_STATUS; -extern int XP_ERRNO_EWOULDBLOCK; -extern int XP_PROGRESS_TRANSFER_DATA; -extern int XP_PROGRESS_TRYAGAIN; -extern int XP_PROGRESS_WAIT_REPLY; -extern int XP_HR_TRANSFER_INTERRUPTED; -extern int XP_TRANSFER_INTERRUPTED; -extern int XP_ERRNO_EIO; - -#ifdef TRUST_LABELS -extern void ProcessCookiesAndTrustLabels( ActiveEntry *ce ); -#endif - -#ifdef PROFILE -#pragma profile on -#endif - -#define MAX_CACHED_HTTP_CONNECTIONS 4 - -#define INTERNET_KEYWORD_METATAG "Content-keywords" - -/* the maximum size of a HTTP servers first line of response - */ -#define MAX_FIRST_LINE_SIZE 250 - -/* temporary - */ -#if defined(XP_WIN) || defined(XP_OS2) /* IBM-SAH */ -PUBLIC char *XP_AppName = 0; -PUBLIC char *XP_AppCodeName = 0; -PUBLIC char *XP_AppVersion = 0; -PUBLIC char *XP_AppLanguage = 0; -PUBLIC char *XP_AppPlatform = 0; -#else -PUBLIC CONST char *XP_AppName = 0; -PUBLIC CONST char *XP_AppCodeName = 0; -PUBLIC CONST char *XP_AppVersion = 0; -PUBLIC CONST char *XP_AppLanguage = 0; -PUBLIC CONST char *XP_AppPlatform = 0; -#endif - -PUBLIC char * FE_UsersFromField=0; /* User's name/email address not used yet */ - -PRIVATE XP_List * http_connection_list=0; -PRIVATE IdentifyMeEnum http_identification_method = DoNotIdentifyMe; -PRIVATE Bool sendRefererHeader=TRUE; - -PUBLIC const HTTP_Version DEFAULT_VERSION = ONE_POINT_ONE; -PRIVATE const char *VERSION_STRING_ONE_ONE = "HTTP/1.1"; -PRIVATE const char *VERSION_STRING_ONE_ZERO = "HTTP/1.0"; -#define VERSION_STRING_LEN 8 - -/* definitions of state for the state machine design - */ -typedef enum { - HTTP_START_CONNECT, - HTTP_FINISH_CONNECT, - HTTP_WAIT_FOR_AUTH, - HTTP_RESUME_WITH_AUTH, - HTTP_SEND_PROXY_TUNNEL_REQUEST, - HTTP_BEGIN_UPLOAD_FILE, - HTTP_SEND_REQUEST, - HTTP_SEND_POST_DATA, - HTTP_PARSE_FIRST_LINE, - HTTP_PARSE_MIME_HEADERS, - HTTP_SETUP_STREAM, - HTTP_BEGIN_PUSH_PARTIAL_CACHE_FILE, - HTTP_PUSH_PARTIAL_CACHE_FILE, - HTTP_PULL_DATA, - HTTP_DONE, - HTTP_ERROR_DONE, - HG93634 - HTTP_FREE -} StatesEnum; - -/* structure to hold data about a tcp connection - * to a news host - */ -typedef struct _HTTPConnection { - char *hostname; /* hostname string (may contain :port) */ - PRFileDesc *sock; /* socket */ - XP_Bool busy; /* is the connection in use already? */ - XP_Bool prev_cache; /* did this connection come from the cache? */ - XP_Bool secure; /* is it a secure connection? */ - XP_Bool doNotSendConHdr; -} HTTPConnection; - -/* structure to hold data pertaining to the active state of - * a transfer in progress. - * - */ -typedef struct _HTTPConData { - StatesEnum next_state; /* the next state or action to be taken */ - char * proxy_server; /* name of proxy server if any */ - char * proxy_conf; /* proxy config ptr from proxy autoconfig */ - char * line_buffer; /* temporary string storage */ - char * server_headers; /* headers from the server for - * the proxy client */ - char * orig_host; /* if the host gets modified - * for my "netscape" -> "www.netscape.com" - * hack, the original host gets put here */ - XP_File partial_cache_fp; - int32 partial_needed; /* the part missing from the cache */ - - int32 total_size_of_files_to_post; - int32 total_amt_written; - - int32 line_buffer_size; /* current size of the line buffer */ - - HTTPConnection *connection; /* struct to hold info about connection */ - - NET_StreamClass * stream; /* The output stream */ - Bool pause_for_read; /* Pause now for next read? */ - Bool send_http1; /* should we send http/1.1? */ - Bool acting_as_proxy; /* are we acting as a proxy? */ - Bool server_busy_retry; /* should we retry the get? */ - Bool posting; /* are we posting? */ - Bool doing_redirect; /* are we redirecting? */ - Bool save_redirect_method; /* don't change METHOD when redirecting */ - Bool sent_authorization; /* did we send auth with the request? */ - Bool sent_proxy_auth; /* did we send proxy auth with the req? */ - Bool authorization_required; /* did we get a 401 auth return code? */ - Bool proxy_auth_required; /* did we get a 407 auth return code? */ - Bool destroy_graph_progress; /* destroy graph progress? */ - Bool destroy_file_upload_progress_dialog; - HTTP_Version protocol_version; /* .9 1.0 or 1.1 */ - int32 original_content_length; /* the content length at the time of - * calling graph progress */ - TCP_ConData *tcp_con_data; /* Data pointer for tcp connect state machine */ - Bool use_proxy_tunnel; /* should we use a proxy tunnel? */ - Bool proxy_tunnel_setup_done; /* is setup done */ - Bool use_copy_from_cache; /* did we get a 304? */ - Bool displayed_some_data; /* have we displayed any data? */ - Bool save_connection; /* save this connection for reuse? */ - Bool partial_cache_file; - Bool reuse_stream; - Bool connection_is_valid; -#ifdef XP_WIN - Bool calling_netlib_all_the_time; /* is SetCallNetlibAllTheTime set? */ -#endif - void *write_post_data_data; /* a data object - * for the WritePostData function */ -} HTTPConData; - - -#if 0 -/* macro's to simplify variable names */ -#define cd->proxy_conf cd->proxy_conf -#define cd->line_buffer cd->line_buffer -#define cd->server_headers cd->server_headers -#define cd->line_buffer_size cd->line_buffer_size -#define cd->stream cd->stream -#define cd->send_http1 cd->send_http1 -#define cd->acting_as_proxy cd->acting_as_proxy -#define cd->server_busy_retry cd->server_busy_retry -#define cd->posting cd->posting -#define cd->doing_redirect cd->doing_redirect -#define cd->sent_authorization cd->sent_authorization -#define cd->sent_proxy_auth cd->sent_proxy_auth -#define cd->authorization_required cd->authorization_required -#define cd->proxy_auth_required cd->proxy_auth_required -#define cd->destroy_graph_progress cd->destroy_graph_progress -#define cd->original_content_length cd->original_content_length -#define cd->tcp_con_data cd->tcp_con_data -#define cd->use_copy_from_cache cd->use_copy_from_cache -#define cd->displayed_some_data cd->displayed_some_data -#define ce->socket ce->socket -#define ce->con_sock ce->con_sock -#define ce->bytes_received ce->bytes_received - -#endif - -#define CD_USE_PROXY_TUNNEL cd->use_proxy_tunnel -#define CD_PROXY_TUNNEL_SETUP_DONE cd->proxy_tunnel_setup_done -#define CD_PAUSE_FOR_READ cd->pause_for_read -#define CD_NEXT_STATE cd->next_state -#define CD_PROXY_SERVER cd->proxy_server -#define CE_URL_S ce->URL_s -#define CE_STATUS ce->status -#define CE_WINDOW_ID ce->window_id -#define CE_FORMAT_OUT ce->format_out - - -/* forward decl */ -PRIVATE int32 net_ProcessHTTP (ActiveEntry *ce); - -/* - * replace - * return(ce->status) - * with - * RETURN_ce->status - */ -PRIVATE -int ReturnErrorStatus (int status) -{ - if (status < 0) - status |= status; /* set a breakpoint HERE to find errors */ - return status; -} - -#define STATUS(Status) ReturnErrorStatus (Status) - -#define PUTBLOCK(b, l) (*cd->stream->put_block) \ - (cd->stream, b, l) -#define PUTSTRING(s) (*cd->stream->put_block) \ - (cd->stream, s, PL_strlen(s)) -#define COMPLETE_STREAM (*cd->stream->complete) \ - (cd->stream) -#define ABORT_STREAM(s) (*cd->stream->abort) \ - (cd->stream, s) - - -PUBLIC void -NET_SetSendRefererHeader(Bool b) { - sendRefererHeader=b; -} - -/* set the method that the user wishes to identify themselves - * with. - * Default is DoNotIdentify unless this is called at startup - */ -PUBLIC void -NET_SetIdentifyMeType(IdentifyMeEnum method) { - http_identification_method = method; -} - -/* Build a string containing the internet keyword extracted from a URL struct. - inURL is the raw data containing the data - outKeyword is where the return value will be built. It will be a - null-terminated string (of 0 length of there is no keyword(s)). - inMaxLength is the size of outKeyword. -*/ -PUBLIC void -NET_getInternetKeyword(const URL_Struct *inURL, char *outKeyword, int16 inMaxLength) { - - uint ctr, - endIndex = inURL->all_headers.empty_index; - Bool doCopy; - char nextChar, - *key, - *header, - *keyEnd = outKeyword+(inMaxLength-1); - - outKeyword[0] = 0; - if (inMaxLength <= 0) - return; - - key = outKeyword; - for (ctr = 0; ctr < inURL->all_headers.empty_index; ctr++) - if (PL_strcasecmp(inURL->all_headers.key[ctr], INTERNET_KEYWORD_METATAG) == 0) { - /* add a separator, if appropriate */ - if (key > outKeyword) - if (key < keyEnd-1) { - *key++ = ';'; - *key++ = ' '; - } - - /* append value, stripping modifiers */ - header = inURL->all_headers.value[ctr]; - doCopy = TRUE; - while (key < keyEnd && (nextChar = *header++) != 0) { - if (nextChar == ',') /* modifiers follow */ - doCopy = FALSE; - else if (nextChar == ';') /* additional keywords follow */ - doCopy = TRUE; - if (doCopy) - *key++ = nextChar; - } - } - *key = 0; -} - -/* look for names like "ford" and "netscape" - * and turn them into "www.ford.com" and "www.netscape.com" - * If goBrowsing is enabled, this feature is turned off and the browser - * asks the search provider to resolve the word into a url. This is - * is prevent a kid typing in bambi (looking for the deer) from being - * taken to a porn site. - * returns 0 if found and replaced - */ - -PRIVATE int -net_check_for_company_hostname(ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - Bool add_www = FALSE; - Bool add_com = FALSE; - PRBool goBrowsing = FALSE; - - if (PREF_GetBoolPref(pref_goBrowsingEnabled, &goBrowsing) != PREF_OK) goBrowsing = 0; - - if(!cd->orig_host) { - char *dot=NULL; - - /* if the hostname doesn't have any - * dots in it, then assume it's of - * the form "netscape" or "ford". - * If we add www. and .com to the front - * and end we will get www.netscape.com :) - */ - char * host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - - if(host && *host && !(dot = PL_strchr(host, '.'))) { - add_www = add_com = TRUE; - - } else if(dot && !PL_strchr(dot+1, '.')) { - /* there is only one dot in the host name - * so it's probably of the form of "netscape.com" - * or "ukans.edu". Add a "www." on the front - * and try again. - */ - add_www = TRUE; - } - - PR_FREEIF(host); - host = NULL; - - if(add_www) { - /* no dots in hostname */ - if (goBrowsing && !PL_strchr(ce->URL_s->address, '/')) { - char *pUrl; - if ( (PREF_OK == PREF_CopyCharPref(pref_searchUrl,&pUrl)) - && pUrl) { - char *tmp = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - char* new_address = PR_smprintf("%sgo+%s", pUrl, tmp); - PR_Free(pUrl); - PR_Free(ce->URL_s->address); - PR_FREEIF(tmp); - ce->URL_s->address = new_address; - - if(cd->connection->sock != NULL) - NET_TotalNumberOfOpenConnections--; - return (0); - } else { - return (-1); - } - } else { - - char *new_address = NET_ParseURL(ce->URL_s->address, - GET_PROTOCOL_PART); - char *tmp = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - - /* save the host for error messages */ - cd->orig_host = tmp; - - StrAllocCat(new_address, "//www."); - StrAllocCat(new_address, tmp); - - if(add_com) - StrAllocCat(new_address, ".com"); - - tmp = NET_ParseURL(ce->URL_s->address, - GET_PATH_PART | GET_SEARCH_PART | GET_HASH_PART); - - StrAllocCat(new_address, tmp); - PR_FREEIF(tmp); - - PR_Free(ce->URL_s->address); - ce->URL_s->address = new_address; - - if(cd->connection->sock != NULL) - NET_TotalNumberOfOpenConnections--; - - return(0); /* will repeat this step */ - } - } - } else { - /* the host mapping trick has already been applied and failed - * redo the error message and fail - */ - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_UNABLE_TO_LOCATE_HOST, - cd->orig_host); - /* fall through for failure case */ - } - - return(-1); -} - -/* begins the connect process - * - * returns the TCP status code - */ -PRIVATE int -net_start_http_connect(ActiveEntry * ce) { - HTTPConData * cd = (HTTPConData *)ce->con_data; - HG29898 - int def_port; - - def_port = DEF_HTTP_PORT; - - HG22201 - - /* if proxy_server is non NULL then use the string as a host:port - * when a proxy server is used a connection is made to the proxy - * host and port and the entire URL is sent instead of just - * the path part. - */ - if(cd->proxy_server) { - /* MKConnect can take a URL or a host name as it's first - * argument - */ - ce->status = NET_BeginConnect (cd->proxy_server, - NULL, - "HTTP", - def_port, - &cd->connection->sock, - HG38738 - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - } else { - ce->status = NET_BeginConnect (ce->URL_s->address, - ce->URL_s->IPAddressString, - "HTTP", - def_port, - &cd->connection->sock, - HG02873 - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - } - - /* set this so mkgeturl can select on it */ - ce->socket = cd->connection->sock; - - if(cd->connection->sock != NULL) - NET_TotalNumberOfOpenConnections++; - - if (ce->status < 0) { - if(ce->status == MK_UNABLE_TO_LOCATE_HOST - && 0 == net_check_for_company_hostname(ce)) - { - /* no need to set the state since this - * is the state we want again - */ - if(cd->connection->sock != NULL) { - PR_Close(cd->connection->sock); - cd->connection->sock = NULL; - ce->socket = NULL; - } - return(0); - } - - TRACEMSG(("HTTP: Unable to connect to host for `%s' (errno = %d).", - ce->URL_s->address, PR_GetOSError())); - /* - * Proxy failover - */ - if (cd->proxy_conf && cd->proxy_server && - (ce->status == MK_UNABLE_TO_CONNECT || - ce->status == MK_CONNECTION_TIMED_OUT || - ce->status == MK_CONNECTION_REFUSED || - ce->status == MK_UNABLE_TO_LOCATE_HOST) - ){ -#ifdef MOZILLA_CLIENT - if (pacf_get_proxy_addr(ce->window_id, cd->proxy_conf, - &ce->proxy_addr, - &ce->socks_host, - &ce->socks_port)) - { - cd->proxy_server = ce->proxy_addr; - return net_start_http_connect(ce); - } -#endif /* MOZILLA_CLIENT */ - } - - if(ce->status == MK_UNABLE_TO_CONNECT && cd->proxy_server) - { - StrAllocCopy (ce->URL_s->error_msg, - XP_GetString(MK_UNABLE_TO_CONNECT_TO_PROXY)); - ce->status = MK_UNABLE_TO_CONNECT_TO_PROXY; - } - - cd->next_state = HTTP_ERROR_DONE; - return STATUS(ce->status); - } /* end status < 0 */ - - if(ce->status == MK_CONNECTED) { - if(cd->use_proxy_tunnel) - cd->next_state = HTTP_SEND_PROXY_TUNNEL_REQUEST; - else if(ce->URL_s->files_to_post) - cd->next_state = HTTP_BEGIN_UPLOAD_FILE; - else { - HG56817 - cd->next_state = HTTP_SEND_REQUEST; - } - TRACEMSG(("Connected to HTTP server on sock #%d",cd->connection->sock)); - NET_SetReadSelect(ce->window_id, cd->connection->sock); - - } else { - cd->next_state = HTTP_FINISH_CONNECT; - cd->pause_for_read = TRUE; - ce->con_sock = cd->connection->sock; /* set the socket for select */ - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - - return STATUS(ce->status); -} - -/* begins the connect process - * - * returns the TCP status code - */ -PRIVATE int -net_finish_http_connect(ActiveEntry * ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - int def_port; - - def_port = DEF_HTTP_PORT; - HG92892 - - /* if proxy_server is non NULL then use the string as a host:port - * when a proxy server is used a connection is made to the proxy - * host and port and the entire URL is sent instead of just - * the path part. - */ - if(cd->proxy_server) { - /* MKConnect can take a URL or a host name as it's first - * argument - */ - ce->status = NET_FinishConnect(cd->proxy_server, - "HTTP", - def_port, - &cd->connection->sock, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - } else { - ce->status = NET_FinishConnect(ce->URL_s->address, - "HTTP", - def_port, - &cd->connection->sock, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - } - - if (ce->status < 0) { - if(ce->status == MK_UNABLE_TO_LOCATE_HOST - && 0 == net_check_for_company_hostname(ce)) - { - if(cd->connection->sock != NULL) { - NET_ClearConnectSelect(ce->window_id, cd->connection->sock); - PR_Close(cd->connection->sock); - cd->connection->sock = NULL; - ce->socket = NULL; - ce->con_sock = NULL; - } - cd->next_state = HTTP_START_CONNECT; - return(0); - } - - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - TRACEMSG(("HTTP: Unable to connect to host for `%s' (errno = %d).", - ce->URL_s->address, PR_GetOSError())); - - /* - * Proxy failover - */ - if (cd->proxy_conf && cd->proxy_server && - (ce->status == MK_UNABLE_TO_CONNECT || - ce->status == MK_CONNECTION_TIMED_OUT || - ce->status == MK_CONNECTION_REFUSED || - ce->status == MK_UNABLE_TO_LOCATE_HOST)) - { -#ifdef MOZILLA_CLIENT - if (pacf_get_proxy_addr(ce->window_id, cd->proxy_conf, - &ce->proxy_addr, - &ce->socks_host, - &ce->socks_port)) - { - cd->proxy_server = ce->proxy_addr; - return net_start_http_connect(ce); - } -#endif /* MOZILLA_CLIENT */ - } - - /* proxy autodiscovery failover needs to be silent. If we were trying to - * connect to a pad server and failed, don't report errors, just go on - * about your business. */ - if(NET_LoadingPac() && NET_UsingPadPac() ) { - /* Don't try to use the pad pac again. */ - net_UsePadPac(FALSE); - cd->next_state=HTTP_DONE; - ce->status=0; - return STATUS(ce->status); - } - - if(ce->status == MK_UNABLE_TO_CONNECT && cd->proxy_server) - { - StrAllocCopy (ce->URL_s->error_msg, - XP_GetString(MK_UNABLE_TO_CONNECT_TO_PROXY)); - ce->status = MK_UNABLE_TO_CONNECT_TO_PROXY; - } - - cd->next_state = HTTP_ERROR_DONE; - return STATUS(ce->status); - } /* end status < 0 */ - - if(ce->status == MK_CONNECTED) { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = NULL; /* reset the socket so we don't select on it */ - /* set this so mkgeturl can select on it */ - ce->socket = cd->connection->sock; - if(cd->use_proxy_tunnel) - cd->next_state = HTTP_SEND_PROXY_TUNNEL_REQUEST; - else if(ce->URL_s->files_to_post) - cd->next_state = HTTP_BEGIN_UPLOAD_FILE; - else { - HG43241 - cd->next_state = HTTP_SEND_REQUEST; - } - NET_SetReadSelect(ce->window_id, cd->connection->sock); - TRACEMSG(("Connected to HTTP server on sock #%d",cd->connection->sock)); - } else { - /* unregister the old ce->socket from the select list - * and register the new value in the case that it changes - */ - if(ce->con_sock != cd->connection->sock) { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = cd->connection->sock; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - - cd->pause_for_read = TRUE; - } - - return STATUS(ce->status); -} - -PRIVATE int -net_send_proxy_tunnel_request (ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - char *host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - char *command=0; - char *auth = NULL; - const char *ver = VERSION_STRING_ONE_ONE; - - StrAllocCopy(command, "CONNECT "); - StrAllocCat(command, host); - - if(!PL_strchr(host, ':')) - { - char small_buf[20]; - sprintf(small_buf, ":%d", DEF_HTTPS_PORT); - StrAllocCat(command, small_buf); - } - - if (ONE_POINT_ONE != DEFAULT_VERSION) - ver = VERSION_STRING_ONE_ZERO; - - sprintf(command, "%c%s%c", ' ', ver, '\n'); - - /* - * Check if proxy is requiring authorization. - * If NULL, not necessary, or the proxy will return 407 to - * require authorization. - * - */ - if (NULL != (auth=NET_BuildProxyAuthString(ce->window_id, - ce->URL_s, - cd->proxy_server))) - { - char *line = (char *)PR_Malloc(strlen(auth) + 30); - if (line) { - sprintf(line, "Proxy-authorization: %s%c%c", auth, CR, LF); - StrAllocCat(command, line); - PR_Free(line); - } - cd->sent_proxy_auth = TRUE; - TRACEMSG(("HTTP: Sending proxy-authorization: %s", auth)); - } - else - { - TRACEMSG(("HTTP: Not sending proxy authorization (yet)")); - } - - { - char line[200]; - sprintf(line, "User-Agent: %.100s/%.90s" CRLF CRLF, - XP_AppCodeName, XP_AppVersion); - StrAllocCat(command, line); - } - - TRACEMSG(("Tx: %s", command)); - - SSL_SetSockPeerID(cd->connection->sock, command); - ce->status = NET_HTTPNetWrite(cd->connection->sock, command, PL_strlen(command)); - - PR_Free(command); - - cd->pause_for_read = TRUE; - - cd->next_state = HTTP_PARSE_FIRST_LINE; - - return(ce->status); -} - -#define POST_DATA_BUFFER_SIZE 2048 - -PRIVATE int32 -net_get_size_with_crlf( char *filename, XP_FileType file_type, XP_Bool add_crlf ) -{ - XP_File xpfileptr; - uint32 return_value = 0; - int line_length; - char *line; - char *buffer; - - if (!add_crlf) - { - /* Don't need to make any cr/lf adjustment, just stat the file and - return the size. */ - - XP_StatStruct stat_entry; - if(-1 == NET_XP_Stat(filename, &stat_entry, file_type)) - return -1; - else - return stat_entry.st_size; - } - - xpfileptr = NET_XP_FileOpen( filename, file_type, XP_FILE_READ ); - if (!xpfileptr) - return -1; - - buffer = (char *) PR_Malloc(POST_DATA_BUFFER_SIZE); - if (!buffer) - return -1; - - do { - line = NET_XP_FileReadLine(buffer, POST_DATA_BUFFER_SIZE-5, xpfileptr); - if (!line) - break; - - line_length = PL_strlen(line); - - if (line_length > 1 && line[line_length-2] == CR && line[line_length-1] == LF) - { - /* already ok */ - } - else if(line_length > 0 && (line[line_length-1] == LF || line[line_length-1] == CR)) - { - /* increment to account for missing CR or missing LF */ - line_length++; - } - - return_value += line_length; - } while (line); - - PR_Free( buffer ); - - return return_value; -} - -/* begin sending a file - */ -PRIVATE int -net_begin_upload_file (ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *) ce->con_data; - char * filename; - char * file_to_post; - char * header=0; - char * last_slash; - char * status_msg; - int i; - int32 adjusted_file_size = -1; - - if(ce->URL_s->server_status == 401) - { - /* retrying with auth, don't change the filename */ - cd->next_state = HTTP_SEND_REQUEST; - return(0); - } - - PR_ASSERT(ce->URL_s->files_to_post && ce->URL_s->files_to_post[0]); - if(!ce->URL_s->files_to_post || !ce->URL_s->files_to_post[0]) - return MK_UNABLE_TO_LOCATE_FILE; - - /* get a filename from the files_to_post array - */ - for(i=0; ce->URL_s->files_to_post[i]; i++) - ; /* find the end */ - - PR_ASSERT(i>0); - - file_to_post = ce->URL_s->files_to_post[i-1]; - - /* zero the file now so that we don't upload it again. */ - ce->URL_s->files_to_post[i-1] = NULL; - -#ifdef XP_MAC - filename = PL_strrchr(file_to_post, '/'); -#elif defined(XP_WIN) - filename = PL_strrchr(file_to_post, '\\'); -#else - filename = PL_strrchr(file_to_post, '/'); -#endif - - if(!filename) - filename = file_to_post; - else - filename++; /* go past delimiter */ - - /* get the size of the file adjusting for crlf conversion */ - adjusted_file_size = net_get_size_with_crlf(file_to_post, xpFileToPost, ce->URL_s->add_crlf ? ce->URL_s->add_crlf[i-1] : FALSE); - if (-1 == adjusted_file_size) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_LOCATE_FILE, file_to_post); - PR_Free(file_to_post); - return MK_UNABLE_TO_LOCATE_FILE; - } - - status_msg = PR_smprintf("Uploading file %s", filename); - if(status_msg) - { -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, status_msg); -#else - NET_Progress(ce->window_id, status_msg); -#endif - PR_Free(status_msg); - } - -/*#ifdef EDITOR - FE_SaveDialogSetFilename(ce->window_id, filename); -#endif */ /* EDITOR */ - - header = PR_smprintf("Content-Length: %ld" CRLF CRLF, adjusted_file_size); - - - PR_FREEIF(ce->URL_s->post_headers); - /* if header is null this won't crash */ - ce->URL_s->post_headers = header; - - /* If the destination URL is explicitly specified in the post_to array, use it, otherwise - * generate destination from URL_s->address and filename. hardts */ - if (ce->URL_s->post_to && ce->URL_s->post_to[i - 1]) { - PR_Free(ce->URL_s->address); /* We don't use it at all. */ - ce->URL_s->address = ce->URL_s->post_to[i - 1]; - ce->URL_s->post_to[i - 1] = NULL; /* zero the element */ - } - else { - /* strip the filename from the last slash and append the - * new filename to the URL - */ - last_slash = PL_strrchr(ce->URL_s->address, '/'); - if(last_slash) - *last_slash = '\0'; - StrAllocCat(ce->URL_s->address, "/"); - StrAllocCat(ce->URL_s->address, filename); - } - -#ifdef EDITOR - { - /* Strip out username and password. from address */ - char *pLocation = NULL; - if (!NET_ParseUploadURL( ce->URL_s->address, &pLocation, NULL,NULL )) { - PR_ASSERT(0); - } - if (CLEAR_CACHE_BIT(ce->format_out) != FO_LOCATION_INDEPENDENCE) - FE_SaveDialogSetFilename(ce->window_id, pLocation); - PR_Free(pLocation); - } -#endif /* EDITOR */ - - /* make the method PUT */ - ce->URL_s->method = URL_PUT_METHOD; - - /* specify the file to be uploaded */ - StrAllocCopy(ce->URL_s->post_data, file_to_post); - - /* specify that the post data is a file */ - ce->URL_s->post_data_is_file = TRUE; - - /* do the request */ - cd->next_state = HTTP_SEND_REQUEST; - - PR_Free(file_to_post); - - return(0); -} - -/* build the HTTP request. - * - * mallocs a big string that must be free'd - * returns the string - */ -PRIVATE unsigned int -net_build_http_request (URL_Struct * URL_s, - FO_Present_Types format_out, - HTTPConData *cd, - MWContext *window_id, - char ** command) -{ - - Bool http1=cd->send_http1; - char *proxy_server=(cd->use_proxy_tunnel ? NULL : cd->proxy_server); - Bool posting=cd->posting; - - char line_buffer[4096]; /* buffer */ - char *auth; /* authorization header string */ - size_t csize; /* size of command */ - const char *tempURL=NULL; - char *proxyServer=NULL; - int tmpSize = 0; - - /* begin the request */ - switch(URL_s->method) { - case URL_MKDIR_METHOD: -#define MKDIR_WORD "MKDIR " - BlockAllocCopy(*command, MKDIR_WORD, 5); - csize = sizeof(MKDIR_WORD)-1; - break; - - case URL_DELETE_METHOD: -#define DELETE_WORD "DELETE " -#define RMDIR_WORD "RMDIR " - if(URL_s->is_directory) { - BlockAllocCopy(*command, RMDIR_WORD, 6); - csize = sizeof(RMDIR_WORD)-1; - } else { - BlockAllocCopy(*command, DELETE_WORD, 7); - csize = sizeof(DELETE_WORD)-1; - } - break; - - case URL_POST_METHOD: -#define POST_WORD "POST " - BlockAllocCopy(*command, POST_WORD, 5); - csize = sizeof(POST_WORD)-1; - break; - - case URL_PUT_METHOD: -#define PUT_WORD "PUT " - BlockAllocCopy(*command, PUT_WORD, 4); - csize = sizeof(PUT_WORD)-1; - break; - - case URL_HEAD_METHOD: -#define HEAD_WORD "HEAD " - BlockAllocCopy(*command, HEAD_WORD, 5); - csize = sizeof(HEAD_WORD)-1; - break; - - case URL_INDEX_METHOD: -#define INDEX_WORD "INDEX " - BlockAllocCopy(*command, INDEX_WORD, 6); - csize = sizeof(INDEX_WORD)-1; - break; - - case URL_MOVE_METHOD: -#define MOVE_WORD "MOVE " - BlockAllocCopy(*command, MOVE_WORD, 5); - csize = sizeof(MOVE_WORD)-1; - break; - - case URL_COPY_METHOD: -#define COPY_WORD "COPY " - BlockAllocCopy(*command, COPY_WORD, 5); - csize = sizeof(COPY_WORD)-1; - break; - - default: - PR_ASSERT(0); - /* fall through to GET */ - - case URL_GET_METHOD: -#define GET_WORD "GET " - BlockAllocCopy(*command, GET_WORD, 4); - csize = sizeof(GET_WORD)-1; - break; - - case URL_GETPROPERTIES_METHOD: -#define GETPROPERTIES_WORD "GETPROPERTIES " - BlockAllocCopy(*command, GETPROPERTIES_WORD, 14); - csize = sizeof(GETPROPERTIES_WORD)-1; - break; - } /* End method switch */ - - - /* if we are using a proxy gateway copy in the entire URL - * minus the hash mark */ - if(proxy_server) { - - char *url_minus_hash = NET_ParseURL(URL_s->address, - GET_PROTOCOL_PART - | GET_USERNAME_PART - | GET_PASSWORD_PART - | GET_HOST_PART - | GET_PATH_PART - | GET_SEARCH_PART); - - if(url_minus_hash) { - tmpSize = PL_strlen(url_minus_hash); - BlockAllocCat(*command, (size_t) csize, url_minus_hash, tmpSize); - csize += tmpSize; - PR_Free(url_minus_hash); - } - - } else { - /* else use just the path and search stuff */ - char *path = NET_ParseURL(URL_s->address, GET_PATH_PART | GET_SEARCH_PART); - tmpSize = PL_strlen(path); - BlockAllocCat(*command, csize, path, tmpSize); - csize += tmpSize; - PR_Free(path); - } - - if(http1) { - const char *ver = VERSION_STRING_ONE_ONE; - if (ONE_POINT_ONE != DEFAULT_VERSION) - ver = VERSION_STRING_ONE_ZERO; - BlockAllocCat(*command, csize, " ", 1); - csize += 1; - PR_ASSERT(VERSION_STRING_LEN == PL_strlen(ver)); - BlockAllocCat(*command, csize, ver, VERSION_STRING_LEN); - csize += VERSION_STRING_LEN; - /* finish the line */ - BlockAllocCat(*command, csize, CRLF, 2); /* CR LF, as in rfc 977 */ - csize += 2; - - if ((URL_s->etag) && (URL_s->force_reload != NET_SUPER_RELOAD)) - { - /* add the If-None-Match header */ - PL_strcpy(line_buffer, "If-None-Match: \""); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, - line_buffer, tmpSize); - csize += tmpSize; - tmpSize = PL_strlen(URL_s->etag); - BlockAllocCat(*command, csize, - URL_s->etag, - tmpSize); - csize += tmpSize; - /* Closing " */ - BlockAllocCat(*command, csize, - "\"", - 1); - csize += 1; - BlockAllocCat(*command, csize, CRLF, 2); - csize += 2; - } - - if(URL_s->last_modified && URL_s->force_reload != NET_SUPER_RELOAD) - { - /* add if modified since - * - * right now this is being added even if the server sent pragma: no-cache - * I'm not sure if this is the right thing to do but it seems - * very efficient since we can still use the cache. - */ - - /* add tmp character storage for strings in order for assert - * to work properly in debug compile. - * IBM compiler does not put "\" to make " work properly. - */ -#ifndef AIX - char *tmp_str = "http"; -#endif - { - /* A conversion from time_t to NSPR's int64 is needed in order to - * use the NSPR time functions. URL_Struct should really be changed - * to use the NSPR time type instead of time_t. - */ - - PRTime timeInSec; - PRTime timeInUSec; - PRTime secToUSec; - PRExplodedTime expandedTime; - - LL_I2L(timeInSec, URL_s->last_modified); - LL_I2L(secToUSec, PR_USEC_PER_SEC); - LL_MUL(timeInUSec, timeInSec, secToUSec); - - PR_ExplodeTime(timeInUSec, PR_GMTParameters, &expandedTime); - - PR_FormatTimeUSEnglish(line_buffer, 400, - "If-Modified-Since: %a, %d %b %Y %H:%M:%S GMT", - &expandedTime); - } - - /* must not be zero for http URL's - * or else I screwed up the cache logic - */ -#ifndef AIX - PR_ASSERT(PL_strncasecmp(URL_s->address, tmp_str, 4) - || URL_s->real_content_length > 0); -#endif - - if(URL_s->real_content_length) - sprintf(&line_buffer[PL_strlen(line_buffer)], - "; length=%ld" CRLF, - URL_s->real_content_length); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - - /* reset the expires since we will want to - * either get a new one from the server or - * set it to zero - */ - URL_s->expires = 0; - } /* end if last_modified */ - - if(URL_s->http_headers) { /* use headers that were passed in */ - tmpSize = PL_strlen(URL_s->http_headers); - BlockAllocCat(*command, csize, URL_s->http_headers, tmpSize); - csize += tmpSize; - - } else { - - /* For MOVE method. This contains the destination uri name */ - int meth=URL_s->method; - if(URL_s->destination - && (*(URL_s->destination) != '\0') - && ( (meth == URL_MOVE_METHOD) - || (meth == URL_COPY_METHOD) ) - ){ - if(meth == URL_MOVE_METHOD) { - sprintf(line_buffer, "New-uri: %s", URL_s->destination); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize+=tmpSize; - } else if(meth == URL_COPY_METHOD) { - ;/* some http copy syntax */ - } - - BlockAllocCat(*command, csize, CRLF, 2); - csize += 2; - } - /* sendRefererHeader is set in NET_SetSendRefererHeaderPref in mkhttp.c. - This condition is set via a javascript pref and was implemented to - settle some privacy/security issue */ - /* NET_SupressRefererForAnonymity is true on the first call after entering - or leaving anonymous mode and false all other times. Note that this - function has a side effect of changing its own state (so that future - calls to it return false until another mode change occurs). For this - reason it must appear first in the if-statement below to make sure it - gets called even if sendReferHeader is false */ - if(!NET_SupressRefererForAnonymity(window_id) && sendRefererHeader) - { - int url_type = NET_URL_Type(URL_s->referer); - char *newReferer=NULL; - /* Don't allow these url types to send the referer field. */ - if(URL_s->referer - && url_type != MAILBOX_TYPE_URL - && url_type != IMAP_TYPE_URL - && url_type != FILE_TYPE_URL) - { - char *colon=NULL, *refToSend=NULL; - TRACEMSG(("Sending referer field")); - PL_strcpy(line_buffer, "Referer: "); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - - /* The URL_s->referer can contain a username and password as it draws - * this data from the session history. The session history can contain - * the username and password if the user types them into the location - * field, like so: http://username:password@www.here.com. We strip out - * the username and password here so this info isn't revealed in the - * referer header. */ - - colon=PL_strchr(URL_s->referer, ':'); - if(colon - && *(colon+1) == '/' - && *(colon+2) == '/' - && *(colon+3) != '\0') - { - char *atSign=NULL; - char *path=NULL; - - if( (path=PL_strchr(colon+3, '/')) != 0) - *path='\0'; - if( (atSign=PL_strchr(colon, '@')) != 0) { - /* We found a username and/or a password, don't let it through */ - char temp; - if(path) - *path='/'; - /* Get the protocol part. */ - temp=*(colon+3); - *(colon+3)='\0'; - StrAllocCopy(newReferer, URL_s->referer); - *(colon+3)=temp; - - /* Get the host part. */ - *atSign='\0'; - StrAllocCat(newReferer, atSign+1); - *atSign='@'; - } - if(path) - *path='/'; - } /* End colon */ - - refToSend= newReferer ? newReferer : URL_s->referer; - tmpSize = PL_strlen(refToSend); - BlockAllocCat(*command, csize, refToSend, tmpSize); - csize += tmpSize; - BlockAllocCat(*command, csize, CRLF, 2); - csize += 2; - PR_FREEIF(newReferer); - } /* end URL_s->refrerer */ - } /* end supress */ - - assert (XP_AppCodeName); - assert (XP_AppVersion); - - if(!(cd->connection->doNotSendConHdr)) { - if(proxy_server) - PL_strcpy(line_buffer, "Proxy-Connection: Keep-Alive" CRLF); - else - PL_strcpy(line_buffer, "Connection: Keep-Alive" CRLF); - } - - sprintf (&line_buffer[PL_strlen(line_buffer)], - "User-Agent: %.100s/%.90s" CRLF, - XP_AppCodeName, XP_AppVersion); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - - if(URL_s->force_reload) { - BlockAllocCat(*command, csize, "Pragma: no-cache" CRLF, 18); - csize += 18; - } - - if(URL_s->range_header) { -#ifndef AIX - char *tmp_str = CRLF; - PR_ASSERT(!PL_strstr(URL_s->range_header, tmp_str)); -#endif -#define REQUEST_RANGE_HEADER "Range: " - tmpSize = PL_strlen(REQUEST_RANGE_HEADER); - BlockAllocCat(*command, csize, - REQUEST_RANGE_HEADER, - tmpSize); - csize += tmpSize; - tmpSize = PL_strlen(URL_s->range_header); - BlockAllocCat(*command, csize, - URL_s->range_header, - tmpSize); - csize += tmpSize; - BlockAllocCat(*command, csize, - CRLF, 2); - csize += 2; - } /* end url_s->range_header */ - -#define OLD_RANGE_SUPPORT -#ifdef OLD_RANGE_SUPPORT - /* this is here for backwards compatibility with - * the old range spec - * It should be removed before final beta 2 - */ - if(URL_s->range_header) { -#ifndef AIX - char *tmp_str = CRLF; - PR_ASSERT(!PL_strstr(URL_s->range_header, tmp_str)); -#endif -#undef REQUEST_RANGE_HEADER -#define REQUEST_RANGE_HEADER "Request-Range: " - tmpSize = PL_strlen(REQUEST_RANGE_HEADER); - BlockAllocCat(*command, csize, - REQUEST_RANGE_HEADER, - tmpSize); - csize += tmpSize; - tmpSize = PL_strlen(URL_s->range_header); - BlockAllocCat(*command, csize, - URL_s->range_header, - tmpSize); - csize += tmpSize; - BlockAllocCat(*command, csize, - CRLF, 2); - csize += 2; - } /* end url_s->range_header */ -#endif - - if(1) { - char * host = NET_ParseURL(URL_s->address, GET_HOST_PART); - - if(host) { - -#define HOST_HEADER "Host: " - BlockAllocCat(*command, - csize, - HOST_HEADER, - sizeof(HOST_HEADER)-1); - csize += sizeof(HOST_HEADER)-1; - tmpSize = PL_strlen(host); - BlockAllocCat(*command, csize, host, tmpSize); - - csize += tmpSize; - - PR_Free(host); - - BlockAllocCat(*command, csize, CRLF, 2); - csize += 2; - } - } - -#ifdef SEND_FROM_FIELD - sprintf(line_buffer, "From: %.256s%c%c", - FE_UsersMailAddress() ? FE_UsersMailAddress() : "unregistered", CR,LF); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; -#endif /* SEND_FROM_FIELD */ - - if(CLEAR_CACHE_BIT(format_out) != FO_INTERNAL_IMAGE) - { - /* send Accept: *(slash)* as well as the others */ - sprintf(line_buffer, "Accept: %s, %s, %s, %s, %s, %s, */*" CRLF, - TEXT_HTML, TEXT_XML, IMAGE_PNG, IMAGE_GIF, IMAGE_JPG, IMAGE_PJPG); - } else { - sprintf(line_buffer, "Accept: %s, %s, %s, %s" CRLF, - IMAGE_PNG, IMAGE_GIF, IMAGE_JPG, IMAGE_PJPG); - } - - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - - /* add Accept-Encoding Header */ - sprintf(line_buffer, "Accept-Encoding: %s" CRLF, ENCODING_GZIP2); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - -#ifdef MOZILLA_CLIENT -#define SEND_ACCEPT_LANGUAGE 1 -#ifdef SEND_ACCEPT_LANGUAGE /* Added by ftang */ - { - char *acceptlang = INTL_GetAcceptLanguage(); - if((acceptlang != NULL) && ( *acceptlang != '\0') ) - { - sprintf(line_buffer, "Accept-Language: %s" CRLF, - acceptlang ); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - } - } -#endif /* SEND_ACCEPT_LANGUAGE */ - -#define SEND_ACCEPT_CHARSET 1 -#ifdef SEND_ACCEPT_CHARSET /* Added by bstell */ - { - char *acceptCharset = INTL_GetAcceptCharset(); - if((acceptCharset != NULL) && ( *acceptCharset != '\0') ) - { - sprintf(line_buffer, "Accept-Charset: %s" CRLF, - acceptCharset ); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - } - } -#endif /* SEND_ACCEPT_CHARSET */ -#endif /* MOZILLA_CLIENT */ - - /* - * Check if proxy is requiring authorization. - * If NULL, not necessary, or the proxy will return 407 to - * require authorization. - * - */ - /* This was hacked in because proxy auth can be required when the Auto-config url - * itself requires authorization. We used to ask for proxy auth only when the proxy was - * input directly into the prefs. Now we check to see if there's a pacurl (if there - * is, there can't be a proxy url simultaneously) use it, otherwise we're using a - * proxy from the prefs. - */ - - /* Figure out which kind of proxy we're using: PAC or straight proxy. - * DON'T FREE tempURL!!! - */ - if ( (tempURL = net_GetPACUrl()) != NULL && (*tempURL) ) - proxyServer = NET_ParseURL(tempURL, - GET_HOST_PART - | GET_PATH_PART - | GET_USERNAME_PART - | GET_PASSWORD_PART); - else - proxyServer = proxy_server; - - if (proxyServer && - NULL != (auth=NET_BuildProxyAuthString(window_id, - URL_s, - proxyServer)) - ){ - if (tempURL) - PR_Free(proxyServer); - cd->sent_proxy_auth = TRUE; - sprintf(line_buffer, "Proxy-authorization: %.3840s%c%c", auth, CR, LF); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, line_buffer, tmpSize); - csize += tmpSize; - TRACEMSG(("HTTP: Sending proxy-authorization: %s", auth)); - } else { - TRACEMSG(("HTTP: Not sending proxy authorization (yet)")); - } - - /* NET_BuildAuthString will return non-NULL if authorization is - * known to be required for this document. - * - * If NULL is returned authorization is not required or is - * not known to be required yet so we will look for a 401 - * return code later on to see if authorization will be - * neccessary - */ - if (NULL!=(auth=NET_BuildAuthString(window_id, URL_s))) - { - cd->sent_authorization = TRUE; - tmpSize = PL_strlen(auth); - BlockAllocCat(*command, csize, auth, tmpSize); - csize += tmpSize; - TRACEMSG(("HTTP: Sending authorization: %s", auth)); - } else { - TRACEMSG(("HTTP: Not sending authorization (yet)")); - } - - if (NULL!=(auth=NET_GetCookie(window_id, URL_s->address))) - { - PL_strcpy(line_buffer, "Cookie: "); - tmpSize = PL_strlen(line_buffer); - BlockAllocCat(*command, csize, - line_buffer, tmpSize); - - csize += tmpSize; - tmpSize = PL_strlen(auth); - BlockAllocCat(*command, csize, auth, tmpSize); - csize += tmpSize; - BlockAllocCat(*command, csize, CRLF, 2); - csize += 2; - TRACEMSG(("HTTP: Sending Cookie: %s", auth)); - PR_Free(auth); - } else { - TRACEMSG(("HTTP: Not sending cookie")); - } - - } /* end of if passed in headers */ - } /* end of if(http1) */ - - /* end of Get/Post request */ - - /* Blank line means "end" of headers - * If we are posting WritePostData will - * add the extra line feed for us - */ - if(!posting) { - BlockAllocCat(*command, csize, CRLF, 2); - csize += 2; - } - - return((unsigned int) csize); -} - -HG12515 - -/* send_http_request makes a connection to the http server - * and sends a request (ethier http1 or http/.9) to the server - * - * returns the TCP status code - */ -#define SOCK_CHUNK_SIZE 1024 -PRIVATE int -net_send_http_request (ActiveEntry *ce) -{ - /* assign it so that we have a typed structure pointer */ - HTTPConData * cd = (HTTPConData *)ce->con_data; - char * command=0; - unsigned int command_size; - - /* we make the assumption that we are always acting as a proxy - * server if we get http_headers passed in the URL structure. - * - * when acting as a proxy_server the clients headers are sent - * to the server instead of being generated here and the headers - * from the server are unparsed and sent on the the client. - */ - if(ce->format_out == FO_OUT_TO_PROXY_CLIENT - || ce->format_out == FO_CACHE_AND_OUT_TO_PROXY_CLIENT) - cd->acting_as_proxy=YES; - - TRACEMSG(("Entered \"send_http_request\"")); - - /* we make the assumption that we will always use the POST - * method if there is post data in the URL structure - * Is that a bad assumption? - */ - if(ce->URL_s->method == URL_POST_METHOD - || ce->URL_s->method == URL_PUT_METHOD) { - cd->posting = YES; -#ifdef MOZILLA_CLIENT - SECNAV_Posting(cd->connection->sock); -#endif /* MOZILLA_CLIENT */ - } else if (ce->URL_s->method == URL_HEAD_METHOD) { -#ifdef MOZILLA_CLIENT - SECNAV_HTTPHead(cd->connection->sock); -#endif /* MOZILLA_CLIENT */ - } - - /* zero out associated mime fields in URL structure - * all except content_length since that may be passed in */ - ce->URL_s->protection_template = 0; - PR_FREEIF(ce->URL_s->redirecting_url); - ce->URL_s->redirecting_url = NULL; - PR_FREEIF(ce->URL_s->authenticate); - ce->URL_s->authenticate = NULL; - PR_FREEIF(ce->URL_s->proxy_authenticate); - ce->URL_s->proxy_authenticate = NULL; - - /* Build the request command. (It must be free'd!!!) - * - * build_http_request will assemble a string containing - * the main request line, HTTP/1.0 MIME headers and - * the post data (if it exits) - */ - - command_size = net_build_http_request(ce->URL_s, - ce->format_out, - cd, - ce->window_id, - &command); - - TRACEMSG(("Sending HTTP Request:\n---------------------------------")); - - TIMING_STARTCLOCK_NAME("http:xfer", ce->URL_s->address); - TIMING_STARTCLOCK_NAME("http:req", ce->URL_s->address); - ce->status = (int) NET_BlockingWrite(cd->connection->sock, command, command_size); - -#if defined(JAVA) -#if defined(DEBUG) - if(MKLib_trace_flag) { - NET_NTrace("Tx: ", 4); - NET_NTrace(command, command_size); - } -#endif /* DEBUG */ -#endif /* JAVA */ - PR_Free (command); /* freeing the request */ - - if (ce->status < 0) { - int err = PR_GetError(); - - if(err == PR_WOULD_BLOCK_ERROR) - return(1); /* continue */ - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, err); - - cd->next_state= HTTP_ERROR_DONE; - - return(MK_TCP_WRITE_ERROR); - } - - - /* make sure these are empty - */ - PR_FREEIF(cd->line_buffer); /* reset */ - cd->line_buffer = NULL; - cd->line_buffer_size=0; /* reset */ - - if(cd->posting && ce->URL_s->post_data) { - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_SetConnectSelect(ce->window_id, cd->connection->sock); -#ifdef XP_WIN - cd->calling_netlib_all_the_time = TRUE; - NET_SetCallNetlibAllTheTime(ce->window_id, "mkhttp"); -#endif /* XP_WIN */ - ce->con_sock = cd->connection->sock; - cd->next_state = HTTP_SEND_POST_DATA; - return(0); - } - - cd->next_state = HTTP_PARSE_FIRST_LINE; - - /* Don't pause for read any more because we need to do - * at least a single read right away to detect if the - * connection is bad. Apparently windows will queue a - * write and not return a failure, but in fact the - * connection has already been closed by the server. - * Windows select will not even detect the exception - * so we end up deadlocked. By doing one read we - * can detect errors immediately - * - * cd->pause_for_read = TRUE; - */ - - { - char * nonProxyHost = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - if (nonProxyHost) { - char* msg = PR_smprintf(XP_GetString(XP_PROGRESS_WAIT_REPLY), - nonProxyHost); - if (msg) { -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, msg); -#else - NET_Progress(ce->window_id, msg); -#endif - PR_Free(msg); - } - PR_Free(nonProxyHost); - } - } - - return STATUS(ce->status); -} /* end of net_send_http_request */ - -PRIVATE int -net_http_send_post_data (ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - /* Default to not add_crlf_to_line_endings for HTTP. */ - XP_Bool add_crlf = FALSE; - - - /* make sure the line buffer is large enough - * for us to use as a buffer - */ - if(cd->line_buffer_size < 200) - { - PR_FREEIF(cd->line_buffer); - cd->line_buffer = (char*)PR_Malloc(256); - cd->line_buffer_size = 256; - } - - /* If the add_crlf field is set in the URL struct, find the - entry corresponding to the current file being posted. */ - if (ce->URL_s->files_to_post && ce->URL_s->add_crlf) { - int n = 0; - while (ce->URL_s->files_to_post[n]) { - n++; - } - /* n should now point after the last entry in files_to_post, - which is the current file being uploaded. */ - add_crlf = ce->URL_s->add_crlf[n]; - } - - TIMING_STARTCLOCK_NAME("http:post", ce->URL_s->address); - - /* returns 0 on done and negative on error - * positive if it needs to continue. - */ - ce->status = NET_WritePostData(ce->window_id, ce->URL_s, - cd->connection->sock, - &cd->write_post_data_data, - add_crlf); - - cd->pause_for_read = TRUE; - - if(ce->status == 0) - { - /* normal done - */ - TRACEMSG(("End of post data data")); - TIMING_STOPCLOCK_NAME("http:post", ce->URL_s->address, ce->window_id, "ok"); - - /* make sure these are empty - */ - PR_FREEIF(cd->line_buffer); /* reset */ - cd->line_buffer = NULL; - cd->line_buffer_size=0; /* reset */ - - NET_ClearConnectSelect(ce->window_id, cd->connection->sock); - NET_SetReadSelect(ce->window_id, cd->connection->sock); - ce->con_sock = NULL; - - { - char * nonProxyHost = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - if (nonProxyHost) { - char* msg = PR_smprintf(XP_GetString(XP_PROGRESS_WAIT_REPLY), - nonProxyHost); - if (msg) { -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, msg); -#else - NET_Progress(ce->window_id, msg); -#endif - PR_Free(msg); - } - PR_Free(nonProxyHost); - } - } - - cd->next_state = HTTP_PARSE_FIRST_LINE; - return(0); - } - else if(cd->total_size_of_files_to_post && ce->status > 0) - { - cd->total_amt_written += ce->status; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, - ce->URL_s, - cd->total_amt_written, - cd->total_size_of_files_to_post); -#else - FE_GraphProgress(ce->window_id, - ce->URL_s, - cd->total_amt_written, - ce->status, - cd->total_size_of_files_to_post); - FE_SetProgressBarPercent(ce->window_id, - cd->total_amt_written*100/cd->total_size_of_files_to_post); -#endif - } - - - - return(ce->status); -} - -/* parse_http_mime_headers - * - * parses the mime headers as they are received from the - * HTTP server. - * - * Returns the TCP status code - * - */ - -PRIVATE int -net_parse_http_mime_headers (ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - char *line; - char *value; - - ce->status = NET_BufferedReadLine(cd->connection->sock, &line, &cd->line_buffer, - &cd->line_buffer_size, &cd->pause_for_read); - - if(ce->status < 0) { - NET_ExplainErrorDetails(MK_TCP_READ_ERROR, PR_GetOSError()); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if(ce->status == 0) { - /* if this is set just return so we can use - * the cached copythat - */ - if(cd->use_copy_from_cache) { - /* clear the URL content fields so that - * the 304 object doesn't effect the actual - * cache file - */ - if(!ce->URL_s->preset_content_type) { - PR_FREEIF(ce->URL_s->content_type); - ce->URL_s->content_type = NULL; - } - ce->URL_s->content_length = 0; - ce->URL_s->real_content_length = 0; - ce->URL_s->last_modified = 0; - PR_FREEIF(ce->URL_s->content_encoding); - ce->URL_s->content_encoding = NULL; - PR_FREEIF(ce->URL_s->transfer_encoding); - ce->URL_s->transfer_encoding=NULL; - PR_FREEIF(ce->URL_s->content_name); - ce->URL_s->content_name = NULL; - cd->next_state = HTTP_DONE; - cd->pause_for_read = FALSE; - return(MK_USE_COPY_FROM_CACHE); - } - - /* no mo data */ - if(cd->use_proxy_tunnel && !cd->proxy_tunnel_setup_done) - { - /* we have now successfully initiated a proxy tunnel - * connection to a remote host - * - * now we need to give the file descriptor - * to the xxx library and let it initiate - * a secure connection - * after that we need to send a normal - * http request - * - * ADD STUFF HERE KIPP!!!! - * - * fd is cd->connection->sock - */ - if(ce->URL_s->files_to_post) - cd->next_state = HTTP_BEGIN_UPLOAD_FILE; - else - cd->next_state = HTTP_SEND_REQUEST; - cd->proxy_tunnel_setup_done = TRUE; - - } else if(ce->URL_s->files_to_post) { - - if(ce->URL_s->files_to_post[0] - && ce->URL_s->server_status/100 == 2) - { - if(ce->URL_s->can_reuse_connection) { - cd->next_state = HTTP_BEGIN_UPLOAD_FILE; - } else { - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - - /* close the old connection - */ - PR_Close(cd->connection->sock); - cd->connection->sock = NULL; - - cd->next_state = HTTP_START_CONNECT; - } - } else { - cd->next_state = HTTP_DONE; - } - } else { - cd->next_state = HTTP_SETUP_STREAM; - } - cd->pause_for_read = FALSE; - return(0); - } /* end status == 0 */ - - if(!line) - return(0); /* wait for next line */ - - TRACEMSG(("parse_http_mime_headers: Parsing headers, got line: %s",line)); - - if(cd->acting_as_proxy) { - /* save all the headers so we can pass them to the client - * when neccessary - */ - StrAllocCat(cd->server_headers, line); - StrAllocCat(cd->server_headers, "\r\n"); /* add the \n back on */ - } - - /* check for end of MIME headers */ - if(*line == '\0' || *line == '\r') { - TRACEMSG(("Finished parsing MIME headers")); - - cd->pause_for_read = FALSE; - HG07606 - if(ce->URL_s->files_to_post - && ce->URL_s->server_status/100 == 2) - { - if(ce->URL_s->files_to_post[0]) { - if(ce->URL_s->can_reuse_connection) { - cd->next_state = HTTP_BEGIN_UPLOAD_FILE; - } else { - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - - /* close the old connection */ - PR_Close(cd->connection->sock); - cd->connection->sock = NULL; - - cd->next_state = HTTP_START_CONNECT; - } - } else { - cd->next_state = HTTP_DONE; - } - } else { - cd->next_state = HTTP_SETUP_STREAM; - } - - return(0); - } - - value = PL_strchr(line, ':'); - if(value) - value++; - NET_ParseMimeHeader(ce->format_out, ce->window_id, ce->URL_s, line, value, TRUE); - - /* If the headers returned from the server indicate that this is a persistant - * connection, we don't need to send the "Connection: keep-alive" header - * on subsequent requests to this server over this connection. So, set the - * HTTPConnection data variable accordingly. This only works when the server is - * speaking 1.1. */ - if( (cd->protocol_version == ONE_POINT_ONE) && ce->URL_s->can_reuse_connection) - cd->connection->doNotSendConHdr=TRUE; - return(1); -} - -/* setup HTTP/1.1 specific protocol defaults */ -PRIVATE void -net_setup_http11_defaults(ActiveEntry *ce) { - HTTPConData * cd; - cd = (HTTPConData *)ce->con_data; - ce->URL_s->can_reuse_connection = TRUE; - return; -} - -/* parses the first line of the http server's response - * and determines if it is an http1 or http/.9 server - * - * returns the tcp status code - */ -PRIVATE int -net_parse_first_http_line (ActiveEntry *ce) { - char *line_feed=0; - char *ptr; - int line_size; - int num_fields; - char server_version[36]; - HTTPConData * cd = (HTTPConData *)ce->con_data; - char small_buf[MAX_FIRST_LINE_SIZE+16]; - Bool do_redirect = TRUE; - - TRACEMSG(("Entered: net_parse_first_http_line")); - - ce->status = PR_Read(cd->connection->sock, small_buf, MAX_FIRST_LINE_SIZE+10); - - if(ce->status == 0) { - /* the server dropped the connection? */ - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_ZERO_LENGTH_FILE); - cd->next_state = HTTP_ERROR_DONE; - cd->pause_for_read = FALSE; - return(MK_ZERO_LENGTH_FILE); - - } else if(ce->status < 0) { - - int s_error = PR_GetError(); - if (s_error == PR_WOULD_BLOCK_ERROR) { - cd->pause_for_read = TRUE; - return(0); - } else { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, s_error); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - } - - HG21899 - -#ifdef MOZILLA_CLIENT - HG19088 -#endif /* MOZILLA_CLIENT */ - - /* ce->status greater than 0 */ - - TIMING_STOPCLOCK_NAME("http:req", ce->URL_s->address, - ce->window_id, "response received"); - BlockAllocCat(cd->line_buffer, cd->line_buffer_size, small_buf, ce->status); - cd->line_buffer_size += ce->status; - - for(ptr = cd->line_buffer, line_size=0; line_size < cd->line_buffer_size; ptr++, line_size++) - if(*ptr == LF) { - line_feed = ptr; - break; - } - - /* assume HTTP/.9 until we know better */ - cd->protocol_version = POINT_NINE; - - if(line_feed) { - *server_version = 0; - - *line_feed = '\0'; - - num_fields = sscanf(cd->line_buffer, "%20s %d", server_version, &ce->URL_s->server_status); - - TRACEMSG(("HTTP: Scanned %d fields from first_line: %s", num_fields, cd->line_buffer)); - - /* Try and make sure this is an HTTP/1.0 reply */ - if (num_fields == 2 || !PL_strncmp("HTTP/", server_version, 5)) - { - double ver = atof(server_version+5); - - if(ver > 1.0) { - /* HTTP1.1 */ - cd->protocol_version = ONE_POINT_ONE; - - net_setup_http11_defaults(ce); - - PR_ASSERT(ver == 1.1); - - } else { - /* HTTP1 */ - cd->protocol_version = ONE_POINT_O; - - PR_ASSERT(ver == 1.0 || ver == 0.0); /* allow 0 bug */ - } - } - - /* put the line back the way it should be - */ - *line_feed = LF; - - } else if(cd->line_buffer_size < MAX_FIRST_LINE_SIZE) { - return(0); /* not ready to process */ - } - - if(cd->connection->prev_cache && cd->protocol_version == POINT_NINE) - { - /* got a non HTTP/1.0 or above response from - * server that must support HTTP/1.0 since it - * supports keep-alive. The connection - * must be in a bad state now so - * restart the whole thang by going to the ERROR state - */ - cd->next_state = HTTP_ERROR_DONE; - } - - /* if we are getting a successful read here - * then the connection is valid - */ - cd->connection_is_valid = TRUE; - - if(cd->protocol_version == POINT_NINE) - { /* HTTP/0.9 */ - NET_cinfo * ctype; - - TRACEMSG(("Receiving HTTP/0.9")); - - ce->URL_s->content_length = 0; - ce->URL_s->real_content_length = 0; - PR_FREEIF(ce->URL_s->content_encoding); - ce->URL_s->content_encoding = NULL; - PR_FREEIF(ce->URL_s->content_name); - ce->URL_s->content_name = NULL; - - if(!ce->URL_s->preset_content_type) { - PR_FREEIF(ce->URL_s->content_type); - ce->URL_s->content_type = NULL; - - /* fake the content_type since we can't get it */ - ctype = NET_cinfo_find_type(ce->URL_s->address); - - /* treat unknown types as HTML */ - if(ctype->is_default) - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - else - StrAllocCopy(ce->URL_s->content_type, ctype->type); - - /* fake the content_encoding since we can't get it */ - StrAllocCopy(ce->URL_s->content_encoding, - (NET_cinfo_find_enc(ce->URL_s->address))->encoding); - } - - cd->next_state = HTTP_SETUP_STREAM; - - } else { - /* Decode full HTTP/1.0 or 1.1 response */ - - TRACEMSG(("Receiving HTTP1 reply, status: %d", ce->URL_s->server_status)); - - if(ce->URL_s->server_status != 304 - && (!cd->use_proxy_tunnel || cd->proxy_tunnel_setup_done)) - { - /* if we don't have a 304, zero all - * the content headers so that they - * don't interfere with the - * incoming object - * - * don't zero these in the case of a proxy tunnel - * since this isn't the real request this - * is just the connection open request response - */ - if(!ce->URL_s->preset_content_type) { - PR_FREEIF(ce->URL_s->content_type); - ce->URL_s->content_type = NULL; - } - ce->URL_s->content_length = 0; - ce->URL_s->real_content_length = 0; - PR_FREEIF(ce->URL_s->content_encoding); - ce->URL_s->content_encoding = NULL; - PR_FREEIF(ce->URL_s->transfer_encoding); - ce->URL_s->transfer_encoding=NULL; - PR_FREEIF(ce->URL_s->content_name); - ce->URL_s->content_name = NULL; - } - - switch (ce->URL_s->server_status / 100) { - case 1: - if(ce->URL_s->server_status == 100) { - char * endOfResp; - char tmp; - int curRespSize=0; - - /* We just got a 100 Continue response from the server. - * Skip it. We don't do any special handling. We're not - * dealing with the status line or any headers sent with - * the response. */ - - /* Get the length of the response as a string. The end - * of the response is a double CRLF sequence. */ - - endOfResp=PL_strstr(cd->line_buffer, CRLF CRLF); - - /* If we can't find the end of the response, either we - * haven't received it all yet, or it's a malformed - * resposne. */ - if(endOfResp) { - endOfResp+=4; - tmp=*endOfResp; - *endOfResp='\0'; - curRespSize=PL_strlen(cd->line_buffer); - *endOfResp=tmp; - - cd->line_buffer_size -= curRespSize; - PR_ASSERT(cd->line_buffer_size >= 0); - if(cd->line_buffer_size > 0) - memmove(cd->line_buffer, endOfResp, cd->line_buffer_size); - } - - /* by not setting cd->next_state to something different - * we will come back to this function and look for another - * first line. - */ - return(0); - } - break; - - case 2: /* Succesful reply */ - - /* Since we - * are getting a new copy, delete the old one - * from the cache - */ -#ifdef MOZILLA_CLIENT -/* NET_RemoveURLFromCache(ce->URL_s); */ -#endif - - - if((ce->URL_s->server_status == 204 - || ce->URL_s->server_status == 201) - && !cd->acting_as_proxy) - { - if(ce->URL_s->files_to_post && ce->URL_s->files_to_post[0]) - { - /* fall through since we need to get - * the headers to complete the - * file transfer - */ - } else { - ce->status = MK_NO_ACTION; - cd->next_state = HTTP_ERROR_DONE; - return STATUS(ce->status); - } - } else if(cd->partial_cache_file - && ce->URL_s->range_header - && ce->URL_s->server_status != 206) - { - /* we asked for a range and got back - * the whole document. Something - * went wrong, error out. - */ - ce->status = MK_TCP_READ_ERROR; - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_TCP_READ_ERROR, - XP_ERRNO_EIO); - cd->next_state = HTTP_ERROR_DONE; - return(ce->status); - } - - break; - - case 3: /* redirection and other such stuff */ - - if(!cd->acting_as_proxy - && (ce->URL_s->server_status == 301 - || ce->URL_s->server_status == 302)) - { - /* Redirect with GET only (change POST to get) - * - * Supported within the HTTP module. - * Will retry after mime parsing - */ - TRACEMSG(("Got Redirect code")); - cd->doing_redirect = TRUE; - } - if(!cd->acting_as_proxy && ce->URL_s->server_status == 307) - { - /* Redirect without changing METHOD - * - * Supported within the HTTP module. - * Will retry after mime parsing - */ - TRACEMSG(("Got Redirect code")); - cd->doing_redirect = TRUE; - cd->save_redirect_method = TRUE; - - } else if(ce->URL_s->server_status == 304) - { - /* use the copy from the cache since it wasn't modified - * - * note: this will work with proxy clients too - */ - if(ce->URL_s->last_modified) - { -#ifdef MOZILLA_CLIENT - /* check to see if we just now entered a secure space - * - * don't do if this is coming from history - * don't do this if about to redirect - */ - if(HG82773 - && (ce->format_out == FO_CACHE_AND_PRESENT - || ce->format_out == FO_PRESENT) - && !ce->URL_s->history_num) - { - History_entry * h = SHIST_GetCurrent(&ce->window_id->hist); - HG03903 - } -#endif /* MOZILLA_CLIENT */ - - cd->use_copy_from_cache = TRUE; - /* no longer return since we need to parse - * headers from the server - * - * return(MK_USE_COPY_FROM_CACHE); - */ - } /* end url_s->last_modified */ - - /* else continue since the server messed up - * and sent us a 304 even without us having sent - * it an if-modified-since header - */ - } - break; - - case 4: /* client error */ - - ce->URL_s->preset_content_type = FALSE; - - if(ce->URL_s->server_status == 401 && !cd->acting_as_proxy) - { - /* never do this if acting as a proxy - * If we are a proxy then just pass on - * the headers and the document. - * - * if authorization_required is set we will check - * below after parsing the MIME headers to see - * if we should redo the request with an authorization - * string - */ - cd->authorization_required = TRUE; - - /* Since we - * are getting a new copy, delete the old one - * from the cache - */ -#ifdef MOZILLA_CLIENT - NET_RemoveURLFromCache(ce->URL_s); -#endif - - /* we probably want to cache this unless - * the user chooses not to authorize himself - */ - } else if (ce->URL_s->server_status == 407 && !cd->acting_as_proxy) - { - /* This happens only if acting as a client */ - cd->proxy_auth_required = TRUE; - - /* we probably want to cache this unless - * the user chooses not to authorize himself - */ - } else { - /* don't cache unless we have a succesful reply */ - TRACEMSG(("Server did not return success: NOT CACHEING!!")); - ce->URL_s->dont_cache = TRUE; - - /* all other codes should be displayed */ - } - break; - - case 5: /* server error code */ - TRACEMSG(("Server did not return success: NOT CACHEING!!!")); - ce->URL_s->dont_cache = TRUE; - ce->URL_s->preset_content_type = FALSE; -#ifdef DO_503 - if(ce->URL_s->server_status == 503 && !cd->acting_as_proxy) - { - cd->server_busy_retry = TRUE; - } -#endif /* DO_503 */ - - /* display the error results */ - break; - - default: /* unexpected reply code */ - { - char message_buffer[256]; - sprintf(message_buffer, - XP_GetString(XP_ALERT_UNKNOWN_STATUS), - ce->URL_s->server_status); - FE_Alert(ce->window_id, message_buffer); - - /* don't cache unless we have a succesful reply */ - TRACEMSG(("Server did not return 200: NOT CACHEING!!!")); - ce->URL_s->dont_cache = TRUE; - } - break; - } /* Switch on server_status/100 */ - - cd->next_state = HTTP_PARSE_MIME_HEADERS; - - } /* Full HTTP reply */ - - return(0); /* good */ -} - -/* if we were posting a file and received an error put the - * current file we were posting back on the end of the list - * so that our state is correctly reset - */ -PRIVATE void -net_revert_post_data(ActiveEntry * ce) -{ - if(ce->URL_s->files_to_post && ce->URL_s->post_data) - { - /* find the end of the files to post array */ - int index=0; - - for(; ce->URL_s->files_to_post[index]; index++) - ; /* null body */ - - /* this will not explode even if the malloc fails */ - ce->URL_s->files_to_post[index] = PL_strdup(ce->URL_s->post_data); - - ce->URL_s->files_to_post[index+1] = NULL; - - if(ce->URL_s->post_to) - { - ce->URL_s->post_to[index] = PL_strdup(ce->URL_s->address); - - ce->URL_s->post_to[index+1] = NULL; - } - } -} - -/* forward declaration */ -PRIVATE int net_finish_setup_http_stream(ActiveEntry * ce); - -/* sets up the stream and performs special actions like redirect and - * retry on authorization - * - * returns the tcp status code - */ -PRIVATE int -net_setup_http_stream(ActiveEntry * ce) { - HTTPConData * cd = (HTTPConData *)ce->con_data; - NET_AuthClosure * auth_closure; - XP_Bool need_to_do_again = FALSE; - - TRACEMSG(("NET_ProcessHTTP: setting up stream: %s", ce->URL_s->address)); - - /* save this since it can be changed in lots - * of places. This will be used for graph progress - * and to terminate the tranfer - */ - if(!ce->URL_s->high_range) - cd->original_content_length = ce->URL_s->content_length; - else - cd->original_content_length = ce->URL_s->high_range - - ce->URL_s->low_range - + 1; - - if ((ce->URL_s->method == URL_HEAD_METHOD) && - ( cd->authorization_required == FALSE)) - { - /* We only wanted the head, so we should stop doing anything else. */ - cd->next_state = HTTP_DONE; - return 0; - } - - /* if this is set just return so that we can use - * the cached copy - */ - if(cd->use_copy_from_cache) { - /* if this is a partial cache file situation - * then we will keep going and switch later - * on in this file. - * - * If it's not a partial cache file then - * leave the HTTP module and go to the - * file module to display the file - */ - if(!cd->partial_cache_file) { - /* clear the URL content fields so that - * the 304 object doesn't effect the actual - * cache file - */ - if(!ce->URL_s->preset_content_type) { - PR_FREEIF(ce->URL_s->content_type); - ce->URL_s->content_type = NULL; - } - ce->URL_s->content_length = 0; - ce->URL_s->real_content_length = 0; - PR_FREEIF(ce->URL_s->content_encoding); - ce->URL_s->content_encoding = NULL; - PR_FREEIF(ce->URL_s->transfer_encoding); - ce->URL_s->transfer_encoding=NULL; - PR_FREEIF(ce->URL_s->content_name); - ce->URL_s->content_name = NULL; - cd->next_state = HTTP_DONE; - cd->pause_for_read = FALSE; - return(MK_USE_COPY_FROM_CACHE); - } else { - /* set the correct content length so that - * the cache gets it right - */ - ce->URL_s->content_length = ce->URL_s->real_content_length; - } - } /* end cd->use_copy_from_cache */ - - /* do we need to start the tranfer over with authorization? - */ - if(cd->authorization_required) { - /* clear to prevent tight loop */ - int status; - - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - -#if defined(SMOOTH_PROGRESS) - PM_Suspend(ce->window_id, ce->URL_s); -#endif - - /* tuck the ce away for the auth callback */ - /* set up the auth closure struct for the password dialog */ - auth_closure = PR_NEWZAP(NET_AuthClosure); - if (!auth_closure) { - return(MK_INTERRUPTED); - } - - auth_closure->_private = (void *) ce; - auth_closure->msg = NULL; - auth_closure->user = NULL; - auth_closure->pass = NULL; - - status = NET_AskForAuthString(ce->window_id, - ce->URL_s, - ce->URL_s->authenticate, - ce->URL_s->protection_template, - cd->sent_authorization, - (void *) auth_closure); - -#if defined(SMOOTH_PROGRESS) - PM_Resume(ce->window_id, ce->URL_s); -#endif - - if (status == NET_RETRY_WITH_AUTH) { - need_to_do_again = TRUE; - } else if (status == NET_WAIT_FOR_AUTH) { - if (!ce->URL_s->password) - cd->next_state = HTTP_WAIT_FOR_AUTH; - return(0); - } - else - ce->URL_s->dont_cache = TRUE; - - NET_SetReadSelect(ce->window_id, cd->connection->sock); - } -#if defined(XP_WIN) && defined(MOZILLA_CLIENT) - -#define COMPUSERVE_HEADER_NAME "Remote-Passphrase" - - else if(ce->URL_s->authenticate && !PL_strncasecmp(ce->URL_s->authenticate, - COMPUSERVE_HEADER_NAME, - sizeof(COMPUSERVE_HEADER_NAME) - 1)) - { - /* compuserve auth requires us to send all authenticate - * headers into their code to verify the authentication - */ - int status = WFE_DoCompuserveAuthenticate(ce->window_id, - ce->URL_s, - ce->URL_s->authenticate); - - if(status == NET_AUTH_FAILED_DONT_DISPLAY) { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_COMPUSERVE_AUTH_FAILED); - return(MK_COMPUSERVE_AUTH_FAILED); - } - } -#endif /* XP_WIN and MOZILLA_CLIENT */ - - if(cd->proxy_auth_required) { - /* This was hacked in because proxy auth can be required when the Auto-config url - * itself requires authorization. We used to ask for proxy auth only when the proxy was - * input directly into the prefs. Now we check to see if there's a pacurl (if there - * is, there can't be a proxy url simultaneously) use it, otherwise we're using a - * proxy from the prefs. - */ - const char *tempURL=NULL; - char *proxyServer=NULL; - - /* Figure out which kind of proxy we're using: PAC or straight proxy. - * DON'T FREE tempURL!!! - */ - if ( (tempURL = net_GetPACUrl()) != NULL && (*tempURL) ) - proxyServer = NET_ParseURL(tempURL, GET_HOST_PART | GET_PATH_PART | GET_USERNAME_PART | GET_PASSWORD_PART); - else - proxyServer = cd->proxy_server; - -#if defined(SMOOTH_PROGRESS) - PM_Suspend(ce->window_id, ce->URL_s); -#endif - - /* tuck the ce away for the auth callback */ - /* set up the auth closure struct for the password dialog */ - auth_closure = PR_NEWZAP(NET_AuthClosure); - if (!auth_closure) { - return(MK_INTERRUPTED); - } - - auth_closure->_private = (void *) ce; - auth_closure->msg = NULL; - auth_closure->user = NULL; - auth_closure->pass = NULL; - - if(NET_AskForProxyAuth(ce->window_id, - proxyServer, - ce->URL_s->proxy_authenticate, - cd->sent_proxy_auth, - (void *) auth_closure)) { - need_to_do_again = TRUE; - TRACEMSG(("NET_AskForProxyAuth(): need_to_do_again: %s", ce->URL_s->address)); - } else - ce->URL_s->dont_cache = TRUE; - -#if defined(SMOOTH_PROGRESS) - PM_Resume(ce->window_id, ce->URL_s); -#endif - - /* Only free the our temp proxy server if it's not pointing to cd->proxy_server. - * We don't want to be freeing someone elses memory, we were just temporarily - * pointing to it. - */ - if (tempURL) - PR_FREEIF(proxyServer); - } /* end if cd->proxy_auth_required */ - - if (need_to_do_again) { - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - PR_Close(cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - cd->connection->sock = NULL; - cd->send_http1 = TRUE; - cd->authorization_required = FALSE; - cd->proxy_auth_required = FALSE; - cd->next_state = HTTP_START_CONNECT; - ce->URL_s->last_modified = 0; /* clear this so we don't get 304 loopage */ - - /* we don't know if the connection is valid anymore */ - cd->connection_is_valid = FALSE; - - /* clear the buffer */ - PR_FREEIF(cd->line_buffer); - cd->line_buffer = NULL; - cd->line_buffer_size = 0; - - /* if necessary */ - PR_FREEIF(cd->server_headers); - cd->server_headers = NULL; - - return(0); /* continue */ - - } - - /* Now finish stream setup. Setup needs to be broken in half - 'cuz in the case of modal dialogs, we need to wait for username - and password, then return to finish */ - return (ce->status = net_finish_setup_http_stream(ce)); -} - -PUBLIC void -net_ResumeHTTP(ActiveEntry * ce, NET_AuthClosure *auth_closure, PRBool resume) -{ - HTTPConData * cd = (HTTPConData *) ce->con_data; - - TRACEMSG (("NET_ResumeHTTP: %s", ce->URL_s->address)); - - if (resume) { - - /* now update the user/pass */ - ce->URL_s->username = PL_strdup (auth_closure->user); - ce->URL_s->password = PL_strdup (auth_closure->pass); - cd->next_state = HTTP_SETUP_STREAM; - - } else { - cd->next_state = HTTP_DONE; - } - - return; -} - -PRIVATE int -net_finish_setup_http_stream(ActiveEntry * ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - MWContext * stream_context; - - if (cd->doing_redirect && ce->URL_s->redirecting_url && - /* try and prevent a circular loop. wont work for dual doc loop */ - PL_strcmp(ce->URL_s->redirecting_url, ce->URL_s->address)) - { - Bool do_redirect=TRUE; - char *curURLHost, *redirectURLHost; - char *curPort, *redirectPort; - -#ifdef MOZILLA_CLIENT - /* update the global history since we wont have the same - * url later */ - GH_UpdateGlobalHistory(ce->URL_s); -#endif /* MOZILLA_CLIENT */ - - /* Inserted for security reasons. Ie. java applets being told to redirect to places they shouldn't be.*/ - if(ce->URL_s->dontAllowDiffHostRedirect) { - - if( !(curURLHost = NET_ParseURL(ce->URL_s->address, GET_HOST_PART)) ) - return MK_INTERRUPTED; - if( !(redirectURLHost = NET_ParseURL(ce->URL_s->redirecting_url, GET_HOST_PART)) ) - { - PR_Free(curURLHost); - return MK_INTERRUPTED; - } - - if ( (curPort = PL_strchr(curURLHost, ':')) != NULL) - *curPort='\0'; - if ( (redirectPort = PL_strchr(redirectURLHost, ':')) != NULL) - *redirectPort='\0'; - - if(PL_strcasecmp(curURLHost, redirectURLHost)) { - PR_Free(curURLHost); - PR_Free(redirectURLHost); - PR_FREEIF(ce->URL_s->redirecting_url); - ce->URL_s->redirecting_url = NULL; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_REDIRECT_ATTEMPT_NOT_ALLOWED); - return MK_REDIRECT_ATTEMPT_NOT_ALLOWED; - } - - PR_Free(curURLHost); - PR_Free(redirectURLHost); - - } /* End URL_s->dontAllowDiffHostRedirect */ - - HG92871 - - /* OK, now we've got the redirection URL stored - * in redirecting_url. - * Now change the URL in the URL structure and do the whole - * thing again */ - StrAllocCopy(ce->URL_s->address, ce->URL_s->redirecting_url); - - /* if we were posting a file and received an error put the - * current file we were posting back on the end of the list - * so that our state is correctly reset*/ - net_revert_post_data(ce); - - if(!cd->save_redirect_method) { - PR_FREEIF(ce->URL_s->post_data); - ce->URL_s->post_data = NULL; - PR_FREEIF(ce->URL_s->post_headers); - ce->URL_s->post_headers = NULL; - ce->URL_s->post_data_size = 0; - ce->URL_s->method = URL_GET_METHOD; - } - - /* clear these */ - if(!ce->URL_s->preset_content_type) { - PR_FREEIF(ce->URL_s->content_type); - ce->URL_s->content_type = NULL; - } - PR_FREEIF(ce->URL_s->content_encoding); - ce->URL_s->content_encoding = NULL; - PR_FREEIF(ce->URL_s->transfer_encoding); - ce->URL_s->transfer_encoding=NULL; - ce->URL_s->content_length = 0; /* reset */ - ce->URL_s->real_content_length = 0; /* reset */ - ce->URL_s->last_modified = 0; /* reset */ - cd->posting = FALSE; - ce->URL_s->address_modified = TRUE; - - if(do_redirect) - return(MK_DO_REDIRECT); /*fall out of HTTP and load the redirecting url */ - else - return(MK_INTERRUPTED); - - } else if(cd->server_busy_retry) { - - /* the redirecting mechanism works well for the retry - * since it is really the same thing except the url stays - * the same */ - return(MK_DO_REDIRECT); /* fall out of HTTP and reload the url */ - } - -#ifdef MOZILLA_CLIENT - /* check to see if we just now entered a secure space */ - /* don't do if this is coming from history */ - /* don't do this if about to redirect */ - if( HG22087 && - (ce->format_out == FO_CACHE_AND_PRESENT || ce->format_out == FO_PRESENT) - && !ce->URL_s->history_num) - { - History_entry * h = SHIST_GetCurrent(&ce->window_id->hist); - XP_Bool warn = FALSE; - - if (h == NULL) { - /* Deal with frames. If the window doesn't have history, */ - /* then it is a new window or a new frame cell. */ - if ( ce->window_id->grid_parent != NULL ) { - h = SHIST_GetCurrent(&ce->window_id->grid_parent->hist); - HG22088 - } else { - /* no parent frame - this is a top level window */ - warn = TRUE; - } - } else if (HG22089) { - warn = TRUE; - } - if ( warn ) { - SECNAV_SecurityDialog(ce->window_id, SD_ENTERING_SECURE_SPACE); - } - } -#endif /* MOZILLA_CLIENT */ - - /* set a default content type if one wasn't given - */ - if(!ce->URL_s->content_type || !*ce->URL_s->content_type) - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - - /* If a stream previously exists from a partial cache - * situation, reuse it - */ - if(!cd->stream) { - /* clear to prevent tight loop */ - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - -#ifdef MOZILLA_CLIENT - /* if the context can't handle HTML then we - * need to generate an HTML dialog to handle - * the message - */ - if(ce->URL_s->files_to_post && EDT_IS_EDITOR(ce->window_id)) - { - Chrome chrome_struct; - - memset(&chrome_struct, 0, sizeof(Chrome)); - - - chrome_struct.is_modal = TRUE; - chrome_struct.allow_close = TRUE; - chrome_struct.allow_resize = TRUE; - chrome_struct.show_scrollbar = TRUE; - chrome_struct.w_hint = 400; - chrome_struct.h_hint = 300; -#ifdef XP_MAC - /* on Mac, topmost windows are floating windows not dialogs */ - chrome_struct.topmost = FALSE; - /* disable commands to change to minimal menu bar; */ - /* avoids confusion about which commands are present */ - chrome_struct.disable_commands = TRUE; -#else - chrome_struct.topmost = TRUE; -#endif - - - stream_context = FE_MakeNewWindow(ce->window_id, - NULL, - NULL, - &chrome_struct); - if(!stream_context) - return (MK_OUT_OF_MEMORY); - - /* zero out the post_data field so that it doesn't get - * pushed onto the history stack. Otherwise it can - * get deleted when the history gets cleared - */ - PR_FREEIF(ce->URL_s->post_data); - ce->URL_s->post_data = NULL; - ce->URL_s->post_data_is_file = FALSE; - } else -#endif /* MOZILLA_CLIENT */ - { - stream_context = ce->window_id; - } - - /* we can get here on server or proxy errors - * if we proceed to build the stream with post_data - * set then the file could get deleted by history - * cleanup code. Make sure we zero the field - */ - if(ce->URL_s->files_to_post && ce->URL_s->post_data) - { - /* we shoved the file to post into the post data. - * remove it so the history doesn't get confused - * and try and delete the file. - */ - PR_FREEIF(ce->URL_s->post_data); - ce->URL_s->post_data = NULL; - ce->URL_s->post_data_is_file = FALSE; - } - - /* Set up the stream stack to handle the body of the message */ - cd->stream = NET_StreamBuilder(ce->format_out, - ce->URL_s, - stream_context); - - if (!cd->stream) { - ce->status = MK_UNABLE_TO_CONVERT; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return STATUS(ce->status); - } - - NET_SetReadSelect(ce->window_id, cd->connection->sock); - - if(ce->URL_s->files_to_post) { - char * tmp_string = PL_strdup("<h2>Error uploading files</h2><b>The server responded:<b><hr><p>\n"); - - if(tmp_string) - PUTSTRING(tmp_string); - } - } else { - /* check to see if it's a multipart respose. - * if it is then we need to do some magic to - * strip the multipart - */ - if(!PL_strncasecmp(ce->URL_s->content_type, "multipart", 9)) - { - /* reset the state to parse_mime_headers to strip - * the multipart headers off - */ - cd->next_state = HTTP_PARSE_MIME_HEADERS; - return STATUS(ce->status); - } - } - - if(cd->use_copy_from_cache) { - /* we can only get here if it's a partial cache file */ - cd->next_state = HTTP_BEGIN_PUSH_PARTIAL_CACHE_FILE; - cd->use_copy_from_cache = FALSE; - - } else { -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, - ce->URL_s, - 0, - cd->original_content_length); -#else - /* start the graph progress indicator */ - FE_GraphProgressInit(ce->window_id, - ce->URL_s, - cd->original_content_length); - cd->destroy_graph_progress = TRUE; /* we will need to destroy it */ -#endif - - cd->next_state = HTTP_PULL_DATA; - - if(cd->acting_as_proxy && cd->server_headers) - { - ce->status = PUTBLOCK(cd->server_headers, - PL_strlen(cd->server_headers)); - cd->displayed_some_data = TRUE; - } - - { /* open brace1 */ - char * nonProxyHost = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - if (nonProxyHost) { - char* msg = PR_smprintf(XP_GetString(XP_PROGRESS_TRANSFER_DATA), - nonProxyHost); - if (msg) { -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, msg); -#else - NET_Progress(ce->window_id, msg); -#endif - PR_Free(msg); - } - PR_Free(nonProxyHost); - } - } /* close brace1 */ - - /* Push though buffered data */ - if(cd->line_buffer_size) - { - /* @@@ bug, check return status and only send - * up to the return value - */ - (*cd->stream->is_write_ready)(cd->stream); - ce->status = PUTBLOCK(cd->line_buffer, cd->line_buffer_size); - ce->bytes_received = cd->line_buffer_size; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, - ce->URL_s, - ce->bytes_received, - cd->original_content_length); -#else - FE_GraphProgress(ce->window_id, - ce->URL_s, - ce->bytes_received, - cd->line_buffer_size, - cd->original_content_length); -#endif - cd->displayed_some_data = TRUE; - } - } - - PR_FREEIF(cd->line_buffer); - cd->line_buffer = NULL; - cd->line_buffer_size=0; - - /* check to see if we have read the whole object, - * and finish the transfer if so. - */ - if(ce->status > -1 - && cd->original_content_length - && ce->bytes_received >= cd->original_content_length) - { - /* normal end of transfer */ - ce->status = MK_DATA_LOADED; - cd->next_state = HTTP_DONE; - cd->pause_for_read = FALSE; - } - - return STATUS(ce->status); -} - -/* begin pushing a partial cache file down the stream - */ -PRIVATE int -net_http_push_partial_cache_file(ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - int32 write_ready, status; - - write_ready = (*cd->stream->is_write_ready)(cd->stream); - - write_ready = MIN(write_ready, NET_Socket_Buffer_Size); - - status = NET_XP_FileRead(NET_Socket_Buffer, write_ready, cd->partial_cache_fp); - - if(status < 0) - { - /* @@@ This is the wrong error code - */ - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, - PR_GetOSError()); - return(MK_TCP_READ_ERROR); - } - else if(status == 0) - { - /* all done with reading this file - */ - NET_ClearFileReadSelect(ce->window_id, XP_Fileno(cd->partial_cache_fp)); - NET_XP_FileClose(cd->partial_cache_fp); - cd->partial_cache_fp = NULL; - - /* set these back in preperation for - * using the http connection again - */ - ce->socket = cd->connection->sock; - ce->local_file = FALSE; - - /* add a request-range header - */ - PR_ASSERT(!ce->URL_s->range_header); - ce->URL_s->range_header = PR_smprintf("bytes=%ld-", - cd->partial_needed); - - /* the byterange part has not been gotten yet */ - ce->URL_s->last_modified = 0; - - /* we don't know if the connection is valid anymore - * because we are going to try it again - */ - cd->connection_is_valid = FALSE; - - if(ce->URL_s->can_reuse_connection) - { - NET_SetReadSelect(ce->window_id, cd->connection->sock); - cd->next_state = HTTP_SEND_REQUEST; - - /* set the connection to be from the connection cache - * since we have used it once - */ - cd->connection->prev_cache = TRUE; - } - else - { - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_ClearConnectSelect(ce->window_id, cd->connection->sock); - PR_Close(cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - cd->connection->sock = NULL; - cd->next_state = HTTP_START_CONNECT; - } - - cd->reuse_stream = TRUE; - - return(0); - } - - /* else, push the data read up the stream - */ - status = (*cd->stream->put_block)(cd->stream, - NET_Socket_Buffer, - status); - - cd->pause_for_read = TRUE; - - return(status); -} - -/* begin pushing a partial cache file down the stream - */ -PRIVATE int -net_http_begin_push_partial_cache_file(ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - char *cache_file = ce->URL_s->cache_file; - XP_File fp; - - if(!cache_file - || NULL == (fp = NET_XP_FileOpen(cache_file, xpCache, XP_FILE_READ_BIN))) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_OPEN_FILE, - cache_file); - return(MK_UNABLE_TO_OPEN_FILE); - } - - /* set up read select on the file instead of the socket - */ - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_SetFileReadSelect(ce->window_id, XP_Fileno(fp)); - ce->socket = NULL; - ce->local_file = TRUE; - - cd->next_state = HTTP_PUSH_PARTIAL_CACHE_FILE; - - cd->partial_cache_fp = fp; - - return(net_http_push_partial_cache_file(ce)); -} - -/* pulls down all the data - * - * returns the tcp status code - */ -PRIVATE int -net_pull_http_data(ActiveEntry * ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - unsigned int write_ready, read_size; - - TRACEMSG(("NET_ProcessHTTP: pulling data")); - - /* check to see if the stream is ready for writing - */ - write_ready = (*cd->stream->is_write_ready)(cd->stream); - - TRACEMSG(("NET_ProcessHTTP: write ready returned %d", write_ready)); - - if(!write_ready) - { - cd->pause_for_read = TRUE; - return(0); /* wait until we are ready to write */ - } - else if(write_ready < (unsigned int) NET_Socket_Buffer_Size) - { - read_size = write_ready; - } - else - { - read_size = NET_Socket_Buffer_Size; - } - - ce->status = PR_Read(cd->connection->sock, NET_Socket_Buffer, read_size); - - TRACEMSG(("NET_ProcessHTTP: just read %d bytes.", ce->status)); - cd->pause_for_read = TRUE; /* pause for the next read */ - - if(ce->status > 0) - { - ce->bytes_received += ce->status; -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, - ce->URL_s, - ce->bytes_received, - cd->original_content_length); -#else - FE_GraphProgress(ce->window_id, - ce->URL_s, - ce->bytes_received, - ce->status, - cd->original_content_length); -#endif - - ce->status = PUTBLOCK(NET_Socket_Buffer, ce->status); /* ALEKS */ - cd->displayed_some_data = TRUE; - - if(cd->original_content_length - && ce->bytes_received >= cd->original_content_length) - { - /* normal end of transfer */ - ce->status = MK_DATA_LOADED; - cd->next_state = HTTP_DONE; - cd->pause_for_read = FALSE; - } - - } - else if(ce->status == 0) - { - /* transfer finished - */ - TRACEMSG(("MKHTTP.c: Caught TCP EOF ending stream")); - - if(!cd->displayed_some_data) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_ZERO_LENGTH_FILE); - cd->next_state = HTTP_ERROR_DONE; - cd->pause_for_read = FALSE; - return(MK_ZERO_LENGTH_FILE); - } - - /* return the server status instead of data loaded - */ - ce->status = MK_DATA_LOADED; - cd->next_state = HTTP_DONE; - cd->pause_for_read = FALSE; - } - else /* error */ - { - int err = PR_GetError(); - - TRACEMSG(("TCP Error: %d", err)); - - if (err == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return (0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, err); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - return STATUS(ce->status); - -} - -/* begin loading an object from an http host - * - * proxy_server If not empty, the name of a host and/or port that will - * act as a proxy server for the request. If proxy_server - * is NULL then no proxy server is used - * - */ -PRIVATE int32 -net_HTTPLoad (ActiveEntry * ce) -{ - /* get memory for Connection Data */ - HTTPConData * cd = PR_NEW(HTTPConData); - HG21092 - char *use_host; - - ce->con_data = cd; - if(!ce->con_data) - { - ce->status = MK_OUT_OF_MEMORY; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return STATUS(ce->status); - } - - /* kill any returns in the URL */ - strtok(ce->URL_s->address, "\r"); - strtok(ce->URL_s->address, "\n"); - - /* init */ - memset(cd, 0, sizeof(HTTPConData)); - cd->proxy_server = ce->proxy_addr; - cd->proxy_conf = ce->proxy_conf; - cd->send_http1 = TRUE; - - /* set partial_cache_file if the whole file is not - * cached - */ - if(ce->URL_s->content_length < ce->URL_s->real_content_length) - { - cd->partial_cache_file = TRUE; - cd->partial_needed = ce->URL_s->content_length; - -#ifdef MOZILLA_CLIENT - /* if this isn't true then partial cacheing is screwed */ - PR_ASSERT(NET_IsPartialCacheFile(ce->URL_s)); -#else - PR_ASSERT(0); -#endif /* MOZILLA_CLIENT */ - } - - if(cd->proxy_server) - { - use_host = PL_strdup(cd->proxy_server); - } - else - { - use_host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - } - - HG09309 - - if(!use_host) - { - PR_Free(ce->con_data); - ce->status = MK_OUT_OF_MEMORY; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return STATUS(ce->status); - } - - /* if we are useing the files_to_post method - * make sure that the directory specified in the - * URL contains a slash at the end, otherwise - * it wont work - */ - if(ce->URL_s->files_to_post) - { - int32 end = PL_strlen(ce->URL_s->address)-1; - XP_StatStruct stat_entry; - int i; - - if(ce->URL_s->address[end] != '/') - StrAllocCat(ce->URL_s->address, "/"); - - /* run through the list of files and - * gather the total size - */ - for(i=0; ce->URL_s->files_to_post[i]; i++) - if(-1 != NET_XP_Stat(ce->URL_s->files_to_post[i], - &stat_entry, - xpFileToPost)) - cd->total_size_of_files_to_post += stat_entry.st_size; - -#if defined(SMOOTH_PROGRESS) - PM_Progress(ce->window_id, - ce->URL_s, - 0, - cd->total_size_of_files_to_post); -#else - /* start the graph progress indicator - */ - FE_GraphProgressInit(ce->window_id, - ce->URL_s, - cd->total_size_of_files_to_post); - - cd->destroy_graph_progress = TRUE; /* we will need to destroy it */ -#endif - -#ifdef EDITOR - /* Don't show the dialog if the data is being delivered to a plug-in */ - if ( (CLEAR_CACHE_BIT(ce->format_out) != FO_PLUGIN) - && (CLEAR_CACHE_BIT(ce->format_out) != FO_LOCATION_INDEPENDENCE)) - { - FE_SaveDialogCreate(ce->window_id, i, ED_SAVE_DLG_PUBLISH); - cd->destroy_file_upload_progress_dialog = TRUE; - } -#endif /* EDITOR */ - } - - /* check for established connection and use it if available - */ - if(http_connection_list) - { - HTTPConnection * tmp_con; - XP_List * list_entry = http_connection_list; - - /* If the url is secure and we are using a proxy server - * then never use a cached connection - */ - if(!cd->use_proxy_tunnel) - { - - while((tmp_con = (HTTPConnection *)XP_ListNextObject(list_entry)) - != NULL) - { - /* if the hostnames match up exactly - * and security matches up. - * and the connection - * is not busy at the moment then reuse this connection. - */ - if(HG29802 - && !tmp_con->busy) - { - cd->connection = tmp_con; - cd->connection->sock = cd->connection->sock; - NET_SetReadSelect(ce->window_id, cd->connection->sock); - ce->socket = cd->connection->sock; - cd->connection->prev_cache = TRUE; /* this was from the cache */ - TRACEMSG(("Found cached HTTP connection: %d", cd->connection->sock)); - - /* reorder the connection in the list to keep most recently - * used connections at the end - */ - XP_ListRemoveObject(http_connection_list, tmp_con); - XP_ListAddObjectToEnd(http_connection_list, tmp_con); - - break; - } - } - } - } - else - { - /* initialize the connection list - */ - http_connection_list = XP_ListNew(); - } - - if(cd->connection) - { - if(cd->use_proxy_tunnel) - cd->next_state = HTTP_SEND_PROXY_TUNNEL_REQUEST; - else if(ce->URL_s->files_to_post) - cd->next_state = HTTP_BEGIN_UPLOAD_FILE; - else - cd->next_state = HTTP_SEND_REQUEST; - - /* set the connection busy - */ - cd->connection->busy = TRUE; - NET_TotalNumberOfOpenConnections++; - } - else - { - /* build a control connection structure so we - * can store the data as we go along - */ - cd->connection = PR_NEW(HTTPConnection); - if(!cd->connection) - { - ce->status = MK_OUT_OF_MEMORY; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - PR_Free(use_host); - PR_Free(ce->con_data); - return(-1); - } - memset(cd->connection, 0, sizeof(HTTPConnection)); - - StrAllocCopy(cd->connection->hostname, use_host); - - HG93882 - - cd->connection->prev_cache = FALSE; /* this wasn't from the cache */ - - cd->connection->sock = NULL; - - /* add this structure to the connection list even - * though it's not really valid yet. - * we will fill it in as we go and if - * an error occurs will will remove it from the - * list. No one else will be able to use it since - * we will mark it busy. - */ - XP_ListAddObject(http_connection_list, cd->connection); - - /* set the connection busy - */ - cd->connection->busy = TRUE; - - /* if the connection list is larger than MAX_CACHED_HTTP_CONNECTIONS - * trim it down - */ - if(XP_ListCount(http_connection_list) > MAX_CACHED_HTTP_CONNECTIONS) - { - HTTPConnection *tmp_con; - XP_List * list_entry = http_connection_list; - - TRACEMSG(("More than %d cached connections. Deleteing one...", - MAX_CACHED_HTTP_CONNECTIONS)); - - while((tmp_con = (HTTPConnection *)XP_ListNextObject(list_entry)) != NULL) - { - if(!tmp_con->busy) - { - - if(!PL_strncasecmp(tmp_con->hostname, "rl.", 3) - && PL_strcasestr(tmp_con->hostname+2, ".netscape.com")) - { - /* if there is max plus one we are done, else - * continue on and remove one - */ - if(XP_ListCount(http_connection_list) - == MAX_CACHED_HTTP_CONNECTIONS+1) - { - break; /* from while */ - } - - } - else - { - /* remove the object */ - XP_ListRemoveObject(http_connection_list, tmp_con); - PR_Close(tmp_con->sock); - PR_Free(tmp_con->hostname); - PR_Free(tmp_con); - break; /* from while */ - } - } - } - } - - cd->next_state = HTTP_START_CONNECT; - - } - - PR_Free(use_host); - - return STATUS (net_ProcessHTTP(ce)); -} - - -/* NET_process_HTTP will control the state machine that - * loads an HTTP document - * - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -PRIVATE int32 -net_ProcessHTTP (ActiveEntry *ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - TRACEMSG(("Entering NET_ProcessHTTP")); - - cd->pause_for_read = FALSE; /* already paused; reset */ - - while(!cd->pause_for_read) { - - switch(cd->next_state) { - - case HTTP_WAIT_FOR_AUTH: - TRACEMSG (("HTTP_WAIT_FOR_AUTH: %s", ce->URL_s->address)); - cd->pause_for_read = TRUE; - break; - case HTTP_RESUME_WITH_AUTH: - TRACEMSG (("HTTP_RESUME_WITH_AUTH: %s", ce->URL_s->address)); - ce->status = net_finish_setup_http_stream(ce); - break; - case HTTP_START_CONNECT: - ce->status = net_start_http_connect(ce); - break; - - case HTTP_FINISH_CONNECT: - ce->status = net_finish_http_connect(ce); - break; - - case HTTP_SEND_PROXY_TUNNEL_REQUEST: - /* send proxy tunnel init stuff */ - ce->status = net_send_proxy_tunnel_request(ce); - break; - - case HTTP_BEGIN_UPLOAD_FILE: - /* form a put request */ - ce->status = net_begin_upload_file (ce); - break; -HG51096 - case HTTP_SEND_REQUEST: - /* send HTTP request */ - ce->status = net_send_http_request(ce); - break; - - case HTTP_SEND_POST_DATA: - ce->status = net_http_send_post_data(ce); - break; - - case HTTP_PARSE_FIRST_LINE: - ce->status = net_parse_first_http_line(ce); - break; - - case HTTP_PARSE_MIME_HEADERS: - ce->status = net_parse_http_mime_headers(ce); - break; - - case HTTP_SETUP_STREAM: - ce->status = net_setup_http_stream(ce); - break; - - case HTTP_BEGIN_PUSH_PARTIAL_CACHE_FILE: - ce->status = net_http_begin_push_partial_cache_file(ce); - break; - - case HTTP_PUSH_PARTIAL_CACHE_FILE: - ce->status = net_http_push_partial_cache_file(ce); - break; - - case HTTP_PULL_DATA: - ce->status = net_pull_http_data(ce); - break; - - case HTTP_DONE: - TIMING_STOPCLOCK_NAME("http:xfer", ce->URL_s->address, - ce->window_id, "ok"); - - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - -#ifdef TRUST_LABELS - ProcessCookiesAndTrustLabels( ce ); -#endif - - if(ce->URL_s->can_reuse_connection && !cd->use_proxy_tunnel) { - cd->connection->busy = FALSE; - } else { - PR_Close(cd->connection->sock); - - /* remove the connection from the cache list - * and free the data */ - XP_ListRemoveObject(http_connection_list, cd->connection); - if(cd->connection) { - PR_FREEIF(cd->connection->hostname); - PR_Free(cd->connection); - } - } - -#ifdef MOZILLA_CLIENT - /* make any meta tag changes take effect */ - NET_RefreshCacheFileExpiration(ce->URL_s); -#endif /* MOZILLA_CLIENT */ - - if(cd->stream) { - COMPLETE_STREAM; - PR_Free(cd->stream); - cd->stream = 0; - } - -#if defined(SMOOTH_PROGRESS) - /* XXX what to do if redirected to cache? */ - PM_StopBinding(ce->window_id, ce->URL_s, 0, NULL); -#endif - - cd->next_state = HTTP_FREE; - break; - - case HTTP_ERROR_DONE: - TIMING_STOPCLOCK_NAME("http:post", ce->URL_s->address, ce->window_id, "error"); - TIMING_STOPCLOCK_NAME("http:request", ce->URL_s->address, ce->window_id, "error"); - TIMING_STOPCLOCK_NAME("http:complete", ce->URL_s->address, ce->window_id, "error"); - if(cd->connection->sock != NULL) { - NET_ClearDNSSelect(ce->window_id, cd->connection->sock); - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_ClearConnectSelect(ce->window_id, cd->connection->sock); - PR_Close(cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - cd->connection->sock = NULL; - } - - if(cd->partial_cache_fp) { - NET_ClearFileReadSelect(ce->window_id, XP_Fileno(cd->partial_cache_fp)); - NET_XP_FileClose(cd->partial_cache_fp); - cd->partial_cache_fp = 0; - } - - if(cd->connection->prev_cache - && !cd->connection_is_valid - && ce->status != MK_INTERRUPTED) { - - if(cd->stream && !cd->reuse_stream) { - ABORT_STREAM(ce->status); - PR_Free(cd->stream); - cd->stream = 0; - } - - /* the connection came from the cache and - * may have been stale. Try it again - */ - /* clear any error message */ - if(ce->URL_s->error_msg) { - PR_Free(ce->URL_s->error_msg); - ce->URL_s->error_msg = NULL; - } - cd->next_state = HTTP_START_CONNECT; - ce->status = 0; - - /* we don't know if the connection is valid anymore - * because we are going to try it again - */ - cd->connection_is_valid = FALSE; - - cd->connection->prev_cache = FALSE; - - /* if we were posting a file and received an error put the - * current file we were posting back on the end of the list - * so that our state is correctly reset - */ - net_revert_post_data(ce); - - } else { - cd->next_state = HTTP_FREE; - - if(cd->stream) { - ABORT_STREAM(ce->status); - PR_Free(cd->stream); - cd->stream = 0; - } - - /* remove the connection from the cache list - * and free the data - */ - XP_ListRemoveObject(http_connection_list, cd->connection); - PR_FREEIF(cd->connection->hostname); - PR_Free(cd->connection); - } - -#if defined(SMOOTH_PROGRESS) - PM_StopBinding(ce->window_id, ce->URL_s, -1, NULL); -#endif - - break; /* HTTP_ERROR_DONE */ - - case HTTP_FREE: - - /* close the file upload progress. If a stream was created - * then some sort of HTTP error occured. Send in an error code */ -#ifdef EDITOR - if(cd->destroy_file_upload_progress_dialog) { - /* Convert from netlib errors to editor errors. */ - ED_FileError error = ED_ERROR_NONE; - if ( (ce->URL_s->server_status != 204 && ce->URL_s->server_status != 201 ) - || ce->status < 0 ) - error = ED_ERROR_PUBLISHING; - FE_SaveDialogDestroy(ce->window_id, error, ce->URL_s->post_data); - /* FE_SaveDialogDestroy(ce->window_id, ce->URL_s->server_status != 204 ? -1 : ce->status, ce->URL_s->post_data); */ - } -#endif /* EDITOR */ - - if(ce->URL_s->files_to_post && ce->URL_s->post_data) { - /* we shoved the file to post into the post data. - * remove it so the history doesn't get confused - * and try and delete the file. */ - PR_FREEIF(ce->URL_s->post_data); - ce->URL_s->post_data = NULL; - ce->URL_s->post_data_is_file = FALSE; - } - -#if !defined(SMOOTH_PROGRESS) - if(cd->destroy_graph_progress) - FE_GraphProgressDestroy(ce->window_id, - ce->URL_s, - cd->original_content_length, - ce->bytes_received); -#endif - - PR_FREEIF(cd->line_buffer); - PR_Free(cd->stream); /* don't forget the stream */ - PR_FREEIF(cd->server_headers); - PR_FREEIF(cd->orig_host); - if(cd->tcp_con_data) - NET_FreeTCPConData(cd->tcp_con_data); - PR_FREEIF(cd); - JSCF_Cleanup(); - return STATUS (-1); /* final end HTTP_FREE */ - - default: /* should never happen !!! */ - TRACEMSG(("HTTP: BAD STATE!")); - cd->next_state = HTTP_ERROR_DONE; - break; - } /* end switch */ - - /* check for errors during load and call error state if found */ - if(ce->status < 0 - && ce->status != MK_USE_COPY_FROM_CACHE - && cd->next_state != HTTP_FREE) { - - if (ce->status == MK_MULTIPART_MESSAGE_COMPLETED) { - /* We found the end of a multipart/mixed response - * from a CGI script in a http keep-alive response - * That signifies the end of a message. */ - TRACEMSG(("mkhttp.c: End of multipart keep-alive response")); - - ce->status = MK_DATA_LOADED; - cd->next_state = HTTP_DONE; - - } else if (ce->status == MK_HTTP_TYPE_CONFLICT - /* Don't retry if were HTTP/.9 */ - && !cd->send_http1 - /* Don't retry if we're posting. */ - && !cd->posting) { - /* Could be a HTTP 0/1 compability problem. */ - TRACEMSG(("HTTP: Read error trying again with HTTP0 request.")); -#if defined(SMOOTH_PROGRESS) - PM_Status(ce->window_id, ce->URL_s, XP_GetString(XP_PROGRESS_TRYAGAIN)); -#else - NET_Progress (ce->window_id, XP_GetString(XP_PROGRESS_TRYAGAIN)); -#endif - - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - NET_ClearConnectSelect(ce->window_id, cd->connection->sock); -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkhttp"); -#endif /* XP_WIN */ - NET_ClearDNSSelect(ce->window_id, cd->connection->sock); - PR_Close(cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - cd->connection->sock = NULL; - - if(cd->stream) - (*cd->stream->abort)(cd->stream, ce->status); - cd->send_http1 = FALSE; - /* go back and send an HTTP0 request */ - cd->next_state = HTTP_START_CONNECT; - } else { - cd->next_state = HTTP_ERROR_DONE; - } - /* don't exit! loop around again and do the free case */ - cd->pause_for_read = FALSE; - } /* ce->status < 0 */ - } /* while(!cd->pause_for_read) */ - - return STATUS(ce->status); -} - - -/* abort the connection in progress - */ -PRIVATE int32 -net_InterruptHTTP(ActiveEntry * ce) -{ - HTTPConData * cd = (HTTPConData *)ce->con_data; - - /* if we are currently pulling data and the data is - * Textual then truncate the file, leave notification and - * end normally - */ - if(cd->next_state == HTTP_PULL_DATA - && ce->URL_s->content_type - && !PL_strcasecmp(ce->URL_s->content_type, TEXT_HTML)) - { - char buffer[127]; - - if(!PL_strcasecmp(ce->URL_s->content_type, TEXT_HTML)) - PR_snprintf(buffer, sizeof(buffer), - XP_GetString(XP_HR_TRANSFER_INTERRUPTED)); - else - PR_snprintf(buffer, sizeof(buffer), - XP_GetString(XP_TRANSFER_INTERRUPTED)); - - PUTSTRING(buffer); - - /* steps from HTTP_DONE duplicated, with the addition of - * NET_RefreshCacheFileExpiration - */ - NET_ClearReadSelect(ce->window_id, cd->connection->sock); - PR_Close(cd->connection->sock); - NET_TotalNumberOfOpenConnections--; - ABORT_STREAM(MK_INTERRUPTED); - PR_Free(cd->stream); - cd->stream = 0; - - ce->URL_s->last_modified = 0; -#ifdef MOZILLA_CLIENT - /* to make the last_modified change take effect - */ - NET_RefreshCacheFileExpiration(ce->URL_s); -#endif /* MOZILLA_CLIENT */ - - cd->next_state = HTTP_FREE; - - ce->status = MK_DATA_LOADED; - } - else - { - cd->next_state = HTTP_ERROR_DONE; - ce->status = MK_INTERRUPTED; - } - - return STATUS (net_ProcessHTTP(ce)); -} - -/* Free any memory that might be used in caching etc. - */ -PRIVATE void -net_CleanupHTTP(void) -{ - /* nothing so far needs freeing */ - return; -} - -PRIVATE void -HTTP_ReadPrefs(void) -{ - PRBool b; - if ( (PREF_OK != PREF_GetBoolPref(pref_sendRefererHeader, &b)) ) { - b = TRUE; - } - NET_SetSendRefererHeader(b); -} - -static int PR_CALLBACK HTTP_PrefChangedFunc(const char *pref, void *data) -{ - HTTP_ReadPrefs(); - return TRUE; -} - -PRIVATE void -HTTP_InitPrefs(void) -{ - HTTP_ReadPrefs(); - PREF_RegisterCallback(pref_sendRefererHeader ,HTTP_PrefChangedFunc,NULL); -} - -#define HTTP_SCHEME "http:" - -MODULE_PRIVATE void -NET_InitHTTPProtocol(void) -{ - static NET_ProtoImpl http_proto_impl; - - HTTP_InitPrefs(); - - http_proto_impl.init = net_HTTPLoad; - http_proto_impl.process = net_ProcessHTTP; - http_proto_impl.interrupt = net_InterruptHTTP; - http_proto_impl.resume = net_ResumeHTTP; - http_proto_impl.cleanup = net_CleanupHTTP; - StrAllocCopy(http_proto_impl.scheme, HTTP_SCHEME); - - - NET_RegisterProtocolImplementation(&http_proto_impl, HTTP_TYPE_URL); - HG93898 -} - -#ifdef TRUST_LABELS -PUBLIC -void ProcessCookiesAndTrustLabels( ActiveEntry *ce ) -{ - unsigned int i; - if ( IsTrustLabelsEnabled() && ce && ce->URL_s) { - /* - * if the trust label parsing is enabled then look at each cookie - * and try to match it to a trust label on the trust list to see - * if one matches the cookie - */ - for(i=0 ;i < ce->URL_s->all_headers.empty_index; i++) { - /* look for a cookie field - allow Set-cookie: or Set-Cookie2: - CASE INSENSITIVE COMPARE */ - if(!PL_strncasecmp(ce->URL_s->all_headers.key[i], "Set-Cookie", 10)) { - NET_SetCookieStringFromHttp(CE_FORMAT_OUT, ce->URL_s, CE_WINDOW_ID, ce->URL_s->address, ce->URL_s->all_headers.value[i]); - } - } - } -} -#endif - -#ifdef PROFILE -#pragma profile off -#endif diff --git a/mozilla/network/protocol/http/nsCookie.cpp b/mozilla/network/protocol/http/nsCookie.cpp deleted file mode 100644 index 0e1537a3da1..00000000000 --- a/mozilla/network/protocol/http/nsCookie.cpp +++ /dev/null @@ -1,2956 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * - * Designed and Implemented by Lou Montulli '94 - * Heavily modified by Judson Valeski '97 - * Yada yada yada... Gagan Saksena '98 - * - * This file implements HTTP access authorization - * and HTTP cookies - */ - -// #define newI18N 1 - -#define alphabetize 1 -#include "nsString.h" -#include "nsINetService.h" -#include "nsIServiceManager.h" -#include "nsIStringBundle.h" -#include "nsFileStream.h" -#include "nsIFileLocator.h" -#include "nsIFileSpec.h" -#include "nsFileLocations.h" - -extern "C" { -#include "xp.h" -#include "mkprefs.h" -#include "netutils.h" -#include "httpauth.h" -#include "prefapi.h" -#include "prmon.h" -} -extern "C" { -#ifdef XP_MAC -#include "prpriv.h" /* for NewNamedMonitor */ -#else -#include "private/prpriv.h" -#endif -} - -extern "C" { -#include "cookies.h" -#include "sechash.h" -#include "rosetta.h" -#include "libevent.h" -#include "mkparse.h" -#include "net_xp_file.h" -} - -extern "C" { -#include "xpgetstr.h" /* for XP_GetString() */ -extern int MK_ACCESS_COOKIES_WISHES0; -extern int MK_ACCESS_COOKIES_WISHES1; -extern int MK_ACCESS_COOKIES_WISHESN; -extern int MK_ACCESS_COOKIES_WISHES_MODIFY; -extern int MK_ACCESS_COOKIES_REMEMBER; -} - -static NS_DEFINE_IID(kINetServiceIID, NS_INETSERVICE_IID); -static NS_DEFINE_IID(kNetServiceCID, NS_NETSERVICE_CID); - -static NS_DEFINE_IID(kIStringBundleServiceIID, NS_ISTRINGBUNDLESERVICE_IID); -static NS_DEFINE_IID(kStringBundleServiceCID, NS_STRINGBUNDLESERVICE_CID); -static NS_DEFINE_IID(kIFileLocatorIID, NS_IFILELOCATOR_IID); -static NS_DEFINE_CID(kFileLocatorCID, NS_FILELOCATOR_CID); - -#define MAX_NUMBER_OF_COOKIES 300 -#define MAX_COOKIES_PER_SERVER 20 -#define MAX_BYTES_PER_COOKIE 4096 /* must be at least 1 */ - -PRIVATE Bool cookies_changed = FALSE; -PRIVATE Bool cookie_permissions_changed = FALSE; -PRIVATE Bool cookie_remember_checked = FALSE; - -PRIVATE NET_CookieBehaviorEnum net_CookieBehavior = NET_Accept; -PRIVATE Bool net_WarnAboutCookies = FALSE; - - -/*-------------------------------------------------- - * The following routines support the - * Set-Cookie: / Cookie: headers - */ - -PRIVATE XP_List * net_cookie_list=0; -PRIVATE XP_List * net_cookie_permission_list=0; -PRIVATE XP_List * net_defer_cookie_list=0; - -typedef struct _net_CookieStruct { - char * path; - char * host; - char * name; - char * cookie; - time_t expires; - time_t last_accessed; - Bool xxx; - Bool is_domain; /* is it a domain instead of an absolute host? */ -} net_CookieStruct; - -typedef struct _net_CookiePermissionStruct { - char * host; - Bool permission; -} net_CookiePermissionStruct; - -typedef struct _net_DeferCookieStruct { - MWContext * context; - char * cur_url; - char * set_cookie_header; - time_t timeToExpire; -} net_DeferCookieStruct; - -/* Routines and data to protect the cookie list so it -** can be accessed by mulitple threads -*/ - -#include "prthread.h" -#include "prmon.h" - -static PRMonitor * cookie_lock_monitor = NULL; -static PRThread * cookie_lock_owner = NULL; -static int cookie_lock_count = 0; - -#define TEST_URL "resource:/res/cookie.properties" - -PRIVATE char* -cookie_Localize(char* genericString) { - nsresult ret; - nsAutoString v(""); - - /* create a URL for the string resource file */ - nsINetService* pNetService = nsnull; - ret = nsServiceManager::GetService(kNetServiceCID, kINetServiceIID, - (nsISupports**) &pNetService); - if (NS_FAILED(ret)) { - printf("cannot get net service\n"); - return v.ToNewCString(); - } - nsIURI *url = nsnull; - ret = pNetService->CreateURL(&url, nsString(TEST_URL), nsnull, nsnull, - nsnull); - if (NS_FAILED(ret)) { - printf("cannot create URL\n"); - nsServiceManager::ReleaseService(kNetServiceCID, pNetService); - return v.ToNewCString(); - } - nsServiceManager::ReleaseService(kNetServiceCID, pNetService); - - /* create a bundle for the localization */ - nsIStringBundleService* pStringService = nsnull; - ret = nsServiceManager::GetService(kStringBundleServiceCID, - kIStringBundleServiceIID, (nsISupports**) &pStringService); - if (NS_FAILED(ret)) { - printf("cannot get string service\n"); - return v.ToNewCString(); - } - nsILocale* locale = nsnull; - nsIStringBundle* bundle = nsnull; -#if 1 - const char* spec = nsnull; - ret = url->GetSpec(&spec); - if (NS_FAILED(ret)) { - printf("cannot get url spec\n"); - nsServiceManager::ReleaseService(kStringBundleServiceCID, pStringService); - return v.ToNewCString(); - } - ret = pStringService->CreateBundle(spec, locale, &bundle); -#else - ret = pStringService->CreateBundle(url, locale, &bundle); -#endif - if (NS_FAILED(ret)) { - printf("cannot create instance\n"); - nsServiceManager::ReleaseService(kStringBundleServiceCID, pStringService); - return v.ToNewCString(); - } - nsServiceManager::ReleaseService(kStringBundleServiceCID, pStringService); - - /* localize the given string */ -#if 1 - nsString strtmp(genericString); - const PRUnichar *ptrtmp = strtmp.GetUnicode(); - PRUnichar *ptrv = nsnull; - ret = bundle->GetStringFromName(ptrtmp, &ptrv); - v = ptrv; -#else - ret = bundle->GetStringFromName(nsString(genericString), v); -#endif - PR_Free(bundle); - if (NS_FAILED(ret)) { - printf("cannot get string from name\n"); - return v.ToNewCString(); - } - return v.ToNewCString(); -} - -PRIVATE nsresult cookie_ProfileDirectory(nsFileSpec& dirSpec) { - nsIFileSpec* spec = NS_LocateFileOrDirectory( - nsSpecialFileSpec::App_UserProfileDirectory50); - if (!spec) - return NS_ERROR_FAILURE; - return spec->GetFileSpec(&dirSpec); -} - -#ifndef XP_MAC -/* - * Write a line to a file - * return NS_OK if no error occurs - */ -nsresult -cookie_Put(nsOutputFileStream strm, const nsString& aLine) -{ - /* allocate a buffer from the heap */ - char * cp = new char[aLine.Length() + 1]; - if (! cp) { - return NS_ERROR_FAILURE; - } - - aLine.ToCString(cp, aLine.Length() + 1); - - /* output each character */ - char* p = cp; - while (*p) { - strm.put(*(p++)); - } - - delete[] cp; - return NS_OK; -} - -/* - * get a line from a file - * return -1 if end of file reached - * strip carriage returns and line feeds from end of line - */ -PRInt32 -cookie_GetLine(nsInputFileStream strm, nsAutoString*& aLine) { - - /* read the line */ - aLine = new nsAutoString(""); - char c; - for (;;) { - c = strm.get(); - if (c == '\n') { - break; - } - - /* note that eof is not set until we read past the end of the file */ - if (strm.eof()) { - return -1; - } - - if (c != '\r') { - *aLine += c; - } - } - return 0; -} -#endif - -PRIVATE void -net_lock_cookie_list(void) -{ - if(!cookie_lock_monitor) - cookie_lock_monitor = PR_NewNamedMonitor("cookie-lock"); - - PR_EnterMonitor(cookie_lock_monitor); - - while(TRUE) { - - /* no current owner or owned by this thread */ - PRThread * t = PR_CurrentThread(); - if(cookie_lock_owner == NULL || cookie_lock_owner == t) { - cookie_lock_owner = t; - cookie_lock_count++; - - PR_ExitMonitor(cookie_lock_monitor); - return; - } - - /* owned by someone else -- wait till we can get it */ - PR_Wait(cookie_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} - -PRIVATE void -net_unlock_cookie_list(void) -{ - PR_EnterMonitor(cookie_lock_monitor); - -#ifdef DEBUG - /* make sure someone doesn't try to free a lock they don't own */ - PR_ASSERT(cookie_lock_owner == PR_CurrentThread()); -#endif - - cookie_lock_count--; - - if(cookie_lock_count == 0) { - cookie_lock_owner = NULL; - PR_Notify(cookie_lock_monitor); - } - PR_ExitMonitor(cookie_lock_monitor); - -} - -static PRMonitor * defer_cookie_lock_monitor = NULL; -static PRThread * defer_cookie_lock_owner = NULL; -static int defer_cookie_lock_count = 0; - -PRIVATE void -net_lock_defer_cookie_list(void) -{ - if(!defer_cookie_lock_monitor) - defer_cookie_lock_monitor = - PR_NewNamedMonitor("defer_cookie-lock"); - - PR_EnterMonitor(defer_cookie_lock_monitor); - - while(TRUE) { - - /* no current owner or owned by this thread */ - PRThread * t = PR_CurrentThread(); - if(defer_cookie_lock_owner == NULL || defer_cookie_lock_owner == t) { - defer_cookie_lock_owner = t; - defer_cookie_lock_count++; - - PR_ExitMonitor(defer_cookie_lock_monitor); - return; - } - - /* owned by someone else -- wait till we can get it */ - PR_Wait(defer_cookie_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} - -PRIVATE void -net_unlock_defer_cookie_list(void) -{ - PR_EnterMonitor(defer_cookie_lock_monitor); - -#ifdef DEBUG - /* make sure someone doesn't try to free a lock they don't own */ - PR_ASSERT(defer_cookie_lock_owner == PR_CurrentThread()); -#endif - - defer_cookie_lock_count--; - - if(defer_cookie_lock_count == 0) { - defer_cookie_lock_owner = NULL; - PR_Notify(defer_cookie_lock_monitor); - } - PR_ExitMonitor(defer_cookie_lock_monitor); - -} - -static PRMonitor * cookie_permission_lock_monitor = NULL; -static PRThread * cookie_permission_lock_owner = NULL; -static int cookie_permission_lock_count = 0; - -PRIVATE void -net_lock_cookie_permission_list(void) -{ - if(!cookie_permission_lock_monitor) - cookie_permission_lock_monitor = - PR_NewNamedMonitor("cookie_permission-lock"); - - PR_EnterMonitor(cookie_permission_lock_monitor); - - while(TRUE) { - - /* no current owner or owned by this thread */ - PRThread * t = PR_CurrentThread(); - if(cookie_permission_lock_owner == NULL || cookie_permission_lock_owner == t) { - cookie_permission_lock_owner = t; - cookie_permission_lock_count++; - - PR_ExitMonitor(cookie_permission_lock_monitor); - return; - } - - /* owned by someone else -- wait till we can get it */ - PR_Wait(cookie_permission_lock_monitor, PR_INTERVAL_NO_TIMEOUT); - - } -} - -PRIVATE void -net_unlock_cookie_permission_list(void) -{ - PR_EnterMonitor(cookie_permission_lock_monitor); - -#ifdef DEBUG - /* make sure someone doesn't try to free a lock they don't own */ - PR_ASSERT(cookie_permission_lock_owner == PR_CurrentThread()); -#endif - - cookie_permission_lock_count--; - - if(cookie_permission_lock_count == 0) { - cookie_permission_lock_owner = NULL; - PR_Notify(cookie_permission_lock_monitor); - } - PR_ExitMonitor(cookie_permission_lock_monitor); - -} - -PRIVATE void -net_SaveCookiePermissions(); -PRIVATE void -net_SaveCookies(); - -PRIVATE void -net_FreeCookiePermission - (net_CookiePermissionStruct * cookie_permission, Bool save) -{ - - /* - * This routine should only be called while holding the - * cookie permission list lock - */ - - if(!cookie_permission) { - return; - } - XP_ListRemoveObject(net_cookie_permission_list, cookie_permission); - PR_FREEIF(cookie_permission->host); - - PR_Free(cookie_permission); - if (save) { - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(); - } -} - -/* blows away all cookie permissions currently in the list */ -PRIVATE void -net_RemoveAllCookiePermissions() -{ - net_CookiePermissionStruct * victim; - XP_List * cookiePermissionList; - - /* check for NULL or empty list */ - net_lock_cookie_permission_list(); - cookiePermissionList = net_cookie_permission_list; - - if(XP_ListIsEmpty(cookiePermissionList)) { - net_unlock_cookie_permission_list(); - return; - } - while((victim = - (net_CookiePermissionStruct *) - XP_ListNextObject(cookiePermissionList)) != 0) { - net_FreeCookiePermission(victim, FALSE); - cookiePermissionList = net_cookie_permission_list; - } - XP_ListDestroy(net_cookie_permission_list); - net_cookie_permission_list = NULL; - net_unlock_cookie_permission_list(); -} - -/* This should only get called while holding the cookie-lock -** -*/ -PRIVATE void -net_FreeCookie(net_CookieStruct * cookie) -{ - - if(!cookie) - return; - XP_ListRemoveObject(net_cookie_list, cookie); - - PR_FREEIF(cookie->path); - PR_FREEIF(cookie->host); - PR_FREEIF(cookie->name); - PR_FREEIF(cookie->cookie); - - PR_Free(cookie); - - cookies_changed = TRUE; -} - - -PUBLIC void -NET_DeleteCookie(char* cookieURL) -{ - net_CookieStruct * cookie; - XP_List * list_ptr; - char * cookieURL2 = 0; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - while((cookie = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - StrAllocCopy(cookieURL2, "cookie:"); - StrAllocCat(cookieURL2, cookie->host); - StrAllocCat(cookieURL2, "!"); - StrAllocCat(cookieURL2, cookie->path); - StrAllocCat(cookieURL2, "!"); - StrAllocCat(cookieURL2, cookie->name); - if (PL_strcmp(cookieURL, cookieURL2)==0) { - net_FreeCookie(cookie); - break; - } - } - PR_FREEIF(cookieURL2); - net_unlock_cookie_list(); -} - - -/* blows away all cookies currently in the list, then blows away the list itself - * nulling it after it's free'd - */ -PRIVATE void -net_RemoveAllCookies() -{ - net_CookieStruct * victim; - XP_List * cookieList; - - /* check for NULL or empty list */ - net_lock_cookie_list(); - cookieList = net_cookie_list; - if(XP_ListIsEmpty(cookieList)) { - net_unlock_cookie_list(); - return; - } - - while((victim = (net_CookieStruct *) XP_ListNextObject(cookieList)) != 0) { - net_FreeCookie(victim); - cookieList=net_cookie_list; - } - XP_ListDestroy(net_cookie_list); - net_cookie_list = NULL; - net_unlock_cookie_list(); -} - -PUBLIC void -NET_RemoveAllCookies() -{ - - net_RemoveAllCookiePermissions(); - net_RemoveAllCookies(); -} - -PRIVATE void -net_remove_oldest_cookie(void) -{ - XP_List * list_ptr; - net_CookieStruct * cookie_s; - net_CookieStruct * oldest_cookie; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - - if(XP_ListIsEmpty(list_ptr)) { - net_unlock_cookie_list(); - return; - } - - oldest_cookie = (net_CookieStruct*) list_ptr->next->object; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(cookie_s->last_accessed < oldest_cookie->last_accessed) - oldest_cookie = cookie_s; - } - - if(oldest_cookie) - { - TRACEMSG(("Freeing cookie because global max cookies has been exceeded")); - net_FreeCookie(oldest_cookie); - } - net_unlock_cookie_list(); -} - -/* Remove any expired cookies from memory -** This routine should only be called while holding the cookie list lock -*/ -PRIVATE void -net_remove_expired_cookies(void) -{ - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * cookie_s; - time_t cur_time = time(NULL); - - if(XP_ListIsEmpty(list_ptr)) - return; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - /* Don't get rid of expire time 0 because these need to last for - * the entire session. They'll get cleared on exit. - */ - if( cookie_s->expires && (cookie_s->expires < cur_time) ) { - net_FreeCookie(cookie_s); - /* Reset the list_ptr to the beginning of the list. - * Do this because list_ptr's object was just freed - * by the call to net_FreeCookie struct, even - * though it's inefficient. - */ - list_ptr = net_cookie_list; - } - } -} - -/* checks to see if the maximum number of cookies per host - * is being exceeded and deletes the oldest one in that - * case - * This routine should only be called while holding the cookie lock - */ -PRIVATE void -net_CheckForMaxCookiesFromHost(const char * cur_host) -{ - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * cookie_s; - net_CookieStruct * oldest_cookie = 0; - int cookie_count = 0; - - if(XP_ListIsEmpty(list_ptr)) - return; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(!PL_strcasecmp(cookie_s->host, cur_host)) - { - cookie_count++; - if(!oldest_cookie - || oldest_cookie->last_accessed > cookie_s->last_accessed) - oldest_cookie = cookie_s; - } - } - - if(cookie_count >= MAX_COOKIES_PER_SERVER && oldest_cookie) - { - TRACEMSG(("Freeing cookie because max cookies per server has been exceeded")); - net_FreeCookie(oldest_cookie); - } -} - - -/* search for previous exact match -** This routine should only be called while holding the cookie lock -*/ -PRIVATE net_CookieStruct * -net_CheckForPrevCookie(char * path, - char * hostname, - char * name) -{ - - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * cookie_s; - - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - if(path && hostname && cookie_s->path && cookie_s->host && cookie_s->name - && !PL_strcmp(name, cookie_s->name) - && !PL_strcmp(path, cookie_s->path) - && !PL_strcasecmp(hostname, cookie_s->host)) - return(cookie_s); - } - return(NULL); -} - -/* cookie utility functions */ -PRIVATE void -NET_SetCookieBehaviorPref(NET_CookieBehaviorEnum x) -{ - net_CookieBehavior = x; - - HG83330 - if(net_CookieBehavior == NET_DontUse) { - NET_XP_FileRemove("", xpHTTPCookie); - NET_XP_FileRemove("", xpHTTPCookiePermission); - } -} - -PRIVATE void -NET_SetCookieWarningPref(Bool x) -{ - net_WarnAboutCookies = x; -} - -PRIVATE NET_CookieBehaviorEnum -NET_GetCookieBehaviorPref(void) -{ - return net_CookieBehavior; -} - -PRIVATE Bool -NET_GetCookieWarningPref(void) -{ - return net_WarnAboutCookies; -} - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieBehaviorPrefChanged(const char * newpref, void * data) -{ - PRInt32 n; - if ( (PREF_OK != PREF_GetIntPref(pref_cookieBehavior, &n)) ) { - n = DEF_COOKIE_BEHAVIOR; - } - NET_SetCookieBehaviorPref((NET_CookieBehaviorEnum)n); - return PREF_NOERROR; -} - -MODULE_PRIVATE int PR_CALLBACK -NET_CookieWarningPrefChanged(const char * newpref, void * data) -{ - PRBool x; - if ( (PREF_OK != PREF_GetBoolPref(pref_warnAboutCookies, &x)) ) { - x = FALSE; - } - NET_SetCookieWarningPref(x); - return PREF_NOERROR; -} - -/* - * search if permission already exists - */ -PRIVATE net_CookiePermissionStruct * -net_CheckForCookiePermission(char * hostname) { - XP_List * list_ptr; - net_CookiePermissionStruct * cookie_s; - - /* ignore leading period in host name */ - while (hostname && (*hostname == '.')) { - hostname++; - } - - net_lock_cookie_permission_list(); - list_ptr = net_cookie_permission_list; - while((cookie_s = (net_CookiePermissionStruct *) XP_ListNextObject(list_ptr))!=0) { - if(hostname && cookie_s->host - && !PL_strcasecmp(hostname, cookie_s->host)) { - net_unlock_cookie_permission_list(); - return(cookie_s); - } - } - net_unlock_cookie_permission_list(); - return(NULL); -} - -/* - * return: - * +1 if cookie permission exists for host and indicates host can set cookies - * 0 if cookie permission does not exist for host - * -1 if cookie permission exists for host and indicates host can't set cookies - */ -PUBLIC int -NET_CookiePermission(char* URLName) { - net_CookiePermissionStruct * cookiePermission; - char * host; - char * colon; - - if (!URLName || !(*URLName)) { - return 0; - } - - /* remove protocol from URL name */ - host = NET_ParseURL(URLName, GET_HOST_PART); - - /* remove port number from URL name */ - colon = PL_strchr(host, ':'); - if(colon) { - *colon = '\0'; - } - cookiePermission = net_CheckForCookiePermission(host); - if(colon) { - *colon = ':'; - } - PR_Free(host); - if (cookiePermission == NULL) { - return 0; - } - if (cookiePermission->permission) { - return 1; - } - return -1; -} - -/* called from mkgeturl.c, NET_InitNetLib(). This sets the module local cookie pref variables - and registers the callbacks */ -PUBLIC void -NET_RegisterCookiePrefCallbacks(void) -{ - PRInt32 n; - PRBool x; - - if ( (PREF_OK != PREF_GetIntPref(pref_cookieBehavior, &n)) ) { - n = DEF_COOKIE_BEHAVIOR; - } - NET_SetCookieBehaviorPref((NET_CookieBehaviorEnum)n); - PREF_RegisterCallback(pref_cookieBehavior, NET_CookieBehaviorPrefChanged, NULL); - - if ( (PREF_OK != PREF_GetBoolPref(pref_warnAboutCookies, &x)) ) { - x = FALSE; - } - NET_SetCookieWarningPref(x); - PREF_RegisterCallback(pref_warnAboutCookies, NET_CookieWarningPrefChanged, NULL); -} - -/* returns TRUE if authorization is required -** -** -** IMPORTANT: Now that this routine is mutli-threaded it is up -** to the caller to free any returned string -*/ -PUBLIC char * -NET_GetCookie(MWContext * context, char * address) -{ - char *name=0; - char *host = NET_ParseURL(address, GET_HOST_PART); - char *path = NET_ParseURL(address, GET_PATH_PART); - XP_List * list_ptr; - net_CookieStruct * cookie_s; - Bool first=TRUE; - HG26748 - time_t cur_time = time(NULL); - int host_length; - int domain_length; - - /* return string to build */ - char * rv=0; - - /* disable cookie's if the user's prefs say so - */ - if(NET_GetCookieBehaviorPref() == NET_DontUse) - return NULL; - - HG98476 - - /* search for all cookies - */ - net_lock_cookie_list(); - list_ptr = net_cookie_list; - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) - { - if(!cookie_s->host) - continue; - - /* check the host or domain first - */ - if(cookie_s->is_domain) - { - char *cp; - domain_length = PL_strlen(cookie_s->host); - - /* calculate the host length by looking at all characters up to - * a colon or '\0'. That way we won't include port numbers - * in domains - */ - for(cp=host; *cp != '\0' && *cp != ':'; cp++) - ; /* null body */ - - host_length = cp - host; - if(domain_length > host_length - || PL_strncasecmp(cookie_s->host, - &host[host_length - domain_length], - domain_length)) - { - HG20476 - /* no match. FAIL - */ - continue; - } - - } - else if(PL_strcasecmp(host, cookie_s->host)) - { - /* hostname matchup failed. FAIL - */ - continue; - } - - /* shorter strings always come last so there can be no - * ambiquity - */ - if(cookie_s->path && !PL_strncmp(path, - cookie_s->path, - PL_strlen(cookie_s->path))) - { - - /* if the cookie is secure and the path isn't - * dont send it - */ - HG83764 - - /* check for expired cookies - */ - if( cookie_s->expires && (cookie_s->expires < cur_time) ) - { - /* expire and remove the cookie - */ - net_FreeCookie(cookie_s); - - /* start the list parsing over :( - * we must also start the string over - */ - PR_FREEIF(rv); - rv = NULL; - list_ptr = net_cookie_list; - first = TRUE; /* reset first */ - continue; - } - - if(first) - first = FALSE; - else - StrAllocCat(rv, "; "); - - if(cookie_s->name && *cookie_s->name != '\0') - { - cookie_s->last_accessed = cur_time; - StrAllocCopy(name, cookie_s->name); - StrAllocCat(name, "="); - -#ifdef PREVENT_DUPLICATE_NAMES - /* make sure we don't have a previous - * name mapping already in the string - */ - if(!rv || !PL_strstr(rv, name)) - { - StrAllocCat(rv, name); - StrAllocCat(rv, cookie_s->cookie); - } -#else - StrAllocCat(rv, name); - StrAllocCat(rv, cookie_s->cookie); -#endif /* PREVENT_DUPLICATE_NAMES */ - } - else - { - StrAllocCat(rv, cookie_s->cookie); - } - } - } - - net_unlock_cookie_list(); - PR_FREEIF(name); - PR_Free(path); - PR_Free(host); - - /* may be NULL */ - return(rv); -} - -void -net_AddCookiePermission - (net_CookiePermissionStruct * cookie_permission, Bool save ) { - - /* - * This routine should only be called while holding the - * cookie permission list lock - */ - if (cookie_permission) { - XP_List * list_ptr = net_cookie_permission_list; - if(!net_cookie_permission_list) { - net_cookie_permission_list = XP_ListNew(); - if(!net_cookie_permission_list) { - PR_Free(cookie_permission->host); - PR_Free(cookie_permission); - return; - } - list_ptr = net_cookie_permission_list; - } - -#ifdef alphabetize - /* add it to the list in alphabetical order */ - { - net_CookiePermissionStruct * tmp_cookie_permission; - Bool permissionAdded = FALSE; - while((tmp_cookie_permission = (net_CookiePermissionStruct *) - XP_ListNextObject(list_ptr))!=0) { - if (PL_strcasecmp - (cookie_permission->host,tmp_cookie_permission->host)<0) { - XP_ListInsertObject - (net_cookie_permission_list, - tmp_cookie_permission, - cookie_permission); - permissionAdded = TRUE; - break; - } - } - if (!permissionAdded) { - XP_ListAddObjectToEnd - (net_cookie_permission_list, cookie_permission); - } - } -#else - /* add it to the end of the list */ - XP_ListAddObjectToEnd (net_cookie_permission_list, cookie_permission); -#endif - - if (save) { - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(); - } - } -} - -MODULE_PRIVATE PRBool -net_CookieIsFromHost(net_CookieStruct *cookie_s, char *host) { - if (!cookie_s || !(cookie_s->host)) { - return FALSE; - } - if (cookie_s->is_domain) { - char *cp; - int domain_length, host_length; - - domain_length = PL_strlen(cookie_s->host); - - /* calculate the host length by looking at all characters up to - * a colon or '\0'. That way we won't include port numbers - * in domains - */ - for(cp=host; *cp != '\0' && *cp != ':'; cp++) { - ; /* null body */ - } - host_length = cp - host; - - /* compare the tail end of host to cook_s->host */ - return (domain_length <= host_length && - PL_strncasecmp(cookie_s->host, - &host[host_length - domain_length], - domain_length) == 0); - } else { - return PL_strcasecmp(host, cookie_s->host) == 0; - } -} - -/* find out how many cookies this host has already set */ -PRIVATE int -net_CookieCount(char * host) { - int count = 0; - XP_List * list_ptr; - net_CookieStruct * cookie; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - while((cookie = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - if (host && net_CookieIsFromHost(cookie, host)) { - count++; - } - } - net_unlock_cookie_list(); - - return count; -} - -PUBLIC int -NET_CookieCount(char * URLName) { - char * host; - char * colon; - int count = 0; - - if (!URLName || !(*URLName)) { - return 0; - } - - /* remove protocol from URL name */ - host = NET_ParseURL(URLName, GET_HOST_PART); - - /* remove port number from URL name */ - colon = PL_strchr(host, ':'); - if(colon) { - *colon = '\0'; - } - - /* get count */ - count = net_CookieCount(host); - - /* free up allocated string and return */ - if(colon) { - *colon = ':'; - } - PR_Free(host); - return count; -} - -PRBool net_IntSetCookieStringInUse = FALSE; - -PRIVATE void -net_DeferCookie( - MWContext * context, - char * cur_url, - char * set_cookie_header, - time_t timeToExpire) { - net_DeferCookieStruct * defer_cookie = PR_NEW(net_DeferCookieStruct); - defer_cookie->context = context; - defer_cookie->cur_url = NULL; - StrAllocCopy(defer_cookie->cur_url, cur_url); - defer_cookie->set_cookie_header = NULL; - StrAllocCopy(defer_cookie->set_cookie_header, set_cookie_header); - defer_cookie->timeToExpire = timeToExpire; - net_lock_defer_cookie_list(); - if (!net_defer_cookie_list) { - net_defer_cookie_list = XP_ListNew(); - if (!net_cookie_list) { - PR_FREEIF(defer_cookie->cur_url); - PR_FREEIF(defer_cookie->set_cookie_header); - PR_Free(defer_cookie); - } - } - XP_ListAddObject(net_defer_cookie_list, defer_cookie); - net_unlock_defer_cookie_list(); -} - -PRIVATE void -net_IntSetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header, - time_t timeToExpire ); - -PRIVATE void -net_UndeferCookies() { - net_DeferCookieStruct * defer_cookie; - net_lock_defer_cookie_list(); - if(XP_ListIsEmpty(net_defer_cookie_list)) { - net_unlock_defer_cookie_list(); - return; - } - defer_cookie = (net_DeferCookieStruct*)XP_ListRemoveEndObject(net_defer_cookie_list); - net_unlock_defer_cookie_list(); - net_IntSetCookieString ( - defer_cookie->context, - defer_cookie->cur_url, - defer_cookie->set_cookie_header, - defer_cookie->timeToExpire); - PR_FREEIF(defer_cookie->cur_url); - PR_FREEIF(defer_cookie->set_cookie_header); - PR_Free(defer_cookie); -} - -/* Java script is calling NET_SetCookieString, netlib is calling -** this via NET_SetCookieStringFromHttp. -*/ - -PRIVATE void -net_IntSetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header, - time_t timeToExpire ) -{ - net_CookieStruct * prev_cookie; - char *path_from_header=NULL, *host_from_header=NULL; - char *host_from_header2=NULL; - char *name_from_header=NULL, *cookie_from_header=NULL; - time_t expires=0; - char *cur_path = NET_ParseURL(cur_url, GET_PATH_PART); - char *cur_host = NET_ParseURL(cur_url, GET_HOST_PART); - char *semi_colon, *ptr, *equal; - PRBool HG83744 is_domain=FALSE, accept=FALSE; - MWContextType type; - Bool bCookieAdded; - PRBool pref_scd = PR_FALSE; - - if(!context) { - PR_Free(cur_path); - PR_Free(cur_host); - return; - } - - /* Only allow cookies to be set in the listed contexts. We - * don't want cookies being set in html mail. - */ - type = context->type; - if(!( (type == MWContextBrowser) - || (type == MWContextHTMLHelp) - || (type == MWContextPane) )) { - PR_Free(cur_path); - PR_Free(cur_host); - return; - } - - if(NET_GetCookieBehaviorPref() == NET_DontUse) { - PR_Free(cur_path); - PR_Free(cur_host); - return; - } - - /* Don't enter this routine if it is already in use by another - thread. Otherwise the "remember this decision" result of the - other cookie (which came first) won't get applied to this cookie. - */ - if (net_IntSetCookieStringInUse) { - PR_Free(cur_path); - PR_Free(cur_host); - net_DeferCookie(context, cur_url, set_cookie_header, timeToExpire); - return; - } - net_IntSetCookieStringInUse = TRUE; - - HG87358 - /* terminate at any carriage return or linefeed */ - for(ptr=set_cookie_header; *ptr; ptr++) - if(*ptr == LF || *ptr == CR) { - *ptr = '\0'; - break; - } - - /* parse path and expires attributes from header if - * present - */ - semi_colon = PL_strchr(set_cookie_header, ';'); - - if(semi_colon) - { - /* truncate at semi-colon and advance - */ - *semi_colon++ = '\0'; - - /* there must be some attributes. (hopefully) - */ - HG83476 - - /* look for the path attribute - */ - ptr = PL_strcasestr(semi_colon, "path="); - - if(ptr) { - /* allocate more than we need */ - StrAllocCopy(path_from_header, XP_StripLine(ptr+5)); - /* terminate at first space or semi-colon - */ - for(ptr=path_from_header; *ptr != '\0'; ptr++) - if(NET_IS_SPACE(*ptr) || *ptr == ';' || *ptr == ',') { - *ptr = '\0'; - break; - } - } - - /* look for the URI or URL attribute - * - * This might be a security hole so I'm removing - * it for now. - */ - - /* look for a domain */ - ptr = PL_strcasestr(semi_colon, "domain="); - - if(ptr) { - char *domain_from_header=NULL; - char *dot, *colon; - int domain_length, cur_host_length; - - /* allocate more than we need */ - StrAllocCopy(domain_from_header, XP_StripLine(ptr+7)); - - /* terminate at first space or semi-colon - */ - for(ptr=domain_from_header; *ptr != '\0'; ptr++) - if(NET_IS_SPACE(*ptr) || *ptr == ';' || *ptr == ',') { - *ptr = '\0'; - break; - } - - /* verify that this host has the authority to set for - * this domain. We do this by making sure that the - * host is in the domain - * We also require that a domain have at least two - * periods to prevent domains of the form ".com" - * and ".edu" - * - * Also make sure that there is more stuff after - * the second dot to prevent ".com." - */ - dot = PL_strchr(domain_from_header, '.'); - if(dot) - dot = PL_strchr(dot+1, '.'); - - if(!dot || *(dot+1) == '\0') { - /* did not pass two dot test. FAIL - */ - PR_Free(domain_from_header); - PR_Free(cur_path); - PR_Free(cur_host); - TRACEMSG(("DOMAIN failed two dot test")); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } - - /* strip port numbers from the current host - * for the domain test - */ - colon = PL_strchr(cur_host, ':'); - if(colon) - *colon = '\0'; - - domain_length = PL_strlen(domain_from_header); - cur_host_length = PL_strlen(cur_host); - - /* check to see if the host is in the domain - */ - if(domain_length > cur_host_length - || PL_strcasecmp(domain_from_header, - &cur_host[cur_host_length-domain_length])) - { - TRACEMSG(("DOMAIN failed host within domain test." - " Domain: %s, Host: %s", domain_from_header, cur_host)); - PR_Free(domain_from_header); - PR_Free(cur_path); - PR_Free(cur_host); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } - -/* - * check that portion of host not in domain does not contain a dot - * This satisfies the fourth requirement in section 4.3.2 of the cookie - * spec rfc 2109 (see www.cis.ohio-state.edu/htbin/rfc/rfc2109.html). - * It prevents host of the form x.y.co.nz from setting cookies in the - * entire .co.nz domain. Note that this doesn't really solve the problem, - * it justs makes it more unlikely. Sites such as y.co.nz can still set - * cookies for the entire .co.nz domain. - */ - -/* - * Although this is the right thing to do(tm), it breaks too many sites. - * So only do it if the restrictCookieDomains pref is TRUE. - * - */ - if ( PREF_GetBoolPref(pref_strictCookieDomains, &pref_scd) < 0 ) { - pref_scd = PR_FALSE; - } - - if ( pref_scd == PR_TRUE ) { - - cur_host[cur_host_length-domain_length] = '\0'; - dot = XP_STRCHR(cur_host, '.'); - cur_host[cur_host_length-domain_length] = '.'; - if (dot) { - TRACEMSG(("host minus domain failed no-dot test." - " Domain: %s, Host: %s", domain_from_header, cur_host)); - PR_Free(domain_from_header); - PR_Free(cur_path); - PR_Free(cur_host); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } - } - - /* all tests passed, copy in domain to hostname field - */ - StrAllocCopy(host_from_header, domain_from_header); - is_domain = TRUE; - - TRACEMSG(("Accepted domain: %s", host_from_header)); - - PR_Free(domain_from_header); - } - - /* now search for the expires header - * NOTE: that this part of the parsing - * destroys the original part of the string - */ - ptr = PL_strcasestr(semi_colon, "expires="); - - if(ptr) { - char *date = ptr+8; - /* terminate the string at the next semi-colon - */ - for(ptr=date; *ptr != '\0'; ptr++) - if(*ptr == ';') { - *ptr = '\0'; - break; - } - if(timeToExpire) - expires = timeToExpire; - else - expires = NET_ParseDate(date); - - TRACEMSG(("Have expires date: %ld", expires)); - } - } - - if(!path_from_header) { - /* strip down everything after the last slash - * to get the path. - */ - char * slash = PL_strrchr(cur_path, '/'); - if(slash) - *slash = '\0'; - - path_from_header = cur_path; - } else { - PR_Free(cur_path); - } - - if(!host_from_header) - host_from_header = cur_host; - else - PR_Free(cur_host); - - /* keep cookies under the max bytes limit */ - if(PL_strlen(set_cookie_header) > MAX_BYTES_PER_COOKIE) - set_cookie_header[MAX_BYTES_PER_COOKIE-1] = '\0'; - - /* separate the name from the cookie */ - equal = PL_strchr(set_cookie_header, '='); - - if(equal) { - *equal = '\0'; - StrAllocCopy(name_from_header, XP_StripLine(set_cookie_header)); - StrAllocCopy(cookie_from_header, XP_StripLine(equal+1)); - } else { - TRACEMSG(("Warning: no name found for cookie")); - StrAllocCopy(cookie_from_header, XP_StripLine(set_cookie_header)); - StrAllocCopy(name_from_header, ""); - } - - net_CookiePermissionStruct * cookie_permission; - cookie_permission = net_CheckForCookiePermission(host_from_header); - if (cookie_permission != NULL) { - if (cookie_permission->permission == FALSE) { - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } else { - accept = TRUE; - } - } - - - if( (NET_GetCookieWarningPref() ) && !accept ) { - /* the user wants to know about cookies so let them - * know about every one that is set and give them - * the choice to accept it or not - */ - char * new_string=0; - int count; - -#ifdef newI18N - char * remember_string = cookie_Localize("RememberThisDecision"); -#else - char * remember_string = 0; - StrAllocCopy - (remember_string, XP_GetString(MK_ACCESS_COOKIES_REMEMBER)); -#endif - - /* find out how many cookies this host has already set */ - count = net_CookieCount(host_from_header); - net_lock_cookie_list(); - prev_cookie = net_CheckForPrevCookie - (path_from_header, host_from_header, name_from_header); - net_unlock_cookie_list(); - char * message; - if (prev_cookie) { -#ifdef newI18N - message = cookie_Localize("PermissionToModifyCookie"); -#else - message = XP_GetString(MK_ACCESS_COOKIES_WISHES_MODIFY); -#endif - new_string = PR_smprintf(message, - host_from_header ? host_from_header : ""); - } else if (count>1) { -#ifdef newI18N - message = cookie_Localize("PermissionToSetAnotherCookie"); -#else - message = XP_GetString(MK_ACCESS_COOKIES_WISHESN); -#endif - new_string = PR_smprintf(message, - host_from_header ? host_from_header : "", - count); - } else if (count==1){ -#ifdef newI18N - message = cookie_Localize("PermissionToSetSecondCookie"); -#else - message = XP_GetString(MK_ACCESS_COOKIES_WISHES1); -#endif - new_string = PR_smprintf(message, - host_from_header ? host_from_header : ""); - } else { -#ifdef newI18N - message = cookie_Localize("PermissionToSetACookie"); -#else - message = XP_GetString(MK_ACCESS_COOKIES_WISHES0); -#endif - new_string = PR_smprintf(message, - host_from_header ? host_from_header : ""); - } -#ifdef newI18N - PR_FREEIF(message); -#endif - - /* - * Who knows what thread we are on. Only the mozilla thread - * is allowed to post dialogs so, if need be, go over there - */ - - { - Bool old_cookie_remember_checked = cookie_remember_checked; - XP_Bool userHasAccepted = ET_PostCheckConfirmBox - (context, - new_string, - remember_string, - 0,0, - &cookie_remember_checked); - PR_FREEIF(new_string); - PR_FREEIF(remember_string); - if (cookie_remember_checked) { - net_CookiePermissionStruct * cookie_permission; - cookie_permission = PR_NEW(net_CookiePermissionStruct); - if (cookie_permission) { - net_lock_cookie_permission_list(); - StrAllocCopy(host_from_header2, host_from_header); - /* ignore leading periods in host name */ - while (host_from_header2 && (*host_from_header2 == '.')) { - host_from_header2++; - } - cookie_permission->host = host_from_header2; /* set host string */ - cookie_permission->permission = userHasAccepted; - net_AddCookiePermission(cookie_permission, TRUE); - net_unlock_cookie_permission_list(); - } - } - - if (old_cookie_remember_checked != cookie_remember_checked) { - cookie_permissions_changed = TRUE; - net_SaveCookiePermissions(); - } - - if (!userHasAccepted) { - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - net_IntSetCookieStringInUse = FALSE; - return; - } - } - } - - TRACEMSG(("mkaccess.c: Setting cookie: %s for host: %s for path: %s", - cookie_from_header, host_from_header, path_from_header)); - - /* - * We have decided we are going to insert a cookie into the list - * Get the cookie lock so that we can munge on the list - */ - net_lock_cookie_list(); - - /* limit the number of cookies from a specific host or domain */ - net_CheckForMaxCookiesFromHost(host_from_header); - - if(XP_ListCount(net_cookie_list) > MAX_NUMBER_OF_COOKIES-1) - net_remove_oldest_cookie(); - - - prev_cookie = net_CheckForPrevCookie - (path_from_header, host_from_header, name_from_header); - - if(prev_cookie) { - prev_cookie->expires = expires; - PR_FREEIF(prev_cookie->cookie); - PR_FREEIF(prev_cookie->path); - PR_FREEIF(prev_cookie->host); - PR_FREEIF(prev_cookie->name); - prev_cookie->cookie = cookie_from_header; - prev_cookie->path = path_from_header; - prev_cookie->host = host_from_header; - prev_cookie->name = name_from_header; - prev_cookie->xxx = FALSE; - HG83263 - prev_cookie->is_domain = is_domain; - prev_cookie->last_accessed = time(NULL); - } else { - XP_List * list_ptr = net_cookie_list; - net_CookieStruct * tmp_cookie_ptr; - size_t new_len; - - /* construct a new cookie_struct - */ - prev_cookie = PR_NEW(net_CookieStruct); - if(!prev_cookie) { - PR_FREEIF(path_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(cookie_from_header); - net_unlock_cookie_list(); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } - - /* copy - */ - prev_cookie->cookie = cookie_from_header; - prev_cookie->name = name_from_header; - prev_cookie->path = path_from_header; - prev_cookie->host = host_from_header; - prev_cookie->expires = expires; - HG22730 - prev_cookie->is_domain = is_domain; - prev_cookie->last_accessed = time(NULL); - - if(!net_cookie_list) { - net_cookie_list = XP_ListNew(); - if(!net_cookie_list) { - PR_FREEIF(path_from_header); - PR_FREEIF(name_from_header); - PR_FREEIF(host_from_header); - PR_FREEIF(cookie_from_header); - PR_Free(prev_cookie); - net_unlock_cookie_list(); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; - } - } - - /* add it to the list so that it is before any strings of - * smaller length - */ - bCookieAdded = FALSE; - new_len = PL_strlen(prev_cookie->path); - while((tmp_cookie_ptr = (net_CookieStruct *) XP_ListNextObject(list_ptr))!=0) { - if(new_len > PL_strlen(tmp_cookie_ptr->path)) { - XP_ListInsertObject(net_cookie_list, tmp_cookie_ptr, prev_cookie); - bCookieAdded = TRUE; - break; - } - } - if ( !bCookieAdded ) { - /* no shorter strings found in list */ - XP_ListAddObjectToEnd(net_cookie_list, prev_cookie); - } - } - - /* At this point we know a cookie has changed. Write the cookies to file. */ - cookies_changed = TRUE; - net_SaveCookies(); - net_unlock_cookie_list(); - net_IntSetCookieStringInUse = FALSE; - net_UndeferCookies(); - return; -} - -PUBLIC void -NET_SetCookieString(MWContext * context, - char * cur_url, - char * set_cookie_header) { - net_IntSetCookieString(context, cur_url, set_cookie_header, 0); -} - -/* Determines whether the inlineHost is in the same domain as the currentHost. For use with rfc 2109 - * compliance/non-compliance. */ -PRIVATE int -NET_SameDomain(char * currentHost, char * inlineHost) -{ - char * dot = 0; - char * currentDomain = 0; - char * inlineDomain = 0; - - if(!currentHost || !inlineHost) - return 0; - - /* case insensitive compare */ - if(PL_strcasecmp(currentHost, inlineHost) == 0) - return 1; - - currentDomain = PL_strchr(currentHost, '.'); - inlineDomain = PL_strchr(inlineHost, '.'); - - if(!currentDomain || !inlineDomain) - return 0; - - /* check for at least two dots before continuing, if there are - not two dots we don't have enough information to determine - whether or not the inlineDomain is within the currentDomain */ - dot = PL_strchr(inlineDomain, '.'); - if(dot) - dot = PL_strchr(dot+1, '.'); - else - return 0; - - /* handle .com. case */ - if(!dot || (*(dot+1) == '\0') ) - return 0; - - if(!PL_strcasecmp(inlineDomain, currentDomain)) - return 1; - return 0; -} - -/* This function wrapper wraps NET_SetCookieString for the purposes of -** determining whether or not a cookie is inline (we need the URL struct, -** and outputFormat to do so). this is called from NET_ParseMimeHeaders -** in mkhttp.c -** This routine does not need to worry about the cookie lock since all of -** the work is handled by sub-routines -*/ -PUBLIC void -NET_SetCookieStringFromHttp(FO_Present_Types outputFormat, - URL_Struct * URL_s, - MWContext * context, - char * cur_url, - char * set_cookie_header) -{ - /* If the outputFormat is not PRESENT (the url is not going to the screen), and not - * SAVE AS (shift-click) then - * the cookie being set is defined as inline so we need to do what the user wants us - * to based on his preference to deal with foreign cookies. If it's not inline, just set - * the cookie. */ - char *ptr=NULL, *date=NULL; - time_t gmtCookieExpires=0, expires=0; - - if(CLEAR_CACHE_BIT(outputFormat) != FO_PRESENT && CLEAR_CACHE_BIT(outputFormat) != FO_SAVE_AS) - { - if (NET_GetCookieBehaviorPref() == NET_DontAcceptForeign) - { - /* the user doesn't want foreign cookies, check to see if its foreign */ - char * curSessionHistHost = 0; - char * theColon = 0; - char * curHost = NET_ParseURL(cur_url, GET_HOST_PART); - History_entry * shistEntry = SHIST_GetCurrent(&context->hist); - if (shistEntry) { - curSessionHistHost = NET_ParseURL(shistEntry->address, GET_HOST_PART); - } - if(!curHost || !curSessionHistHost) - { - PR_FREEIF(curHost); - PR_FREEIF(curSessionHistHost); - return; - } - - /* strip ports */ - theColon = PL_strchr(curHost, ':'); - if(theColon) - *theColon = '\0'; - theColon = PL_strchr(curSessionHistHost, ':'); - if(theColon) - *theColon = '\0'; - - /* if it's foreign, get out of here after a little clean up */ - if(!NET_SameDomain(curHost, curSessionHistHost)) - { - PR_FREEIF(curHost); - PR_FREEIF(curSessionHistHost); - return; - } - PR_FREEIF(curHost); - PR_FREEIF(curSessionHistHost); - } - } - - /* Determine when the cookie should expire. This is done by taking the difference between - the server time and the time the server wants the cookie to expire, and adding that - difference to the client time. This localizes the client time regardless of whether or - not the TZ environment variable was set on the client. */ - - /* Get the time the cookie is supposed to expire according to the attribute*/ - ptr = PL_strcasestr(set_cookie_header, "expires="); - if(ptr) - { - char *date = ptr+8; - char origLast = '\0'; - for(ptr=date; *ptr != '\0'; ptr++) - if(*ptr == ';') - { - origLast = ';'; - *ptr = '\0'; - break; - } - expires = NET_ParseDate(date); - *ptr=origLast; - } - if( URL_s->server_date && expires ) - { - if( expires < URL_s->server_date ) - { - gmtCookieExpires=1; - } - else - { - gmtCookieExpires = expires - URL_s->server_date + time(NULL); - /* if overflow */ - if( gmtCookieExpires < time(NULL) ) - gmtCookieExpires = (((unsigned) (~0) << 1) >> 1); /* max int */ - } - } - - net_IntSetCookieString(context, cur_url, set_cookie_header, gmtCookieExpires); -} - -#ifndef XP_MAC -/* saves the HTTP cookies permissions to disk */ -PRIVATE void -net_SaveCookiePermissions() -{ - XP_List * list_ptr; - net_CookiePermissionStruct * cookie_permission_s; - - if (NET_GetCookieBehaviorPref() == NET_DontUse) { - return; - } - - if (!cookie_permissions_changed) { - return; - } - - net_lock_cookie_permission_list(); - list_ptr = net_cookie_permission_list; - - if (!(net_cookie_permission_list)) { - net_unlock_cookie_permission_list(); - return; - } - - nsFileSpec dirSpec; - nsresult rval = cookie_ProfileDirectory(dirSpec); - if (NS_FAILED(rval)) { - net_unlock_cookie_permission_list(); - return; - } - nsOutputFileStream strm(dirSpec + "cookperm.txt"); - if (!strm.is_open()) { - net_unlock_cookie_permission_list(); - return; - } - - cookie_Put(strm, "# Netscape HTTP Cookie Permission File\n"); - cookie_Put(strm, "# http://www.netscape.com/newsref/std/cookie_spec.html\n"); - cookie_Put(strm, "# This is a generated file! Do not edit.\n\n"); - - /* format shall be: - * host \t permission - */ - while ((cookie_permission_s = (net_CookiePermissionStruct *) - XP_ListNextObject(list_ptr)) != NULL) { - cookie_Put(strm, cookie_permission_s->host); - if (cookie_permission_s->permission) { - cookie_Put(strm, "\tTRUE\n"); - } else { - cookie_Put(strm, "\tFALSE\n"); - } - } - - /* save current state of cookie nag-box's checkmark */ - if (cookie_remember_checked) { - cookie_Put(strm, "@@@@\tTRUE\n"); - } else { - cookie_Put(strm, "@@@@\tFALSE\n"); - } - - cookie_permissions_changed = FALSE; - strm.flush(); - strm.close(); - net_unlock_cookie_permission_list(); -} - -/* reads the HTTP cookies permission from disk */ -PRIVATE void -net_ReadCookiePermissions() -{ - nsAutoString * buffer; - net_CookiePermissionStruct * new_cookie_permission; - - nsFileSpec dirSpec; - nsresult rv = cookie_ProfileDirectory(dirSpec); - if (NS_FAILED(rv)) { - return; - } - nsInputFileStream strm(dirSpec + "cookperm.txt"); - if (!strm.is_open()) { - /* file doesn't exist -- that's not an error */ - return; - } - - /* format is: - * host \t permission - * if this format isn't respected we move onto the next line in the file. - */ - - net_lock_cookie_permission_list(); - while(cookie_GetLine(strm,buffer) != -1) { - if (buffer->CharAt(0) == '#' || buffer->CharAt(0) == CR || - buffer->CharAt(0) == LF || buffer->CharAt(0) == 0) { - PR_Free(buffer); - continue; - } - - int hostIndex, permissionIndex; - hostIndex = 0; - if ((permissionIndex=buffer->FindChar('\t',PR_FALSE, hostIndex)+1) == 0) { - PR_Free(buffer); - continue; - } - - /* ignore leading periods in host name */ - while (hostIndex < permissionIndex && (buffer->CharAt(hostIndex) == '.')) { - hostIndex++; - } - - nsString host, permission; - buffer->Mid(host, hostIndex, permissionIndex-hostIndex-1); - buffer->Mid(permission, permissionIndex, buffer->Length()-permissionIndex); - - /* create a new cookie_struct and fill it in */ - new_cookie_permission = PR_NEW(net_CookiePermissionStruct); - if (!new_cookie_permission) { - net_unlock_cookie_permission_list(); - strm.close(); - return; - } - - new_cookie_permission->host = host.ToNewCString(); - if (permission == "TRUE") { - new_cookie_permission->permission = PR_TRUE; - } else { - new_cookie_permission->permission = PR_FALSE; - } - - /* - * a host value of "@@@@" is a special code designating the - * state of the cookie nag-box's checkmark - */ - if (host == "@@@@") { - cookie_remember_checked = new_cookie_permission->permission; - } else { - /* add the permission entry */ - net_AddCookiePermission(new_cookie_permission, FALSE ); - } - } - - strm.close(); - net_unlock_cookie_permission_list(); - cookie_permissions_changed = FALSE; - return; -} - -/* saves out the HTTP cookies to disk */ -PRIVATE void -net_SaveCookies() -{ - XP_List * list_ptr; - net_CookieStruct * cookie_s; - time_t cur_date = time(NULL); - char date_string[36]; - - if (NET_GetCookieBehaviorPref() == NET_DontUse) { - return; - } - if (!cookies_changed) { - return; - } - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - if (!(list_ptr)) { - net_unlock_cookie_list(); - return; - } - - nsFileSpec dirSpec; - nsresult rv = cookie_ProfileDirectory(dirSpec); - if (NS_FAILED(rv)) { - net_unlock_cookie_list(); - return; - } - nsOutputFileStream strm(dirSpec + "cookies.txt"); - if (!strm.is_open()) { - /* file doesn't exist -- that's not an error */ - net_unlock_cookie_list(); - return; - } - - cookie_Put(strm, "# Netscape HTTP Cookie File\n"); - cookie_Put(strm, "# http://www.netscape.com/newsref/std/cookie_spec.html\n"); - cookie_Put(strm, "# This is a generated file! Do not edit.\n\n"); - - /* format shall be: - * - * host \t is_domain \t path \t secure \t expires \t name \t cookie - * - * is_domain is TRUE or FALSE - * xxx is TRUE or FALSE - * expires is a time_t integer - * cookie can have tabs - */ - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr)) != NULL) { - if (cookie_s->expires < cur_date) { - /* don't write entry if cookie has expired or has no expiration date */ - continue; - } - cookie_Put(strm, cookie_s->host); - - if (cookie_s->is_domain) { - cookie_Put(strm, "\tTRUE\t"); - } else { - cookie_Put(strm, "\tFALSE\t"); - } - - cookie_Put(strm, cookie_s->path); - - if (cookie_s->xxx) { - cookie_Put(strm, "\tTRUE\t"); - } else { - cookie_Put(strm, "\tFALSE\t"); - } - - PR_snprintf(date_string, sizeof(date_string), "%lu", cookie_s->expires); - cookie_Put(strm, date_string); - cookie_Put(strm, "\t"); - - cookie_Put(strm, cookie_s->name); - cookie_Put(strm, "\t"); - - cookie_Put(strm, cookie_s->cookie); - cookie_Put(strm, "\n"); - } - - cookies_changed = FALSE; - strm.flush(); - strm.close(); - net_unlock_cookie_list(); -} - -/* reads HTTP cookies from disk */ -PRIVATE void -net_ReadCookies() -{ - XP_List * list_ptr; - net_CookieStruct *new_cookie, *tmp_cookie_ptr; - size_t new_len; - nsAutoString * buffer; - Bool added_to_list; - - net_ReadCookiePermissions(); - - nsFileSpec dirSpec; - nsresult rv = cookie_ProfileDirectory(dirSpec); - if (NS_FAILED(rv)) { - return; - } - nsInputFileStream strm(dirSpec + "cookies.txt"); - if (!strm.is_open()) { - /* file doesn't exist -- that's not an error */ - return; - } - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - - /* format is: - * - * host \t is_domain \t path \t xxx \t expires \t name \t cookie - * - * if this format isn't respected we move onto the next line in the file. - * is_domain is TRUE or FALSE -- defaulting to FALSE - * xxx is TRUE or FALSE -- should default to TRUE - * expires is a time_t integer - * cookie can have tabs - */ - while (cookie_GetLine(strm,buffer) != -1){ - added_to_list = FALSE; - - if (buffer->CharAt(0) == '#' || buffer->CharAt(0) == CR || - buffer->CharAt(0) == LF || buffer->CharAt(0) == 0) { - PR_Free(buffer); - continue; - } - - int hostIndex, isDomainIndex, pathIndex, xxxIndex, expiresIndex, nameIndex, cookieIndex; - hostIndex = 0; - if ((isDomainIndex=buffer->FindChar('\t', PR_FALSE,hostIndex)+1) == 0 || - (pathIndex=buffer->FindChar('\t', PR_FALSE,isDomainIndex)+1) == 0 || - (xxxIndex=buffer->FindChar('\t', PR_FALSE,pathIndex)+1) == 0 || - (expiresIndex=buffer->FindChar('\t', PR_FALSE,xxxIndex)+1) == 0 || - (nameIndex=buffer->FindChar('\t', PR_FALSE,expiresIndex)+1) == 0 || - (cookieIndex=buffer->FindChar('\t', PR_FALSE,nameIndex)+1) == 0 ) { - PR_Free(buffer); - continue; - } - - nsString host, isDomain, path, xxx, expires, name, cookie; - buffer->Mid(host, hostIndex, isDomainIndex-hostIndex-1); - buffer->Mid(isDomain, isDomainIndex, pathIndex-isDomainIndex-1); - buffer->Mid(path, pathIndex, xxxIndex-pathIndex-1); - buffer->Mid(xxx, xxxIndex, expiresIndex-xxxIndex-1); - buffer->Mid(expires, expiresIndex, nameIndex-expiresIndex-1); - buffer->Mid(name, nameIndex, cookieIndex-nameIndex-1); - buffer->Mid(cookie, cookieIndex, buffer->Length()-cookieIndex); - PR_Free(buffer); - - /* create a new cookie_struct and fill it in */ - new_cookie = PR_NEW(net_CookieStruct); - if (!new_cookie) { - net_unlock_cookie_list(); - strm.close(); - return; - } - memset(new_cookie, 0, sizeof(net_CookieStruct)); - new_cookie->name = name.ToNewCString(); - new_cookie->cookie = cookie.ToNewCString(); - new_cookie->host = host.ToNewCString(); - new_cookie->path = path.ToNewCString(); - if (isDomain == "TRUE") { - new_cookie->is_domain = PR_TRUE; - } else { - new_cookie->is_domain = PR_FALSE; - } - if (xxx == "TRUE") { - new_cookie->xxx = PR_TRUE; - } else { - new_cookie->xxx = PR_FALSE; - } - char * expiresCString = expires.ToNewCString(); - new_cookie->expires = atol(expiresCString); - delete[] expiresCString; - - /* start new cookie list if one does not already exist */ - if (!net_cookie_list) { - net_cookie_list = XP_ListNew(); - if (!net_cookie_list) { - net_unlock_cookie_list(); - strm.close(); - return; - } - } - - /* add new cookie to the list so that it is before any strings of smaller length */ - new_len = PL_strlen(new_cookie->path); - while ((tmp_cookie_ptr = (net_CookieStruct *) XP_ListNextObject(list_ptr)) != NULL) { - if (new_len > PL_strlen(tmp_cookie_ptr->path)) { - XP_ListInsertObject(net_cookie_list, tmp_cookie_ptr, new_cookie); - added_to_list = TRUE; - break; - } - } - - /* no shorter strings found in list so add new cookie at end */ - if (!added_to_list) { - XP_ListAddObjectToEnd(net_cookie_list, new_cookie); - } - } - - strm.close(); - net_unlock_cookie_list(); - cookies_changed = FALSE; - return; -} -#else - -/* saves the HTTP cookies permissions to disk - * the parameter passed in on entry is ignored - * returns 0 on success -1 on failure. - */ -PRIVATE void -net_SaveCookiePermissions() -{ - XP_List * list_ptr; - net_CookiePermissionStruct * cookie_permission_s; - XP_File fp; - int32 len = 0; - - if(NET_GetCookieBehaviorPref() == NET_DontUse) { - return; - } - - if(!cookie_permissions_changed) { - return; - } - - net_lock_cookie_permission_list(); - list_ptr = net_cookie_permission_list; - - if(!(net_cookie_permission_list)) { - net_unlock_cookie_permission_list(); - return; - } - - if(!(fp = NET_XP_FileOpen(NULL, xpHTTPCookiePermission, XP_FILE_WRITE))) { - net_unlock_cookie_permission_list(); - return; - } - len = NET_XP_FileWrite("# Netscape HTTP Cookie Permission File" LINEBREAK - "# http://www.netscape.com/newsref/std/cookie_spec.html" - LINEBREAK "# This is a generated file! Do not edit." - LINEBREAK LINEBREAK, -1, fp); - - if (len < 0) { - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return; - } - - /* format shall be: - * host \t permission <optional trust label information > - */ - while((cookie_permission_s = (net_CookiePermissionStruct *) - XP_ListNextObject(list_ptr)) != NULL) { - len = NET_XP_FileWrite(cookie_permission_s->host, -1, fp); - if (len < 0) { - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return; - } - - NET_XP_FileWrite("\t", 1, fp); - - if(cookie_permission_s->permission) { - NET_XP_FileWrite("TRUE", -1, fp); - } else { - NET_XP_FileWrite("FALSE", -1, fp); - } - - len = NET_XP_FileWrite(LINEBREAK, -1, fp); - if (len < 0) { - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return; - } - } - - /* save current state of cookie nag-box's checkmark */ - NET_XP_FileWrite("@@@@", -1, fp); - NET_XP_FileWrite("\t", 1, fp); - if (cookie_remember_checked) { - NET_XP_FileWrite("TRUE", -1, fp); - } else { - NET_XP_FileWrite("FALSE", -1, fp); - } - NET_XP_FileWrite(LINEBREAK, -1, fp); - - cookie_permissions_changed = FALSE; - NET_XP_FileClose(fp); - net_unlock_cookie_permission_list(); - return; -} - -/* reads the HTTP cookies permission from disk - * the parameter passed in on entry is ignored - * returns 0 on success -1 on failure. - * - */ -#define PERMISSION_LINE_BUFFER_SIZE 4096 - -PRIVATE void -net_ReadCookiePermissions() -{ - XP_File fp; - char buffer[PERMISSION_LINE_BUFFER_SIZE]; - char *host, *p; - Bool permission_value; - net_CookiePermissionStruct * cookie_permission; - char *host_from_header2; - - if(!(fp = NET_XP_FileOpen(NULL, xpHTTPCookiePermission, XP_FILE_READ))) - return; - - /* format is: - * host \t permission <optional trust label information> - * if this format isn't respected we move onto the next line in the file. - */ - - net_lock_cookie_permission_list(); - while(NET_XP_FileReadLine(buffer, PERMISSION_LINE_BUFFER_SIZE, fp)) { - if (*buffer == '#' || *buffer == CR || *buffer == LF || *buffer == 0) { - continue; - } - - XP_StripLine(buffer); /* remove '\n' from end of the line */ - - host = buffer; - /* isolate the host field which is the first field on the line */ - if( !(p = PL_strchr(host, '\t')) ) { - continue; /* no permission field */ - } - *p++ = '\0'; - if(*p == CR || *p == LF || *p == 0) { - continue; /* no permission field */ - } - - /* ignore leading periods in host name */ - while (host && (*host == '.')) { - host++; - } - - /* - * the first part of the permission file is valid - - * allocate a new permission struct and fill it in - */ - cookie_permission = PR_NEW(net_CookiePermissionStruct); - if (cookie_permission) { - host_from_header2 = PL_strdup(host); - cookie_permission->host = host_from_header2; - - /* - * Now handle the permission field. - * a host value of "@@@@" is a special code designating the - * state of the cookie nag-box's checkmark - */ - permission_value = (!PL_strncmp(p, "TRUE", sizeof("TRUE")-1)); - if (!PL_strcmp(host, "@@@@")) { - cookie_remember_checked = permission_value; - } else { - cookie_permission->permission = permission_value; - - - /* add the permission entry */ - net_AddCookiePermission( cookie_permission, FALSE ); - } - } /* end if (cookie_permission) */ - } /* while(NET_XP_FileReadLine( */ - - net_unlock_cookie_permission_list(); - NET_XP_FileClose(fp); - cookie_permissions_changed = FALSE; - return; -} - -/* saves out the HTTP cookies to disk - * - * on entry pass in the name of the file to save - * - * returns 0 on success -1 on failure. - * - */ -PRIVATE void -net_SaveCookies() -{ - XP_List * list_ptr; - net_CookieStruct * cookie_s; - time_t cur_date = time(NULL); - XP_File fp; - int32 len = 0; - char date_string[36]; - - if(NET_GetCookieBehaviorPref() == NET_DontUse) - return; - - if(!cookies_changed) - return; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - if(!(list_ptr)) { - net_unlock_cookie_list(); - return; - } - - if(!(fp = NET_XP_FileOpen(NULL, xpHTTPCookie, XP_FILE_WRITE))) { - net_unlock_cookie_list(); - return; - } - - len = NET_XP_FileWrite("# Netscape HTTP Cookie File" LINEBREAK - "# http://www.netscape.com/newsref/std/cookie_spec.html" - LINEBREAK "# This is a generated file! Do not edit." - LINEBREAK LINEBREAK, - -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return; - } - - /* format shall be: - * - * host \t is_domain \t path \t secure \t expires \t name \t cookie - * - * is_domain is TRUE or FALSE - * secure is TRUE or FALSE - * expires is a time_t integer - * cookie can have tabs - */ - while((cookie_s = (net_CookieStruct *) XP_ListNextObject(list_ptr)) != NULL) - { - if(cookie_s->expires < cur_date) - continue; /* don't write entry if cookie has expired - * or has no expiration date - */ - - len = NET_XP_FileWrite(cookie_s->host, -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return; - } - NET_XP_FileWrite("\t", 1, fp); - - if(cookie_s->is_domain) - NET_XP_FileWrite("TRUE", -1, fp); - else - NET_XP_FileWrite("FALSE", -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - NET_XP_FileWrite(cookie_s->path, -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - HG74640 - NET_XP_FileWrite("FALSE", -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - PR_snprintf(date_string, sizeof(date_string), "%lu", cookie_s->expires); - NET_XP_FileWrite(date_string, -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - NET_XP_FileWrite(cookie_s->name, -1, fp); - NET_XP_FileWrite("\t", 1, fp); - - NET_XP_FileWrite(cookie_s->cookie, -1, fp); - len = NET_XP_FileWrite(LINEBREAK, -1, fp); - if (len < 0) - { - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return; - } - } - - cookies_changed = FALSE; - - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - return; -} - -/* reads HTTP cookies from disk - * - * on entry pass in the name of the file to read - * - * returns 0 on success -1 on failure. - * - * - */ -#define LINE_BUFFER_SIZE 4096 - -PRIVATE void -net_ReadCookies() -{ - XP_List * list_ptr; - net_CookieStruct *new_cookie, *tmp_cookie_ptr; - size_t new_len; - XP_File fp; - char buffer[LINE_BUFFER_SIZE]; - char *host, *is_domain, *path, *xxx, *expires, *name, *cookie; - Bool added_to_list; - - net_ReadCookiePermissions(); - - if(!(fp = NET_XP_FileOpen(NULL, xpHTTPCookie, XP_FILE_READ))) - return; - - net_lock_cookie_list(); - list_ptr = net_cookie_list; - - /* format is: - * - * host \t is_domain \t path \t xxx \t expires \t name \t cookie - * - * if this format isn't respected we move onto the next line in the file. - * is_domain is TRUE or FALSE -- defaulting to FALSE - * xxx is TRUE or FALSE -- should default to TRUE - * expires is a time_t integer - * cookie can have tabs - */ - while(NET_XP_FileReadLine(buffer, LINE_BUFFER_SIZE, fp)) - { - added_to_list = FALSE; - - if (*buffer == '#' || *buffer == CR || *buffer == LF || *buffer == 0) - continue; - - host = buffer; - - if( !(is_domain = PL_strchr(host, '\t')) ) - continue; - *is_domain++ = '\0'; - if(*is_domain == CR || *is_domain == LF || *is_domain == 0) - continue; - - if( !(path = PL_strchr(is_domain, '\t')) ) - continue; - *path++ = '\0'; - if(*path == CR || *path == LF || *path == 0) - continue; - - if( !(xxx = PL_strchr(path, '\t')) ) - continue; - *xxx++ = '\0'; - if(*xxx == CR || *xxx == LF || *xxx == 0) - continue; - - if( !(expires = PL_strchr(xxx, '\t')) ) - continue; - *expires++ = '\0'; - if(*expires == CR || *expires == LF || *expires == 0) - continue; - - if( !(name = PL_strchr(expires, '\t')) ) - continue; - *name++ = '\0'; - if(*name == CR || *name == LF || *name == 0) - continue; - - if( !(cookie = PL_strchr(name, '\t')) ) - continue; - *cookie++ = '\0'; - if(*cookie == CR || *cookie == LF || *cookie == 0) - continue; - - /* remove the '\n' from the end of the cookie */ - XP_StripLine(cookie); - - /* construct a new cookie_struct - */ - new_cookie = PR_NEW(net_CookieStruct); - if(!new_cookie) - { - net_unlock_cookie_list(); - return; - } - - memset(new_cookie, 0, sizeof(net_CookieStruct)); - - /* copy - */ - StrAllocCopy(new_cookie->cookie, cookie); - StrAllocCopy(new_cookie->name, name); - StrAllocCopy(new_cookie->path, path); - StrAllocCopy(new_cookie->host, host); - new_cookie->expires = atol(expires); - - HG87365 - - if(!PL_strcmp(is_domain, "TRUE")) - new_cookie->is_domain = TRUE; - else - new_cookie->is_domain = FALSE; - - if(!net_cookie_list) - { - net_cookie_list = XP_ListNew(); - if(!net_cookie_list) - { - net_unlock_cookie_list(); - return; - } - } - - /* add it to the list so that it is before any strings of - * smaller length - */ - new_len = PL_strlen(new_cookie->path); - while((tmp_cookie_ptr = (net_CookieStruct *) XP_ListNextObject(list_ptr)) != NULL) - { - if(new_len > PL_strlen(tmp_cookie_ptr->path)) - { - XP_ListInsertObject(net_cookie_list, tmp_cookie_ptr, new_cookie); - added_to_list = TRUE; - break; - } - } - - /* no shorter strings found in list */ - if(!added_to_list) - XP_ListAddObjectToEnd(net_cookie_list, new_cookie); - } - - NET_XP_FileClose(fp); - net_unlock_cookie_list(); - - cookies_changed = FALSE; - - return; -} -#endif - -PUBLIC int -NET_SaveCookies(char * filename) -{ - net_SaveCookies(); - return 0; -} - -PUBLIC int -NET_ReadCookies(char * filename) -{ - net_ReadCookies(); - return 0; -} - -/* return TRUE if "number" is in sequence of comma-separated numbers */ -Bool net_InSequence(char* sequence, int number) { - char* ptr; - char* endptr; - char* undo = NULL; - Bool retval = FALSE; - int i; - - /* not necessary -- routine will work even with null sequence */ - if (!*sequence) { - return FALSE; - } - - for (ptr = sequence ; ptr ; ptr = endptr) { - - /* get to next comma */ - endptr = PL_strchr(ptr, ','); - - /* if comma found, process it */ - if (endptr) { - - /* restore last comma-to-null back to comma */ - if (undo) { - *undo = ','; - } - - /* set the comma to a null */ - undo = endptr; - *endptr++ = '\0'; - - /* compare the number before the comma with "number" */ - if (*ptr) { - i = atoi(ptr); - if (i == number) { - - /* "number" was in the sequence so return TRUE */ - retval = TRUE; - break; - } - } - } - } - - /* restore last comma-to-null back to comma */ - if (undo) { - *undo = ','; - } - return retval; -} - -PRIVATE Bool -CookieCompare (net_CookieStruct * cookie1, net_CookieStruct * cookie2) { - char * host1 = cookie1->host; - char * host2 = cookie2->host; - - /* get rid of leading period on host name, if any */ - if (*host1 == '.') { - host1++; - } - if (*host2 == '.') { - host2++; - } - - /* make decision based on host name if they are unequal */ - if (PL_strcmp (host1, host2) < 0) { - return -1; - } - if (PL_strcmp (host1, host2) > 0) { - return 1; - } - - /* if host names are equal, make decision based on cookie name */ - return (PL_strcmp (cookie1->name, cookie2->name)); -} - -/* - * find the next cookie that is alphabetically after the specified cookie - * ordering is based on hostname and the cookie name - * if specified cookie is NULL, find the first cookie alphabetically - */ -PRIVATE net_CookieStruct * -NextCookieAfter(net_CookieStruct * cookie, int * cookieNum) { - XP_List *cookie_list=net_cookie_list; - net_CookieStruct *cookie_ptr; - net_CookieStruct *lowestCookie = NULL; - int localCookieNum = 0; - int lowestCookieNum; - - while ( (cookie_ptr=(net_CookieStruct *) XP_ListNextObject(cookie_list)) ) { - if (!cookie || (CookieCompare(cookie_ptr, cookie) > 0)) { - if (!lowestCookie || - (CookieCompare(cookie_ptr, lowestCookie) < 0)) { - lowestCookie = cookie_ptr; - lowestCookieNum = localCookieNum; - } - } - localCookieNum++; - } - - *cookieNum = lowestCookieNum; - return lowestCookie; -} - -/* - * return a string that has each " of the argument sting - * replaced with \" so it can be used inside a quoted string - */ -PRIVATE char* -net_FixQuoted(char* s) { - char * result; - int count = PL_strlen(s); - char *quote = s; - unsigned int i, j; - while (quote = PL_strchr(quote, '"')) { - count = count++; - quote++; - } - result = (char*)XP_ALLOC(count + 1); - for (i=0, j=0; i<PL_strlen(s); i++) { - if (s[i] == '"') { - result[i+(j++)] = '\\'; - } - result[i+j] = s[i]; - } - result[i+j] = '\0'; - return result; -} - -PUBLIC void -COOKIE_DisplayCookieInfoAsHTML() -{ - /* Get rid of any expired cookies now so user doesn't - * think/see that we're keeping cookies in memory. - */ - net_lock_cookie_list(); - net_remove_expired_cookies(); - net_unlock_cookie_list(); -} - -/* return PR_TRUE if "number" is in sequence of comma-separated numbers */ -PRIVATE -PRBool cookie_InSequence(char* sequence, int number) { - char* ptr; - char* endptr; - char* undo = NULL; - PRBool retval = PR_FALSE; - int i; - - /* not necessary -- routine will work even with null sequence */ - if (!*sequence) { - return PR_FALSE; - } - - for (ptr = sequence ; ptr ; ptr = endptr) { - - /* get to next comma */ - endptr = PL_strchr(ptr, ','); - - /* if comma found, process it */ - if (endptr) { - - /* restore last comma-to-null back to comma */ - if (undo) { - *undo = ','; - } - - /* set the comma to a null */ - undo = endptr; - *endptr++ = '\0'; - - /* compare the number before the comma with "number" */ - if (*ptr) { - i = atoi(ptr); - if (i == number) { - - /* "number" was in the sequence so return PR_TRUE */ - retval = PR_TRUE; - break; - } - } - } - } - - /* restore last comma-to-null back to comma */ - if (undo) { - *undo = ','; - } - return retval; -} - -PRIVATE char* -cookie_FindValueInArgs(nsAutoString results, char* name) { - /* note: name must start and end with a vertical bar */ - nsAutoString value; - PRInt32 start, length; - start = results.Find(name); - XP_ASSERT(start >= 0); - if (start < 0) { - return nsAutoString("").ToNewCString(); - } - start += PL_strlen(name); /* get passed the |name| part */ - length = results.FindChar('|', PR_FALSE,start) - start; - results.Mid(value, start, length); - return value.ToNewCString(); -} - -PUBLIC void -COOKIE_CookieViewerReturn(nsAutoString results) -{ - XP_List *cookie_ptr; - XP_List *permission_ptr; - net_CookieStruct * cookie; - net_CookieStruct * cookieToDelete = 0; - net_CookiePermissionStruct * permission; - net_CookiePermissionStruct * permissionToDelete = 0; - int cookieNumber; - int permissionNumber; - - /* step through all cookies and delete those that are in the sequence - * Note: we can't delete cookie while "cookie_ptr" is pointing to it because - * that would destroy "cookie_ptr". So we do a lazy deletion - */ - char * gone = cookie_FindValueInArgs(results, "|goneC|"); - cookieNumber = 0; - net_lock_cookie_list(); - cookie_ptr = net_cookie_list; - while ((cookie = (net_CookieStruct *) XP_ListNextObject(cookie_ptr))) { - if (cookie_InSequence(gone, cookieNumber)) { - if (cookieToDelete) { - net_FreeCookie(cookieToDelete); - } - cookieToDelete = cookie; - } - cookieNumber++; - } - if (cookieToDelete) { - net_FreeCookie(cookieToDelete); - NET_SaveCookies(NULL); - } - net_unlock_cookie_list(); - delete[] gone; - - /* step through all permissions and delete those that are in the sequence - * Note: we can't delete permission while "permission_ptr" is pointing to it because - * that would destroy "permission_ptr". So we do a lazy deletion - */ - gone = cookie_FindValueInArgs(results, "|goneP|"); - permissionNumber = 0; - net_lock_cookie_permission_list(); - permission_ptr = net_cookie_permission_list; - while ((permission = (net_CookiePermissionStruct *) XP_ListNextObject(permission_ptr))) { - if (cookie_InSequence(gone, permissionNumber)) { - if (permissionToDelete) { - net_FreeCookiePermission(permissionToDelete, PR_FALSE); - } - permissionToDelete = permission; - } - permissionNumber++; - } - if (permissionToDelete) { - net_FreeCookiePermission(permissionToDelete, PR_TRUE); - } - net_unlock_cookie_permission_list(); - delete[] gone; -} - -#define BUFLEN2 5000 -#define BREAK '\001' - -PUBLIC void -COOKIE_GetCookieListForViewer(nsString& aCookieList) -{ - char *buffer = (char*)XP_ALLOC(BUFLEN2); - int g = 0, cookieNum; - XP_List *cookie_ptr; - net_CookieStruct * cookie; - - net_lock_cookie_list(); - buffer[0] = '\0'; - cookie_ptr = net_cookie_list; - cookieNum = 0; - - /* generate the list of cookies in alphabetical order */ - cookie = NULL; - while (cookie = NextCookieAfter(cookie, &cookieNum)) { - char *fixed_name = net_FixQuoted(cookie->name); - char *fixed_value = net_FixQuoted(cookie->cookie); - char *fixed_domain_or_host = net_FixQuoted(cookie->host); - char *fixed_path = net_FixQuoted(cookie->path); - char * Domain = cookie_Localize("Domain"); - char * Host = cookie_Localize("Host"); - char * Yes = cookie_Localize("Yes"); - char * No = cookie_Localize("No"); - char * AtEnd = cookie_Localize("AtEndOfSession"); - - g += PR_snprintf(buffer+g, BUFLEN2-g, - "%c%d%c%s%c%s%c%s%c%s%c%s%c%s%c%s", - BREAK, cookieNum, - BREAK, fixed_name, - BREAK, fixed_value, - BREAK, cookie->is_domain ? Domain : Host, - BREAK, fixed_domain_or_host, - BREAK, fixed_path, - BREAK, HG78111 ? Yes : No, - BREAK, cookie->expires ? ctime(&(cookie->expires)) : AtEnd - ); - cookieNum++; - PR_FREEIF(fixed_name); - PR_FREEIF(fixed_value); - PR_FREEIF(fixed_domain_or_host); - PR_FREEIF(fixed_path); - PR_FREEIF(Domain); - PR_FREEIF(Host); - PR_FREEIF(Yes); - PR_FREEIF(No); - PR_FREEIF(AtEnd); - } - aCookieList = buffer; - PR_FREEIF(buffer); - net_unlock_cookie_list(); -} - -PUBLIC void -COOKIE_GetPermissionListForViewer(nsString& aPermissionList) -{ - char *buffer = (char*)XP_ALLOC(BUFLEN2); - int g = 0, permissionNum; - XP_List *permission_ptr; - net_CookiePermissionStruct * permission; - - net_lock_cookie_permission_list(); - buffer[0] = '\0'; - permission_ptr = net_cookie_permission_list; - permissionNum = 0; - while ( (permission=(net_CookiePermissionStruct *) XP_ListNextObject(permission_ptr)) ) { - g += PR_snprintf(buffer+g, BUFLEN2-g, - "%c%d%c%c%s", - BREAK, - permissionNum, - BREAK, - permission->permission ? '+' : '-', - permission->host - ); - permissionNum++; - } - aPermissionList = buffer; - PR_FREEIF(buffer); - net_unlock_cookie_permission_list(); -} diff --git a/mozilla/network/protocol/http/nsGetBrowsingProfile.cpp b/mozilla/network/protocol/http/nsGetBrowsingProfile.cpp deleted file mode 100644 index 339e866d53b..00000000000 --- a/mozilla/network/protocol/http/nsGetBrowsingProfile.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - - This is the hook code which puts together the browsing profile - cookie. - - */ - -#include "nsIServiceManager.h" -#include "nsIBrowsingProfile.h" -#include "plstr.h" - -static NS_DEFINE_CID(kBrowsingProfileCID, NS_BROWSINGPROFILE_CID); - -extern "C" -PRBool BP_GetProfile(char** aProfileStringCopy) -{ - nsresult rv; - nsIBrowsingProfile* profile; - if (NS_FAILED(rv = nsServiceManager::GetService(kBrowsingProfileCID, - nsIBrowsingProfile::GetIID(), - (nsISupports**) &profile))) - // browsing profile not available - return PR_FALSE; - - char buf[kBrowsingProfileCookieSize]; - if (NS_FAILED(rv = profile->GetCookieString(buf))) { - NS_ERROR("unable to get cookie string"); - goto done; - } - - if (! (*aProfileStringCopy = PL_strdup(buf))) - rv = NS_ERROR_OUT_OF_MEMORY; - -done: - nsServiceManager::ReleaseService(kBrowsingProfileCID, profile); - return NS_SUCCEEDED(rv); -} - diff --git a/mozilla/network/protocol/imap4/MANIFEST b/mozilla/network/protocol/imap4/MANIFEST deleted file mode 100644 index fb83670f9ea..00000000000 --- a/mozilla/network/protocol/imap4/MANIFEST +++ /dev/null @@ -1,9 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -imap4pvt.h -imap4url.h -imapbody.h -imaphier.h -mkimap4.h diff --git a/mozilla/network/protocol/imap4/Makefile.in b/mozilla/network/protocol/imap4/Makefile.in deleted file mode 100644 index cc990937cdf..00000000000 --- a/mozilla/network/protocol/imap4/Makefile.in +++ /dev/null @@ -1,52 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = imap4url -LIBRARY_NAME = imap4url - -REQUIRES = util network security netcache network nspr2 dbm util pref js java fileurl security layer img httpurl mimetype htmldlgs - -CSRCS = imap4url.c - -CPPSRCS = \ - imapbody.cpp \ - imapearl.cpp \ - imaphier.cpp \ - imappars.cpp \ - mkimap4.cpp \ - $(NULL) - -EXPORTS = imap4pvt.h imap4url.h imapbody.h imaphier.h mkimap4.h -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - -INCLUDES += -I$(topsrcdir)/lib/libmsg - diff --git a/mozilla/network/protocol/imap4/imap4pvt.h b/mozilla/network/protocol/imap4/imap4pvt.h deleted file mode 100644 index 37eba47e8b3..00000000000 --- a/mozilla/network/protocol/imap4/imap4pvt.h +++ /dev/null @@ -1,1590 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* classes and functions used to implement the IMAP4 netlib module. -*/ - -/* 45678901234567890123456789012345678901234567890123456789012345678901234567890 -*/ -#ifndef IMAP4PVT_H -#define IMAP4PVT_H - -#include "rosetta.h" -#include "mkimap4.h" -#include "prthread.h" -#include "prtypes.h" -#include "prmon.h" -#include "xp_list.h" -#include "imap.h" -#include "imaphier.h" -#include "idarray.h" -#include "ptrarray.h" -#include "mktcp.h" - - -#define IMAP4_PORT 143 /* the iana port for imap4 */ -#define IMAP4_PORT_SSL_DEFAULT 993 /* use a separate port for imap4 over ssl */ - -/* amount to expand for imap entry flags when we need more */ -#define kFlagEntrySize 100 - -// convenient function for atol on int32's -int32 atoint32(char *ascii); - -/* - Using a separate thread to drive the IMAP4 server connection algorithm - is being introduced in 4.0. Since this adding another thread to an - otherwise single threaded program (navigator), then we need a mechanism - for the IMAP thread to use existing, non thread safe, code. - It is a basic rule that all pre-existing code should be executed in the - main 'mozilla' thread. - - TImapFEEventQueue and TImapFEEvent exist to accomplish this goal. - - Whenever the imap thread needs to do something like post an alert or - operate a thermo, then it will add an TImapFEEvent to a TImapFEEventQueue. - - The main (mozilla) thread, in NET_ProcessIMAP4, will periodically check the queue - and execute any events. - - The mozilla thread will also run events in NET_InterruptIMAP4. However, some events - should not be run when interrupted. This is mainly because of sharing memory - between threads through these events, but it can also be for reasons of context - as well. (For instace, running a certain event might not make sense if we get - interrupted). In general, if any event dispatcher creates an event and passes memory - to it which will be freed in the IMAP thread after that event has run, then it should - tell it not to execute when interrupted. This is because interruption tells the thread - to die, which notifies the Event Completion monitor. So, we think these events have - finished, and therefore free the memory; however, the next thing that NET_InterruptIMAP4 - does is try to run these events, which access freed memory, and then bad things happen... - -*/ -typedef void (FEEventFunctionPointer)(void*,void*); - -class TImapFEEvent { -public: - TImapFEEvent(FEEventFunctionPointer *function, void *arg1, void*arg2, XP_Bool executeWhenInterrupted); - virtual ~TImapFEEvent(); - - virtual XP_Bool ShouldExecuteWhenInterrupted() { return fExecuteWhenInterrupted; } - virtual void DoEvent(); - virtual FEEventFunctionPointer *GetEventFunction() { return fEventFunction; } - virtual void SetEventFunction(FEEventFunctionPointer *f) { fEventFunction = f; } - -private: - FEEventFunctionPointer *fEventFunction; - void *fArg1, *fArg2; - XP_Bool fExecuteWhenInterrupted; -}; - -// all of the member functions of TImapFEEventQueue are multithread safe -class TImapFEEventQueue { -public: - static TImapFEEventQueue *CreateFEEventQueue(); - virtual ~TImapFEEventQueue(); - - virtual void AdoptEventToEnd(TImapFEEvent *event); - virtual void AdoptEventToBeginning(TImapFEEvent *event); - virtual TImapFEEvent* OrphanFirstEvent(); - - virtual int NumberOfEventsInQueue(); -protected: - TImapFEEventQueue(); - -private: - XP_List *fEventList; - PRMonitor *fListMonitor; - int fNumberOfEvents; -}; - - -/* This class is used by the imap module to get info about a - url. This ensures that the knowledge about the URL syntax - is not spread across hundreds of strcmp calls. -*/ - -#define IMAP_URL_TOKEN_SEPARATOR ">" - -class TIMAPUrl { -public: - TIMAPUrl(const char *url_string, XP_Bool internal); - virtual ~TIMAPUrl(); - - XP_Bool ValidIMAPUrl(); - - enum EUrlIMAPstate { - kAuthenticatedStateURL, - kSelectedStateURL - }; - - EUrlIMAPstate GetUrlIMAPstate(); - - - enum EIMAPurlType { - // kAuthenticatedStateURL urls - kTest, - kSelectFolder, - kLiteSelectFolder, - kExpungeFolder, - kCreateFolder, - kDeleteFolder, - kRenameFolder, - kMoveFolderHierarchy, - kLsubFolders, - kGetMailAccountUrl, - kDiscoverChildrenUrl, - kDiscoverLevelChildrenUrl, - kDiscoverAllBoxesUrl, - kDiscoverAllAndSubscribedBoxesUrl, - kAppendMsgFromFile, - kSubscribe, - kUnsubscribe, - kRefreshACL, - kRefreshAllACLs, - kListFolder, - kUpgradeToSubscription, - kFolderStatus, - kRefreshFolderUrls, - - // kSelectedStateURL urls - kMsgFetch, - kMsgHeader, - kSearch, - kDeleteMsg, - kDeleteAllMsgs, - kAddMsgFlags, - kSubtractMsgFlags, - kSetMsgFlags, - kOnlineCopy, - kOnlineMove, - kOnlineToOfflineCopy, - kOnlineToOfflineMove, - kOfflineToOnlineMove, - kBiff - }; - - EIMAPurlType GetIMAPurlType(); - - const char *GetUrlHost() { return fHostSubString; } - - // these functions have Preconditions - char *CreateCanonicalSourceFolderPathString(); - char *CreateCanonicalDestinationFolderPathString(); - - char *CreateServerSourceFolderPathString(); - char *CreateServerDestinationFolderPathString(); - - char *CreateSearchCriteriaString(); - char *CreateListOfMessageIdsString(); - char *GetIMAPPartToFetch(); - imapMessageFlagsType GetMsgFlags(); // kAddMsgFlags, kSubtractMsgFlags, or kSetMsgFlags only - - XP_Bool MessageIdsAreUids(); - XP_Bool MimePartSelectorDetected() { return fMimePartSelectorDetected; } - - void SetOnlineSubDirSeparator(char onlineDirSeparator); - char GetOnlineSubDirSeparator(); - - char *AllocateServerPath(const char *canonicalPath); - char *AllocateCanonicalPath(const char *serverPath); - - int GetChildDiscoveryDepth() { return fDiscoveryDepth; } - XP_Bool GetShouldSubscribeToAll(); - -private: - // assigning and copying not allowed - TIMAPUrl(const TIMAPUrl& copy); - TIMAPUrl& operator=(const TIMAPUrl& copy); - - void Parse(); - void ParseSearchCriteriaString(); - void ParseListofMessageIds(); - void ParseUidChoice(); - void ParseMsgFlags(); - void ParseChildDiscoveryDepth(); - - void ParseFolderPath(char **resultingCanonicalPath); - - char *ReplaceCharsInCopiedString(const char *stringToCopy, char oldChar, char newChar); - - - char *fUrlString; - char *fHostSubString; - char *fUrlidSubString; - char *fSourceCanonicalFolderPathSubString; - char *fDestinationCanonicalFolderPathSubString; - char *fSearchCriteriaString; - char *fListOfMessageIds; - char *fTokenPlaceHolder; - char fOnlineSubDirSeparator; // not static anymore - one delimiter for each URL we run. - - imapMessageFlagsType fFlags; - - XP_Bool fIdsAreUids; - XP_Bool fMimePartSelectorDetected; - - EUrlIMAPstate fIMAPstate; - EIMAPurlType fUrlType; - - XP_Bool fValidURL; - XP_Bool fInternal; - int fDiscoveryDepth; -}; - - -class TSearchResultSequence { -public: - virtual ~TSearchResultSequence(); - static TSearchResultSequence *CreateSearchResultSequence(); - - virtual void AddSearchResultLine(const char *searchLine); - virtual void ResetSequence(); - - friend class TSearchResultIterator; -private: - TSearchResultSequence(); - XP_List *fListOfLines; -}; - -class TSearchResultIterator { -public: - TSearchResultIterator(TSearchResultSequence &sequence); - virtual ~TSearchResultIterator(); - - void ResetIterator(); - int32 GetNextMessageNumber(); // returns 0 at end of list -private: - TSearchResultSequence &fSequence; - XP_List *fCurrentLine; - char *fPositionInCurrentLine; -}; - - -class TIMAP4BlockingConnection; - - -class TImapFlagAndUidState { -public: - TImapFlagAndUidState(int numberOfMessages, XP_Bool bSupportUserFlag = FALSE); - TImapFlagAndUidState(const TImapFlagAndUidState& state, XP_Bool bSupportUserFlag = FALSE); - virtual ~TImapFlagAndUidState(); - - int GetNumberOfMessages(); - int GetNumberOfDeletedMessages(); - - imap_uid GetUidOfMessage(int zeroBasedIndex); - imapMessageFlagsType GetMessageFlags(int zeroBasedIndex); - imapMessageFlagsType GetMessageFlagsFromUID(imap_uid uid, XP_Bool *foundIt, int32 *ndx); - XP_Bool IsLastMessageUnseen(void); - void ExpungeByIndex(uint32 index); - // adds to sorted list. protects against duplicates and going past fNumberOfMessageSlotsAllocated - void AddUidFlagPair(imap_uid uid, imapMessageFlagsType flags); - - imap_uid GetHighestNonDeletedUID(); - void Reset(uint32 howManyLeft); -private: - - int32 fNumberOfMessagesAdded; - int32 fNumberOfMessageSlotsAllocated; - int32 fNumberDeleted; - IDArray fUids; - imapMessageFlagsType *fFlags; - XP_Bool fSupportUserFlag; -}; - - -class TIMAPGenericParser { - -public: - TIMAPGenericParser(); - virtual ~TIMAPGenericParser(); - - // Connected() && !SyntaxError() - // Add any specific stuff in the derived class - virtual XP_Bool LastCommandSuccessful(); - - XP_Bool SyntaxError(); - virtual XP_Bool ContinueParse(); - - // if we get disconnected, end the current url processing and report to the - // the user. - XP_Bool Connected(); - virtual void SetConnected(XP_Bool error); - - char *CreateSyntaxErrorLine(); - -protected: - - // This is a pure virtual member which must be overridden in the derived class - // for each different implementation of a TIMAPGenericParser. - // For instance, one implementation (the TImapServerState) might get the next line - // from an open socket, whereas another implementation might just get it from a buffer somewhere. - // This fills in nextLine with the buffer, and returns TRUE if everything is OK. - // Returns FALSE if there was some error encountered. In that case, we reset the parser. - virtual XP_Bool GetNextLineForParser(char **nextLine) = 0; - - virtual void HandleMemoryFailure(); - virtual void skip_to_CRLF(); - virtual void skip_to_close_paren(); - virtual char *CreateString(); - virtual char *CreateAstring(); - virtual char *CreateNilString(); - virtual char *CreateLiteral(); - virtual char *CreateAtom(); - virtual char *CreateQuoted(XP_Bool skipToEnd = TRUE); - virtual char *CreateParenGroup(); - virtual void SetSyntaxError(XP_Bool error); - virtual XP_Bool at_end_of_line(); - - char *GetNextToken(); - void AdvanceToNextLine(); - void AdvanceTokenizerStartingPoint (int32 bytesToAdvance); - void ResetLexAnalyzer(); - -protected: - // use with care - char *fNextToken; - char *fCurrentLine; - char *fLineOfTokens; - char *fStartOfLineOfTokens; - char *fCurrentTokenPlaceHolder; - -private: - XP_Bool fAtEndOfLine; - XP_Bool fTokenizerAdvanced; - - char *fSyntaxErrorLine; - XP_Bool fDisconnected; - XP_Bool fSyntaxError; - -}; - -class TIMAPNamespace; -class TIMAPNamespaceList; -class TIMAPBodyShell; - -class TImapServerState : public TIMAPGenericParser { -public: - TImapServerState(TIMAP4BlockingConnection &imapConnection); - virtual ~TImapServerState(); - - // Overridden from the base parser class - virtual XP_Bool LastCommandSuccessful(); - virtual void HandleMemoryFailure(); - - virtual void ParseIMAPServerResponse(const char *currentCommand); - virtual void InitializeState(); - XP_Bool CommandFailed(); - - enum eIMAPstate { - kNonAuthenticated, - kAuthenticated, - kFolderSelected, - kWaitingForMoreClientInput - } ; - - virtual eIMAPstate GetIMAPstate(); - virtual void SetIMAPstate(eIMAPstate state) { fIMAPstate = state; }; - - const char *GetSelectedMailboxName(); // can be NULL - - // if we get a PREAUTH greeting from the server, initialize the parser to begin in - // the kAuthenticated state - void PreauthSetAuthenticatedState(); - - // these functions represent the state of the currently selected - // folder - XP_Bool CurrentFolderReadOnly(); - int32 NumberOfMessages(); - int32 NumberOfRecentMessages(); - int32 NumberOfUnseenMessages(); - int32 FolderUID(); - uint32 CurrentResponseUID(); - uint32 HighestRecordedUID(); - int32 SizeOfMostRecentMessage(); - void SetTotalDownloadSize(int32 newSize) { fTotalDownloadSize = newSize; } - - TSearchResultIterator *CreateSearchResultIterator(); - void ResetSearchResultSequence() {fSearchResults->ResetSequence();} - - // create a struct mailbox_spec from our info, used in - // libmsg c interface - struct mailbox_spec *CreateCurrentMailboxSpec(const char *mailboxName = NULL); - - // zero stops a list recording of flags and causes the flags for - // each individual message to be sent back to libmsg - void ResetFlagInfo(int numberOfInterestingMessages); - - // set this to false if you don't want to alert the user to server - // error messages - void SetReportingErrors(XP_Bool reportThem) { fReportingErrors=reportThem;} - XP_Bool GetReportingErrors() { return fReportingErrors; } - - uint32 GetCapabilityFlag() { return fCapabilityFlag; } - void SetCapabilityFlag(uint32 capability) {fCapabilityFlag = capability;} - XP_Bool ServerHasIMAP4Rev1Capability() { return (fCapabilityFlag & kIMAP4rev1Capability); } - XP_Bool ServerHasACLCapability() { return (fCapabilityFlag & kACLCapability); } - XP_Bool ServerHasNamespaceCapability() { return (fCapabilityFlag & kNamespaceCapability); } - XP_Bool ServerIsNetscape3xServer() { return fServerIsNetscape3xServer; } - XP_Bool ServerHasServerInfo() {return (fCapabilityFlag & kXServerInfoCapability);} - void ResetCapabilityFlag() ; - - const char *GetMailAccountUrl() { return fMailAccountUrl; } - const char *GetXSenderInfo() { return fXSenderInfo; } - void FreeXSenderInfo() { FREEIF(fXSenderInfo); } - const char *GetManageListsUrl() { return fManageListsUrl; } - const char *GetManageFiltersUrl() {return fManageFiltersUrl;} - const char *GetManageFolderUrl() {return fFolderAdminUrl;} - - - TImapFlagAndUidState *GetCurrentFlagState() { return fFlagState; } - - // Call this when adding a pipelined command to the session - void IncrementNumberOfTaggedResponsesExpected(const char *newExpectedTag); - - // Interrupt a Fetch, without really Interrupting (through netlib) - XP_Bool GetLastFetchChunkReceived(); - void ClearLastFetchChunkReceived(); - virtual XP_Bool SupportsUserFlags() { return fSupportsUserDefinedFlags; }; - void SetFlagState(TImapFlagAndUidState *state); - - XP_Bool GetFillingInShell(); - void UseCachedShell(TIMAPBodyShell *cachedShell); - -protected: - virtual void flags(); - virtual void response_data(); - virtual void resp_text(); - virtual void resp_cond_state(); - virtual void text_mime2(); - virtual void text(); - virtual void resp_text_code(); - virtual void response_done(); - virtual void response_tagged(); - virtual void response_fatal(); - virtual void resp_cond_bye(); - virtual void mailbox_data(); - virtual void numeric_mailbox_data(); - virtual void capability_data(); - virtual void xserverinfo_data(); - virtual void xmailboxinfo_data(); - virtual void namespace_data(); - virtual void myrights_data(); - virtual void acl_data(); - virtual void bodystructure_data(); - virtual void mime_data(); - virtual void mime_part_data(); - virtual void mime_header_data(); - virtual void msg_fetch(); - virtual void msg_obsolete(); - virtual void msg_fetch_headers(const char *partNum); - virtual void msg_fetch_content(XP_Bool chunk, int32 origin, const char *content_type); - virtual XP_Bool msg_fetch_quoted(XP_Bool chunk, int32 origin); - virtual XP_Bool msg_fetch_literal(XP_Bool chunk, int32 origin); - virtual void mailbox_list(XP_Bool discoveredFromLsub); - virtual void mailbox(mailbox_spec *boxSpec); - - virtual XP_Bool IsNumericString(const char *string); - - virtual void ProcessOkCommand(const char *commandToken); - virtual void ProcessBadCommand(const char *commandToken); - virtual void PreProcessCommandToken(const char *commandToken, - const char *currentCommand); - virtual void PostProcessEndOfLine(); - - // Overridden from the TIMAPGenericParser, to retrieve the next line - // from the open socket. - virtual XP_Bool GetNextLineForParser(char **nextLine); - virtual void end_of_line(); - -private: - XP_Bool fProcessingTaggedResponse; - XP_Bool fCurrentCommandFailed; - XP_Bool fReportingErrors; - - - XP_Bool fCurrentFolderReadOnly; - - XP_Bool fCurrentLineContainedFlagInfo; - imapMessageFlagsType fSavedFlagInfo; - - - XP_Bool fSupportsUserDefinedFlags; - - int32 fFolderUIDValidity; - int32 fNumberOfUnseenMessages; - int32 fNumberOfExistingMessages; - int32 fNumberOfRecentMessages; - uint32 fCurrentResponseUID; - uint32 fHighestRecordedUID; - int32 fSizeOfMostRecentMessage; - int32 fTotalDownloadSize; - - int fNumberOfTaggedResponsesExpected; - - char *fCurrentCommandTag; - - char *fZeroLengthMessageUidString; - - char *fSelectedMailboxName; - - TSearchResultSequence *fSearchResults; - - TImapFlagAndUidState *fFlagState; // NOT owned by this object, it's a copy, do not destroy - - eIMAPstate fIMAPstate; - - uint32 fCapabilityFlag; - char *fMailAccountUrl; - char *fNetscapeServerVersionString; - char *fXSenderInfo; /* changed per message download */ - char *fLastAlert; /* used to avoid displaying the same alert over and over */ - char *fManageListsUrl; - char *fManageFiltersUrl; - char *fFolderAdminUrl; - - // used for index->uid mapping - XP_Bool fCurrentCommandIsSingleMessageFetch; - int32 fUidOfSingleMessageFetch; - int32 fFetchResponseIndex; - - // used for aborting a fetch stream when we're pseudo-Interrupted - XP_Bool fDownloadingHeaders; - int32 numberOfCharsInThisChunk; - int32 charsReadSoFar; - XP_Bool fLastChunk; - - // Is the server a Netscape 3.x Messaging Server? - XP_Bool fServerIsNetscape3xServer; - - // points to the current body shell, if any - TIMAPBodyShell *m_shell; - - // The connection object - TIMAP4BlockingConnection &fServerConnection; -}; - -/* - This virtual base class contains the interface and the code - that drives the algorithms for performing imap4 server - transactions. - - This base class contains no knowledge of 'how things were' before - 4.0. The knowledge of our URL language, how we do socket io, - and how we perform events in other threads is found in a concrete - subclass. -*/ - -#define kOutputBufferSize 2048 - -class TNavigatorImapConnection; - - -class TIMAP4BlockingConnection { -public: - enum eFetchFields { - kEveryThingRFC822, - kEveryThingRFC822Peek, - kHeadersRFC822andUid, - kUid, - kFlags, - kRFC822Size, - kRFC822HeadersOnly, - kMIMEPart, - kMIMEHeader - }; - - - virtual ~TIMAP4BlockingConnection(); - - // This should be used only for setting the connection status, i.e. MK_CONNECTED, MK_WAITING_FOR_CONNECTION, etc. - // This should not be used for getting/setting the status of the currently running ActiveEntry. - // (Use Get/SetCurrentEntryStatus()) for passing values back to libnet about the currently running ActiveEntry. - int GetConnectionStatus(); - void SetConnectionStatus(int status); - - // safe downcast, returns non-null if cast worked - virtual TNavigatorImapConnection *GetNavigatorConnection(); - - // Have we detected new mail ? - virtual XP_Bool NewMailDetected(void) { return FALSE; }; - virtual void ParseIMAPandCheckForNewMail(char *buff = NULL) = 0; - - // These 2 functions are thread safe. If BlockedForIO then it will - // become unblocked with a call to NotifyIOCompletionMonitor - void NotifyIOCompletionMonitor(); - XP_Bool BlockedForIO(); - - virtual void ProcessBIFFRequest(); - - // non-authenticated state commands - virtual void InsecureLogin(const char *userName, const char *password); - // Authenticate will happen later - - virtual void AuthLogin(const char *userName, const char *password); - - // authenticated state commands - virtual void SelectMailbox(const char *mailboxName); - // will do examine as needed - virtual void CreateMailbox(const char *mailboxName); - virtual void DeleteMailbox(const char *mailboxName); - virtual void RenameMailbox(const char *existingName, const char *newName); - - virtual void AppendMessage(const char *mailboxName, - const char *messageSizeString, - imapMessageFlagsType flags); - - virtual void Subscribe(const char *mailboxName); - virtual void Unsubscribe(const char *mailboxName); - - virtual void List(const char *mailboxPattern,XP_Bool pipeLined = FALSE, XP_Bool dontTimeStamp = FALSE); - virtual void Lsub(const char *mailboxPattern, XP_Bool pipelined = FALSE); - - // selected state commands - virtual void FetchMessage(const char *messageIds, - eFetchFields whatToFetch, - XP_Bool idAreUid, - uint32 startByte = 0, uint32 endByte = 0, - char *part = 0) = 0; - virtual void Bodystructure(const char *messageId, XP_Bool idIsUid) = 0; - - virtual void Close(); - virtual void Expunge(); - virtual void Check(); - - virtual void Search(const char *searchCriteria, XP_Bool useUID, - XP_Bool notifyHit = TRUE); - - virtual void Store(const char *messageList, - const char *messageData, - XP_Bool idsAreUid); - - virtual void Copy( const char *messageList, - const char *destinationMailbox, - XP_Bool idsAreUid); - - - virtual void Netscape(); - virtual void XServerInfo(); - virtual void XMailboxInfo(const char *mailboxName); - - - // any state commands - virtual void Logout(); - virtual void Noop(); - virtual void Capability(); - - virtual void Namespace(); - virtual void MailboxData(); - virtual void GetMyRightsForFolder(const char *mailboxName); - virtual void GetACLForFolder(const char *mailboxName); - - virtual void StatusForFolder(const char *mailboxName); - - virtual void AlertUserEvent_UsingId(uint32 msgId) = 0; - virtual void AlertUserEvent(char *message) = 0; - virtual void AlertUserEventFromServer (char *serverSaid) = 0; - virtual void ProgressUpdateEvent(char *message) = 0; - virtual void ProgressEventFunction_UsingId(uint32 msgId) = 0; - virtual void ProgressEventFunction_UsingIdWithString(uint32 msgId, const char * extraInfo) = 0; - virtual void PercentProgressUpdateEvent(char *message, int percent) = 0; - virtual void PastPasswordCheckEvent() = 0; - - // does a blocking read of the socket, returns a newly allocated - // line or nil and a status - virtual char *CreateNewLineFromSocket() = 0; - // does a write to the socket - virtual int WriteLineToSocket(char *line) = 0; - - // Use these functions to stream a message fetch to the current context - // Used initially by TImapServerState - virtual void BeginMessageDownLoad(uint32 total_size, - const char *content_type)=0; // some downloads are header only - virtual void HandleMessageDownLoadLine(const char *line, XP_Bool chunkEnd)=0; - virtual void NormalMessageEndDownload()=0; - virtual void AbortMessageDownLoad()=0; - virtual void AddXMozillaStatusLine(uint16 flags)=0; // for XSender auth info - - // used to notify the fe to upload the message to this - // connection's socket - virtual void UploadMessage() = 0; - - // notify the fe about a message's imap message flags - virtual void NotifyMessageFlags( imapMessageFlagsType flags, MessageKey key) = 0; - - // notify the fe about a search hit - virtual void NotifySearchHit(const char *hitLine) = 0; - - // a call back from TImapServerState to handle mailbox discovery - virtual void DiscoverMailboxSpec(mailbox_spec *adoptedBoxSpec) = 0; - - // notify the fe about the state of the selected mailbox - virtual void UpdatedMailboxSpec(mailbox_spec *adoptedBoxSpec) = 0; - virtual void UpdateMailboxStatus(mailbox_spec *adoptedBoxSpec) = 0; - - // notify the fe that the current online copy is done - virtual void OnlineCopyCompleted(ImapOnlineCopyState copyState) = 0; - - // notify the fe that a folder was deleted - virtual void FolderDeleted(const char *mailboxName) = 0; - - // notify the fe that a folder creation failed - virtual void FolderNotCreated(const char *mailboxName) = 0; - - // notify the fe that a folder was deleted - virtual void FolderRenamed(const char *oldName, - const char *newName) = 0; - - // notify the fe that we're done finding folders - virtual void MailboxDiscoveryFinished() = 0; - - // return the server response parser - virtual TImapServerState &GetServerStateParser(); - - - // This function will report the low mem conditions to the user, - // empty the fe event queue and set the connection status to negative - // so netlib will exit ProcessImap4. - virtual void HandleMemoryFailure() = 0; - - - // if you call TellThreadToDie(FALSE) then you are responsible for - // calling SetIsSafeToDie when you are ready for the imap thread to - // delete the connection. - virtual void TellThreadToDie(XP_Bool isSafeToDie = TRUE)=0; - virtual void SetIsSafeToDie()=0; - virtual XP_Bool DeathSignalReceived()=0; - - virtual void ShowProgress()=0; - virtual const char *GetHostName()=0; - - void SetDeleteIsMoveToTrash(XP_Bool deleteIsMoveToTrash) {fDeleteModelIsMoveToTrash = deleteIsMoveToTrash;} - - // used the convert to/from UTF7IMAP - virtual char* CreateUtf7ConvertedString(const char *sourceString, XP_Bool toUtf7Imap)=0; - - static int64 GetTimeStampOfNonPipelinedList() { return fgTimeStampOfNonPipelinedList; } -protected: - void WaitForIOCompletion(); - void WaitForFEEventCompletion(); - void WaitForTunnelCompletion(); - - // manage the IMAP server command tags - void IncrementCommandTagNumber(); - - char *CreateEscapedMailboxName(const char *rawName); - - - // establish connection, this will not alert the user if there is a problem - // affects GetConnectionStatus() - virtual void EstablishServerConnection() = 0; - - - // called from concrete subclass constructor - TIMAP4BlockingConnection(); - virtual XP_Bool ConstructionSuccess(); // called by subclass factory - - char *GetOutputBuffer(); - char *GetServerCommandTag(); - PRMonitor *GetDataMemberMonitor(); - - // returns TRUE if the messageIdString indicates that this is an operation - // on more than one message. - XP_Bool HandlingMultipleMessages(char *messageIdString); - - void TimeStampListNow(); - - XP_Bool SupportsUserDefinedFlags() { return fServerState.SupportsUserFlags(); }; - -protected: - static int64 fgTimeStampOfNonPipelinedList; - TImapServerState fServerState; - XP_Bool fBlockedForIO; - XP_Bool fCloseNeededBeforeSelect; - XP_Bool fDeleteModelIsMoveToTrash; - int fConnectionStatus; - PRMonitor *fDataMemberMonitor; - PRMonitor *fIOMonitor; - char fCurrentServerCommandTag[10]; // enough for a billion - int fCurrentServerCommandTagNumber; - char fOutputBuffer[kOutputBufferSize]; - XP_Bool fFromHeaderSeen; - XP_Bool fNotifyHit; -}; - - -#define kDownLoadCacheSize 1536 -struct msg_line_info; - -class TLineDownloadCache { -public: - TLineDownloadCache(); - virtual ~TLineDownloadCache(); - - uint32 CurrentUID(); - uint32 SpaceAvailable(); - XP_Bool CacheEmpty(); - - msg_line_info *GetCurrentLineInfo(); - - void ResetCache(); - void CacheLine(const char *line, uint32 uid); -private: - char fLineCache[kDownLoadCacheSize]; - uint32 fBytesUsed; - - msg_line_info *fLineInfo; - -}; - -class TIMAPSocketInfo; -class TIMAPBodyShellCache; - -// this is a linked list of host info's -class TIMAPHostInfo -{ -public: - - // Host List - static XP_Bool AddHostToList(const char *hostName); - static void ResetAll(); - - // Capabilities - static uint32 GetCapabilityForHost(const char *hostName); - static XP_Bool SetCapabilityForHost(const char *hostName, uint32 capability); - static XP_Bool GetHostHasAdminURL(const char *hostName); - static XP_Bool SetHostHasAdminURL(const char *hostName, XP_Bool hasAdminUrl); - // Subscription - static XP_Bool GetHostIsUsingSubscription(const char *hostName); - static XP_Bool SetHostIsUsingSubscription(const char *hostName, XP_Bool usingSubscription); - - // Passwords - static char *GetPasswordForHost(const char *hostName); - static XP_Bool SetPasswordForHost(const char *hostName, const char *password); - static XP_Bool GetPasswordVerifiedOnline(const char *hostName); - static XP_Bool SetPasswordVerifiedOnline(const char *hostName); - - // Folders - static XP_Bool SetHaveWeEverDiscoveredFoldersForHost(const char *hostName, XP_Bool discovered); - static XP_Bool GetHaveWeEverDiscoveredFoldersForHost(const char *hostName); - - // Trash Folder - static XP_Bool SetOnlineTrashFolderExistsForHost(const char *hostName, XP_Bool exists); - static XP_Bool GetOnlineTrashFolderExistsForHost(const char *hostName); - - // INBOX - static char *GetOnlineInboxPathForHost(const char *hostName); - static XP_Bool GetShouldAlwaysListInboxForHost(const char *hostName); - static XP_Bool SetShouldAlwaysListInboxForHost(const char *hostName, XP_Bool shouldList); - - // Namespaces - static TIMAPNamespace *GetNamespaceForMailboxForHost(const char *hostName, const char *mailbox_name); - static XP_Bool AddNewNamespaceForHost(const char *hostName, TIMAPNamespace *ns); - static XP_Bool ClearServerAdvertisedNamespacesForHost(const char *hostName); - static XP_Bool ClearPrefsNamespacesForHost(const char *hostName); - static TIMAPNamespace *GetDefaultNamespaceOfTypeForHost(const char *hostName, EIMAPNamespaceType type); - static XP_Bool SetNamespacesOverridableForHost(const char *hostName, XP_Bool overridable); - static XP_Bool GetNamespacesOverridableForHost(const char *hostName); - static int GetNumberOfNamespacesForHost(const char *hostName); - static TIMAPNamespace *GetNamespaceNumberForHost(const char *hostName, int n); - static XP_Bool CommitNamespacesForHost(const char *hostName, MSG_Master *master); - - - // Hierarchy Delimiters - static XP_Bool AddHierarchyDelimiter(const char *hostName, char delimiter); - static char *GetHierarchyDelimiterStringForHost(const char *hostName); - static XP_Bool SetNamespaceHierarchyDelimiterFromMailboxForHost(const char *hostName, const char *boxName, char delimiter); - - // Message Body Shells - static XP_Bool AddShellToCacheForHost(const char *hostName, TIMAPBodyShell *shell); - static TIMAPBodyShell *FindShellInCacheForHost(const char *hostName, const char *mailboxName, const char *UID); - - static PRMonitor *gCachedHostInfoMonitor; - static TIMAPHostInfo *fHostInfoList; -protected: - TIMAPHostInfo(const char *hostName); - static TIMAPHostInfo *FindHost(const char *hostName); - ~TIMAPHostInfo(); - char *fHostName; - char *fCachedPassword; - TIMAPHostInfo *fNextHost; - uint32 fCapabilityFlags; - char *fHierarchyDelimiters; // string of top-level hierarchy delimiters - XP_Bool fHaveWeEverDiscoveredFolders; - char *fCanonicalOnlineSubDir; - TIMAPNamespaceList *fNamespaceList; - XP_Bool fNamespacesOverridable; - XP_Bool fUsingSubscription; - XP_Bool fOnlineTrashFolderExists; - XP_Bool fShouldAlwaysListInbox; - XP_Bool fHaveAdminURL; - XP_Bool fPasswordVerifiedOnline; - TIMAPBodyShellCache *fShellCache; -}; - -class MSG_FolderInfo; -class TIMAPMessagePartIDArray; - -class TNavigatorImapConnection : public TIMAP4BlockingConnection { -public: - static TNavigatorImapConnection* - Create(const char *hostName); - - virtual ~TNavigatorImapConnection(); - - static SetupConnection(ActiveEntry * ce, MSG_Master *master, XP_Bool loadingURL); - - // Performs a PR_LOG on logData, formatting it to a standard IMAP i/o log format. - // This checks the state of the parser and tells us which connection we're using, the selected folder, etc. - // logSubName is a name like "BODYSHELL," "NETWORK," "URL," etc... basically, a way to subcategorize what - // type of log entry this is. - // extraInfo is any extra notes that should be added to this log entry. For instance, a "NETWORK" entry - // might also pass in "READ" or "WRITE" as extraInfo. extraInfo can be NULL, in which case we don't add anything. - // logData is the data to be logged. - - void Log(const char *logSubName, const char *extraInfo, const char *logData); - - - // checks for new mail and gets headers if nescesary - virtual XP_Bool CheckNewMail(void); - virtual void SelectMailbox(const char *mailboxName); - virtual void Configure(XP_Bool GetHeaders, int32 TooFastTime, int32 IdealTime, - int32 ChunkAddSize, int32 ChunkSize, int32 ChunkThreshold, - XP_Bool FetchByChunks, int32 MaxChunkSize); - - // dumb but usefull safe downcast, returns non-null if cast worked - virtual TNavigatorImapConnection *GetNavigatorConnection(); - - // gets/sets the status of the currently running ActiveEntry. - // This should not be used for setting the connection status, i.e. MK_CONNECTED, MK_WAITING_FOR_CONNECTION, etc. - int GetCurrentEntryStatus(); - void SetCurrentEntryStatus(int status); - - // call by imap thread to endlessly process active entries - virtual void StartProcessingActiveEntries(); - - // thread safe: Called by main thread to submit ActiveEntry - // for processing - // Will block if !BlockedWaitingForActiveEntry - virtual void SubmitActiveEntry(ActiveEntry * ce, XP_Bool newConnection); - - // returns true if another thread is blocked waiting - virtual XP_Bool BlockedWaitingForActiveEntry(); - - /* I don't know about this! - // thread safe call to add another ActiveEntry to the queue - virtual void AddActiveEntryJob(ActiveEntry *entry); - - // thread safe call that will - // 1. Stop processing the current entry if it shares - // the same context with the passed entry - // - // 2. Remove entries from the queue if they share the - // same context with the passed entry - virtual void AbortActiveEntry(ActiveEntry *entry); - */ - - - // Tunnels - virtual int32 OpenTunnel (int32 maxNumberOfBytesToRead); - XP_Bool GetIOTunnellingEnabled(); - int32 GetTunnellingThreshold(); - - - TImapFEEventQueue &GetFEEventQueue(); - void SetBlockingThread(PRThread *blockingThread); - - // if you call TellThreadToDie(FALSE) then you are responsible for - // calling SetIsSafeToDie when you are ready for the imap thread to - // delete the connection. - virtual void TellThreadToDie(XP_Bool isSafeToDie = TRUE); - virtual void SetIsSafeToDie(); - - virtual XP_Bool DeathSignalReceived(); - - // this function is thread safe - // this function is used by the fe functions to signal their completion - void NotifyEventCompletionMonitor(); - - // This function is threadsafe - // It is used by certain FE events to signal the completion of an IO tunnel. - void NotifyTunnelCompletionMonitor(); - - // this function is thread safe - // this function is used by the fe signal complete message upload - void NotifyMessageUploadMonitor(); - - // this function is thread safe - // notifies that the fe thread is done processing fe events - void SignalEventQueueEmpty(); - - // not thread safe. intended to be called from the fe event functions - ActiveEntry *GetActiveEntry(); - TCP_ConData **GetTCPConData(); - - - // these functions might seem silly but I don't want the IMAP thread - // to ever muck with the ActiveEntry structure fields, so the socket - // will be set when we begin the connection. These setters and getters - // are thread safe - void SetIOSocket(PRFileDesc *socket); - PRFileDesc * GetIOSocket(); - - void SetOutputStream(NET_StreamClass *outputStream); - NET_StreamClass *GetOutputStream(); - - virtual XP_Bool UseSSL() { return FALSE; }; - - virtual void FetchMessage(const char *messageIds, - eFetchFields whatToFetch, - XP_Bool idAreUid, - uint32 startByte = 0, uint32 endByte = 0, - char *part = 0); - virtual void FetchTryChunking(const char *messageIds, - eFetchFields whatToFetch, - XP_Bool idAreUid, - char *part, - uint32 downloadSize); - virtual void PipelinedFetchMessageParts(const char *uid, - TIMAPMessagePartIDArray *parts); - virtual void Bodystructure(const char *messageId, XP_Bool idIsUid); - - virtual void Logout(); - - virtual void AlertUserEvent_UsingId(uint32 msgId); - virtual void AlertUserEvent(char *message); - virtual void AlertUserEventFromServer(char *serverSaid); - virtual void ProgressUpdateEvent(char *message); - virtual void ProgressEventFunction_UsingId(uint32 msgId); - virtual void ProgressEventFunction_UsingIdWithString(uint32 msgId, const char* extraInfo); - virtual void PercentProgressUpdateEvent(char *message, int percent); - virtual void PastPasswordCheckEvent(); - - void WaitForFEEventCompletion(); - void WaitForTunnelCompletion(); - - // does a blocking read of the socket, returns a newly allocated - // line or nil and a status - virtual char *CreateNewLineFromSocket(); - - // does a write to the socket - virtual int WriteLineToSocket(char *line); - - // establish connection, this will not alert the user if there is a - // problem. affects GetConnectionStatus() - virtual void EstablishServerConnection(); - - // Use these functions to stream a message fetch to the current context - // Used initially by TImapServerState - virtual void BeginMessageDownLoad(uint32 total_size, // for user, headers and body - const char *content_type); // some downloads are header only - virtual void HandleMessageDownLoadLine(const char *line, XP_Bool chunkEnd); - virtual void NormalMessageEndDownload(); - virtual void AbortMessageDownLoad(); - virtual void PostLineDownLoadEvent(msg_line_info *downloadLineDontDelete); - virtual void AddXMozillaStatusLine(uint16 flags); // for XSender auth info - - // used to notify the fe to upload the message to this - // connection's socket - virtual void UploadMessage(); - - virtual void UploadMessageFromFile(const char *srcFilePath, - const char *mailboxName, - imapMessageFlagsType flags); - - // notify the fe about a message's imap message flags - virtual void NotifyMessageFlags( imapMessageFlagsType flags, MessageKey key); - - // notify the fe about a search hit - virtual void NotifySearchHit(const char *hitLine); - - // a call back from TImapServerState to handle mailbox discovery - virtual void DiscoverMailboxSpec(mailbox_spec *adoptedBoxSpec); - - // notify the fe about the state of the selected mailbox - virtual void UpdatedMailboxSpec(mailbox_spec *adoptedBoxSpec); - virtual void UpdateMailboxStatus(mailbox_spec *adoptedBoxSpec); - - // notify the fe that the current online copy is done - virtual void OnlineCopyCompleted(ImapOnlineCopyState copyState); - - // notify the fe that a folder was deleted - virtual void FolderDeleted(const char *mailboxName); - - // notify the fe that a folder was renamed - virtual void FolderRenamed(const char *oldName, - const char *newName); - - // notify the fe that a folder creation failed - virtual void FolderNotCreated(const char *mailboxName); - - // handle any post-mailbox-discovery tasks (Trash folder, etc.) - virtual void MailboxDiscoveryFinished(); - - // notify the fe that we're done finding folders - virtual void SetFolderDiscoveryFinished(); - - // This function will report the low mem conditions to the user, - // empty the fe event queue and set the connection status to negative - // so netlib will exit ProcessImap4. - // threadsafe - virtual void HandleMemoryFailure(); - - // These three functions are used to graph the progress of a - // message download - int32 GetMessageSizeForProgress(); - int32 GetBytesMovedSoFarForProgress(); - void SetBytesMovedSoFarForProgress(int32 bytesMoved); - - // Returns true if a msg move/copy is happening - XP_Bool CurrentConnectionIsMove(); - - // receive the list of msg ids for fetching msgs - void NotifyKeyList(uint32 *bodyKeys, uint32 bodyCount); // storage adopted - - // receive the size of the next message append - void NotifyAppendSize(uint32 msgSize, imapMessageFlagsType flags); - - virtual XP_Bool NewMailDetected(void); - virtual void ParseIMAPandCheckForNewMail(char *buff = NULL); - - // returns a newly allocated string - char *GetCurrentConnectionURL(); - - // These calls are not thread safe. Called from the mozilla - // thread to keep track of whether we have set call netlib all the time - inline void SetCallingNetlibAllTheTime(XP_Bool callingNetlib) - { fCallingNetlibAllTheTime = callingNetlib; }; - - inline XP_Bool GetCallingNetlibAllTheTime() { return fCallingNetlibAllTheTime; }; - - static void ResetCachedConnectionInfo(); - - // sets the folder info for the currently running URL - void SetFolderInfo(MSG_FolderInfo *folder, XP_Bool folderNeedsSubscribing, - XP_Bool folderNeedsACLRefreshed); - - virtual void ShowProgress(); - - virtual void SetMailboxDiscoveryStatus(EMailboxDiscoverStatus status); - virtual EMailboxDiscoverStatus GetMailboxDiscoveryStatus(); - //static XP_Bool HaveWeEverDiscoveredNewMailboxes() { return fHaveWeEverFoundImapMailboxes; } - - void BodyIdMonitor(XP_Bool enter); - - void SetNeedsGreeting(XP_Bool need) { fNeedGreeting = need; } - void SetNeedsNoop(XP_Bool need) {fNeedNoop = need;} - static void ImapStartup(); - static void ImapShutDown(); - - TIMAPUrl *GetCurrentUrl() {return fCurrentUrl;} - - // used the convert to/from UTF7IMAP - virtual char* CreateUtf7ConvertedString(const char *sourceString, XP_Bool toUtf7Imap); - - uint32 GetMessageSize(const char *messageId, XP_Bool idsAreUids); - - virtual const char *GetHostName() {return fHostName;} - void PseudoInterrupt(XP_Bool interrupt); - void SetSubscribeParameters(XP_Bool autoSubscribe, - XP_Bool autoUnsubscribe, XP_Bool autoSubscribeOnOpen, XP_Bool autoUnsubscribeFromNoSelect, - XP_Bool shouldUpgrade, XP_Bool upgradeLeaveAlone, XP_Bool upgradeSubscribeAll); - XP_Bool GetSubscribingNow(); - - // includes subscription management - XP_Bool CreateMailboxRespectingSubscriptions(const char *mailboxName); - XP_Bool DeleteMailboxRespectingSubscriptions(const char *mailboxName); - XP_Bool RenameMailboxRespectingSubscriptions(const char *existingName, const char *newName, XP_Bool reallyRename); - - // notifies libmsg that we have a new personal/default namespace that we're using - void CommitNamespacesForHostEvent(); - // notifies libmsg that we have new capability data for the current host - void CommitCapabilityForHostEvent(); - - // Adds a set of rights for a given user on a given mailbox on the current host. - // if userName is NULL, it means "me," or MYRIGHTS. - // rights is a single string of rights, as specified by RFC2086, the IMAP ACL extension. - void AddFolderRightsForUser(const char *mailboxName, const char *userName, const char *rights); - // Clears all rights for a given folder, for all users. - void ClearAllFolderRights(const char *mailboxName); - // Refreshes the icon / flags for the given folder - void RefreshFolderACLView(const char *mailboxName); - XP_Bool FolderNeedsACLInitialized(const char *folderName); - // Returns true if we know that the given mailbox on the current host is \NoSelect - XP_Bool MailboxIsNoSelectMailbox(const char *mailboxName); - virtual void StatusForFolder(const char *mailboxName); - XP_Bool InitializeFolderUrl(const char *folderName); - - // We really need to break out the thread synchronizer from the - // connection class... - XP_Bool GetShowAttachmentsInline(); - - XP_Bool GetPseudoInterrupted(); - - void ResetProgressInfo(); - void SetActive(XP_Bool active); - XP_Bool GetActive(); - - // Sets whether or not the content referenced by the current ActiveEntry has been modified. - // Used for MIME parts on demand. - void SetContentModified(XP_Bool modified); - XP_Bool GetShouldFetchAllParts(); - -protected: - TNavigatorImapConnection(const char *hostName); - - // Given the canonical pattern prefix, list the children of the pattern - void CanonicalChildList(const char *canonicalPrefix, XP_Bool pipeLined); - void NthLevelChildList(const char *canonicalPrefix, int depth); - void ChildDiscoverySucceeded(); - - // called within the IMAP thread - virtual XP_Bool TryToLogon(); - virtual void ProcessCurrentURL(); - - // called immediately after we have been authenticated, to do - // an assorted variety of housekeeping (NAMESPACE, etc...) - virtual void ProcessAfterAuthenticated(); - - virtual void WaitForNextActiveEntry(); - virtual void WaitForEventQueueEmptySignal(); - - virtual void WaitForPotentialListOfMsgsToFetch(uint32 **msgs, uint32 &count); - virtual void WaitForNextAppendMessageSize(); - - - virtual uint32 GetAppendSize(); - virtual imapMessageFlagsType GetAppendFlags(); - - virtual void WaitForMessageUploadToComplete(); - - XP_Bool DeleteSubFolders(const char *selectedMailbox); - XP_Bool RenameHierarchyByHand(const char *oldParentMailboxName, const char *newParentMailboxName); - - virtual XP_Bool ConstructionSuccess(); // called by subclass factory - - virtual void ProcessStoreFlags(const char *messageIds, - XP_Bool idsAreUids, - imapMessageFlagsType flags, - XP_Bool addFlags); - - - virtual void ProcessAuthenticatedStateURL(); - virtual void ProcessSelectedStateURL(); - virtual void HandleCurrentUrlError(); - virtual void ProcessMailboxUpdate(XP_Bool handlePossibleUndo, XP_Bool fromBiffUpdate = FALSE); - - virtual void HeaderFetchCompleted(); - - virtual void FolderHeaderDump(uint32 *hdrUids, uint32 hdrCount); - virtual void FolderMsgDump(uint32 *bodyUids, uint32 bodyCount, TIMAP4BlockingConnection::eFetchFields fields); - virtual void FolderMsgDumpRecurse(uint32 *bodyUids, uint32 bodyCount, TIMAP4BlockingConnection::eFetchFields fields); - - virtual void PeriodicBiff(); - virtual void SendSetBiffIndicatorEvent(MSG_BIFF_STATE newState); - - virtual void AutoSubscribeToMailboxIfNecessary(const char *mailboxName); - virtual void FindMailboxesIfNecessary(); - virtual void DiscoverMailboxList(); - virtual void DiscoverAllAndSubscribedBoxes(); - - int GetNumberOfListedMailboxesWithUnlistedChildren(); - void GetOldIMAPHostNameEvent(char **oldHostName); - void UpgradeToSubscriptionFinishedEvent(EIMAPSubscriptionUpgradeState); - XP_Bool PromptUserForSubscribeUpgradePath(); - virtual void SubscribeToAllFolders(); - virtual void UpgradeToSubscription(); - - virtual void RefreshACLForFolder(const char *mailboxName); - virtual void RefreshACLForFolderIfNecessary(const char *mailboxName); - virtual void RefreshAllACLs(); - - char *CreatePossibleTrashName(const char *prefix); - - uint32 CountMessagesInIdString(const char *idString); - - void AdjustChunkSize(void); - - char *GetArbitraryHeadersToDownload(); - -protected: - TImapFEEventQueue *fFEEventQueue; - ActiveEntry *fCurrentEntry; - int32 fInputBufferSize; - char *fInputSocketBuffer; - TImapFlagAndUidState *fFlagState; - time_t fStartTime; // time in secs we started to download last message - time_t fEndTime; // ending time - int32 fTooFastTime; // secs, buffer filled ? make it bigger - int32 fIdealTime; // secs, buffer filled, good. - int32 fChunkAddSize; // size to add to buffer when not big enough - int32 fChunkStartSize; // size of buffer to start with or to reset to in bad connections - int32 fMaxChunkSize; // max size buffer can grow - XP_Bool fNewMail; // is there new mail waiting for next biff ? - XP_Bool fTrackingTime; // are we supposed to track it ? - -private: - XP_Bool fFEeventCompleted; - XP_Bool fTunnelCompleted; - XP_Bool fEventQueueEmptySignalHappened; - XP_Bool fMessageUploadCompleted; - XP_Bool fFetchMsgListIsNew; - XP_Bool fMsgAppendSizeIsNew; - XP_Bool fNextEntryEventSignalHappened; - XP_Bool fThreadShouldDie; - XP_Bool fCallingNetlibAllTheTime; - XP_Bool fIsSafeToDie; - XP_Bool fNeedGreeting; - XP_Bool fNeedNoop; - XP_Bool fMailToFetch; - XP_Bool fGetHeaders; - XP_Bool fShouldUpgradeToSubscription; - XP_Bool fUpgradeShouldLeaveAlone; - XP_Bool fUpgradeShouldSubscribeAll; - - int fProgressStringId; - uint32 fProgressIndex; - uint32 fProgressCount; - int64 fLastProgressTime; - int fLastPercent; - int fLastProgressStringId; - - - uint32 *fFetchMsgIdList; - uint32 fFetchCount; - - TIMAPUrl *fCurrentUrl; - TCP_ConData *fTCPConData; - PRThread *fBlockingThread; - PRMonitor *fEventCompletionMonitor; - PRMonitor *fTunnelCompletionMonitor; - PRMonitor *fActiveEntryMonitor; - PRMonitor *fEventQueueEmptySignalMonitor; - PRMonitor *fMessageUploadMonitor; - PRMonitor *fMsgCopyDataMonitor; - PRMonitor *fThreadDeathMonitor; - PRMonitor *fPermissionToDieMonitor; - PRMonitor *fPseudoInterruptMonitor; - PRMonitor *fWaitForBodyIdsMonitor; - PRFileDesc *fIOSocket; - NET_StreamClass *fOutputStream; - - enum EMailboxHierarchyNameState { - kNoOperationInProgress, - kDiscoverBaseFolderInProgress, - kDiscoverTrashFolderInProgress, - kDeleteSubFoldersInProgress, - kListingForInfoOnly, - kListingForInfoAndDiscovery, - kDiscoveringNamespacesOnly - }; - - XP_Bool fOnlineBaseFolderExists; - - ImapHierarchyMover *fHierarchyMover; - const char *fRootToBeRenamed; - EMailboxHierarchyNameState fHierarchyNameState; - - XP_List *fDeletableChildren; - - int32 fBytesMovedSoFarForProgress; - - uint32 fAppendMessageSize; - imapMessageFlagsType fAppendMsgFlags; - - TLineDownloadCache fDownLoadLineCache; - - EMailboxDiscoverStatus fDiscoveryStatus; - - static PRMonitor *fFindingMailboxesMonitor; - static PRMonitor *fUpgradeToSubscriptionMonitor; - static XP_Bool fHaveWeEverCheckedForSubscriptionUpgrade; - static MSG_BIFF_STATE fCurrentBiffState; - - // chunking prefs - XP_Bool fFetchByChunks; - int32 fChunkSize; - int32 fChunkThreshold; - - XP_Bool fAutoSubscribe, fAutoUnsubscribe, fAutoSubscribeOnOpen, fAutoUnsubscribeFromNoSelect; - - XP_List *fListedMailboxList; - static XP_Bool IsConnectionActive(const char *hostName, const char *folderName); - -protected: - static XPPtrArray *connectionList; - TIMAPSocketInfo *fSocketInfo; - XP_Bool fPseudoInterrupted; - char *fHostName; - MSG_FolderInfo *fFolderInfo; - XP_Bool fFolderNeedsSubscribing, fFolderNeedsACLRefreshed; - XP_Bool fActive; - -}; - - - - -HG83666 - - -class TIMAPSocketInfo { - - // methods -public: - TIMAPSocketInfo(); - - PRFileDesc * GetIOSocket() { return fIOSocket; } - void SetIOSocket(PRFileDesc *sock) { fIOSocket = sock; } - - char** GetNewLineBuffer() { return &newLine; } - void SetNewLineBuffer(char *buffer) { newLine = buffer; } - - int GetReadStatus() { return readStatus; } - void SetReadStatus(int status) { readStatus = status; } - - int32* GetInputBufferSize() { return pInputBufferSize; } - void SetInputBufferSize(int32 *size) { pInputBufferSize = size; } - - char** GetInputSocketBuffer() { return pInputSocketBuffer; } - void SetInputSocketBuffer(char **buf) { pInputSocketBuffer = buf; } - - Bool GetPauseForRead() { return pauseForRead; } - void SetPauseForRead(Bool pause) { pauseForRead = pause; } - - // members -public: - PRFileDesc *fIOSocket; - char** pInputSocketBuffer; - int32* pInputBufferSize; - char* newLine; - Bool pauseForRead; - int readStatus; - int writeStatus; - char* writeLine; -}; - - -// This class is only used for passing data -// between the IMAP and mozilla thread -class TIMAPACLRightsInfo -{ -public: - char *hostName, *mailboxName, *userName, *rights; -}; - -// a simple reference counting class used to keep Biff from interrupting an INBOX connection -// the inbox usage count is incremented by one if TRUE is passed to the constructor and then -// decremented by the destructor -class TInboxReferenceCount { -public: - TInboxReferenceCount(XP_Bool bumpInboxCount); - ~TInboxReferenceCount(); - - int GetInboxUsageCount(); - - static void ImapStartup(); - static void ImapShutDown(); -private: - static PRMonitor *fgDataSafeMonitor; - static int fgInboxUsageCount; - XP_Bool fInboxCountWasBumped; -}; - - - -class TIMAPNamespace -{ - -public: - TIMAPNamespace(EIMAPNamespaceType type, const char *prefix, char delimiter, XP_Bool from_prefs); - - ~TIMAPNamespace(); - - EIMAPNamespaceType GetType() { return m_namespaceType; } - const char * GetPrefix() { return m_prefix; } - char GetDelimiter() { return m_delimiter; } - void SetDelimiter(char delimiter); - XP_Bool GetIsDelimiterFilledIn() { return m_delimiterFilledIn; } - XP_Bool GetIsNamespaceFromPrefs() { return m_fromPrefs; } - - // returns -1 if this box is not part of this namespace, - // or the length of the prefix if it is part of this namespace - int MailboxMatchesNamespace(const char *boxname); - -protected: - EIMAPNamespaceType m_namespaceType; - char *m_prefix; - char m_delimiter; - XP_Bool m_fromPrefs; - XP_Bool m_delimiterFilledIn; - -}; - - -// represents a list of namespaces for a given host -// Basically, a C++ wrapper around an XP_List -class TIMAPNamespaceList -{ -public: - ~TIMAPNamespaceList(); - - static TIMAPNamespaceList *CreateTIMAPNamespaceList(); - - void ClearNamespaces(XP_Bool deleteFromPrefsNamespaces, XP_Bool deleteServerAdvertisedNamespaces); - int GetNumberOfNamespaces(); - int GetNumberOfNamespaces(EIMAPNamespaceType); - TIMAPNamespace *GetNamespaceNumber(int nodeIndex); - TIMAPNamespace *GetNamespaceNumber(int nodeIndex, EIMAPNamespaceType); - - TIMAPNamespace *GetDefaultNamespaceOfType(EIMAPNamespaceType type); - int AddNewNamespace(TIMAPNamespace *ns); - TIMAPNamespace *GetNamespaceForMailbox(const char *boxname); - -protected: - TIMAPNamespaceList(); // use CreateTIMAPNamespaceList to create one - - XP_List *m_NamespaceList; - -}; - - -// This class is currently only used for the one-time upgrade -// process from a LIST view to the subscribe model. -// It basically contains the name of a mailbox and whether or not -// its children have been listed. -class TIMAPMailboxInfo -{ -public: - TIMAPMailboxInfo(const char *name); - virtual ~TIMAPMailboxInfo(); - void SetChildrenListed(XP_Bool childrenListed) { m_childrenListed = childrenListed; } - XP_Bool GetChildrenListed() { return m_childrenListed; } - const char *GetMailboxName() { return m_mailboxName; } - -protected: - XP_Bool m_childrenListed; - char *m_mailboxName; -}; - - - -#endif // IMAP4PVT_H diff --git a/mozilla/network/protocol/imap4/imap4url.c b/mozilla/network/protocol/imap4/imap4url.c deleted file mode 100644 index afd10f95a67..00000000000 --- a/mozilla/network/protocol/imap4/imap4url.c +++ /dev/null @@ -1,662 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" - -#ifndef __imap__ -#include "imap.h" -#endif - -#ifndef _MCOM_H_ -#include "xp_mcom.h" -#endif - -/* 45678901234567890123456789012345678901234567890123456789012345678901234567890 -*/ - -char useme; - -static char *createStartOfIMAPurl(const char *imapHost, int additionalSize) -{ - static const char *formatString = "IMAP://%s?"; - - char *returnString = XP_ALLOC(XP_STRLEN(formatString) + XP_STRLEN(imapHost) + additionalSize); - if (returnString) - sprintf(returnString, formatString, imapHost); - - return returnString; -} - - -/* Selecting a mailbox */ -/* imap4://HOST>select>MAILBOXPATH */ -char *CreateImapMailboxSelectUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *undoDeleteIdentifierList) -{ - static const char *formatString = "select>%c%s>%s"; - - /* 22 enough for huge index string */ - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + - XP_STRLEN(mailbox) + - (undoDeleteIdentifierList ? XP_STRLEN(undoDeleteIdentifierList) : 1) + - 22); - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), - formatString, - hierarchySeparator, - mailbox, - undoDeleteIdentifierList ? undoDeleteIdentifierList : ""); - - return returnString; -} - -/* lite select, used to verify UIDVALIDITY while going on/offline */ -char *CreateImapMailboxLITESelectUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator) -{ - static const char *formatString = "liteselect>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), - formatString, - hierarchySeparator, - mailbox); - - return returnString; -} - -/* expunge, used in traditional imap delete model */ -char *CreateImapMailboxExpungeUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator) -{ - static const char *formatString = "expunge>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), - formatString, - hierarchySeparator, - mailbox); - - return returnString; -} - -/* Creating a mailbox */ -/* imap4://HOST>create>MAILBOXPATH */ -char *CreateImapMailboxCreateUrl(const char *imapHost, const char *mailbox,char hierarchySeparator) -{ - static const char *formatString = "create>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, hierarchySeparator, mailbox); - - return returnString; -} - -/* discover the mailboxes of this account */ -char *CreateImapAllMailboxDiscoveryUrl(const char *imapHost) -{ - static const char *formatString = "discoverallboxes"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString); - - return returnString; -} - - -/* discover the mailboxes of this account, and the subscribed mailboxes */ -char *CreateImapAllAndSubscribedMailboxDiscoveryUrl(const char *imapHost) -{ - static const char *formatString = "discoverallandsubscribedboxes"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString); - - return returnString; -} - -/* discover the children of this mailbox */ -char *CreateImapChildDiscoveryUrl(const char *imapHost, const char *mailbox,char hierarchySeparator) -{ - static const char *formatString = "discoverchildren>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, hierarchySeparator, mailbox); - - return returnString; -} -/* discover the n-th level deep children of this mailbox */ -char *CreateImapLevelChildDiscoveryUrl(const char *imapHost, const char *mailbox,char hierarchySeparator, int n) -{ - static const char *formatString = "discoverlevelchildren>%d>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, n, hierarchySeparator, mailbox); - - return returnString; -} - -/* deleting a mailbox */ -/* imap4://HOST>delete>MAILBOXPATH */ -char *CreateImapMailboxDeleteUrl(const char *imapHost, const char *mailbox, char hierarchySeparator) -{ - static const char *formatString = "delete>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, hierarchySeparator, mailbox); - - return returnString; -} - -/* renaming a mailbox */ -/* imap4://HOST>rename>OLDNAME>NEWNAME */ -char *CreateImapMailboxRenameLeafUrl(const char *imapHost, - const char *oldBoxPathName, - char hierarchySeparator, - const char *newBoxLeafName) -{ - static const char *formatString = "rename>%c%s>%c%s"; - - char *returnString = NULL; - - /* figure out the new mailbox name */ - char *slash; - char *newPath = XP_ALLOC(XP_STRLEN(oldBoxPathName) + XP_STRLEN(newBoxLeafName) + 1); - if (newPath) - { - XP_STRCPY (newPath, oldBoxPathName); - slash = XP_STRRCHR (newPath, '/'); - if (slash) - slash++; - else - slash = newPath; /* renaming a 1st level box */ - - XP_STRCPY (slash, newBoxLeafName); - - - returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(oldBoxPathName) + XP_STRLEN(newPath)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, hierarchySeparator, oldBoxPathName, hierarchySeparator, newPath); - - XP_FREE( newPath); - } - - return returnString; -} - -/* renaming a mailbox, moving hierarchy */ -/* imap4://HOST>movefolderhierarchy>OLDNAME>NEWNAME */ -/* oldBoxPathName is the old name of the child folder */ -/* destinationBoxPathName is the name of the new parent */ -char *CreateImapMailboxMoveFolderHierarchyUrl(const char *imapHost, - const char *oldBoxPathName, - char oldHierarchySeparator, - const char *newBoxPathName, - char newHierarchySeparator) -{ - static const char *formatString = "movefolderhierarchy>%c%s>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(oldBoxPathName) + XP_STRLEN(newBoxPathName)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, oldHierarchySeparator, oldBoxPathName, newHierarchySeparator, newBoxPathName); - - return returnString; -} - -/* listing available mailboxes */ -/* imap4://HOST>list>referenceName>MAILBOXPATH */ -/* MAILBOXPATH can contain wildcard */ -/* **** jefft -- I am using this url to detect whether an mailbox - exists on the Imap sever - */ -char *CreateImapListUrl(const char *imapHost, - const char *mailbox, - const char hierarchySeparator) -{ - static const char *formatString = "list>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, - XP_STRLEN(formatString) + - XP_STRLEN(mailbox) + 1); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, - hierarchySeparator, mailbox); - - return returnString; -} - -/* biff */ -char *CreateImapBiffUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - uint32 uidHighWater) -{ - static const char *formatString = "biff>%c%s>%ld"; - - /* 22 enough for huge uid string */ - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + - XP_STRLEN(mailbox) + 22); - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, hierarchySeparator, mailbox, (long)uidHighWater); - - return returnString; -} - - -static const char *sequenceString = "SEQUENCE"; -static const char *uidString = "UID"; - -/* fetching RFC822 messages */ -/* imap4://HOST>fetch><UID/SEQUENCE>>MAILBOXPATH>x */ -/* 'x' is the message UID or sequence number list */ -/* will set the 'SEEN' flag */ -char *CreateImapMessageFetchUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *messageIdentifierList, - XP_Bool messageIdsAreUID) -{ - static const char *formatString = "fetch>%s>%c%s>%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(messageIdentifierList)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, messageIdsAreUID ? uidString : sequenceString, hierarchySeparator, mailbox, messageIdentifierList); - - return returnString; -} - -/* fetching the headers of RFC822 messages */ -/* imap4://HOST>header><UID/SEQUENCE>>MAILBOXPATH>x */ -/* 'x' is the message UID or sequence number list */ -/* will not affect the 'SEEN' flag */ -char *CreateImapMessageHeaderUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *messageIdentifierList, - XP_Bool messageIdsAreUID) -{ - static const char *formatString = "header>%s>%c%s>%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(messageIdentifierList)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, messageIdsAreUID ? uidString : sequenceString, hierarchySeparator, mailbox, messageIdentifierList); - - return returnString; -} - -/* search an online mailbox */ -/* imap4://HOST>search><UID/SEQUENCE>>MAILBOXPATH>SEARCHSTRING */ -/* 'x' is the message sequence number list */ -char *CreateImapSearchUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *searchString, - XP_Bool messageIdsAreUID) -{ - static const char *formatString = "search>%s>%c%s>%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(searchString)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, messageIdsAreUID ? uidString : sequenceString, hierarchySeparator, mailbox, searchString); - - return returnString; -} - -/* delete messages */ -/* imap4://HOST>deletemsg><UID/SEQUENCE>>MAILBOXPATH>x */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapDeleteMessageUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *messageIds, - XP_Bool idsAreUids) -{ - static const char *formatString = "deletemsg>%s>%c%s>%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(messageIds)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, idsAreUids ? uidString : sequenceString, hierarchySeparator, mailbox, messageIds); - - return returnString; -} - -/* delete all messages */ -/* imap4://HOST>deleteallmsgs>MAILBOXPATH */ -char *CreateImapDeleteAllMessagesUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator) -{ - static const char *formatString = "deleteallmsgs>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, hierarchySeparator, mailbox); - - return returnString; -} - -/* store +flags url */ -/* imap4://HOST>store+flags><UID/SEQUENCE>>MAILBOXPATH>x>f */ -/* 'x' is the message UID or sequence number list */ -/* 'f' is the byte of flags */ -char *CreateImapAddMessageFlagsUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *messageIds, - imapMessageFlagsType flags, - XP_Bool idsAreUids) -{ - static const char *formatString = "addmsgflags>%s>%c%s>%s>%d"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(messageIds) + 10); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, idsAreUids ? uidString : sequenceString, hierarchySeparator, mailbox, messageIds, (int) flags); - - return returnString; -} - -/* store -flags url */ -/* imap4://HOST>store-flags><UID/SEQUENCE>>MAILBOXPATH>x>f */ -/* 'x' is the message UID or sequence number list */ -/* 'f' is the byte of flags */ -char *CreateImapSubtractMessageFlagsUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *messageIds, - imapMessageFlagsType flags, - XP_Bool idsAreUids) -{ - static const char *formatString = "subtractmsgflags>%s>%c%s>%s>%d"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(messageIds) + 10); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, idsAreUids ? uidString : sequenceString, hierarchySeparator, mailbox, messageIds, (int) flags); - - return returnString; -} - -/* set flags url, make the flags match */ -char *CreateImapSetMessageFlagsUrl(const char *imapHost, - const char *mailbox, - char hierarchySeparator, - const char *messageIds, - imapMessageFlagsType flags, - XP_Bool idsAreUids) -{ - static const char *formatString = "setmsgflags>%s>%c%s>%s>%d"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(sequenceString) + XP_STRLEN(mailbox) + XP_STRLEN(messageIds) + 10); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, idsAreUids ? uidString : sequenceString, hierarchySeparator, mailbox, messageIds, (int) flags); - - return returnString; -} - -/* copy messages from one online box to another */ -/* imap4://HOST>onlineCopy><UID/SEQUENCE>>SOURCEMAILBOXPATH>x> - DESTINATIONMAILBOXPATH */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapOnlineCopyUrl(const char *imapHost, - const char *sourceMailbox, - char sourceHierarchySeparator, - const char *messageIds, - const char *destinationMailbox, - char destinationHierarchySeparator, - XP_Bool idsAreUids, - XP_Bool isMove) -{ - static const char *formatString = "%s>%s>%c%s>%s>%c%s"; - static const char *moveString = "onlinemove"; - static const char *copyString = "onlinecopy"; - - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(moveString) + XP_STRLEN(sequenceString) + XP_STRLEN(sourceMailbox) + XP_STRLEN(messageIds) + XP_STRLEN(destinationMailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, - isMove ? moveString : copyString, - idsAreUids ? uidString : sequenceString, - sourceHierarchySeparator, sourceMailbox, - messageIds, - destinationHierarchySeparator, destinationMailbox); - - - - return returnString; -} - -/* copy messages from one online box to another */ -/* imap4://HOST>onlineCopy><UID/SEQUENCE>>SOURCEMAILBOXPATH>x> - DESTINATIONMAILBOXPATH */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapOnToOfflineCopyUrl(const char *imapHost, - const char *sourceMailbox, - char sourceHierarchySeparator, - const char *messageIds, - const char *destinationMailbox, - XP_Bool idsAreUids, - XP_Bool isMove) -{ - static const char *formatString = "%s>%s>%c%s>%s>%c%s"; - static const char *moveString = "onlinetoofflinemove"; - static const char *copyString = "onlinetoofflinecopy"; - - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(moveString) + XP_STRLEN(sequenceString) + XP_STRLEN(sourceMailbox) + XP_STRLEN(messageIds) + XP_STRLEN(destinationMailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, - isMove ? moveString : copyString, - idsAreUids ? uidString : sequenceString, - sourceHierarchySeparator, sourceMailbox, - messageIds, - kOnlineHierarchySeparatorUnknown, destinationMailbox); - - - - return returnString; -} - -/* copy messages from an offline box to an online box */ -/* imap4://HOST>offtoonCopy>SOURCEMAILBOXPATH>x> - DESTINATIONMAILBOXPATH */ -/* 'x' is the size of the message to upload */ -char *CreateImapOffToOnlineCopyUrl(const char *imapHost, - const char *destinationMailbox, - char destinationHierarchySeparator) -{ - static const char *formatString = "offlinetoonlinecopy>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(destinationMailbox)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, destinationHierarchySeparator, destinationMailbox); - - return returnString; -} - -/* get mail account rul */ -/* imap4://HOST>NETSCAPE */ -char *CreateImapManageMailAccountUrl(const char *imapHost) -{ - static const char *formatString = "netscape"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + 1); - StrAllocCat(returnString, formatString);; - - return returnString; -} - -/* append message from file url */ -/* imap4://HOST>appendmsgfromfile>DESTINATIONMAILBOXPATH */ -char *CreateImapAppendMessageFromFileUrl(const char *imapHost, - const char *destinationMailboxPath, - const char hierarchySeparator, - XP_Bool isDraft) -{ - const char *formatString = isDraft ? "appenddraftfromfile>%c%s" : - "appendmsgfromfile>%c%s"; - char *returnString = - createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + - XP_STRLEN(destinationMailboxPath)); - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, - hierarchySeparator, destinationMailboxPath); - - return returnString; -} - -/* Subscribe to a mailbox on the given IMAP host */ -char *CreateIMAPSubscribeMailboxURL(const char *imapHost, const char *mailboxName) -{ - /* we don't need the hierarchy delimiter, so just use slash ("/") */ - static const char *formatString = "subscribe>/%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailboxName)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, mailboxName); - - return returnString; - -} - -/* Unsubscribe from a mailbox on the given IMAP host */ -char *CreateIMAPUnsubscribeMailboxURL(const char *imapHost, const char *mailboxName) -{ - /* we don't need the hierarchy delimiter, so just use slash ("/") */ - static const char *formatString = "unsubscribe>/%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailboxName)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, mailboxName); - - return returnString; - -} - - -/* Refresh the ACL for a folder on the given IMAP host */ -char *CreateIMAPRefreshACLForFolderURL(const char *imapHost, const char *mailboxName) -{ - /* we don't need the hierarchy delimiter, so just use slash ("/") */ - static const char *formatString = "refreshacl>/%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailboxName)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, mailboxName); - - return returnString; - -} - -/* Refresh the ACL for all folders on the given IMAP host */ -char *CreateIMAPRefreshACLForAllFoldersURL(const char *imapHost) -{ - /* we don't need the hierarchy delimiter, so just use slash ("/") */ - static const char *formatString = "refreshallacls>/"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString); - - return returnString; - -} - -/* Auto-Upgrade to IMAP subscription */ -char *CreateIMAPUpgradeToSubscriptionURL(const char *imapHost, XP_Bool subscribeToAll) -{ - static char *formatString = "upgradetosubscription>/"; - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString)); - if (subscribeToAll) - formatString[XP_STRLEN(formatString)-1] = '.'; - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString); - - return returnString; - -} - -/* do a status command on a folder on the given IMAP host */ -char *CreateIMAPStatusFolderURL(const char *imapHost, const char *mailboxName, char hierarchySeparator) -{ - static const char *formatString = "folderstatus>%c%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailboxName)); - - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), - formatString, - hierarchySeparator, - mailboxName); - - return returnString; - -} - -/* Refresh the admin url for a folder on the given IMAP host */ -char *CreateIMAPRefreshFolderURLs(const char *imapHost, const char *mailboxName) -{ - /* we don't need the hierarchy delimiter, so just use slash ("/") */ - static const char *formatString = "refreshfolderurls>/%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailboxName)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, mailboxName); - - return returnString; - -} - -/* Force the reload of all parts of the message given in url */ -char *IMAP_CreateReloadAllPartsUrl(const char *url) -{ - char *returnUrl = PR_smprintf("%s&allparts", url); - return returnUrl; -} - -/* Explicitly LIST a given mailbox, and refresh its flags in the folder list */ -char *CreateIMAPListFolderURL(const char *imapHost, const char *mailboxName) -{ - /* we don't need the hierarchy delimiter, so just use slash ("/") */ - static const char *formatString = "listfolder>/%s"; - - char *returnString = createStartOfIMAPurl(imapHost, XP_STRLEN(formatString) + XP_STRLEN(mailboxName)); - if (returnString) - sprintf(returnString + XP_STRLEN(returnString), formatString, mailboxName); - - return returnString; -} diff --git a/mozilla/network/protocol/imap4/imap4url.h b/mozilla/network/protocol/imap4/imap4url.h deleted file mode 100644 index 21743164bcd..00000000000 --- a/mozilla/network/protocol/imap4/imap4url.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* this file defines the syntax of the imap4 url's and offers functions - that create url strings. If the functions do not offer enough - functionality then let kevin know before you starting creating strings - from scratch. */ - -#ifndef IMAP4URL_H -#define IMAP4URL_H - -#include "xp_mcom.h" - -/* 45678901234567890123456789012345678901234567890123456789012345678901234567890 -*/ - - -XP_BEGIN_PROTOS - -/* need mailbox status urls to get the number of message and the - number of unread messages */ - -/* Creating a mailbox */ -/* imap4://HOST?create?MAILBOXPATH */ -char *CreateImapMailboxCreateUrl(const char *imapHost, const char *mailbox); - -/* deleting a mailbox */ -/* imap4://HOST?delete?MAILBOXPATH */ -char *CreateImapMailboxDeleteUrl(const char *imapHost, const char *mailbox); - -/* renaming a mailbox */ -/* imap4://HOST?rename?OLDNAME?NEWNAME */ -char *CreateImapMailboxRenameUrl(const char *imapHost, - const char *oldBoxName, - const char *newBoxName); - -/* listing available mailboxes */ -/* imap4://HOST?list */ -char *CreateImapListUrl(const char *imapHost); - - -/* fetching RFC822 messages */ -/* imap4://HOST?fetch?<UID/SEQUENCE>?MAILBOXPATH?x */ -/* 'x' is the message UID or sequence number list */ -/* will set the 'SEEN' flag */ -char *CreateImapMessageFetchUrl(const char *imapHost, - const char *mailbox, - const char *messageIdentifierList, - XP_Bool messageIdsAreUID); - - -/* fetching the headers of RFC822 messages */ -/* imap4://HOST?header?<UID/SEQUENCE>?MAILBOXPATH?x */ -/* 'x' is the message UID or sequence number list */ -/* will not affect the 'SEEN' flag */ -char *CreateImapMessageHeaderUrl(const char *imapHost, - const char *mailbox, - const char *messageIdentifierList, - XP_Bool messageIdsAreUID); - -/* dump headers url. Notify the front end when the mailbox is selected and - when each message line is dumped */ -char *CreateImapMessageHeaderDumpUrl(const char *imapHost, - const char *mailbox); - -/* search an online mailbox */ -/* imap4://HOST?search?<UID/SEQUENCE>?MAILBOXPATH?SEARCHSTRING */ -/* 'x' is the message sequence number list */ -char *CreateImapSearchUrl(const char *imapHost, - const char *mailbox, - const char *searchString, - XP_Bool messageIdsAreUID); - -/* delete messages */ -/* imap4://HOST?deletemsg?<UID/SEQUENCE>?MAILBOXPATH?x */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapDeleteMessageUrl(const char *imapHost, - const char *mailbox, - const char *messageIds, - XP_Bool idsAreUids); - -/* mark messages as read */ -/* imap4://HOST?markread?<UID/SEQUENCE>?MAILBOXPATH?x */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapMarkMessageReadUrl(const char *imapHost, - const char *mailbox, - const char *messageIds, - XP_Bool idsAreUids); - -/* mark messages as unread */ -/* imap4://HOST?markunread?<UID/SEQUENCE>?MAILBOXPATH?x */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapMarkMessageUnReadUrl(const char *imapHost, - const char *mailbox, - const char *messageIds, - XP_Bool idsAreUids); - -/* copy messages from one online box to another */ -/* imap4://HOST?onlineCopy?<UID/SEQUENCE>? - SOURCEMAILBOXPATH?x?DESTINATIONMAILBOXPATH */ -/* 'x' is the message UID or sequence number list */ -char *CreateImapOnlineCopyUrl(const char *imapHost, - const char *sourceMailbox, - const char *messageIds, - const char *destinationMailbox, - XP_Bool idsAreUids); - -#if DOTHISSTUFFLATER -/* copy a message from an online box to an offline box */ -/* imap4://HOST?ontooffCopy?SOURCEMAILBOXPATH?number=x? - DESTINATIONMAILBOXPATH */ -/* 'x' is the message sequence number */ -char *CreateImapOnToOfflineCopyUrl(const char *imapHost, - const char *sourceOnlineMailbox, - int32 messageSequenceNumber, - const char *destinationOfflineMailbox); - -/* copy a message from an offline box to an online box */ -/* imap4://HOST?offtoonCopy?SOURCEMAILBOXPATH?number=x? - DESTINATIONMAILBOXPATH */ -/* 'x' is the message sequence number */ -char *CreateImapOffToOnlineCopyUrl(const char *imapHost, - const char *sourceOnlineMailbox, - int32 messageSequenceNumber, - const char *destinationOfflineMailbox); - -/* get mail account rul */ -/* imap4://HOST?NETSCAPE */ -char *CreateImapManageMailAccountUrl(const char *imapHost); - -/* append message from file url */ -/* imap4://HOST?appendmsgfromfile>DESTINATIONMAILBOXPATH */ -char *CreateImapAppendMessageFromFileUrl(const char *imapHost, - const char *destinationMailboxPath, - const char hierarchySeparator, - XP_Bool isDraft); - -#endif - -XP_END_PROTOS - -#endif /* IMAP4URL_H */ - diff --git a/mozilla/network/protocol/imap4/imapbody.cpp b/mozilla/network/protocol/imap4/imapbody.cpp deleted file mode 100644 index dc94307568b..00000000000 --- a/mozilla/network/protocol/imap4/imapbody.cpp +++ /dev/null @@ -1,1619 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -// imapbody.cpp -// Implementation of the TIMAPBodyShell and associated classes -// These are used to parse IMAP BODYSTRUCTURE responses, and intelligently (?) -// figure out what parts we need to display inline. - -#include "mkutils.h" -#include "ptrarray.h" -#include "imap4pvt.h" -#include "imapbody.h" -#include "xpgetstr.h" -#include "xp_hash.h" -#include "mime.h" // for IMAP_EXTERNAL_CONTENT_HEADER -#include "prlog.h" -#include "mktcp.h" - -extern "C" -{ - extern int MK_IMAP_EMPTY_MIME_PART; - extern int MK_IMAP_X_MOZ_IMAP_PART_HEADER; -} - - - -/* - Create a TIMAPBodyShell from a full BODYSTRUCUTRE response from the parser. - - The body shell represents a single, top-level object, the message. The message body - might be treated as either a container or a leaf (just like any arbitrary part). - - Steps for creating a part: - 1. Pull out the paren grouping for the part - 2. Create a generic part object with that buffer - 3. The factory will return either a leaf or container, depending on what it really is. - 4. It is responsible for parsing its children, if there are any -*/ - - -///////////// TIMAPBodyShell //////////////////////////////////// - -TIMAPBodyShell::TIMAPBodyShell(TNavigatorImapConnection *connection, const char *buf, uint32 UID, const char *folderName) -{ - m_isValid = FALSE; - m_isBeingGenerated = FALSE; - m_cached = FALSE; - m_gotAttachmentPref = FALSE; - m_generatingWholeMessage = FALSE; - m_showAttachmentsInline = TRUE; - m_generatingPart = NULL; - m_connection = connection; - XP_ASSERT(m_connection); - if (!m_connection) - return; - m_prefetchQueue = new TIMAPMessagePartIDArray(); - if (!m_prefetchQueue) - return; - XP_ASSERT(buf); - if (!buf) - return; - m_UID = PR_smprintf("%ld",UID); - XP_ASSERT(m_UID); - if (!m_UID) - return; -#ifdef DEBUG_chrisf - XP_ASSERT(folderName); -#endif - if (!folderName) - return; - m_folderName = XP_STRDUP(folderName); - if (!m_folderName) - return; - // Turn the BODYSTRUCTURE response into a form that the TIMAPBodypartMessage can be constructed from. - char *doctoredBuf = PR_smprintf("(\"message\" \"rfc822\" NIL NIL NIL NIL 0 () %s 0)", buf); - if (!doctoredBuf) - return; - SetIsValid(TRUE); - m_message = new TIMAPBodypartMessage(this, NULL, doctoredBuf, NULL, TRUE); - XP_FREE(doctoredBuf); - if (!m_message || !m_message->GetIsValid()) - return; -} - -TIMAPBodyShell::~TIMAPBodyShell() -{ - delete m_message; - delete m_prefetchQueue; - FREEIF(m_UID); - FREEIF(m_folderName); -} - -void TIMAPBodyShell::SetIsValid(XP_Bool valid) -{ -// if (!valid) -// PR_LOG(IMAP, out, ("BODYSHELL: Shell is invalid.")); - m_isValid = valid; -} - - -XP_Bool TIMAPBodyShell::GetShowAttachmentsInline() -{ - if (!m_gotAttachmentPref) - { - m_showAttachmentsInline = m_connection->GetShowAttachmentsInline(); - m_gotAttachmentPref = TRUE; - } - - return m_showAttachmentsInline; -} - - -// Fills in buffer (and adopts storage) for header object -void TIMAPBodyShell::AdoptMessageHeaders(char *headers, const char *partNum) -{ - if (!GetIsValid()) - return; - - if (!partNum) - partNum = "0"; - - // we are going to say that a message header object only has - // part data, and no header data. - TIMAPBodypart *foundPart = m_message->FindPartWithNumber(partNum); - if (foundPart) - { - TIMAPBodypartMessage *messageObj = foundPart->GetTIMAPBodypartMessage(); - if (messageObj) - { - messageObj->AdoptMessageHeaders(headers); - if (!messageObj->GetIsValid()) - SetIsValid(FALSE); - } - else - { - // We were filling in message headers for a given part number. - // We looked up that part number, found an object, but it - // wasn't of type message/rfc822. - // Something's wrong. - XP_ASSERT(FALSE); - } - } - else - SetIsValid(FALSE); -} - -// Fills in buffer (and adopts storage) for MIME headers in appropriate object. -// If object can't be found, sets isValid to FALSE. -void TIMAPBodyShell::AdoptMimeHeader(const char *partNum, char *mimeHeader) -{ - if (!GetIsValid()) - return; - - XP_ASSERT(partNum); - - TIMAPBodypart *foundPart = m_message->FindPartWithNumber(partNum); - - if (foundPart) - { - foundPart->AdoptHeaderDataBuffer(mimeHeader); - if (!foundPart->GetIsValid()) - SetIsValid(FALSE); - } - else - { - SetIsValid(FALSE); - } -} - - -void TIMAPBodyShell::AddPrefetchToQueue(TIMAP4BlockingConnection::eFetchFields fields, const char *partNumber) -{ - TIMAPMessagePartID *newPart = new TIMAPMessagePartID(fields, partNumber); - if (newPart) - { - m_prefetchQueue->Add(newPart); - } - else - { - // HandleMemoryFailure(); - } -} - -// Flushes all of the prefetches that have been queued up in the prefetch queue, -// freeing them as we go -void TIMAPBodyShell::FlushPrefetchQueue() -{ - m_connection->PipelinedFetchMessageParts(GetUID(), m_prefetchQueue); - m_prefetchQueue->RemoveAndFreeAll(); -} - -// Requires that the shell is valid when called -// Performs a preflight check on all message parts to see if they are all -// inline. Returns TRUE if all parts are inline, FALSE otherwise. -XP_Bool TIMAPBodyShell::PreflightCheckAllInline() -{ - XP_Bool rv = m_message->PreflightCheckAllInline(); -// if (rv) -// PR_LOG(IMAP, out, ("BODYSHELL: All parts inline. Reverting to whole message download.")); - return rv; -} - -// When partNum is NULL, Generates a whole message and intelligently -// leaves out parts that are not inline. - -// When partNum is not NULL, Generates a MIME part that hasn't been downloaded yet -// Ok, here's how we're going to do this. Essentially, this -// will be the mirror image of the "normal" generation. -// All parts will be left out except a single part which is -// explicitly specified. All relevant headers will be included. -// Libmime will extract only the part of interest, so we don't -// have to worry about the other parts. This also has the -// advantage that it looks like it will be more workable for -// nested parts. For instance, if a user clicks on a link to -// a forwarded message, then that forwarded message may be -// generated along with any images that the forwarded message -// contains, for instance. - - -int32 TIMAPBodyShell::Generate(char *partNum) -{ - m_isBeingGenerated = TRUE; - m_generatingPart = partNum; - int32 contentLength = 0; - - if (!GetIsValid() || PreflightCheckAllInline()) - { - // We don't have a valid shell, or all parts are going to be inline anyway. Fall back to fetching the whole message. -#ifdef DEBUG_chrisf - XP_ASSERT(GetIsValid()); -#endif - m_generatingWholeMessage = TRUE; - uint32 messageSize = m_connection->GetMessageSize(GetUID(), TRUE); - m_connection->SetContentModified(FALSE); // So that when we cache it, we know we have the whole message - if (!DeathSignalReceived()) - m_connection->FetchTryChunking(GetUID(), TIMAP4BlockingConnection::kEveryThingRFC822, TRUE, NULL, messageSize); - contentLength = (int32) messageSize; // ugh - } - else - { - // We have a valid shell. - XP_Bool streamCreated = FALSE; - m_generatingWholeMessage = FALSE; - - ////// PASS 1 : PREFETCH /////// - // First, prefetch any additional headers/data that we need - if (!GetPseudoInterrupted()) - m_message->Generate(FALSE, TRUE); // This queues up everything we need to prefetch - // Now, run a single pipelined prefetch (neato!) - FlushPrefetchQueue(); - - ////// PASS 2 : COMPUTE STREAM SIZE /////// - // Next, figure out the size from the parts that we're going to fill in, - // plus all of the MIME headers, plus the message header itself - if (!GetPseudoInterrupted()) - contentLength = m_message->Generate(FALSE, FALSE); - - // Setup the stream - if (!GetPseudoInterrupted() && !DeathSignalReceived()) - { - m_connection->BeginMessageDownLoad(contentLength, MESSAGE_RFC822); - streamCreated = TRUE; - } - - ////// PASS 3 : GENERATE /////// - // Generate the message - if (!GetPseudoInterrupted() && !DeathSignalReceived()) - m_message->Generate(TRUE, FALSE); - - // Close the stream here - normal. If pseudointerrupted, the connection will abort the download stream - if (!GetPseudoInterrupted() && !DeathSignalReceived()) - m_connection->NormalMessageEndDownload(); - else if (streamCreated) - m_connection->AbortMessageDownLoad(); - - m_generatingPart = NULL; - - } - - m_isBeingGenerated = FALSE; - return contentLength; -} - -XP_Bool TIMAPBodyShell::GetPseudoInterrupted() -{ - XP_Bool rv = m_connection->GetPseudoInterrupted(); - return rv; -} - -XP_Bool TIMAPBodyShell::DeathSignalReceived() -{ - XP_Bool rv = m_connection->DeathSignalReceived(); - return rv; -} - - -////////////// Helpers ////////////////////////////////////////////////// - - -// Pass in a buffer starting at the first open paren -// Returns the location of the corresponding closing paren, -// or NULL if there is none in the buffer -static char *findEndParenInBuffer(char *buf) -{ - char *where = buf; - int numCloseParensNeeded = 1; - while (where && *where && (numCloseParensNeeded > 0)) - { - where++; - if (*where == '(') - numCloseParensNeeded++; - else if (*where == ')') - numCloseParensNeeded--; - } - return where; -} - - -///////////// TIMAPBodypart //////////////////////////////////// - - - -/* static */ -TIMAPBodypart *TIMAPBodypart::CreatePart(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart) -{ - // Check to see if this buffer is a leaf or container - // (Look at second character - if an open paren, then it is a container) - if (buf[0] != '(' || !buf[1]) - { - XP_ASSERT(FALSE); - return NULL; - } - - if (buf[1] == '(') - { - // If a container: - return new TIMAPBodypartMultipart(shell, partNum, buf, parentPart); - } - else - { - // If a leaf: - TIMAPBodypart *rv = new TIMAPBodypartLeaf(shell, partNum, buf, parentPart); - if (rv && rv->GetIsValid()) - { - const char *bodyType = rv->GetBodyType(); - const char *bodySubType = rv->GetBodySubType(); - if (!XP_STRCASECMP(bodyType, "message") && - !XP_STRCASECMP(bodySubType, "rfc822")) - { - // This is actually a part of type message/rfc822, - // probably a forwarded message. delete this and return - // the new type - char *keepPartNum = XP_STRDUP(partNum); // partNum will be deleted next... - delete rv; - return new TIMAPBodypartMessage(shell, keepPartNum, buf, parentPart, FALSE); - } - } - return rv; - } -} - - -TIMAPBodypart::TIMAPBodypart(TIMAPBodyShell *shell, char *partNumber, const char *buf, TIMAPBodypart *parentPart) : - TIMAPGenericParser() -{ - SetIsValid(TRUE); - m_parentPart = parentPart; - m_partNumberString = partNumber; // storage adopted - if (!shell) - { - SetIsValid(FALSE); - return; - } - if (buf) - m_responseBuffer = XP_STRDUP(buf); - else - m_responseBuffer = NULL; - m_shell = shell; - m_partData = NULL; - m_headerData = NULL; - m_boundaryData = NULL; // initialize from parsed BODYSTRUCTURE - m_contentLength = 0; - m_partLength = 0; - - m_contentType = NULL; - m_bodyType = NULL; - m_bodySubType = NULL; - m_bodyID = NULL; - m_bodyDescription = NULL; - m_bodyEncoding = NULL; -} - -TIMAPBodypart::~TIMAPBodypart() -{ - FREEIF(m_partNumberString); - FREEIF(m_responseBuffer); - FREEIF(m_contentType); - FREEIF(m_bodyType); - FREEIF(m_bodySubType); - FREEIF(m_bodyID); - FREEIF(m_bodyDescription); - FREEIF(m_bodyEncoding); - FREEIF(m_partData); - FREEIF(m_headerData); - FREEIF(m_boundaryData); -} - -void TIMAPBodypart::SetIsValid(XP_Bool valid) -{ - m_isValid = valid; - if (!m_isValid) - { - //PR_LOG(IMAP, out, ("BODYSHELL: Part is invalid. Part Number: %s Content-Type: %s", m_partNumberString, m_contentType)); - m_shell->SetIsValid(FALSE); - } -} - -XP_Bool TIMAPBodypart::GetNextLineForParser(char **nextLine) -{ - XP_Bool rv = TRUE; - *nextLine = m_responseBuffer; - if (!m_responseBuffer) - rv = FALSE; - m_responseBuffer = NULL; - return rv; -} - -XP_Bool TIMAPBodypart::ContinueParse() -{ - return GetIsValid() && TIMAPGenericParser::ContinueParse() && m_shell->GetIsValid(); -} - -// Adopts storage for part data buffer. If NULL, sets isValid to FALSE. -void TIMAPBodypart::AdoptPartDataBuffer(char *buf) -{ - m_partData = buf; - if (!m_partData) - { - SetIsValid(FALSE); - } -} - -// Adopts storage for header data buffer. If NULL, sets isValid to FALSE. -void TIMAPBodypart::AdoptHeaderDataBuffer(char *buf) -{ - m_headerData = buf; - if (!m_headerData) - { - SetIsValid(FALSE); - } -} - -// Finds the part with given part number -// Returns a TIMAPBodystructure of the matched part if it is this -// or one of its children. Returns NULL otherwise. -TIMAPBodypart *TIMAPBodypart::FindPartWithNumber(const char *partNum) -{ - // either brute force, or do it the smart way - look at the number. - // (the parts should be ordered, and hopefully indexed by their number) - - if (m_partNumberString && !XP_STRCASECMP(partNum, m_partNumberString)) - return this; - - //if (!m_partNumberString && !XP_STRCASECMP(partNum, "1")) - // return this; - - return NULL; -} - -/* -void TIMAPBodypart::PrefetchMIMEHeader() -{ - if (!m_headerData && !m_shell->DeathSignalReceived()) - { - m_shell->GetConnection()->FetchMessage(m_shell->GetUID(), TIMAP4BlockingConnection::kMIMEHeader, TRUE, 0, 0, m_partNumberString); - // m_headerLength will be filled in when it is adopted from the parser - } - if (!m_headerData) - { - SetIsValid(FALSE); - } -} -*/ - -void TIMAPBodypart::QueuePrefetchMIMEHeader() -{ - m_shell->AddPrefetchToQueue(TIMAP4BlockingConnection::kMIMEHeader, m_partNumberString); -} - -int32 TIMAPBodypart::GenerateMIMEHeader(XP_Bool stream, XP_Bool prefetch) -{ - if (prefetch && !m_headerData) - { - QueuePrefetchMIMEHeader(); - return 0; - } - else if (m_headerData) - { - int32 mimeHeaderLength = 0; - - if (!ShouldFetchInline()) - { - // if this part isn't inline, add the X-Mozilla-IMAP-Part header - char *xPartHeader = PR_smprintf("%s: %s", IMAP_EXTERNAL_CONTENT_HEADER, m_partNumberString); - if (xPartHeader) - { - if (stream) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-XHeader",m_partNumberString); - m_shell->GetConnection()->HandleMessageDownLoadLine(xPartHeader, FALSE); - } - mimeHeaderLength += XP_STRLEN(xPartHeader); - XP_FREE(xPartHeader); - } - } - - mimeHeaderLength += XP_STRLEN(m_headerData); - if (stream) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-MIMEHeader",m_partNumberString); - m_shell->GetConnection()->HandleMessageDownLoadLine(m_headerData, FALSE); // all one line? Can we do that? - } - - return mimeHeaderLength; - } - else - { - SetIsValid(FALSE); // prefetch didn't adopt a MIME header - return 0; - } -} - -int32 TIMAPBodypart::GeneratePart(XP_Bool stream, XP_Bool prefetch) -{ - if (prefetch) - return 0; // don't need to prefetch anything - - if (m_partData) // we have prefetched the part data - { - if (stream) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-Part-Prefetched",m_partNumberString); - m_shell->GetConnection()->HandleMessageDownLoadLine(m_partData, FALSE); - } - return XP_STRLEN(m_partData); - } - else // we are fetching and streaming this part's body as we go - { - if (stream && !m_shell->DeathSignalReceived()) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-Part-Inline",m_partNumberString); - m_shell->GetConnection()->FetchTryChunking(m_shell->GetUID(), TIMAP4BlockingConnection::kMIMEPart, TRUE, m_partNumberString, m_partLength); - } - return m_partLength; // the part length has been filled in from the BODYSTRUCTURE response - } -} - -int32 TIMAPBodypart::GenerateBoundary(XP_Bool stream, XP_Bool prefetch, XP_Bool lastBoundary) -{ - if (prefetch) - return 0; // don't need to prefetch anything - - if (m_boundaryData) - { - if (!lastBoundary) - { - if (stream) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-Boundary",m_partNumberString); - m_shell->GetConnection()->HandleMessageDownLoadLine(m_boundaryData, FALSE); - } - return XP_STRLEN(m_boundaryData); - } - else // the last boundary - { - char *lastBoundaryData = PR_smprintf("%s--", m_boundaryData); - if (lastBoundaryData) - { - if (stream) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-Boundary-Last",m_partNumberString); - m_shell->GetConnection()->HandleMessageDownLoadLine(lastBoundaryData, FALSE); - } - int32 rv = XP_STRLEN(lastBoundaryData); - XP_FREE(lastBoundaryData); - return rv; - } - else - { - //HandleMemoryFailure(); - return 0; - } - } - } - else - return 0; -} - -int32 TIMAPBodypart::GenerateEmptyFilling(XP_Bool stream, XP_Bool prefetch) -{ - if (prefetch) - return 0; // don't need to prefetch anything - - char *emptyString = XP_GetString(MK_IMAP_EMPTY_MIME_PART); - if (emptyString) - { - if (stream) - { - m_shell->GetConnection()->Log("SHELL","GENERATE-Filling",m_partNumberString); - m_shell->GetConnection()->HandleMessageDownLoadLine(emptyString, FALSE); - } - return XP_STRLEN(emptyString); - } - else - return 0; -} - - -// Returns TRUE if the prefs say that this content type should -// explicitly be kept in when filling in the shell -XP_Bool TIMAPBodypart::ShouldExplicitlyFetchInline() -{ - return FALSE; -} - - -// Returns TRUE if the prefs say that this content type should -// explicitly be left out when filling in the shell -XP_Bool TIMAPBodypart::ShouldExplicitlyNotFetchInline() -{ - return FALSE; -} - - -///////////// TIMAPBodypartLeaf ///////////////////////////// - - -TIMAPBodypartLeaf::TIMAPBodypartLeaf(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart) : -TIMAPBodypart(shell, partNum, buf, parentPart) -{ - SetIsValid(ParseIntoObjects()); -} - -TIMAPBodypartType TIMAPBodypartLeaf::GetType() -{ - return IMAP_BODY_LEAF; -} - -int32 TIMAPBodypartLeaf::Generate(XP_Bool stream, XP_Bool prefetch) -{ - int32 len = 0; - - if (GetIsValid()) - { - - if (stream && !prefetch) - m_shell->GetConnection()->Log("SHELL","GENERATE-Leaf",m_partNumberString); - - // Stream out the MIME part boundary - //GenerateBoundary(); - XP_ASSERT(m_parentPart); - //TIMAPBodypartMessage *parentMessage = m_parentPart ? m_parentPart->GetTIMAPBodypartMessage() : NULL; - - // Stream out the MIME header of this part, if this isn't the only body part of a message - //if (parentMessage ? !parentMessage->GetIsTopLevelMessage() : TRUE) - if ((m_parentPart->GetType() != IMAP_BODY_MESSAGE_RFC822) - && !m_shell->GetPseudoInterrupted()) - len += GenerateMIMEHeader(stream, prefetch); - - if (!m_shell->GetPseudoInterrupted()) - { - if (ShouldFetchInline()) - { - // Fetch and stream the content of this part - len += GeneratePart(stream, prefetch); - } - else - { - // fill in the filling within the empty part - len += GenerateEmptyFilling(stream, prefetch); - } - } - } - m_contentLength = len; - return m_contentLength; -} - - -// leaves parser at next token after basic fields are parsed. -// This can therefore be used for types derived from leaves, -// such as message/rfc822 and text/*. -XP_Bool TIMAPBodypartLeaf::ParseIntoObjects() -{ - // No children for a leaf - just parse this - - // Eat the buffer into the parser - fNextToken = GetNextToken(); - - // body type ("application", "text", "image", etc.) - if (ContinueParse()) - { - fNextToken++; // eat the first '(' - m_bodyType = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - // body subtype ("gif", "html", etc.) - if (ContinueParse()) - { - m_bodySubType = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - // body parameter parenthesized list - if (ContinueParse()) - { - if (!fNextToken) - SetIsValid(FALSE); - else if (fNextToken[0] == '(') - { - if (!fNextToken[1]) - SetIsValid(FALSE); - else - { - if (fNextToken[1] != ')') - { - fNextToken++; - skip_to_close_paren(); - } - else - { - fNextToken = GetNextToken(); - } - } - } - else if (!XP_STRCASECMP(fNextToken, "NIL")) - fNextToken = GetNextToken(); - } - else - SetIsValid(FALSE); - - // body id - if (ContinueParse()) - { - m_bodyID = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - // body description - if (ContinueParse()) - { - m_bodyDescription = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - // body encoding - if (ContinueParse()) - { - m_bodyEncoding = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - // body size - if (ContinueParse()) - { - char *bodySizeString = CreateAtom(); - if (bodySizeString) - { - // convert to an int32 here, set m_partLength - m_partLength = atoint32(bodySizeString); - XP_FREE(bodySizeString); - } - else - SetIsValid(FALSE); - - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - - // that's it, we can just leave the parser the way it is since - // we'll never use it again. - - if (GetIsValid() && m_bodyType && m_bodySubType) - { - m_contentType = PR_smprintf("%s/%s",m_bodyType,m_bodySubType); - } - - return TRUE; -} - -// returns TRUE if this part should be fetched inline for generation. -XP_Bool TIMAPBodypartLeaf::ShouldFetchInline() -{ - char *generatingPart = m_shell->GetGeneratingPart(); - if (generatingPart) - { - // If we are generating a specific part - if (!XP_STRCMP(generatingPart, m_partNumberString)) - { - // This is the part we're generating - return TRUE; - } - else - { - // If this is the only body part of a message, and that - // message is the part being generated, then this leaf should - // be inline as well. - if ((m_parentPart->GetType() == IMAP_BODY_MESSAGE_RFC822) && - (!XP_STRCMP(m_parentPart->GetPartNumberString(), generatingPart))) - return TRUE; - - // Leave out all other leaves if this isn't the one - // we're generating. - // Maybe change later to check parents, etc. - return FALSE; - } - } - else - { - // We are generating the whole message, possibly (hopefully) - // leaving out non-inline parts - - if (ShouldExplicitlyFetchInline()) - return TRUE; - if (ShouldExplicitlyNotFetchInline()) - return FALSE; - - // If the parent is a message (this is the only body part of that - // message), and that message should be inline, then its body - // should inherit the inline characteristics of that message - if (m_parentPart->GetType() == IMAP_BODY_MESSAGE_RFC822) - return m_parentPart->ShouldFetchInline(); - - if (!m_shell->GetShowAttachmentsInline()) - { - // The first text part is still displayed inline, - // even if View Attachments As Links is on. - if (!XP_STRCMP(m_partNumberString, "1") && - !XP_STRCASECMP(m_bodyType, "text")) - return TRUE; // we're downloading it inline - else - return FALSE; // we can leave it on the server - } - if (!XP_STRCASECMP(m_bodyType, "APPLICATION") && // If it is of type "application" - XP_STRNCASECMP(m_bodySubType, "x-pkcs7", 7) // and it's not a signature (signatures are inline) -#ifdef XP_MAC - && XP_STRCASECMP(m_bodySubType, "applefile") // and it's not an appledouble resource fork on Mac (they're inline) -#endif - ) - return FALSE; // we can leave it on the server - return TRUE; // we're downloading it inline - } -} - -XP_Bool TIMAPBodypartLeaf::PreflightCheckAllInline() -{ - // only need to check this part, since it has no children. - return ShouldFetchInline(); -} - - -///////////// TIMAPBodypartMessage //////////////////////// - -TIMAPBodypartMessage::TIMAPBodypartMessage(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart, - XP_Bool topLevelMessage) : TIMAPBodypartLeaf(shell, partNum, buf, parentPart) -{ - m_topLevelMessage = topLevelMessage; - if (m_topLevelMessage) - { - m_partNumberString = PR_smprintf("0"); - if (!m_partNumberString) - { - SetIsValid(FALSE); - return; - } - } - m_body = NULL; - m_headers = new TIMAPMessageHeaders(shell, m_partNumberString, this); // We always have a Headers object - if (!m_headers || !m_headers->GetIsValid()) - { - SetIsValid(FALSE); - return; - } - SetIsValid(ParseIntoObjects()); -} - -TIMAPBodypartType TIMAPBodypartMessage::GetType() -{ - return IMAP_BODY_MESSAGE_RFC822; -} - -TIMAPBodypartMessage::~TIMAPBodypartMessage() -{ - delete m_headers; - delete m_body; -} - -int32 TIMAPBodypartMessage::Generate(XP_Bool stream, XP_Bool prefetch) -{ - if (!GetIsValid()) - return 0; - - m_contentLength = 0; - - if (stream && !prefetch) - m_shell->GetConnection()->Log("SHELL","GENERATE-MessageRFC822",m_partNumberString); - - if (!m_topLevelMessage && !m_shell->GetPseudoInterrupted()) // not the top-level message - we need the MIME header as well as the message header - { - m_contentLength += GenerateMIMEHeader(stream, prefetch); - } - - if (!m_shell->GetPseudoInterrupted()) - m_contentLength += m_headers->Generate(stream, prefetch); - if (!m_shell->GetPseudoInterrupted()) - m_contentLength += m_body->Generate(stream, prefetch); - - return m_contentLength; -} - - -XP_Bool TIMAPBodypartMessage::ParseIntoObjects() -{ - if (ContinueParse()) // basic fields parsed out ok - { - // three additional fields: envelope structure, bodystructure, and size in lines - if (*fNextToken == '(') - { - // ignore the envelope... maybe when we have time we can parse it for fields - // char *envelope = CreateParenGroup(); - fNextToken++; - skip_to_close_paren(); - } - else - SetIsValid(FALSE); - - if (ContinueParse()) - { - if (*fNextToken == '(') - { - // extract the bodystructure and create the body from it - char *parenGroup = CreateParenGroup(); - if (parenGroup) - { - char *bodyPartNum = NULL; - if (!m_topLevelMessage) - bodyPartNum = PR_smprintf("%s.1", m_partNumberString); - else - bodyPartNum = PR_smprintf("1"); - if (bodyPartNum && ContinueParse()) // storage adopted by child part - { - m_body = TIMAPBodypart::CreatePart(m_shell, bodyPartNum, parenGroup, this); - } - else - { - // HandleMemoryFailure(); - } - XP_FREE(parenGroup); - } - else - { - SetSyntaxError(TRUE); - SetIsValid(FALSE); - } - } - else - SetIsValid(FALSE); - } - else - SetIsValid(FALSE); - - // ignore size in lines - } - - if (!m_body || !m_body->GetIsValid()) - SetIsValid(FALSE); - - return GetIsValid(); -} - - -XP_Bool TIMAPBodypartMessage::ShouldFetchInline() -{ - if (m_topLevelMessage) // the main message should always be defined as "inline" - return TRUE; - - char *generatingPart = m_shell->GetGeneratingPart(); - if (generatingPart) - { - // If we are generating a specific part - // Always generate containers (just don't fill them in) - // because it is low cost (everything is cached) - // and it gives the message its full MIME structure, - // to avoid any potential mishap. - return TRUE; - } - else - { - // Generating whole message - - if (ShouldExplicitlyFetchInline()) - return TRUE; - if (ShouldExplicitlyNotFetchInline()) - return FALSE; - - - if (!m_shell->GetShowAttachmentsInline()) - return FALSE; - - // Message types are inline, by default. - return TRUE; - } -} - -XP_Bool TIMAPBodypartMessage::PreflightCheckAllInline() -{ - if (!ShouldFetchInline()) - return FALSE; - - return m_body->PreflightCheckAllInline(); -} - -// Fills in buffer (and adopts storage) for header object -void TIMAPBodypartMessage::AdoptMessageHeaders(char *headers) -{ - if (!GetIsValid()) - return; - - // we are going to say that the message headers only have - // part data, and no header data. - m_headers->AdoptPartDataBuffer(headers); - if (!m_headers->GetIsValid()) - SetIsValid(FALSE); -} - -// Finds the part with given part number -// Returns a TIMAPBodystructure of the matched part if it is this -// or one of its children. Returns NULL otherwise. -TIMAPBodypart *TIMAPBodypartMessage::FindPartWithNumber(const char *partNum) -{ - // either brute force, or do it the smart way - look at the number. - // (the parts should be ordered, and hopefully indexed by their number) - - if (!XP_STRCASECMP(partNum, m_partNumberString)) - return this; - - return m_body->FindPartWithNumber(partNum); -} - -///////////// TIMAPBodypartMultipart //////////////////////// - - -TIMAPBodypartMultipart::TIMAPBodypartMultipart(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart) : -TIMAPBodypart(shell, partNum, buf, parentPart) -{ - if (!m_parentPart || (m_parentPart->GetType() == IMAP_BODY_MESSAGE_RFC822)) - { - // the multipart (this) will inherit the part number of its parent - FREEIF(m_partNumberString); - if (!m_parentPart) - { - m_partNumberString = PR_smprintf("0"); - } - else - { - m_partNumberString = XP_STRDUP(m_parentPart->GetPartNumberString()); - } - } - m_partList = new XPPtrArray(); - if (!m_partList) - { - SetIsValid(FALSE); - return; - } - if (!m_parentPart) - { - SetIsValid(FALSE); - return; - } - SetIsValid(ParseIntoObjects()); -} - -TIMAPBodypartType TIMAPBodypartMultipart::GetType() -{ - return IMAP_BODY_MULTIPART; -} - -TIMAPBodypartMultipart::~TIMAPBodypartMultipart() -{ - TIMAPBodypart *bp = NULL; - for (int i = m_partList->GetSize() - 1; i >= 0; i--) - { - delete (TIMAPBodypart *)(m_partList->GetAt(i)); - } - delete m_partList; -} - -int32 TIMAPBodypartMultipart::Generate(XP_Bool stream, XP_Bool prefetch) -{ - int32 len = 0; - - if (GetIsValid()) - { - if (stream && !prefetch) - m_shell->GetConnection()->Log("SHELL","GENERATE-Multipart",m_partNumberString); - - // Stream out the MIME header of this part - - XP_Bool parentIsMessageType = GetParentPart() ? (GetParentPart()->GetType() == IMAP_BODY_MESSAGE_RFC822) : TRUE; - - // If this is multipart/signed, then we always want to generate the MIME headers of this multipart. - // Otherwise, we only want to do it if the parent is not of type "message" - XP_Bool needMIMEHeader = !parentIsMessageType; // !XP_STRCASECMP(m_bodySubType, "signed") ? TRUE : !parentIsMessageType; - if (needMIMEHeader && !m_shell->GetPseudoInterrupted()) // not a message body's type - { - len += GenerateMIMEHeader(stream, prefetch); - } - - if (ShouldFetchInline()) - { - for (int i = 0; i < m_partList->GetSize(); i++) - { - if (!m_shell->GetPseudoInterrupted()) - len += GenerateBoundary(stream, prefetch, FALSE); - if (!m_shell->GetPseudoInterrupted()) - len += ((TIMAPBodypart *)(m_partList->GetAt(i)))->Generate(stream, prefetch); - } - if (!m_shell->GetPseudoInterrupted()) - len += GenerateBoundary(stream, prefetch, TRUE); - } - else - { - // fill in the filling within the empty part - if (!m_shell->GetPseudoInterrupted()) - len += GenerateEmptyFilling(stream, prefetch); - } - } - m_contentLength = len; - return m_contentLength; -} - -XP_Bool TIMAPBodypartMultipart::ParseIntoObjects() -{ - char *where = m_responseBuffer+1; - int childCount = 0; - // Parse children - // Pull out all the children parts from buf, and send them on their way - while (where[0] == '(' && ContinueParse()) - { - char *endParen = findEndParenInBuffer(where); - if (endParen) - { - int32 len = 1 + endParen - where; - char *parenGroup = (char *)XP_ALLOC((len + 1)*sizeof(char)); - if (parenGroup) - { - XP_STRNCPY_SAFE(parenGroup, where, len + 1); - parenGroup[len] = 0; - childCount++; - char *childPartNum = NULL; - if (XP_STRCMP(m_partNumberString, "0")) // not top-level - childPartNum = PR_smprintf("%s.%d", m_partNumberString, childCount); - else // top-level - childPartNum = PR_smprintf("%d", childCount); - if (childPartNum) // storage adopted for childPartNum - { - TIMAPBodypart *child = TIMAPBodypart::CreatePart(m_shell, childPartNum, parenGroup, this); - if (child) - { - m_partList->Add(child); - } - else - { - SetIsValid(FALSE); - } - } - else - { - SetIsValid(FALSE); - } - XP_FREE(parenGroup); - - // move the next child down - char *newBuf = NULL; - if (*(endParen + 1) == ' ') // last child - newBuf = PR_smprintf("(%s", endParen + 2); - else - newBuf = PR_smprintf("(%s", endParen + 1); - FREEIF(m_responseBuffer); - m_responseBuffer = newBuf; - where = m_responseBuffer+1; - } - else - { - SetIsValid(FALSE); - } - } - else - { - SetIsValid(FALSE); - } - } - - if (GetIsValid()) - { - m_bodyType = XP_STRDUP("multipart"); - - // Parse what's left of this. - - // Eat the buffer into the parser - fNextToken = GetNextToken(); - if (ContinueParse()) - { - // multipart subtype (mixed, alternative, etc.) - fNextToken++; - m_bodySubType = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - } - - if (ContinueParse()) - { - // body parameter parenthesized list, including - // boundary - fNextToken++; - while (ContinueParse() && *fNextToken != ')') - { - char *attribute = CreateNilString(); - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - - if (ContinueParse() && attribute && - !XP_STRCASECMP(attribute, "BOUNDARY")) - { - char *boundary = CreateNilString(); - if (boundary) - { - m_boundaryData = PR_smprintf("--%s", boundary); - XP_FREE(boundary); - } - - if (ContinueParse()) - fNextToken = GetNextToken(); - else - SetIsValid(FALSE); - XP_FREE(attribute); - } - else - { - FREEIF(attribute); - if (ContinueParse()) - { - // removed because parser was advancing one too many tokens - //fNextToken = GetNextToken(); - char *value = CreateNilString(); - FREEIF(value); - if (ContinueParse()) - fNextToken = GetNextToken(); - //if (ContinueParse()) - // fNextToken = GetNextToken(); - } - } - } - } - - // We might want the disposition, but I think we can leave it like this for now. - - m_contentType = PR_smprintf("%s/%s", m_bodyType, m_bodySubType); - } - - if (!m_boundaryData) - { - // Actually, we should probably generate a boundary here. - SetIsValid(FALSE); - } - - return GetIsValid(); -} - -XP_Bool TIMAPBodypartMultipart::ShouldFetchInline() -{ - char *generatingPart = m_shell->GetGeneratingPart(); - if (generatingPart) - { - // If we are generating a specific part - // Always generate containers (just don't fill them in) - // because it is low cost (everything is cached) - // and it gives the message its full MIME structure, - // to avoid any potential mishap. - return TRUE; - } - else - { - // Generating whole message - - if (ShouldExplicitlyFetchInline()) - return TRUE; - if (ShouldExplicitlyNotFetchInline()) - return FALSE; - - // If "Show Attachments as Links" is on, and - // the parent of this multipart is not a message, - // then it's not inline. - if (!m_shell->GetShowAttachmentsInline() && - (m_parentPart->GetType() != IMAP_BODY_MESSAGE_RFC822)) - return FALSE; - - // multiparts are always inline - // (their children might not be, though) - return TRUE; - } -} - -XP_Bool TIMAPBodypartMultipart::PreflightCheckAllInline() -{ - XP_Bool rv = ShouldFetchInline(); - - int i = 0; - while (rv && (i < m_partList->GetSize())) - { - rv = ((TIMAPBodypart *)(m_partList->GetAt(i)))->PreflightCheckAllInline(); - i++; - } - - return rv; -} - -TIMAPBodypart *TIMAPBodypartMultipart::FindPartWithNumber(const char *partNum) -{ - XP_ASSERT(partNum); - - // check this - if (!XP_STRCMP(partNum, m_partNumberString)) - return this; - - // check children - for (int i = m_partList->GetSize() - 1; i >= 0; i--) - { - TIMAPBodypart *foundPart = ((TIMAPBodypart *)(m_partList->GetAt(i)))->FindPartWithNumber(partNum); - if (foundPart) - return foundPart; - } - - // not this, or any of this's children - return NULL; -} - - - -///////////// TIMAPMessageHeaders //////////////////////////////////// - - - -TIMAPMessageHeaders::TIMAPMessageHeaders(TIMAPBodyShell *shell, char *partNum, TIMAPBodypart *parentPart) : -TIMAPBodypart(shell, partNum, NULL, parentPart) -{ - if (!partNum) - { - SetIsValid(FALSE); - return; - } - m_partNumberString = XP_STRDUP(partNum); - if (!m_partNumberString) - { - SetIsValid(FALSE); - return; - } - if (!m_parentPart || !m_parentPart->GetTIMAPBodypartMessage()) - { - // Message headers created without a valid Message parent - XP_ASSERT(FALSE); - SetIsValid(FALSE); - } -} - -TIMAPBodypartType TIMAPMessageHeaders::GetType() -{ - return IMAP_BODY_MESSAGE_HEADER; -} - -void TIMAPMessageHeaders::QueuePrefetchMessageHeaders() -{ - - if (!m_parentPart->GetTIMAPBodypartMessage()->GetIsTopLevelMessage()) // not top-level headers - m_shell->AddPrefetchToQueue(TIMAP4BlockingConnection::kRFC822HeadersOnly, m_partNumberString); - else - m_shell->AddPrefetchToQueue(TIMAP4BlockingConnection::kRFC822HeadersOnly, NULL); -} - -int32 TIMAPMessageHeaders::Generate(XP_Bool stream, XP_Bool prefetch) -{ - // prefetch the header - if (prefetch && !m_partData && !m_shell->DeathSignalReceived()) - { - QueuePrefetchMessageHeaders(); - } - - if (stream && !prefetch) - m_shell->GetConnection()->Log("SHELL","GENERATE-MessageHeaders",m_partNumberString); - - // stream out the part data - if (ShouldFetchInline()) - { - if (!m_shell->GetPseudoInterrupted()) - m_contentLength = GeneratePart(stream, prefetch); - } - else - { - m_contentLength = 0; // don't fill in any filling for the headers - } - return m_contentLength; -} - -XP_Bool TIMAPMessageHeaders::ParseIntoObjects() -{ - return TRUE; -} - -XP_Bool TIMAPMessageHeaders::ShouldFetchInline() -{ - return m_parentPart->ShouldFetchInline(); -} - - -///////////// TIMAPBodyShellCache //////////////////////////////////// - - -static int -imap_shell_cache_strcmp (const void *a, const void *b) -{ - return XP_STRCMP ((const char *) a, (const char *) b); -} - - -TIMAPBodyShellCache::TIMAPBodyShellCache() -{ - m_shellHash = XP_HashTableNew(20, XP_StringHash, imap_shell_cache_strcmp); - m_shellList = new XPPtrArray(); -} - -/* static */ TIMAPBodyShellCache *TIMAPBodyShellCache::Create() -{ - TIMAPBodyShellCache *cache = new TIMAPBodyShellCache(); - if (!cache || !cache->m_shellHash || !cache->m_shellList) - return NULL; - - return cache; -} - -TIMAPBodyShellCache::~TIMAPBodyShellCache() -{ - while (EjectEntry()) ; - XP_HashTableDestroy(m_shellHash); - delete m_shellList; -} - -// We'll use an LRU scheme here. -// We will add shells in numerical order, so the -// least recently used one will be in slot 0. -XP_Bool TIMAPBodyShellCache::EjectEntry() -{ - if (m_shellList->GetSize() < 1) - return FALSE; - - TIMAPBodyShell *removedShell = (TIMAPBodyShell *) (m_shellList->GetAt(0)); - m_shellList->RemoveAt(0); - XP_Remhash(m_shellHash, removedShell->GetUID()); - delete removedShell; - - return TRUE; -} - -XP_Bool TIMAPBodyShellCache::AddShellToCache(TIMAPBodyShell *shell) -{ - // If it's already in the cache, then just return. - // This has the side-effect of re-ordering the LRU list - // to put this at the top, which is good, because it's what we want. - if (FindShellForUID(shell->GetUID(), shell->GetFolderName())) - return TRUE; - - // OK, so it's not in the cache currently. - - // First, for safety sake, remove any entry with the given UID, - // just in case we have a collision between two messages in different - // folders with the same UID. - TIMAPBodyShell *foundShell = (TIMAPBodyShell *) XP_Gethash(m_shellHash, shell->GetUID(), NULL); - if (foundShell) - { - XP_Remhash(m_shellHash, foundShell); - m_shellList->Remove(foundShell); - } - - // Add the new one to the cache - m_shellList->Add(shell); - XP_Puthash(m_shellHash, shell->GetUID(), shell); - shell->SetIsCached(TRUE); - - // while we're not over our size limit, eject entries - XP_Bool rv = TRUE; - while (GetSize() > GetMaxSize()) - { - rv = EjectEntry(); - } - - return rv; - -} - -TIMAPBodyShell *TIMAPBodyShellCache::FindShellForUID(const char *UID, const char *mailboxName) -{ - if (!UID) - return NULL; - - TIMAPBodyShell *foundShell = (TIMAPBodyShell *) XP_Gethash(m_shellHash, UID, NULL); - - if (!foundShell) - return NULL; - - // mailbox names must match also. - if (XP_STRCMP(mailboxName, foundShell->GetFolderName())) - return NULL; - - // adjust the LRU stuff - m_shellList->Remove(foundShell); // oh well, I suppose this defeats the performance gain of the hash if it actually is found - m_shellList->Add(foundShell); // Adds to end - - return foundShell; -} - -TIMAPBodyShell *TIMAPBodyShellCache::FindShellForUID(uint32 UID, const char *mailboxName) -{ - char *uidString = PR_smprintf("%ld", UID); - TIMAPBodyShell *rv = FindShellForUID(uidString, mailboxName); - FREEIF(uidString); - return rv; -} - - -///////////// TIMAPMessagePartID //////////////////////////////////// - - -TIMAPMessagePartID::TIMAPMessagePartID(TIMAP4BlockingConnection::eFetchFields fields, const char *partNumberString) -{ - m_fields = fields; - m_partNumberString = partNumberString; -} - -TIMAPMessagePartIDArray::TIMAPMessagePartIDArray() -{ -} - -TIMAPMessagePartIDArray::~TIMAPMessagePartIDArray() -{ - RemoveAndFreeAll(); -} - -void TIMAPMessagePartIDArray::RemoveAndFreeAll() -{ - while (GetSize() > 0) - { - TIMAPMessagePartID *part = GetPart(0); - delete part; - RemoveAt(0); - } -} diff --git a/mozilla/network/protocol/imap4/imapbody.h b/mozilla/network/protocol/imap4/imapbody.h deleted file mode 100644 index 0ba1328c2bb..00000000000 --- a/mozilla/network/protocol/imap4/imapbody.h +++ /dev/null @@ -1,368 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* -TIMAPBodyShell and associated classes -*/ - -#ifndef IMAPBODY_H -#define IMAPBODY_H - -#include "imap.h" -#include "xp_list.h" - - -typedef enum _TIMAPBodypartType { - IMAP_BODY_MESSAGE_RFC822, - IMAP_BODY_MESSAGE_HEADER, - IMAP_BODY_LEAF, - IMAP_BODY_MULTIPART -} TIMAPBodypartType; - -class TIMAPGenericParser; -class TNavigatorImapConnection; -class TIMAPBodyShell; -class XPPtrArray; -class TIMAPBodypartMessage; -typedef struct xp_HashTable *XP_HashTable; - - -class TIMAPBodypart : public TIMAPGenericParser -{ -public: - // Construction - static TIMAPBodypart *CreatePart(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart); - virtual XP_Bool GetIsValid() { return m_isValid; } - virtual void SetIsValid(XP_Bool valid); - virtual TIMAPBodypartType GetType() = 0; - - // Generation - virtual int32 Generate(XP_Bool /*stream*/, XP_Bool /* prefetch */) { return -1; } // Generates an HTML representation of this part. Returns content length generated, -1 if failed. - virtual void AdoptPartDataBuffer(char *buf); // Adopts storage for part data buffer. If NULL, sets isValid to FALSE. - virtual void AdoptHeaderDataBuffer(char *buf); // Adopts storage for header data buffer. If NULL, sets isValid to FALSE. - virtual XP_Bool ShouldFetchInline() { return TRUE; } // returns TRUE if this part should be fetched inline for generation. - virtual XP_Bool PreflightCheckAllInline() { return TRUE; } - - virtual XP_Bool ShouldExplicitlyFetchInline(); - virtual XP_Bool ShouldExplicitlyNotFetchInline(); - -protected: // If stream is FALSE, simply returns the content length that will be generated - virtual int32 GeneratePart(XP_Bool stream, XP_Bool prefetch); // the body of the part itself - virtual int32 GenerateMIMEHeader(XP_Bool stream, XP_Bool prefetch); // the MIME headers of the part - virtual int32 GenerateBoundary(XP_Bool stream, XP_Bool prefetch, XP_Bool lastBoundary); // Generates the MIME boundary wrapper for this part. - // lastBoundary indicates whether or not this should be the boundary for the - // final MIME part of the multipart message. - virtual int32 GenerateEmptyFilling(XP_Bool stream, XP_Bool prefetch); // Generates (possibly empty) filling for a part that won't be filled in inline. - - // Part Numbers / Hierarchy -public: - virtual int GetPartNumber() { return m_partNumber; } // Returns the part number on this hierarchy level - virtual char *GetPartNumberString() { return m_partNumberString; } - virtual TIMAPBodypart *FindPartWithNumber(const char *partNum); // Returns the part object with the given number - virtual TIMAPBodypart *GetParentPart() { return m_parentPart; } // Returns the parent of this part. - // We will define a part of type message/rfc822 to be the - // parent of its body and header. - // A multipart is a parent of its child parts. - // All other leafs do not have children. - - // Other / Helpers -public: - virtual ~TIMAPBodypart(); - virtual XP_Bool GetNextLineForParser(char **nextLine); - virtual XP_Bool ContinueParse(); // overrides the parser, but calls it anyway - virtual TIMAPBodypartMessage *GetTIMAPBodypartMessage() { return NULL; } - - -protected: - virtual void QueuePrefetchMIMEHeader(); - //virtual void PrefetchMIMEHeader(); // Initiates a prefetch for the MIME header of this part. - virtual XP_Bool ParseIntoObjects() = 0; // Parses buffer and fills in both this and any children with associated objects - // Returns TRUE if it produced a valid Shell - // Must be overridden in the concerte derived class - const char *GetBodyType() { return m_bodyType; } - const char *GetBodySubType() { return m_bodySubType; } - - TIMAPBodypart(TIMAPBodyShell *shell, char *partNumber, const char *buf, TIMAPBodypart *parentPart); - -protected: - TIMAPBodyShell *m_shell; // points back to the shell - XP_Bool m_isValid; // If this part is valid. - int m_partNumber; // part number on this hierarchy level - char *m_partNumberString; // string representation of this part's full-hierarchy number. Define 0 to be the top-level message - char *m_partData; // data for this part. NULL if not filled in yet. - char *m_headerData; // data for this part's MIME header. NULL if not filled in yet. - char *m_boundaryData; // MIME boundary for this part - int32 m_partLength; - int32 m_contentLength; // Total content length which will be Generate()'d. -1 if not filled in yet. - char *m_responseBuffer; // The buffer for this object - TIMAPBodypart *m_parentPart; // Parent of this part - - // Fields - Filled in from parsed BODYSTRUCTURE response (as well as others) - char *m_contentType; // constructed from m_bodyType and m_bodySubType - char *m_bodyType; - char *m_bodySubType; - char *m_bodyID; - char *m_bodyDescription; - char *m_bodyEncoding; - // we ignore extension data for now - - -}; - - - -// Message headers -// A special type of TIMAPBodypart -// These may be headers for the top-level message, -// or any body part of type message/rfc822. -class TIMAPMessageHeaders : public TIMAPBodypart -{ -public: - TIMAPMessageHeaders(TIMAPBodyShell *shell, char *partNum, TIMAPBodypart *parentPart); - virtual TIMAPBodypartType GetType(); - virtual int32 Generate(XP_Bool stream, XP_Bool prefetch); // Generates an HTML representation of this part. Returns content length generated, -1 if failed. - virtual XP_Bool ShouldFetchInline(); - virtual void QueuePrefetchMessageHeaders(); -protected: - virtual XP_Bool ParseIntoObjects(); // Parses m_responseBuffer and fills in m_partList with associated objects - // Returns TRUE if it produced a valid Shell - -}; - - -class TIMAPBodypartMultipart : public TIMAPBodypart -{ -public: - TIMAPBodypartMultipart(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart); - virtual TIMAPBodypartType GetType(); - virtual ~TIMAPBodypartMultipart(); - virtual XP_Bool ShouldFetchInline(); - virtual XP_Bool PreflightCheckAllInline(); - virtual int32 Generate(XP_Bool stream, XP_Bool prefetch); // Generates an HTML representation of this part. Returns content length generated, -1 if failed. - virtual TIMAPBodypart *FindPartWithNumber(const char *partNum); // Returns the part object with the given number - -protected: - virtual XP_Bool ParseIntoObjects(); - -protected: - XPPtrArray *m_partList; // An ordered list of top-level body parts for this shell -}; - - -// The name "leaf" is somewhat misleading, since a part of type message/rfc822 is technically -// a leaf, even though it can contain other parts within it. -class TIMAPBodypartLeaf : public TIMAPBodypart -{ -public: - TIMAPBodypartLeaf(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart); - virtual TIMAPBodypartType GetType(); - virtual int32 Generate(XP_Bool stream, XP_Bool prefetch); // Generates an HTML representation of this part. Returns content length generated, -1 if failed. - virtual XP_Bool ShouldFetchInline(); // returns TRUE if this part should be fetched inline for generation. - virtual XP_Bool PreflightCheckAllInline(); - -protected: - virtual XP_Bool ParseIntoObjects(); - -}; - - -class TIMAPBodypartMessage : public TIMAPBodypartLeaf -{ -public: - TIMAPBodypartMessage(TIMAPBodyShell *shell, char *partNum, const char *buf, TIMAPBodypart *parentPart, XP_Bool topLevelMessage); - virtual TIMAPBodypartType GetType(); - virtual ~TIMAPBodypartMessage(); - virtual int32 Generate(XP_Bool stream, XP_Bool prefetch); - virtual XP_Bool ShouldFetchInline(); - virtual XP_Bool PreflightCheckAllInline(); - virtual TIMAPBodypart *FindPartWithNumber(const char *partNum); // Returns the part object with the given number - void AdoptMessageHeaders(char *headers); // Fills in buffer (and adopts storage) for header object - // partNum specifies the message part number to which the - // headers correspond. NULL indicates the top-level message - virtual TIMAPBodypartMessage *GetTIMAPBodypartMessage() { return this; } - virtual XP_Bool GetIsTopLevelMessage() { return m_topLevelMessage; } - -protected: - virtual XP_Bool ParseIntoObjects(); - -protected: - TIMAPMessageHeaders *m_headers; // Every body shell should have headers - TIMAPBodypart *m_body; - XP_Bool m_topLevelMessage; // Whether or not this is the top-level message - -}; - - -class TIMAPMessagePartIDArray; - -// We will refer to a Body "Shell" as a hierarchical object representation of a parsed BODYSTRUCTURE -// response. A shell contains representations of Shell "Parts." A Body Shell can undergo essentially -// two operations: Construction and Generation. -// Shell Construction occurs by parsing a BODYSTRUCTURE response into empty Parts. -// Shell Generation generates a "MIME Shell" of the message and streams it to libmime for -// display. The MIME Shell has selected (inline) parts filled in, and leaves all others -// for on-demand retrieval through explicit part fetches. - -class TIMAPBodyShell -{ -public: - - // Construction - TIMAPBodyShell(TNavigatorImapConnection *connection, const char *bs, uint32 UID, const char *folderName); // Constructor takes in a buffer containing an IMAP - // bodystructure response from the server, with the associated - // tag/command/etc. stripped off. - // That is, it takes in something of the form: - // (("TEXT" "PLAIN" ..... )) - virtual ~TIMAPBodyShell(); - void SetConnection(TNavigatorImapConnection *con) { m_connection = con; } // To be used after a shell is uncached - virtual XP_Bool GetIsValid() { return m_isValid; } - virtual void SetIsValid(XP_Bool valid); - - // Prefetch - void AddPrefetchToQueue(TIMAP4BlockingConnection::eFetchFields, const char *partNum); // Adds a message body part to the queue to be prefetched - // in a single, pipelined command - void FlushPrefetchQueue(); // Runs a single pipelined command which fetches all of the - // elements in the prefetch queue - void AdoptMessageHeaders(char *headers, const char *partNum); // Fills in buffer (and adopts storage) for header object - // partNum specifies the message part number to which the - // headers correspond. NULL indicates the top-level message - void AdoptMimeHeader(const char *partNum, char *mimeHeader); // Fills in buffer (and adopts storage) for MIME headers in appropriate object. - // If object can't be found, sets isValid to FALSE. - - // Generation - virtual int32 Generate(char *partNum); // Streams out an HTML representation of this IMAP message, going along and - // fetching parts it thinks it needs, and leaving empty shells for the parts - // it doesn't. - // Returns number of bytes generated, or -1 if invalid. - // If partNum is not NULL, then this works to generates a MIME part that hasn't been downloaded yet - // and leaves out all other parts. By default, to generate a normal message, partNum should be NULL. - - XP_Bool GetShowAttachmentsInline(); // Returns TRUE if the user has the pref "Show Attachments Inline" set. - // Returns FALSE if the setting is "Show Attachments as Links" - XP_Bool PreflightCheckAllInline(); // Returns TRUE if all parts are inline, FALSE otherwise. Does not generate anything. - - // Helpers - TNavigatorImapConnection *GetConnection() { return m_connection; } - XP_Bool GetPseudoInterrupted(); - XP_Bool DeathSignalReceived(); - const char *GetUID() { return m_UID; } - const char *GetFolderName() { return m_folderName; } - char *GetGeneratingPart() { return m_generatingPart; } - XP_Bool IsBeingGenerated() { return m_isBeingGenerated; } // Returns TRUE if this is in the process of being - // generated, so we don't re-enter - XP_Bool IsShellCached() { return m_cached; } - void SetIsCached(XP_Bool isCached) { m_cached = isCached; } - XP_Bool GetGeneratingWholeMessage() { return m_generatingWholeMessage; } - -protected: - - TIMAPBodypartMessage *m_message; - - TIMAPMessagePartIDArray *m_prefetchQueue; // array of pipelined part prefetches. Ok, so it's not really a queue. - - XP_Bool m_isValid; - TNavigatorImapConnection *m_connection; // Connection, for filling in parts - char *m_UID; // UID of this message - char *m_folderName; // folder that contains this message - char *m_generatingPart; // If a specific part is being generated, this is it. Otherwise, NULL. - XP_Bool m_isBeingGenerated; // TRUE if this body shell is in the process of being generated - XP_Bool m_showAttachmentsInline; - XP_Bool m_gotAttachmentPref; - XP_Bool m_cached; // Whether or not this shell is cached - XP_Bool m_generatingWholeMessage; // whether or not we are generating the whole (non-MPOD) message - // Set to FALSE if we are generating by parts -}; - - - -// This class caches shells, so we don't have to always go and re-fetch them. -// This does not cache any of the filled-in inline parts; those are cached individually -// in the libnet memory cache. (ugh, how will we do that?) -// Since we'll only be retrieving shells for messages over a given size, and since the -// shells themselves won't be very large, this cache will not grow very big (relatively) -// and should handle most common usage scenarios. - -// A body cache is associated with a given host, spanning folders. -// It should pay attention to UIDVALIDITY. - -class TIMAPBodyShellCache -{ - -public: - static TIMAPBodyShellCache *Create(); - virtual ~TIMAPBodyShellCache(); - - XP_Bool AddShellToCache(TIMAPBodyShell *shell); // Adds shell to cache, possibly ejecting - // another entry based on scheme in EjectEntry(). - TIMAPBodyShell *FindShellForUID(const char *UID, const char *mailboxName); // Looks up a shell in the cache given the message's UID. - TIMAPBodyShell *FindShellForUID(uint32 UID, const char *mailboxName); // Looks up a shell in the cache given the message's UID. - // Returns the shell if found, NULL if not found. - -protected: - TIMAPBodyShellCache(); - XP_Bool EjectEntry(); // Chooses an entry to eject; deletes that entry; and ejects it from the cache, - // clearing up a new space. Returns TRUE if it found an entry to eject, FALSE otherwise. - uint32 GetSize() { return m_shellList->GetSize(); } - uint32 GetMaxSize() { return 20; } - - -protected: - XPPtrArray *m_shellList; // For maintenance - XP_HashTable m_shellHash; // For quick lookup based on UID - -}; - - - - -// MessagePartID and MessagePartIDArray are used for pipelining prefetches. - -class TIMAPMessagePartID -{ -public: - TIMAPMessagePartID(TIMAP4BlockingConnection::eFetchFields fields, const char *partNumberString); - TIMAP4BlockingConnection::eFetchFields GetFields() { return m_fields; } - const char *GetPartNumberString() { return m_partNumberString; } - - -protected: - const char *m_partNumberString; - TIMAP4BlockingConnection::eFetchFields m_fields; -}; - - -class TIMAPMessagePartIDArray : public XPPtrArray { -public: - TIMAPMessagePartIDArray(); - ~TIMAPMessagePartIDArray(); - - void RemoveAndFreeAll(); - int GetNumParts() {return GetSize();} - TIMAPMessagePartID *GetPart(int i) - { - XP_ASSERT(i >= 0 && i < GetSize()); - return (TIMAPMessagePartID *) GetAt(i); - } -}; - - -#endif // IMAPBODY_H diff --git a/mozilla/network/protocol/imap4/imapearl.cpp b/mozilla/network/protocol/imap4/imapearl.cpp deleted file mode 100644 index f0d346ffb00..00000000000 --- a/mozilla/network/protocol/imap4/imapearl.cpp +++ /dev/null @@ -1,681 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" -#include "imap.h" -#include "imap4pvt.h" - -#define ISHEX(c) ( ((c) >= '0' && (c) <= '9') || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F') ) -#define NONHEX(c) (!ISHEX(c)) - -extern "C" char * escape_unescaped_percents(const char *incomingURL); - -extern "C" -{ -char * escape_unescaped_percents(const char *incomingURL) -{ - const char *inC; - char *outC; - char *result = (char *) XP_ALLOC(XP_STRLEN(incomingURL)*3+1); - - if (result) - { - for(inC = incomingURL, outC = result; *inC != '\0'; inC++) - { - if (*inC == '%') - { - // Check if either of the next two characters are non-hex. - if ( !*(inC+1) || NONHEX(*(inC+1)) || !*(inC+2) || NONHEX(*(inC+2)) ) - { - // Hex characters don't follow, escape the - // percent char - *outC++ = '%'; *outC++ = '2'; *outC++ = '5'; - } - else - { - // Hex characters follow, so assume the percent - // is escaping something else - *outC++ = *inC; - } - } - else - *outC++ = *inC; - } - *outC = '\0'; - } - - return result; -} -} - -// member functions of the TIMAPUrl class -TIMAPUrl::TIMAPUrl(const char *url_string, XP_Bool internal) - : fHostSubString(nil), - fUrlidSubString(nil), - fSourceCanonicalFolderPathSubString(nil), - fDestinationCanonicalFolderPathSubString(nil), - fSearchCriteriaString(nil), - fListOfMessageIds(nil), - fTokenPlaceHolder(nil), - fFlags(0), - fIdsAreUids(FALSE), - fIMAPstate(kAuthenticatedStateURL), - fUrlType(kTest), - fValidURL(FALSE), - fMimePartSelectorDetected(FALSE), - fInternal(internal), - fDiscoveryDepth(0) -{ - fOnlineSubDirSeparator = '/'; // initial guess - fUrlString = escape_unescaped_percents(url_string); // this duplicates url_string - fUrlString = NET_UnEscape(fUrlString); // ### mwelch - Put spaces and '>'s back in. - Parse(); -} - - -TIMAPUrl::~TIMAPUrl() -{ - FREEIF( fUrlString); -} - -void TIMAPUrl::ParseFolderPath(char **resultingCanonicalPath) -{ - *resultingCanonicalPath = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - - if (!*resultingCanonicalPath) - { - fValidURL = FALSE; - return; - } - - // The delimiter will be set for a given URL, but will not be statically available - // from an arbitrary URL. It is the creator's responsibility to fill in the correct - // delimiter from the folder's namespace when creating the URL. - char dirSeparator = *(*resultingCanonicalPath)++; - if (dirSeparator != kOnlineHierarchySeparatorUnknown) - SetOnlineSubDirSeparator( dirSeparator); - - // if dirSeparator == kOnlineHierarchySeparatorUnknown, then this must be a create - // of a top level imap box. If there is an online subdir, we will automatically - // use its separator. If there is not an online subdir, we don't need a separator. - - /* - - // I don't think we want to do any of this anymore (for 5.0). - - const char *hostDir = TIMAPHostInfo::GetPersonalOrDefaultOnlineSubDirForHost(GetUrlHost()); - if (!hostDir) - { - // couldn't find the host in our list - fValidURL = FALSE; - return; - } - int lengthOfImapSubDirString = XP_STRLEN(hostDir); - - if (*resultingCanonicalPath && - ((lengthOfImapSubDirString + XP_STRLEN("INBOX")) == XP_STRLEN(*resultingCanonicalPath)) && - !XP_STRCASECMP("INBOX", *resultingCanonicalPath + lengthOfImapSubDirString)) - { - // this is the inbox - *resultingCanonicalPath = "INBOX"; - } - */ -} - - -void TIMAPUrl::ParseSearchCriteriaString() -{ - fSearchCriteriaString = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - if (!fSearchCriteriaString) - fValidURL = FALSE; -} - - -void TIMAPUrl::ParseChildDiscoveryDepth() -{ - char *discoveryDepth = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - if (!discoveryDepth) - { - fValidURL = FALSE; - fDiscoveryDepth = 0; - return; - } - fDiscoveryDepth = atoi(discoveryDepth); -} - -void TIMAPUrl::ParseUidChoice() -{ - char *uidChoiceString = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - if (!uidChoiceString) - fValidURL = FALSE; - else - fIdsAreUids = XP_STRCMP(uidChoiceString, "UID") == 0; -} - -void TIMAPUrl::ParseMsgFlags() -{ - char *flagsPtr = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - if (flagsPtr) - { - // the url is encodes the flags byte as ascii - int intFlags = atoi(flagsPtr); - fFlags = (imapMessageFlagsType) intFlags; // cast here - } - else - fFlags = 0; -} - -void TIMAPUrl::ParseListofMessageIds() -{ - fListOfMessageIds = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - if (!fListOfMessageIds) - fValidURL = FALSE; - else - { - fMimePartSelectorDetected = XP_STRSTR(fListOfMessageIds, "&part=") != 0; - } -} - -void TIMAPUrl::Parse() -{ - fValidURL = TRUE; // hope for the best - - // first token separator is a "?" so others can grab the host - char *urlStartToken = XP_STRTOK_R(fUrlString, "?", &fTokenPlaceHolder); - - if (!XP_STRNCASECMP(urlStartToken, "IMAP://",7) ) - { - fHostSubString = urlStartToken + 7; - fUrlidSubString = fTokenPlaceHolder ? XP_STRTOK_R(nil, IMAP_URL_TOKEN_SEPARATOR, &fTokenPlaceHolder) : (char *)NULL; - if (!fUrlidSubString) - { - fValidURL = FALSE; - return; - } - - if (!XP_STRCASECMP(fUrlidSubString, "fetch")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kMsgFetch; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - } - else if (fInternal) - { - if (!XP_STRCASECMP(fUrlidSubString, "header")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kMsgHeader; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "deletemsg")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kDeleteMsg; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "deleteallmsgs")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kDeleteAllMsgs; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "addmsgflags")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kAddMsgFlags; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseMsgFlags(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "subtractmsgflags")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kSubtractMsgFlags; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseMsgFlags(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "setmsgflags")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kSetMsgFlags; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseMsgFlags(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "onlinecopy")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kOnlineCopy; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "onlinemove")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kOnlineMove; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "onlinetoofflinecopy")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kOnlineToOfflineCopy; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "onlinetoofflinemove")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kOnlineToOfflineMove; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "offlinetoonlinecopy")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kOfflineToOnlineMove; - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "search")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kSearch; - ParseUidChoice(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseSearchCriteriaString(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "test")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kTest; - } - else if (!XP_STRCASECMP(fUrlidSubString, "select")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kSelectFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - if (fTokenPlaceHolder && *fTokenPlaceHolder) - ParseListofMessageIds(); - else - fListOfMessageIds = ""; - } - else if (!XP_STRCASECMP(fUrlidSubString, "liteselect")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kLiteSelectFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "expunge")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kExpungeFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - fListOfMessageIds = ""; // no ids to UNDO - } - else if (!XP_STRCASECMP(fUrlidSubString, "create")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kCreateFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "discoverchildren")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kDiscoverChildrenUrl; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "discoverlevelchildren")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kDiscoverLevelChildrenUrl; - ParseChildDiscoveryDepth(); - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "discoverallboxes")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kDiscoverAllBoxesUrl; - } - else if (!XP_STRCASECMP(fUrlidSubString, "discoverallandsubscribedboxes")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kDiscoverAllAndSubscribedBoxesUrl; - } - else if (!XP_STRCASECMP(fUrlidSubString, "delete")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kDeleteFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "rename")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kRenameFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "movefolderhierarchy")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kMoveFolderHierarchy; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - if (fTokenPlaceHolder && *fTokenPlaceHolder) // handle promote to root - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "list")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kLsubFolders; - ParseFolderPath(&fDestinationCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "biff")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kBiff; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - ParseListofMessageIds(); - } - else if (!XP_STRCASECMP(fUrlidSubString, "netscape")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kGetMailAccountUrl; - } - else if (!XP_STRCASECMP(fUrlidSubString, "appendmsgfromfile")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kAppendMsgFromFile; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "appenddraftfromfile")) - { - fIMAPstate = kSelectedStateURL; - fUrlType = kAppendMsgFromFile; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "subscribe")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kSubscribe; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "unsubscribe")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kUnsubscribe; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "refreshacl")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kRefreshACL; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "refreshfolderurls")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kRefreshFolderUrls; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "refreshallacls")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kRefreshAllACLs; - } - else if (!XP_STRCASECMP(fUrlidSubString, "listfolder")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kListFolder; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "upgradetosubscription")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kUpgradeToSubscription; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else if (!XP_STRCASECMP(fUrlidSubString, "folderstatus")) - { - fIMAPstate = kAuthenticatedStateURL; - fUrlType = kFolderStatus; - ParseFolderPath(&fSourceCanonicalFolderPathSubString); - } - else - fValidURL = FALSE; - } - else fValidURL = FALSE; - } - else - fValidURL = FALSE; -} - -TIMAPUrl::EUrlIMAPstate TIMAPUrl::GetUrlIMAPstate() -{ - return fIMAPstate; -} - -TIMAPUrl::EIMAPurlType TIMAPUrl::GetIMAPurlType() -{ - return fUrlType; -} - - - -char *TIMAPUrl::CreateCanonicalSourceFolderPathString() -{ - return XP_STRDUP(fSourceCanonicalFolderPathSubString ? fSourceCanonicalFolderPathSubString : ""); -} - -char *TIMAPUrl::CreateCanonicalDestinationFolderPathString() -{ - return XP_STRDUP(fDestinationCanonicalFolderPathSubString); -} - -char *TIMAPUrl::CreateServerSourceFolderPathString() -{ - return AllocateServerPath(fSourceCanonicalFolderPathSubString); -} - -char *TIMAPUrl::CreateServerDestinationFolderPathString() -{ - // its possible for the destination folder path to be the root - if (!fDestinationCanonicalFolderPathSubString) - return XP_STRDUP(""); - else - return AllocateServerPath(fDestinationCanonicalFolderPathSubString); -} - -char *TIMAPUrl::CreateSearchCriteriaString() -{ - return XP_STRDUP(fSearchCriteriaString); -} - -char *TIMAPUrl::CreateListOfMessageIdsString() -{ - char *returnIdString = XP_STRDUP(fListOfMessageIds); - if (returnIdString) - { - // mime may have glommed a "&part=" for a part download - // we return the entire message and let mime extract - // the part. Pop and news work this way also. - // this algorithm truncates the "&part" string. - char *currentChar = returnIdString; - while (*currentChar && (*currentChar != '&')) - currentChar++; - if (*currentChar == '&') - *currentChar = 0; - - // we should also strip off anything after "/;section=" - // since that can specify an IMAP MIME part - char *wherepart = XP_STRSTR(returnIdString, "/;section="); - if (wherepart) - *wherepart = 0; - } - return returnIdString; -} - -char *TIMAPUrl::GetIMAPPartToFetch() -{ - char *wherepart = NULL, *rv = NULL; - if (fListOfMessageIds && (wherepart = XP_STRSTR(fListOfMessageIds, "/;section=")) != NULL) - { - wherepart += 10; // XP_STRLEN("/;section=") - if (wherepart) - { - char *wherelibmimepart = XP_STRSTR(wherepart, "&part="); - int len = XP_STRLEN(fListOfMessageIds), numCharsToCopy = 0; - if (wherelibmimepart) - numCharsToCopy = (wherelibmimepart - wherepart); - else - numCharsToCopy = XP_STRLEN(fListOfMessageIds) - (wherepart - fListOfMessageIds); - if (numCharsToCopy) - { - rv = (char *) XP_ALLOC(sizeof(char) * (numCharsToCopy + 1)); - if (rv) - XP_STRNCPY_SAFE(rv, wherepart, numCharsToCopy + 1); // appends a \0 - } - } - } - return rv; -} - - -imapMessageFlagsType TIMAPUrl::GetMsgFlags() // kAddMsgFlags or kSubtractMsgFlags only -{ - return fFlags; -} - - - -XP_Bool TIMAPUrl::ValidIMAPUrl() -{ - return fValidURL; -} - -XP_Bool TIMAPUrl::MessageIdsAreUids() -{ - return fIdsAreUids; -} - -char *TIMAPUrl::AllocateServerPath(const char *canonicalPath) -{ - XP_ASSERT(GetOnlineSubDirSeparator() != kOnlineHierarchySeparatorUnknown); - return ReplaceCharsInCopiedString(canonicalPath, '/', GetOnlineSubDirSeparator()); -} - -char *TIMAPUrl::AllocateCanonicalPath(const char *serverPath) -{ - char *canonicalPath = ReplaceCharsInCopiedString(serverPath, GetOnlineSubDirSeparator() , '/'); - - // eat any escape characters for escaped dir separators - if (canonicalPath) - { - char *currentEscapeSequence = XP_STRSTR(canonicalPath, "\\/"); - while (currentEscapeSequence) - { - XP_STRCPY(currentEscapeSequence, currentEscapeSequence+1); - currentEscapeSequence = XP_STRSTR(currentEscapeSequence+1, "\\/"); - } - } - - return canonicalPath; -} - -char *TIMAPUrl::ReplaceCharsInCopiedString(const char *stringToCopy, char oldChar, char newChar) -{ - char oldCharString[2]; - *oldCharString = oldChar; - *(oldCharString+1) = 0; - - char *translatedString = XP_STRDUP(stringToCopy); - char *currentSeparator = strstr(translatedString, oldCharString); - - while(currentSeparator) - { - *currentSeparator = newChar; - currentSeparator = strstr(currentSeparator+1, oldCharString); - } - - return translatedString; -} - -void TIMAPUrl::SetOnlineSubDirSeparator(char onlineDirSeparator) -{ - fOnlineSubDirSeparator = onlineDirSeparator; -} - -char TIMAPUrl::GetOnlineSubDirSeparator() -{ - return fOnlineSubDirSeparator; -} - -XP_Bool TIMAPUrl::GetShouldSubscribeToAll() -{ - return (GetOnlineSubDirSeparator() == '.'); -} - -#if 0 -// According to the comment in imap.h, where the prototype lives and has been commented out, -// this is obsolete. So let's get rid of the "no prototype" warning. -extern "C" { - void - IMAP_SetNamespacesFromPrefs(const char *hostName, char *personalPrefix, char *publicPrefixes, char *otherUsersPrefixes) - { - TIMAPHostInfo::ClearPrefsNamespacesForHost(hostName); - if (XP_STRCMP(personalPrefix,"")) - { - TIMAPNamespace *ns = new TIMAPNamespace(kPersonalNamespace, personalPrefix, '/', TRUE); - if (ns) - TIMAPHostInfo::AddNewNamespaceForHost(hostName, ns); - } - if (XP_STRCMP(publicPrefixes,"")) - { - TIMAPNamespace *ns = new TIMAPNamespace(kPublicNamespace, publicPrefixes, '/', TRUE); - if (ns) - TIMAPHostInfo::AddNewNamespaceForHost(hostName, ns); - } - if (XP_STRCMP(otherUsersPrefixes,"")) - { - TIMAPNamespace *ns = new TIMAPNamespace(kOtherUsersNamespace, otherUsersPrefixes, '/', TRUE); - if (ns) - TIMAPHostInfo::AddNewNamespaceForHost(hostName, ns); - } - } -} // extern "C" -#endif // 0 - diff --git a/mozilla/network/protocol/imap4/imaphier.cpp b/mozilla/network/protocol/imap4/imaphier.cpp deleted file mode 100644 index f65ec8ed443..00000000000 --- a/mozilla/network/protocol/imap4/imaphier.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" - -#include "imaphier.h" -#include "imap4pvt.h" -#include "imap.h" - -ImapHierarchyMover::ImapHierarchyMover( - const char *destinationNodeName, - const char *sourceNodeName, - TNavigatorImapConnection &connection) - : fIMAPConnection(connection) -{ - fDestinationNodeName = XP_STRDUP(destinationNodeName); - fSourceNodeName = XP_STRDUP(sourceNodeName); - fMailboxHierarchy = XP_ListNew(); -} - - - -ImapHierarchyMover::~ImapHierarchyMover() -{ - // this is a leak, delete the structs - if (fMailboxHierarchy) - XP_ListDestroy(fMailboxHierarchy); - FREEIF(fDestinationNodeName); - FREEIF(fSourceNodeName); -} - - - -void ImapHierarchyMover::AddToHierarchy(const char *nodeName) -{ - int stringLength = XP_STRLEN(nodeName); - char *nodeTokens = new char [stringLength + 2]; // end the string in double null so AddToSubTree - XP_STRCPY(nodeTokens, nodeName); // will work - *(nodeTokens + stringLength) = 0; - *(nodeTokens + stringLength+1) = 0; - AddToSubTree(nodeTokens, nodeName, fMailboxHierarchy); - delete nodeTokens; -} - - -void ImapHierarchyMover::AddToSubTree(char *nodeTokens, const char *nodeName, XP_List *subTree) -{ - char *positionOfNodeTokens = XP_STRSTR(nodeName, nodeTokens); - // make sure we find the last one - char *currentPositionOfNodeTokens = positionOfNodeTokens; - while (currentPositionOfNodeTokens && strlen(nodeTokens)) - { - currentPositionOfNodeTokens = XP_STRSTR(currentPositionOfNodeTokens + 1, nodeTokens); - if (currentPositionOfNodeTokens) - positionOfNodeTokens = currentPositionOfNodeTokens; - } - - char *placeHolderInTokenString = nil; - char *currentNodeToken = XP_STRTOK_R(nodeTokens, "/",&placeHolderInTokenString); - if (currentNodeToken) - { - // find the current node, if it exists - HierarchyNode *currentNode = NULL; - int numberOfNodes = XP_ListCount(subTree); - XP_Bool nodeFound = FALSE; - while (numberOfNodes && !nodeFound) - { - currentNode = (HierarchyNode *) XP_ListGetObjectNum(subTree, numberOfNodes--); - nodeFound = XP_STRCMP(currentNode->fNodeToken, currentNodeToken) == 0; - } - - if (!nodeFound) - { - // create the node - currentNode = (HierarchyNode *) XP_ALLOC(sizeof(HierarchyNode)); - if (currentNode) - { - currentNode->fPresentName = XP_STRDUP(nodeName); - // less the remaining tokens - *(currentNode->fPresentName + (positionOfNodeTokens-nodeName) + XP_STRLEN(currentNodeToken)) = 0; - - currentNode->fNodeToken = XP_STRDUP(currentNodeToken); - currentNode->fSubFolders = XP_ListNew(); - XP_ListAddObjectToEnd(subTree, currentNode); - } - } - - // recurse! - char *subNodeTokens = nodeTokens + XP_STRLEN(currentNodeToken) + 1; // +1 see note in AddToHierarchy - AddToSubTree(subNodeTokens, nodeName, currentNode->fSubFolders); - } -} - - -// depth first, post process unsubscribe and delete everything including and below source node name -void ImapHierarchyMover::DestroyOldFolderTree(XP_List *subTree) -{ - int numberOfNodesAtThisLevel = XP_ListCount(subTree); - for (int nodeIndex=numberOfNodesAtThisLevel; nodeIndex > 0; nodeIndex--) - { - HierarchyNode *currentNode = (HierarchyNode *) XP_ListGetObjectNum(subTree, nodeIndex); - DestroyOldFolderTree(currentNode->fSubFolders); - - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful() && - XP_STRSTR(currentNode->fPresentName, fSourceNodeName)) - { - fIMAPConnection.Unsubscribe(currentNode->fPresentName); - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - fIMAPConnection.DeleteMailbox(currentNode->fPresentName); - } - } -} - - - -// depth first, pre-process create, subscribe, and fill with messages -void ImapHierarchyMover::CreateNewFolderTree(const char *destinationNodeName, XP_List *subTree) -{ - int numberOfNodesAtThisLevel = XP_ListCount(subTree); - for (int nodeIndex=1; nodeIndex <= numberOfNodesAtThisLevel; nodeIndex++) - { - HierarchyNode *currentNode = (HierarchyNode *) XP_ListGetObjectNum(subTree, nodeIndex); - - if (!XP_STRSTR(fSourceNodeName, currentNode->fPresentName) || - !XP_STRCMP(fSourceNodeName, currentNode->fPresentName)) // if we are not yet at the node name, don't rename - { - char *newNodeName = (char *) XP_ALLOC(XP_STRLEN(destinationNodeName) + - XP_STRLEN(currentNode->fNodeToken) + 2); - XP_STRCPY(newNodeName, destinationNodeName); - XP_STRCAT(newNodeName, "/"); - XP_STRCAT(newNodeName, currentNode->fNodeToken); - - fIMAPConnection.CreateMailbox(newNodeName); - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - { - fIMAPConnection.Subscribe(newNodeName); - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - { - // close the current folder if one is selected - if (fIMAPConnection.GetServerStateParser().GetIMAPstate() == - TImapServerState::kFolderSelected) - fIMAPConnection.Close(); - - // select the old folder - fIMAPConnection.SelectMailbox(currentNode->fPresentName); - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - { - // copy its entire contents to the destination - int numOfMsgs = fIMAPConnection.GetServerStateParser().NumberOfMessages(); - if (numOfMsgs) - { - char msgList[100]; // enough for trillions? - sprintf(msgList, "1:%d", numOfMsgs); - fIMAPConnection.Copy(msgList, newNodeName, FALSE); // not uids - } - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - fIMAPConnection.Close(); - } - } - } - // recurse to my children - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - CreateNewFolderTree(newNodeName, currentNode->fSubFolders); - FREEIF( newNodeName); - } - else - CreateNewFolderTree(destinationNodeName, currentNode->fSubFolders); - } -} - - -int ImapHierarchyMover::DoMove() -{ - int returnValue = 0; - - CreateNewFolderTree(fDestinationNodeName, fMailboxHierarchy); - - if (fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - { - DestroyOldFolderTree(fMailboxHierarchy); - if (!fIMAPConnection.GetServerStateParser().LastCommandSuccessful()) - returnValue = -1; - } - else - returnValue = -1; - - return returnValue; -} - diff --git a/mozilla/network/protocol/imap4/imaphier.h b/mozilla/network/protocol/imap4/imaphier.h deleted file mode 100644 index 39650bad16b..00000000000 --- a/mozilla/network/protocol/imap4/imaphier.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef IMAPHIER -#define IMAPHIER - -#include "xp_list.h" - - -class TNavigatorImapConnection; - -struct HierarchyNode { - char *fPresentName; - char *fNodeToken; // leaf name of node - XP_List *fSubFolders; -}; - -class ImapHierarchyMover { -public: - ImapHierarchyMover(const char *destinationNodeName, - const char *sourceNodeName, - TNavigatorImapConnection &connection); - virtual ~ImapHierarchyMover(); - - virtual void AddToHierarchy(const char *nodeName); - virtual int DoMove(); -protected: - virtual void AddToSubTree(char *nodeTokens, const char *nodeName, XP_List *subTree); - virtual void CreateNewFolderTree(const char *destinationNodeName, XP_List *subTree); - virtual void DestroyOldFolderTree(XP_List *subTree); - -private: - XP_List *fMailboxHierarchy; - - TNavigatorImapConnection &fIMAPConnection; - char *fDestinationNodeName; - char *fSourceNodeName; -}; - -#endif - diff --git a/mozilla/network/protocol/imap4/imappars.cpp b/mozilla/network/protocol/imap4/imappars.cpp deleted file mode 100644 index e2256ec36cb..00000000000 --- a/mozilla/network/protocol/imap4/imappars.cpp +++ /dev/null @@ -1,3302 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#include "mkutils.h" -#include "imap4pvt.h" -#include "prlog.h" -#include "imapbody.h" - -extern "C" { -#include "xpgetstr.h" - -extern int MK_OUT_OF_MEMORY; -extern int MK_SERVER_DISCONNECTED; -extern int MK_IMAP_DOWNLOADING_MESSAGE; -} - -#define WHITESPACE " \015\012" // token delimiter - -/* 45678901234567890123456789012345678901234567890123456789012345678901234567890 -*/ -TImapFlagAndUidState::TImapFlagAndUidState(int numberOfMessages, XP_Bool bSupportUserFlag) -{ - fNumberOfMessagesAdded = 0; - fNumberOfMessageSlotsAllocated = numberOfMessages; - if (!fNumberOfMessageSlotsAllocated) - fNumberOfMessageSlotsAllocated = kFlagEntrySize; - fFlags = (imapMessageFlagsType*) XP_ALLOC(sizeof(imapMessageFlagsType) * fNumberOfMessageSlotsAllocated); // new imapMessageFlagsType[fNumberOfMessageSlotsAllocated]; - - fUids.SetSize(fNumberOfMessageSlotsAllocated); - XP_MEMSET(fFlags, 0, sizeof(imapMessageFlagsType) * fNumberOfMessageSlotsAllocated); - fSupportUserFlag = bSupportUserFlag; - fNumberDeleted = 0; -} - -TImapFlagAndUidState::TImapFlagAndUidState(const TImapFlagAndUidState& state, XP_Bool bSupportUserFlag) -{ - fNumberOfMessagesAdded = state.fNumberOfMessagesAdded; - - fNumberOfMessageSlotsAllocated = state.fNumberOfMessageSlotsAllocated; - fFlags = (imapMessageFlagsType*) XP_ALLOC(sizeof(imapMessageFlagsType) * fNumberOfMessageSlotsAllocated); // new imapMessageFlagsType[fNumberOfMessageSlotsAllocated]; - fUids.CopyArray((IDArray*) &state.fUids); - - XP_MEMCPY(fFlags, state.fFlags, sizeof(imapMessageFlagsType) * fNumberOfMessageSlotsAllocated); - fSupportUserFlag = bSupportUserFlag; - fNumberDeleted = 0; -} - -TImapFlagAndUidState::~TImapFlagAndUidState() -{ - FREEIF(fFlags); -} - - -// we need to reset our flags, (re-read all) but chances are the memory allocation needed will be -// very close to what we were already using - -void TImapFlagAndUidState::Reset(uint32 howManyLeft) -{ - if (!howManyLeft) - fNumberOfMessagesAdded = fNumberDeleted = 0; // used space is still here -} - - -// Remove (expunge) a message from our array, since now it is gone for good - -void TImapFlagAndUidState::ExpungeByIndex(uint32 index) -{ - uint32 counter = 0; - - if ((uint32) fNumberOfMessagesAdded < index) - return; - index--; - fNumberOfMessagesAdded--; - if (fFlags[index] & kImapMsgDeletedFlag) // see if we already had counted this one as deleted - fNumberDeleted--; - for (counter = index; counter < (uint32) fNumberOfMessagesAdded; counter++) - { - fUids.SetAt(counter, fUids[counter + 1]); - fFlags[counter] = fFlags[counter + 1]; - } -} - - - // adds to sorted list. protects against duplicates and going past fNumberOfMessageSlotsAllocated -void TImapFlagAndUidState::AddUidFlagPair(imap_uid uid, imapMessageFlagsType flags) -{ - // make sure there is room for this pair - if (fNumberOfMessagesAdded >= fNumberOfMessageSlotsAllocated) - { - fNumberOfMessageSlotsAllocated += kFlagEntrySize; - fUids.SetSize(fNumberOfMessageSlotsAllocated); - fFlags = (imapMessageFlagsType*) XP_REALLOC(fFlags, sizeof(imapMessageFlagsType) * fNumberOfMessageSlotsAllocated); // new imapMessageFlagsType[fNumberOfMessageSlotsAllocated]; - } - - // optimize the common case of placing on the end - if (!fNumberOfMessagesAdded || (uid > (int32) fUids[fNumberOfMessagesAdded - 1])) - { - fUids.SetAt(fNumberOfMessagesAdded, uid); - fFlags[fNumberOfMessagesAdded] = flags; - fNumberOfMessagesAdded++; - if (flags & kImapMsgDeletedFlag) - fNumberDeleted++; - return; - } - - // search for the slot for this uid-flag pair - - int32 insertionIndex = -1; - XP_Bool foundIt = FALSE; - - GetMessageFlagsFromUID(uid, &foundIt, &insertionIndex); - - // Hmmm, is the server sending back unordered fetch responses? - if (((int32) fUids[insertionIndex]) != uid) - { - // shift the uids and flags to the right - for (int32 shiftIndex = fNumberOfMessagesAdded; shiftIndex > insertionIndex; shiftIndex--) - { - fUids.SetAt(shiftIndex, fUids[shiftIndex - 1]); - fFlags[shiftIndex] = fFlags[shiftIndex - 1]; - } - fFlags[insertionIndex] = flags; - fUids.SetAt(insertionIndex, uid); - fNumberOfMessagesAdded++; - if (fFlags[insertionIndex] & kImapMsgDeletedFlag) - fNumberDeleted++; - } else { - if ((fFlags[insertionIndex] & kImapMsgDeletedFlag) && !(flags & kImapMsgDeletedFlag)) - fNumberDeleted--; - else - if (!(fFlags[insertionIndex] & kImapMsgDeletedFlag) && (flags & kImapMsgDeletedFlag)) - fNumberDeleted++; - fFlags[insertionIndex] = flags; - } -} - - -int TImapFlagAndUidState::GetNumberOfMessages() -{ - return fNumberOfMessagesAdded; -} - -int TImapFlagAndUidState::GetNumberOfDeletedMessages() -{ - return fNumberDeleted; -} - -// since the uids are sorted, start from the back (rb) - -imap_uid TImapFlagAndUidState::GetHighestNonDeletedUID() -{ - uint32 index = fNumberOfMessagesAdded; - do { - if (index <= 0) - return(0); - index--; - if (fUids[index] && !(fFlags[index] & kImapMsgDeletedFlag)) - return fUids[index]; - } while (index > 0); - return 0; -} - - -// Has the user read the last message here ? Used when we first open the inbox to see if there -// really is new mail there. - -XP_Bool TImapFlagAndUidState::IsLastMessageUnseen() -{ - uint32 index = fNumberOfMessagesAdded; - - if (index <= 0) - return FALSE; - index--; - // if last message is deleted, it was probably filtered the last time around - if (fUids[index] && (fFlags[index] & (kImapMsgSeenFlag | kImapMsgDeletedFlag))) - return FALSE; - return TRUE; -} - - -imap_uid TImapFlagAndUidState::GetUidOfMessage(int zeroBasedIndex) -{ - if (zeroBasedIndex < fNumberOfMessagesAdded) - return fUids[zeroBasedIndex]; - return (-1); // so that value is non-zero and we don't ask for bad msgs -} - - -// find a message flag given a key with non-recursive binary search, since some folders -// may have thousand of messages, once we find the key set its index, or the index of -// where the key should be inserted - -imapMessageFlagsType TImapFlagAndUidState::GetMessageFlagsFromUID(imap_uid uid, XP_Bool *foundIt, int32 *ndx) -{ - int index = 0; - int hi = fNumberOfMessagesAdded - 1; - int lo = 0; - - *foundIt = FALSE; - *ndx = -1; - while (lo <= hi) - { - index = (lo + hi) / 2; - if (fUids[index] == (uint32) uid) - { - int returnFlags = fFlags[index]; - - *foundIt = TRUE; - *ndx = index; - if (fSupportUserFlag) - returnFlags |= kImapMsgSupportUserFlag; - return returnFlags; - } - if (fUids[index] > (uint32) uid) - hi = index -1; - else if (fUids[index] < (uint32) uid) - lo = index + 1; - } - index = lo; - while ((index > 0) && (fUids[index] > (uint32) uid)) - index--; - if (index < 0) - index = 0; - *ndx = index; - return 0; -} - - - -imapMessageFlagsType TImapFlagAndUidState::GetMessageFlags(int zeroBasedIndex) -{ - imapMessageFlagsType returnFlags = kNoImapMsgFlag; - if (zeroBasedIndex < fNumberOfMessagesAdded) - returnFlags = fFlags[zeroBasedIndex]; - - if (fSupportUserFlag) - returnFlags |= kImapMsgSupportUserFlag; - - return returnFlags; -} - -extern "C" { -TImapFlagAndUidState *IMAP_CreateFlagState(int numberOfMessages) -{ - return new TImapFlagAndUidState(numberOfMessages); -} - - -void IMAP_DeleteFlagState(TImapFlagAndUidState *state) -{ - delete state; -} - - -int IMAP_GetFlagStateNumberOfMessages(TImapFlagAndUidState *state) -{ - return state->GetNumberOfMessages(); -} - - -imap_uid IMAP_GetUidOfMessage(int zeroBasedIndex, TImapFlagAndUidState *state) -{ - return state->GetUidOfMessage(zeroBasedIndex); -} - - -imapMessageFlagsType IMAP_GetMessageFlags(int zeroBasedIndex, TImapFlagAndUidState *state) -{ - return state->GetMessageFlags(zeroBasedIndex); -} - - -imapMessageFlagsType IMAP_GetMessageFlagsFromUID(imap_uid uid, XP_Bool *foundIt, TImapFlagAndUidState *state) -{ - int32 index = -1; - return state->GetMessageFlagsFromUID(uid, foundIt, &index); -} - - -} // extern "C" - -TSearchResultSequence::TSearchResultSequence() -{ - fListOfLines = XP_ListNew(); -} - -TSearchResultSequence *TSearchResultSequence::CreateSearchResultSequence() -{ - TSearchResultSequence *returnObject = new TSearchResultSequence; - if (!returnObject || - !returnObject->fListOfLines) - { - delete returnObject; - returnObject = nil; - } - - return returnObject; -} - -TSearchResultSequence::~TSearchResultSequence() -{ - if (fListOfLines) - XP_ListDestroy(fListOfLines); -} - - -void TSearchResultSequence::ResetSequence() -{ - if (fListOfLines) - XP_ListDestroy(fListOfLines); - fListOfLines = XP_ListNew(); -} - -void TSearchResultSequence::AddSearchResultLine(const char *searchLine) -{ - // The first add becomes node 2. Fix this. - char *copiedSequence = XP_STRDUP(searchLine + 9); // 9 == "* SEARCH " - - if (copiedSequence) // if we can't allocate this then the search won't hit - XP_ListAddObjectToEnd(fListOfLines, copiedSequence); -} - - -TSearchResultIterator::TSearchResultIterator(TSearchResultSequence &sequence) : - fSequence(sequence) -{ - ResetIterator(); -} - -TSearchResultIterator::~TSearchResultIterator() -{} - -void TSearchResultIterator::ResetIterator() -{ - fCurrentLine = fSequence.fListOfLines->next; - if (fCurrentLine) - fPositionInCurrentLine = (char *) fCurrentLine->object; - else - fPositionInCurrentLine = nil; -} - -int32 TSearchResultIterator::GetNextMessageNumber() -{ - int32 returnValue = 0; - if (fPositionInCurrentLine) - { - returnValue = atoint32(fPositionInCurrentLine); - - // eat the current number - while (isdigit(*++fPositionInCurrentLine)) - ; - - if (*fPositionInCurrentLine == 0xD) // found CR, no more digits on line - { - fCurrentLine = fCurrentLine->next; - if (fCurrentLine) - fPositionInCurrentLine = (char *) fCurrentLine->object; - else - fPositionInCurrentLine = nil; - } - else // eat the space - fPositionInCurrentLine++; - } - - return returnValue; -} - - - -////////////////// TIMAPGenericParser ///////////////////////// - - -TIMAPGenericParser::TIMAPGenericParser() : - fNextToken(nil), - fCurrentLine(nil), - fLineOfTokens(nil), - fCurrentTokenPlaceHolder(nil), - fStartOfLineOfTokens(nil), - fSyntaxErrorLine(nil), - fAtEndOfLine(FALSE), - fDisconnected(FALSE), - fSyntaxError(FALSE), - fTokenizerAdvanced(FALSE) -{ -} - -TIMAPGenericParser::~TIMAPGenericParser() -{ - FREEIF( fCurrentLine ); - FREEIF( fStartOfLineOfTokens); - FREEIF( fSyntaxErrorLine ); -} - -void TIMAPGenericParser::HandleMemoryFailure() -{ - SetConnected(FALSE); -} - -void TIMAPGenericParser::ResetLexAnalyzer() -{ - FREEIF( fCurrentLine ); - FREEIF( fStartOfLineOfTokens ); - fTokenizerAdvanced = FALSE; - - fCurrentLine = fNextToken = fLineOfTokens = fStartOfLineOfTokens = fCurrentTokenPlaceHolder = nil; - fAtEndOfLine = FALSE; -} - -XP_Bool TIMAPGenericParser::LastCommandSuccessful() -{ - return Connected() && !SyntaxError(); -} - -void TIMAPGenericParser::SetSyntaxError(XP_Bool error) -{ - fSyntaxError = error; - FREEIF( fSyntaxErrorLine ); - if (error) - { - XP_ASSERT(FALSE); // If you hit this assert, file a bug on chrisf. Promise to include a protocol log. - fSyntaxErrorLine = XP_STRDUP(fCurrentLine); - if (!fSyntaxErrorLine) - { - HandleMemoryFailure(); -// PR_LOG(IMAP, out, ("PARSER: Internal Syntax Error: <no line>")); - } - else - { -// if (!XP_STRCMP(fSyntaxErrorLine, CRLF)) -// PR_LOG(IMAP, out, ("PARSER: Internal Syntax Error: <CRLF>")); -// else -// PR_LOG(IMAP, out, ("PARSER: Internal Syntax Error: %s", fSyntaxErrorLine)); - } - } - else - fSyntaxErrorLine = NULL; -} - -char *TIMAPGenericParser::CreateSyntaxErrorLine() -{ - return XP_STRDUP(fSyntaxErrorLine); -} - - -XP_Bool TIMAPGenericParser::SyntaxError() -{ - return fSyntaxError; -} - -void TIMAPGenericParser::SetConnected(XP_Bool connected) -{ - fDisconnected = !connected; -} - -XP_Bool TIMAPGenericParser::Connected() -{ - return !fDisconnected; -} - -XP_Bool TIMAPGenericParser::ContinueParse() -{ - return !fSyntaxError && !fDisconnected; -} - - -XP_Bool TIMAPGenericParser::at_end_of_line() -{ - return XP_STRCMP(fNextToken, CRLF) == 0; -} - -void TIMAPGenericParser::skip_to_CRLF() -{ - while (Connected() && !at_end_of_line()) - fNextToken = GetNextToken(); -} - -// fNextToken initially should point to -// a string after the initial open paren ("(") -// After this call, fNextToken points to the -// first character after the matching close -// paren. Only call GetNextToken to get the NEXT -// token after the one returned in fNextToken. -void TIMAPGenericParser::skip_to_close_paren() -{ - int numberOfCloseParensNeeded = 1; - if (fNextToken && *fNextToken == ')') - { - numberOfCloseParensNeeded--; - fNextToken++; - if (!fNextToken || !*fNextToken) - fNextToken = GetNextToken(); - } - - while (ContinueParse() && numberOfCloseParensNeeded > 0) - { - // go through fNextToken, count the number - // of open and close parens, to account - // for nested parens which might come in - // the response - char *loc = 0; - for (loc = fNextToken; loc && *loc; loc++) - { - if (*loc == '(') - numberOfCloseParensNeeded++; - else if (*loc == ')') - numberOfCloseParensNeeded--; - if (numberOfCloseParensNeeded == 0) - { - fNextToken = loc + 1; - if (!fNextToken || !*fNextToken) - fNextToken = GetNextToken(); - break; // exit the loop - } - } - - if (numberOfCloseParensNeeded > 0) - fNextToken = GetNextToken(); - } -} - -char *TIMAPGenericParser::GetNextToken() -{ - if (!fCurrentLine || fAtEndOfLine) - AdvanceToNextLine(); - else if (Connected()) - { - if (fTokenizerAdvanced) - { - fNextToken = XP_STRTOK_R(fLineOfTokens, WHITESPACE, &fCurrentTokenPlaceHolder); - fTokenizerAdvanced = FALSE; - } - else - { - fNextToken = XP_STRTOK_R(nil, WHITESPACE, &fCurrentTokenPlaceHolder); - } - if (!fNextToken) - { - fAtEndOfLine = TRUE; - fNextToken = CRLF; - } - } - - return fNextToken; -} - -void TIMAPGenericParser::AdvanceToNextLine() -{ - FREEIF( fCurrentLine ); - FREEIF( fStartOfLineOfTokens); - fTokenizerAdvanced = FALSE; - - XP_Bool ok = GetNextLineForParser(&fCurrentLine); - if (!ok) - { - SetConnected(FALSE); - fStartOfLineOfTokens = nil; - fLineOfTokens = nil; - fCurrentTokenPlaceHolder = nil; - fNextToken = CRLF; - } - else if (fCurrentLine) // might be NULL if we are would_block ? - { - fStartOfLineOfTokens = XP_STRDUP(fCurrentLine); - if (fStartOfLineOfTokens) - { - fLineOfTokens = fStartOfLineOfTokens; - fNextToken = XP_STRTOK_R(fLineOfTokens, WHITESPACE, &fCurrentTokenPlaceHolder); - if (!fNextToken) - { - fAtEndOfLine = TRUE; - fNextToken = CRLF; - } - else - fAtEndOfLine = FALSE; - } - else - HandleMemoryFailure(); - } - else - HandleMemoryFailure(); -} - -void TIMAPGenericParser::AdvanceTokenizerStartingPoint(int32 bytesToAdvance) -{ - FREEIF(fStartOfLineOfTokens); - if (fCurrentLine) - { - fStartOfLineOfTokens = XP_STRDUP(fCurrentLine); - if (fStartOfLineOfTokens && ((int32) XP_STRLEN(fStartOfLineOfTokens) >= bytesToAdvance)) - { - fLineOfTokens = fStartOfLineOfTokens + bytesToAdvance; - fTokenizerAdvanced = TRUE; - } - else - HandleMemoryFailure(); - } - else - HandleMemoryFailure(); -} - -// Lots of things in the IMAP protocol are defined as an "astring." -// An astring is either an atom or a string. -// An atom is just a series of one or more characters such as: hello -// A string can either be quoted or literal. -// Quoted: "Test Folder 1" -// Literal: {13}Test Folder 1 -// This function leaves us off with fCurrentTokenPlaceHolder immediately after -// the end of the Astring. Call GetNextToken() to get the token after it. -char *TIMAPGenericParser::CreateAstring() -{ - if (*fNextToken == '{') - { - return CreateLiteral(); // literal - } - else if (*fNextToken == '"') - { - return CreateQuoted(); // quoted - } - else - { - return CreateAtom(); // atom - } -} - - -// Create an atom -// This function does not advance the parser. -// Call GetNextToken() to get the next token after the atom. -char *TIMAPGenericParser::CreateAtom() -{ - char *rv = XP_STRDUP(fNextToken); - //fNextToken = GetNextToken(); - return (rv); -} - -// CreateNilString creates either NIL (reutrns NULL) or a string -// Call with fNextToken pointing to the thing which we think is the nilstring. -// This function leaves us off with fCurrentTokenPlaceHolder immediately after -// the end of the string, if it is a string, or at the NIL. -// Regardless of type, call GetNextToken() to get the token after it. -char *TIMAPGenericParser::CreateNilString() -{ - if (!XP_STRCASECMP(fNextToken, "NIL")) - { - //fNextToken = GetNextToken(); - return NULL; - } - else - return CreateString(); -} - - -// Create a string, which can either be quoted or literal, -// but not an atom. -// This function leaves us off with fCurrentTokenPlaceHolder immediately after -// the end of the String. Call GetNextToken() to get the token after it. -char *TIMAPGenericParser::CreateString() -{ - if (*fNextToken == '{') - { - char *rv = CreateLiteral(); // literal - return (rv); - } - else if (*fNextToken == '"') - { - char *rv = CreateQuoted(); // quoted - //fNextToken = GetNextToken(); - return (rv); - } - else - { - SetSyntaxError(TRUE); - return NULL; - } -} - - -// This function leaves us off with fCurrentTokenPlaceHolder immediately after -// the end of the closing quote. Call GetNextToken() to get the token after it. -// Note that if the current line ends without the -// closed quote then we have to fetch another line from the server, until -// we find the close quote. -char *TIMAPGenericParser::CreateQuoted(XP_Bool /*skipToEnd*/) -{ - char *currentChar = fCurrentLine + - (fNextToken - fStartOfLineOfTokens) - + 1; // one char past opening '"' - - int charIndex = 0; - int tokenIndex = 0; - XP_Bool closeQuoteFound = FALSE; - char *returnString = XP_STRDUP(currentChar); - - while (returnString && !closeQuoteFound && ContinueParse()) - { - if (!*(returnString + charIndex)) - { - AdvanceToNextLine(); - StrAllocCat(returnString, fCurrentLine); - charIndex++; - } - else if (*(returnString + charIndex) == '"') - { - // don't check to see if it was escaped, - // that was handled in the next clause - closeQuoteFound = TRUE; - } - else if (*(returnString + charIndex) == '\\') - { - // eat the escape character - XP_STRCPY(returnString + charIndex, returnString + charIndex + 1); - // whatever the escaped character was, we want it - charIndex++; - - // account for charIndex not reflecting the eat of the escape character - tokenIndex++; - } - else - charIndex++; - } - - if (closeQuoteFound && returnString) - { - *(returnString + charIndex) = 0; - //if ((charIndex == 0) && skipToEnd) // it's an empty string. Why skip to end? - // skip_to_CRLF(); - //else if (charIndex == XP_STRLEN(fCurrentLine)) // should we have this? - //AdvanceToNextLine(); - //else - if (charIndex < (int) (XP_STRLEN(fNextToken) - 2)) // -2 because of the start and end quotes - { - // the quoted string was fully contained within fNextToken, - // and there is text after the quote in fNextToken that we - // still need - int charDiff = XP_STRLEN(fNextToken) - charIndex - 1; - fCurrentTokenPlaceHolder -= charDiff; - if (!XP_STRCMP(fCurrentTokenPlaceHolder, CRLF)) - fAtEndOfLine = TRUE; - } - else - { - fCurrentTokenPlaceHolder += tokenIndex + charIndex + 2 - XP_STRLEN(fNextToken); - if (!XP_STRCMP(fCurrentTokenPlaceHolder, CRLF)) - fAtEndOfLine = TRUE; - /* - tokenIndex += charIndex; - fNextToken = currentChar + tokenIndex + 1; - if (!XP_STRCMP(fNextToken, CRLF)) - fAtEndOfLine = TRUE; - */ - } - } - - return returnString; -} - - -// This function leaves us off with fCurrentTokenPlaceHolder immediately after -// the end of the literal string. Call GetNextToken() to get the token after it -// the literal string. -char *TIMAPGenericParser::CreateLiteral() -{ - int32 numberOfCharsInMessage = atoint32(fNextToken + 1); - int32 charsReadSoFar = 0, currentLineLength = 0; - int32 bytesToCopy = 0; - - char *returnString = (char *) XP_ALLOC(numberOfCharsInMessage + 1); - - if (returnString) - { - *(returnString + numberOfCharsInMessage) = 0; // Null terminate it first - - while (ContinueParse() && (charsReadSoFar < numberOfCharsInMessage)) - { - AdvanceToNextLine(); - currentLineLength = XP_STRLEN(fCurrentLine); - bytesToCopy = (currentLineLength > numberOfCharsInMessage - charsReadSoFar ? - numberOfCharsInMessage - charsReadSoFar : currentLineLength); - XP_ASSERT (bytesToCopy); - - if (ContinueParse()) - { - XP_MEMCPY(returnString + charsReadSoFar, fCurrentLine, bytesToCopy); - charsReadSoFar += bytesToCopy; - } - } - - if (ContinueParse()) - { - if (bytesToCopy == 0) - { - skip_to_CRLF(); - fAtEndOfLine = TRUE; - //fNextToken = GetNextToken(); - } - else if (currentLineLength == bytesToCopy) - { - fAtEndOfLine = TRUE; - //AdvanceToNextLine(); - } - else - { - // Move fCurrentTokenPlaceHolder - - //fCurrentTokenPlaceHolder = fStartOfLineOfTokens + bytesToCopy; - AdvanceTokenizerStartingPoint (bytesToCopy); - if (!*fCurrentTokenPlaceHolder) // landed on a token boundary - fCurrentTokenPlaceHolder++; - if (!XP_STRCMP(fCurrentTokenPlaceHolder, CRLF)) - fAtEndOfLine = TRUE; - - // The first token on the line might not - // be at the beginning of the line. There might be ONLY - // whitespace before it, in which case, fNextToken - // will be pointing to the right thing. Otherwise, - // we want to advance to the next token. - /* - int32 numCharsChecked = 0; - XP_Bool allWhitespace = TRUE; - while ((numCharsChecked < bytesToCopy)&& allWhitespace) - { - allWhitespace = (XP_STRCHR(WHITESPACE, fCurrentLine[numCharsChecked]) != NULL); - numCharsChecked++; - } - - if (!allWhitespace) - { - //fNextToken = fCurrentLine + bytesToCopy; - fNextToken = GetNextToken(); - if (!XP_STRCMP(fNextToken, CRLF)) - fAtEndOfLine = TRUE; - } - */ - } - } - } - - return returnString; -} - - -// Call this to create a buffer containing all characters within -// a given set of parentheses. -// Call this with fNextToken[0]=='(', that is, the open paren -// of the group. -// It will allocate and return all characters up to and including the corresponding -// closing paren, and leave the parser in the right place afterwards. -char *TIMAPGenericParser::CreateParenGroup() -{ - int numOpenParens = 1; - // count the number of parens in the current token - int count, tokenLen = XP_STRLEN(fNextToken); - for (count = 1; (count < tokenLen) && (numOpenParens > 0); count++) - { - if (fNextToken[count] == '(') - numOpenParens++; - else if (fNextToken[count] == ')') - numOpenParens--; - } - - // build up a buffer with the paren group. - char *buf = NULL; - if ((numOpenParens > 0) && ContinueParse()) - { - // First, copy that first token from before - StrAllocCat(buf, fNextToken); - StrAllocCat(buf, " "); // space that got stripped off the token - - // Go through the current line and look for the last close paren. - // We're not trying to parse it just yet, just separate it out. - int len = XP_STRLEN(fCurrentTokenPlaceHolder); - for (count = 0; (count < len) && (numOpenParens > 0); count++) - { - if (fCurrentTokenPlaceHolder[count] == '(') - numOpenParens++; - else if (fCurrentTokenPlaceHolder[count] == ')') - numOpenParens--; - } - - if (count < len) - { - // we found the last close paren. - // Set fNextToken, fCurrentTokenPlaceHolder, etc. - char oldChar = fCurrentTokenPlaceHolder[count]; - fCurrentTokenPlaceHolder[count] = 0; - StrAllocCat(buf, fCurrentTokenPlaceHolder); - fCurrentTokenPlaceHolder[count] = oldChar; - fCurrentTokenPlaceHolder = fCurrentTokenPlaceHolder + count; - fNextToken = GetNextToken(); - } - else - { - // there should always be either a space or CRLF after the response, right? - SetSyntaxError(TRUE); - } - } - else if ((numOpenParens == 0) && ContinueParse()) - { - // the whole paren group response was a single token - buf = XP_STRDUP(fNextToken); - } - - if (numOpenParens < 0) - SetSyntaxError(TRUE); - - return buf; -} - - -////////////////// TIMAPServerState ///////////////////////// - - -TImapServerState::TImapServerState(TIMAP4BlockingConnection &imapConnection) : - TIMAPGenericParser(), - fServerConnection(imapConnection), - fCurrentCommandTag(nil), - fCurrentFolderReadOnly(FALSE), - fNumberOfExistingMessages(0), - fNumberOfRecentMessages(0), - fNumberOfUnseenMessages(0), - fSizeOfMostRecentMessage(0), - fTotalDownloadSize(0), - fIMAPstate(kNonAuthenticated), - fSelectedMailboxName(nil), - fFlagState(nil), - fCurrentLineContainedFlagInfo(FALSE), - fZeroLengthMessageUidString(nil), - fReportingErrors(TRUE), - fLastChunk(FALSE), - fServerIsNetscape3xServer(FALSE), - m_shell(NULL) -{ - fSearchResults = TSearchResultSequence::CreateSearchResultSequence(); - fMailAccountUrl = NULL; - fManageFiltersUrl = NULL; - fManageListsUrl = NULL; - fFolderAdminUrl = NULL; - fNetscapeServerVersionString = NULL; - fXSenderInfo = NULL; - fSupportsUserDefinedFlags = FALSE; - fCapabilityFlag = kCapabilityUndefined; - fLastAlert = NULL; -} - -TImapServerState::~TImapServerState() -{ - FREEIF( fCurrentCommandTag ); - //delete fFlagState; // not our object - delete fSearchResults; - FREEIF( fZeroLengthMessageUidString ); - FREEIF( fMailAccountUrl ); - FREEIF( fFolderAdminUrl ); - FREEIF( fNetscapeServerVersionString ); - FREEIF( fXSenderInfo ); - FREEIF( fLastAlert ); - FREEIF( fManageListsUrl ); - FREEIF( fManageFiltersUrl ); -} - -XP_Bool TImapServerState::LastCommandSuccessful() -{ - return (!CommandFailed() && - !fServerConnection.DeathSignalReceived() && - TIMAPGenericParser::LastCommandSuccessful()); -} - -// returns TRUE if things look ok to continue -XP_Bool TImapServerState::GetNextLineForParser(char **nextLine) -{ - XP_Bool rv = TRUE; - *nextLine = fServerConnection.CreateNewLineFromSocket(); - if (fServerConnection.DeathSignalReceived() || (fServerConnection.GetConnectionStatus() <= 0)) - rv = FALSE; - // we'd really like to try to silently reconnect, but we shouldn't put this - // message up just in the interrupt case - if (fServerConnection.GetConnectionStatus() <= 0 && !fServerConnection.DeathSignalReceived()) - fServerConnection.AlertUserEvent_UsingId(MK_SERVER_DISCONNECTED); - return rv; -} - -// This should probably be in the base class... -void TImapServerState::end_of_line() -{ - // if current commands failed, don't reset the lex analyzer - // we need the info for the user - if (!at_end_of_line()) - SetSyntaxError(TRUE); - else if (fProcessingTaggedResponse && !fCurrentCommandFailed) - ResetLexAnalyzer(); // no more tokens until we send a command - else if (!fCurrentCommandFailed) - fNextToken = GetNextToken(); -} - -XP_Bool TImapServerState::CommandFailed() -{ - return fCurrentCommandFailed; -} - -void TImapServerState::SetFlagState(TImapFlagAndUidState *state) -{ - fFlagState = state; -} - -int32 TImapServerState::SizeOfMostRecentMessage() -{ - return fSizeOfMostRecentMessage; -} - -// Call this when adding a pipelined command to the session -void TImapServerState::IncrementNumberOfTaggedResponsesExpected(const char *newExpectedTag) -{ - fNumberOfTaggedResponsesExpected++; - FREEIF( fCurrentCommandTag ); - fCurrentCommandTag = XP_STRDUP(newExpectedTag); - if (!fCurrentCommandTag) - HandleMemoryFailure(); -} -/* - response ::= *response_data response_done -*/ - - -void TImapServerState::InitializeState() -{ - fProcessingTaggedResponse = FALSE; - fCurrentCommandFailed = FALSE; -} - -void TImapServerState::ParseIMAPServerResponse(const char *currentCommand) -{ - - // Reinitialize the parser - SetConnected(TRUE); - SetSyntaxError(FALSE); - - // Reinitialize our state - InitializeState(); - - // the default is to not pipeline - fNumberOfTaggedResponsesExpected = 1; - int numberOfTaggedResponsesReceived = 0; - - char *copyCurrentCommand = XP_STRDUP(currentCommand); - if (copyCurrentCommand && !fServerConnection.DeathSignalReceived()) - { - char *placeInTokenString = NULL; - char *tagToken = XP_STRTOK_R(copyCurrentCommand, WHITESPACE,&placeInTokenString); - char *commandToken = XP_STRTOK_R(nil, WHITESPACE,&placeInTokenString); - if (tagToken) - { - FREEIF( fCurrentCommandTag ); - fCurrentCommandTag = XP_STRDUP(tagToken); - if (!fCurrentCommandTag) - HandleMemoryFailure(); - } - - if (commandToken && ContinueParse()) - PreProcessCommandToken(commandToken, currentCommand); - - if (ContinueParse()) - { - // Clears any syntax error lines - SetSyntaxError(FALSE); - ResetLexAnalyzer(); - - do { - fNextToken = GetNextToken(); - while (ContinueParse() && !XP_STRCMP(fNextToken, "*") ) - { - response_data(); - } - - if (*fNextToken == '+') // never pipeline APPEND or AUTHENTICATE - { - XP_ASSERT((fNumberOfTaggedResponsesExpected - numberOfTaggedResponsesReceived) == 1); - numberOfTaggedResponsesReceived = fNumberOfTaggedResponsesExpected; - } - else - numberOfTaggedResponsesReceived++; - - if (numberOfTaggedResponsesReceived < fNumberOfTaggedResponsesExpected) - { - response_tagged(); - fProcessingTaggedResponse = FALSE; - } - - } while (ContinueParse() && (numberOfTaggedResponsesReceived < fNumberOfTaggedResponsesExpected)); - - // check and see if the server is waiting for more input - if (*fNextToken == '+') - fIMAPstate = kWaitingForMoreClientInput; - else - { - if (ContinueParse()) - response_done(); - - if (ContinueParse() && !CommandFailed()) - { - // a sucessful command may change the eIMAPstate - ProcessOkCommand(commandToken); - } - else if (CommandFailed()) - { - // a failed command may change the eIMAPstate - ProcessBadCommand(commandToken); - if (fReportingErrors) - fServerConnection.AlertUserEventFromServer(fCurrentLine); - } - } - } - } - else if (!fServerConnection.DeathSignalReceived()) - HandleMemoryFailure(); - - FREEIF(copyCurrentCommand); -} - -void TImapServerState::HandleMemoryFailure() -{ -#ifdef DEBUG_chrisf - XP_ASSERT(FALSE); -#endif - fServerConnection.AlertUserEvent(XP_GetString(MK_OUT_OF_MEMORY)); - TIMAPGenericParser::HandleMemoryFailure(); -} - - -// SEARCH is the only command that requires pre-processing for now. -// others will be added here. -void TImapServerState::PreProcessCommandToken(const char *commandToken, - const char *currentCommand) -{ - fCurrentCommandIsSingleMessageFetch = FALSE; - - if (!XP_STRCASECMP(commandToken, "SEARCH")) - fSearchResults->ResetSequence(); - else if (!XP_STRCASECMP(commandToken, "SELECT") && currentCommand) - { - // the mailbox name must be quoted, so strip the quotes - const char *openQuote = XP_STRSTR(currentCommand, "\""); - XP_ASSERT(openQuote); - - FREEIF( fSelectedMailboxName); - fSelectedMailboxName = XP_STRDUP(openQuote + 1); - if (fSelectedMailboxName) - { - // strip the escape chars and the ending quote - char *currentChar = fSelectedMailboxName; - while (*currentChar) - { - if (*currentChar == '\\') - { - XP_STRCPY(currentChar, currentChar+1); - currentChar++; // skip what we are escaping - } - else if (*currentChar == '\"') - *currentChar = 0; // end quote - else - currentChar++; - } - } - else - HandleMemoryFailure(); - - // we don't want bogus info for this new box - //delete fFlagState; // not our object - //fFlagState = NULL; - } - else if (!XP_STRCASECMP(commandToken, "CLOSE")) - { - return; // just for debugging - // we don't want bogus info outside the selected state - //delete fFlagState; // not our object - //fFlagState = NULL; - } - else if (!XP_STRCASECMP(commandToken, "UID")) - { - - char *copyCurrentCommand = XP_STRDUP(currentCommand); - if (copyCurrentCommand && !fServerConnection.DeathSignalReceived()) - { - char *placeInTokenString = NULL; - char *tagToken = XP_STRTOK_R(copyCurrentCommand, WHITESPACE,&placeInTokenString); - char *uidToken = XP_STRTOK_R(nil, WHITESPACE,&placeInTokenString); - char *fetchToken = XP_STRTOK_R(nil, WHITESPACE,&placeInTokenString); - - if (!XP_STRCASECMP(fetchToken, "FETCH") ) - { - char *uidStringToken = XP_STRTOK_R(nil, WHITESPACE,&placeInTokenString); - if (!XP_STRCHR(uidStringToken, ',') && !XP_STRCHR(uidStringToken, ':')) // , and : are uid delimiters - { - fCurrentCommandIsSingleMessageFetch = TRUE; - fUidOfSingleMessageFetch = atoint32(uidStringToken); - } - } - XP_FREE(copyCurrentCommand); - } - } -} - -const char *TImapServerState::GetSelectedMailboxName() -{ - return fSelectedMailboxName; -} - -TSearchResultIterator *TImapServerState::CreateSearchResultIterator() -{ - return new TSearchResultIterator(*fSearchResults); -} - -TImapServerState::eIMAPstate TImapServerState::GetIMAPstate() -{ - return fIMAPstate; -} - -void TImapServerState::PreauthSetAuthenticatedState() -{ - fIMAPstate = kAuthenticated; -} - -void TImapServerState::ProcessOkCommand(const char *commandToken) -{ - if (!XP_STRCASECMP(commandToken, "LOGIN") || - !XP_STRCASECMP(commandToken, "AUTHENTICATE")) - fIMAPstate = kAuthenticated; - else if (!XP_STRCASECMP(commandToken, "LOGOUT")) - fIMAPstate = kNonAuthenticated; - else if (!XP_STRCASECMP(commandToken, "SELECT") || - !XP_STRCASECMP(commandToken, "EXAMINE")) - fIMAPstate = kFolderSelected; - else if (!XP_STRCASECMP(commandToken, "CLOSE")) - fIMAPstate = kAuthenticated; - else if ((!XP_STRCASECMP(commandToken, "LIST")) || - (!XP_STRCASECMP(commandToken, "LSUB"))) - { - //fServerConnection.MailboxDiscoveryFinished(); - // This used to be reporting that we were finished - // discovering folders for each time we issued a - // LIST or LSUB. So if we explicitly listed the - // INBOX, or Trash, or namespaces, we would get multiple - // "done" states, even though we hadn't finished. - // Move this to be called from the connection object - // itself. - } - else if (!XP_STRCASECMP(commandToken, "FETCH")) - { - if (fZeroLengthMessageUidString) - { - // "Deleting zero length message"); - fServerConnection.Store(fZeroLengthMessageUidString, "+Flags (\\Deleted)", TRUE); - if (LastCommandSuccessful()) - fServerConnection.Expunge(); - - FREEIF( fZeroLengthMessageUidString ); - fZeroLengthMessageUidString = nil; - } - } - if (GetFillingInShell()) - { - // There is a BODYSTRUCTURE response. Now let's generate the stream... - // that is, if we're not doing it already - if (!m_shell->IsBeingGenerated()) - { - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - XP_ASSERT(navCon); // we should always have this - - m_shell->Generate(navCon ? navCon->GetCurrentUrl()->GetIMAPPartToFetch() : (char *)NULL); - - if ((navCon && navCon->GetPseudoInterrupted()) - || fServerConnection.DeathSignalReceived()) - { - // we were pseudointerrupted or interrupted - if (!m_shell->IsShellCached()) - { - // if it's not in the cache, then we were (pseudo)interrupted while generating - // for the first time. Delete it. - delete m_shell; - } - navCon->PseudoInterrupt(FALSE); - } - else if (m_shell->GetIsValid()) - { - // If we have a valid shell that has not already been cached, then cache it. - if (!m_shell->IsShellCached()) // cache is responsible for destroying it - { -// PR_LOG(IMAP, out, ("BODYSHELL: Adding shell to cache.")); - TIMAPHostInfo::AddShellToCacheForHost(fServerConnection.GetHostName(), m_shell); - } - } - else - { - // The shell isn't valid, so we don't cache it. - // Therefore, we have to destroy it here. - delete m_shell; - } - m_shell = NULL; - } - } -} - -void TImapServerState::ProcessBadCommand(const char *commandToken) -{ - if (!XP_STRCASECMP(commandToken, "LOGIN") || - !XP_STRCASECMP(commandToken, "AUTHENTICATE")) - fIMAPstate = kNonAuthenticated; - else if (!XP_STRCASECMP(commandToken, "LOGOUT")) - fIMAPstate = kNonAuthenticated; // ?? - else if (!XP_STRCASECMP(commandToken, "SELECT") || - !XP_STRCASECMP(commandToken, "EXAMINE")) - fIMAPstate = kAuthenticated; // nothing selected - else if (!XP_STRCASECMP(commandToken, "CLOSE")) - fIMAPstate = kAuthenticated; // nothing selected - if (GetFillingInShell()) - { - if (!m_shell->IsBeingGenerated()) - { - delete m_shell; - m_shell = NULL; - } - } -} -/* - response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye / - mailbox_data / message_data / capability_data) - CRLF - - The RFC1730 grammar spec did not allow one symbol look ahead to determine - between mailbox_data / message_data so I combined the numeric possibilities - of mailbox_data and all of message_data into numeric_mailbox_data. - - The production implemented here is - - response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye / - mailbox_data / numeric_mailbox_data / - capability_data) - CRLF - -Instead of comparing lots of strings and make function calls, try to pre-flight -the possibilities based on the first letter of the token. - -*/ -void TImapServerState::response_data() -{ - fNextToken = GetNextToken(); - - if (ContinueParse()) - { - switch (toupper(fNextToken[0])) - { - case 'O': // OK - if (toupper(fNextToken[1]) == 'K') - resp_cond_state(); - else SetSyntaxError(TRUE); - break; - case 'N': // NO - if (toupper(fNextToken[1]) == 'O') - resp_cond_state(); - else if (!XP_STRCASECMP(fNextToken, "NAMESPACE")) - namespace_data(); - else SetSyntaxError(TRUE); - break; - case 'B': // BAD - if (!XP_STRCASECMP(fNextToken, "BAD")) - resp_cond_state(); - else if (!XP_STRCASECMP(fNextToken, "BYE")) - resp_cond_bye(); - else SetSyntaxError(TRUE); - break; - case 'F': - if (!XP_STRCASECMP(fNextToken, "FLAGS")) - mailbox_data(); - else SetSyntaxError(TRUE); - break; - case 'P': - if (XP_STRCASECMP(fNextToken, "PERMANENTFLAGS")) - mailbox_data(); - else SetSyntaxError(TRUE); - break; - case 'L': - if (!XP_STRCASECMP(fNextToken, "LIST") || !XP_STRCASECMP(fNextToken, "LSUB")) - mailbox_data(); - else SetSyntaxError(TRUE); - break; - case 'M': - if (!XP_STRCASECMP(fNextToken, "MAILBOX")) - mailbox_data(); - else if (!XP_STRCASECMP(fNextToken, "MYRIGHTS")) - myrights_data(); - else SetSyntaxError(TRUE); - break; - case 'S': - if (!XP_STRCASECMP(fNextToken, "SEARCH")) - mailbox_data(); - else if (!XP_STRCASECMP(fNextToken, "STATUS")) - { - XP_Bool gotMailboxName = FALSE; - while ( ContinueParse() && - !at_end_of_line() ) - { - fNextToken = GetNextToken(); - if (!fNextToken) - break; - - if (!gotMailboxName) // if we haven't got the mailbox name, get it - { - // this couldn't be more bogus, but I don't know how to parse the status response. - // I need to find the next open parenthesis, and it looks like folder names with - // parentheses are quoted...but not ones with spaces... - fCurrentTokenPlaceHolder = XP_STRCHR(fCurrentTokenPlaceHolder, '('); - - gotMailboxName = TRUE; - continue; - } - - if (*fNextToken == '(') fNextToken++; - if (!XP_STRCASECMP(fNextToken, "UIDNEXT")) - { - fNextToken = GetNextToken(); - if (fNextToken) - { - fCurrentResponseUID = atoint32(fNextToken); - // if this token ends in ')', then it is the last token - // else we advance - if ( *(fNextToken + XP_STRLEN(fNextToken) - 1) == ')') - fNextToken += XP_STRLEN(fNextToken) - 1; - } - } - else if (!XP_STRCASECMP(fNextToken, "MESSAGES")) - { - fNextToken = GetNextToken(); - if (fNextToken) - { - fNumberOfExistingMessages = atoint32(fNextToken); - // if this token ends in ')', then it is the last token - // else we advance - if ( *(fNextToken + XP_STRLEN(fNextToken) - 1) == ')') - fNextToken += XP_STRLEN(fNextToken) - 1; - } - } - else if (!XP_STRCASECMP(fNextToken, "UNSEEN")) - { - fNextToken = GetNextToken(); - if (fNextToken) - { - fNumberOfUnseenMessages = atoint32(fNextToken); - // if this token ends in ')', then it is the last token - // else we advance - if ( *(fNextToken + XP_STRLEN(fNextToken) - 1) == ')') - fNextToken += XP_STRLEN(fNextToken) - 1; - } - } - else if (*fNextToken == ')') - break; - else if (!at_end_of_line()) - SetSyntaxError(TRUE); - } - } else SetSyntaxError(TRUE); - break; - case 'C': - if (!XP_STRCASECMP(fNextToken, "CAPABILITY")) - capability_data(); - else SetSyntaxError(TRUE); - break; - case 'V': - if (!XP_STRCASECMP(fNextToken, "VERSION")) - { - // figure out the version of the Netscape server here - FREEIF(fNetscapeServerVersionString); - fNextToken = GetNextToken(); - if (! fNextToken) - SetSyntaxError(TRUE); - else - { - fNetscapeServerVersionString = CreateAstring(); - fNextToken = GetNextToken(); - if (fNetscapeServerVersionString) - { - fServerIsNetscape3xServer = (*fNetscapeServerVersionString == '3'); - } - } - skip_to_CRLF(); - } - else SetSyntaxError(TRUE); - break; - case 'A': - if (!XP_STRCASECMP(fNextToken, "ACL")) - { - acl_data(); - } - else if (!XP_STRCASECMP(fNextToken, "ACCOUNT-URL")) - { - FREEIF(fMailAccountUrl); - fNextToken = GetNextToken(); - if (! fNextToken) - SetSyntaxError(TRUE); - else - { - fMailAccountUrl = CreateAstring(); - fNextToken = GetNextToken(); - } - } - else SetSyntaxError(TRUE); - break; - case 'X': - if (!XP_STRCASECMP(fNextToken, "XSERVERINFO")) - xserverinfo_data(); - else if (!XP_STRCASECMP(fNextToken, "XMAILBOXINFO")) - xmailboxinfo_data(); - else - SetSyntaxError(TRUE); - break; - default: - if (IsNumericString(fNextToken)) - numeric_mailbox_data(); - else - SetSyntaxError(TRUE); - break; - } - - if (ContinueParse()) - { - PostProcessEndOfLine(); - end_of_line(); - } - } -} - - -void TImapServerState::PostProcessEndOfLine() -{ - // for now we only have to do one thing here - // a fetch response to a 'uid store' command might return the flags - // before it returns the uid of the message. So we need both before - // we report the new flag info to the front end - - // also check and be sure that there was a UID in the current response - if (fCurrentLineContainedFlagInfo && CurrentResponseUID()) - { - fCurrentLineContainedFlagInfo = FALSE; - fServerConnection.NotifyMessageFlags(fSavedFlagInfo, CurrentResponseUID()); - } -} - - -/* - mailbox_data ::= "FLAGS" SPACE flag_list / - "LIST" SPACE mailbox_list / - "LSUB" SPACE mailbox_list / - "MAILBOX" SPACE text / - "SEARCH" [SPACE 1#nz_number] / - number SPACE "EXISTS" / number SPACE "RECENT" - -This production was changed to accomodate predictive parsing - - mailbox_data ::= "FLAGS" SPACE flag_list / - "LIST" SPACE mailbox_list / - "LSUB" SPACE mailbox_list / - "MAILBOX" SPACE text / - "SEARCH" [SPACE 1#nz_number] -*/ -void TImapServerState::mailbox_data() -{ - XP_Bool userDefined = FALSE; - XP_Bool perm = FALSE; - - if (!XP_STRCASECMP(fNextToken, "FLAGS")) { - skip_to_CRLF(); - } - else if (!XP_STRCASECMP(fNextToken, "LIST")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - mailbox_list(FALSE); - } - else if (!XP_STRCASECMP(fNextToken, "LSUB")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - mailbox_list(TRUE); - } - else if (!XP_STRCASECMP(fNextToken, "MAILBOX")) - skip_to_CRLF(); - else if (!XP_STRCASECMP(fNextToken, "SEARCH")) - { - fSearchResults->AddSearchResultLine(fCurrentLine); - fServerConnection.NotifySearchHit(fCurrentLine); - skip_to_CRLF(); - } -} - -/* - mailbox_list ::= "(" #("\Marked" / "\Noinferiors" / - "\Noselect" / "\Unmarked" / flag_extension) ")" - SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox -*/ - -void TImapServerState::mailbox_list(XP_Bool discoveredFromLsub) -{ - mailbox_spec *boxSpec = (mailbox_spec *)XP_ALLOC(sizeof(mailbox_spec)); - if (!boxSpec) - HandleMemoryFailure(); - else - { - boxSpec->folderSelected = FALSE; - boxSpec->box_flags = kNoFlags; - boxSpec->allocatedPathName = NULL; - boxSpec->hostName = NULL; - boxSpec->connection = fServerConnection.GetNavigatorConnection(); - boxSpec->flagState = NULL; - boxSpec->discoveredFromLsub = discoveredFromLsub; - boxSpec->onlineVerified = TRUE; - - XP_Bool endOfFlags = FALSE; - fNextToken++; // eat the first "(" - do { - if (!XP_STRNCASECMP(fNextToken, "\\Marked", 7)) - boxSpec->box_flags |= kMarked; - else if (!XP_STRNCASECMP(fNextToken, "\\Unmarked", 9)) - boxSpec->box_flags |= kUnmarked; - else if (!XP_STRNCASECMP(fNextToken, "\\Noinferiors", 12)) - boxSpec->box_flags |= kNoinferiors; - else if (!XP_STRNCASECMP(fNextToken, "\\Noselect", 9)) - boxSpec->box_flags |= kNoselect; - // we ignore flag extensions - - endOfFlags = *(fNextToken + XP_STRLEN(fNextToken) - 1) == ')'; - fNextToken = GetNextToken(); - } while (!endOfFlags && ContinueParse()); - - if (ContinueParse()) - { - if (*fNextToken == '"') - { - fNextToken++; - if (*fNextToken == '\\') // handle escaped char - boxSpec->hierarchySeparator = *(fNextToken + 1); - else - boxSpec->hierarchySeparator = *fNextToken; - } - else // likely NIL. Discovered late in 4.02 that we do not handle literals here (e.g. {10} <10 chars>), although this is almost impossibly unlikely - boxSpec->hierarchySeparator = kOnlineHierarchySeparatorUnknown; - fNextToken = GetNextToken(); - if (ContinueParse()) - mailbox(boxSpec); - } - } -} - -/* mailbox ::= "INBOX" / astring -*/ -void TImapServerState::mailbox(mailbox_spec *boxSpec) -{ - char *boxname = NULL; - - if (!XP_STRCASECMP(fNextToken, "INBOX")) - { - boxname = XP_STRDUP("INBOX"); - fNextToken = GetNextToken(); - } - else - { - boxname = CreateAstring(); - fNextToken = GetNextToken(); - } - - if (boxname) - { - // sometimes the uwash server will return a list response with a '/' hanging on the - // end. - - /* - // chrisf: I think we should "discover" whatever the server tells us, and do any munging in - // libmsg if it is necessary. - if (XP_STRLEN(boxname) && *(boxname + XP_STRLEN(boxname) - 1) == TIMAPUrl::GetOnlineSubDirSeparator()) - *(boxname + XP_STRLEN(boxname) - 1) = '\0'; - */ - - // should the namespace check go before or after the Utf7 conversion? - TIMAPHostInfo::SetNamespaceHierarchyDelimiterFromMailboxForHost(fServerConnection.GetHostName(), boxname, boxSpec->hierarchySeparator); - - - TIMAPNamespace *ns = TIMAPHostInfo::GetNamespaceForMailboxForHost(fServerConnection.GetHostName(),boxname); - if (ns) - { - switch (ns->GetType()) - { - case kPersonalNamespace: - boxSpec->box_flags |= kPersonalMailbox; - break; - case kPublicNamespace: - boxSpec->box_flags |= kPublicMailbox; - break; - case kOtherUsersNamespace: - boxSpec->box_flags |= kOtherUsersMailbox; - break; - default: // (kUnknownNamespace) - break; - } - } - - char *convertedName = fServerConnection.CreateUtf7ConvertedString(boxname, FALSE); - XP_FREE(boxname); - boxname = convertedName; - } - - if (!boxname) - { - if (!fServerConnection.DeathSignalReceived()) - HandleMemoryFailure(); - } - else - { - XP_ASSERT(boxSpec->connection); - XP_ASSERT(boxSpec->connection->GetCurrentUrl()); - //boxSpec->hostName = NULL; - //if (boxSpec->connection && boxSpec->connection->GetCurrentUrl()) - boxSpec->allocatedPathName = boxSpec->connection->GetCurrentUrl()->AllocateCanonicalPath(boxname); - boxSpec->hostName = boxSpec->connection->GetCurrentUrl()->GetUrlHost(); - FREEIF( boxname); - // storage for the boxSpec is now owned by server connection - fServerConnection.DiscoverMailboxSpec(boxSpec); - - // if this was cancelled by the user,then we sure don't want to - // send more mailboxes their way - if (fServerConnection.GetConnectionStatus() < 0) - SetConnected(FALSE); - } -} - - -/* - message_data ::= nz_number SPACE ("EXPUNGE" / - ("FETCH" SPACE msg_fetch) / msg_obsolete) - -was changed to - -numeric_mailbox_data ::= number SPACE "EXISTS" / number SPACE "RECENT" - / nz_number SPACE ("EXPUNGE" / - ("FETCH" SPACE msg_fetch) / msg_obsolete) - -*/ -void TImapServerState::numeric_mailbox_data() -{ - int32 tokenNumber = atoint32(fNextToken); - fNextToken = GetNextToken(); - - if (ContinueParse()) - { - if (!XP_STRCASECMP(fNextToken, "FETCH")) - { - fFetchResponseIndex = tokenNumber; - fNextToken = GetNextToken(); - if (ContinueParse()) - msg_fetch(); - } - else if (!XP_STRCASECMP(fNextToken, "EXISTS")) - { - fNumberOfExistingMessages = tokenNumber; - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken, "RECENT")) - { - fNumberOfRecentMessages = tokenNumber; - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken, "EXPUNGE")) - { - fFlagState->ExpungeByIndex((uint32) tokenNumber); - skip_to_CRLF(); - } - else - msg_obsolete(); - } -} - -/* - msg_fetch ::= "(" 1#("BODY" SPACE body / - "BODYSTRUCTURE" SPACE body / - "BODY[" section "]" SPACE nstring / - "ENVELOPE" SPACE envelope / - "FLAGS" SPACE "(" #(flag / "\Recent") ")" / - "INTERNALDATE" SPACE date_time / - "RFC822" [".HEADER" / ".TEXT"] SPACE nstring / - "RFC822.SIZE" SPACE number / - "UID" SPACE uniqueid) ")" - -*/ - -void TImapServerState::msg_fetch() -{ - // we have not seen a uid response or flags for this fetch, yet - fCurrentResponseUID = 0; - fCurrentLineContainedFlagInfo = FALSE; - - // show any incremental progress, for instance, for header downloading - fServerConnection.ShowProgress(); - - fNextToken++; // eat the '(' character - - // some of these productions are ignored for now - while (ContinueParse() && (*fNextToken != ')') ) - { - if (!XP_STRCASECMP(fNextToken, "FLAGS")) - { - if (fCurrentResponseUID == 0) - fCurrentResponseUID = fFlagState->GetUidOfMessage(fFetchResponseIndex - 1); - - fNextToken = GetNextToken(); - if (ContinueParse()) - flags(); - - if (ContinueParse()) - { // eat the closing ')' - fNextToken++; - // there may be another ')' to close out - // msg_fetch. If there is then don't advance - if (*fNextToken != ')') - fNextToken = GetNextToken(); - } - } - else if (!XP_STRCASECMP(fNextToken, "UID")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - { - fCurrentResponseUID = atoint32(fNextToken); - if (fCurrentResponseUID > fHighestRecordedUID) - fHighestRecordedUID = fCurrentResponseUID; - - // if this token ends in ')', then it is the last token - // else we advance - if ( *(fNextToken + XP_STRLEN(fNextToken) - 1) == ')') - fNextToken += XP_STRLEN(fNextToken) - 1; - else - fNextToken = GetNextToken(); - } - } - else if (!XP_STRCASECMP(fNextToken, "RFC822") || - !XP_STRCASECMP(fNextToken, "RFC822.HEADER") || - !XP_STRNCASECMP(fNextToken, "BODY[HEADER",11) || - !XP_STRNCASECMP(fNextToken, "BODY[]", 6) || - !XP_STRCASECMP(fNextToken, "RFC822.TEXT") || - (!XP_STRNCASECMP(fNextToken, "BODY[", 5) && - XP_STRSTR(fNextToken, "HEADER")) - ) - { - if (fCurrentResponseUID == 0) - fCurrentResponseUID = fFlagState->GetUidOfMessage(fFetchResponseIndex - 1); - - if (!XP_STRCASECMP(fNextToken, "RFC822.HEADER") || - !XP_STRCASECMP(fNextToken, "BODY[HEADER]")) - { - // all of this message's headers - fNextToken = GetNextToken(); - fDownloadingHeaders = TRUE; - if (ContinueParse()) - msg_fetch_headers(NULL); - } - else if (!XP_STRNCASECMP(fNextToken, "BODY[HEADER.FIELDS",19)) - { - fDownloadingHeaders = TRUE; - // specific message header fields - while (ContinueParse() && fNextToken[XP_STRLEN(fNextToken)-1] != ']') - fNextToken = GetNextToken(); - if (ContinueParse()) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - msg_fetch_headers(NULL); - } - } - else - { - char *whereHeader = XP_STRSTR(fNextToken, "HEADER"); - if (whereHeader) - { - char *startPartNum = fNextToken + 5; - char *partNum = (char *)XP_ALLOC((whereHeader - startPartNum) * sizeof (char)); - if (partNum) - { - XP_STRNCPY_SAFE(partNum, startPartNum, (whereHeader - startPartNum)); - if (ContinueParse()) - { - if (XP_STRSTR(fNextToken, "FIELDS")) - { - while (ContinueParse() && fNextToken[XP_STRLEN(fNextToken)-1] != ']') - fNextToken = GetNextToken(); - } - if (ContinueParse()) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - msg_fetch_headers(partNum); - } - } - XP_FREE(partNum); - } - } - else - { - fDownloadingHeaders = FALSE; - - XP_Bool chunk = FALSE; - int32 origin = 0; - if (!XP_STRNCASECMP(fNextToken, "BODY[]<", 7)) - { - char *tokenCopy = 0; - StrAllocCopy(tokenCopy, fNextToken); - if (tokenCopy) - { - char *originString = tokenCopy + 7; // where the byte number starts - char *closeBracket = XP_STRCHR(tokenCopy,'>'); - if (closeBracket && originString && *originString) - { - *closeBracket = 0; - origin = atoint32(originString); - chunk = TRUE; - } - XP_FREE(tokenCopy); - } - } - - fNextToken = GetNextToken(); - if (ContinueParse()) - { - msg_fetch_content(chunk, origin, MESSAGE_RFC822); - } - } - } - } - else if (!XP_STRCASECMP(fNextToken, "RFC822.SIZE")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - { - fSizeOfMostRecentMessage = atoint32(fNextToken); - - if (fSizeOfMostRecentMessage == 0 && CurrentResponseUID()) - { - // on no, bogus Netscape 2.0 mail server bug - char uidString[100]; - sprintf(uidString, "%ld", (long)CurrentResponseUID()); - - if (!fZeroLengthMessageUidString) - fZeroLengthMessageUidString = XP_STRDUP(uidString); - else - { - StrAllocCat(fZeroLengthMessageUidString, ","); - StrAllocCat(fZeroLengthMessageUidString, uidString); - } - } - - // if this token ends in ')', then it is the last token - // else we advance - if ( *(fNextToken + XP_STRLEN(fNextToken) - 1) == ')') - fNextToken += XP_STRLEN(fNextToken) - 1; - else - fNextToken = GetNextToken(); - } - } - else if (!XP_STRCASECMP(fNextToken, "XSENDER")) - { - FREEIF(fXSenderInfo); - fNextToken = GetNextToken(); - if (! fNextToken) - SetSyntaxError(TRUE); - else - { - fXSenderInfo = CreateAstring(); - fNextToken = GetNextToken(); - } - } - // I only fetch RFC822 so I should never see these BODY responses - else if (!XP_STRCASECMP(fNextToken, "BODY")) - skip_to_CRLF(); // I never ask for this - else if (!XP_STRCASECMP(fNextToken, "BODYSTRUCTURE")) - { - bodystructure_data(); - } - else if (!XP_STRNCASECMP(fNextToken, "BODY[", 5) && XP_STRNCASECMP(fNextToken, "BODY[]", 6)) - { - fDownloadingHeaders = FALSE; - // A specific MIME part, or MIME part header - mime_data(); - } - else if (!XP_STRCASECMP(fNextToken, "ENVELOPE")) - skip_to_CRLF(); // I never ask for this - else if (!XP_STRCASECMP(fNextToken, "INTERNALDATE")) - skip_to_CRLF(); // I will need to implement this - else - SetSyntaxError(TRUE); - - } - - if (ContinueParse()) - { - if (CurrentResponseUID() && fCurrentLineContainedFlagInfo && fFlagState) - { - fFlagState->AddUidFlagPair(CurrentResponseUID(), fSavedFlagInfo); - fCurrentLineContainedFlagInfo = FALSE; // do not fire if in PostProcessEndOfLine - } - fCurrentLineContainedFlagInfo = FALSE; // do not fire if in PostProcessEndOfLine - - fNextToken = GetNextToken(); // eat the ')' ending token - // should be at end of line - } -} - -void TImapServerState::flags() -{ - imapMessageFlagsType messageFlags = kNoImapMsgFlag; - - // eat the opening '(' - fNextToken++; - - while (ContinueParse() && (*fNextToken != ')')) - { - switch (toupper(fNextToken[1])) { - case 'S': - if (!XP_STRNCASECMP(fNextToken, "\\Seen",5)) - messageFlags |= kImapMsgSeenFlag; - break; - case 'A': - if (!XP_STRNCASECMP(fNextToken, "\\Answered",9)) - messageFlags |= kImapMsgAnsweredFlag; - break; - case 'F': - if (!XP_STRNCASECMP(fNextToken, "\\Flagged",8)) - messageFlags |= kImapMsgFlaggedFlag; - else if (fSupportsUserDefinedFlags && !XP_STRNCASECMP(fNextToken, "\\Forwarded",10)) - messageFlags |= kImapMsgForwardedFlag; - break; - case 'D': - if (!XP_STRNCASECMP(fNextToken, "\\Deleted",8)) - messageFlags |= kImapMsgDeletedFlag; - else if (!XP_STRNCASECMP(fNextToken, "\\Draft",6)) - messageFlags |= kImapMsgDraftFlag; - break; - case 'R': - if (!XP_STRNCASECMP(fNextToken, "\\Recent",7)) - messageFlags |= kImapMsgRecentFlag; - break; - case 'M': - if (fSupportsUserDefinedFlags && !XP_STRNCASECMP(fNextToken, "\\MDNSent",7)) - messageFlags |= kImapMsgMDNSentFlag; - break; - default: - break; - } - - if (strcasestr(fNextToken, ")")) - { - // eat token chars until we get the ')' - while (*fNextToken != ')') - fNextToken++; - } - else - fNextToken = GetNextToken(); - } - - if (ContinueParse()) - while(*fNextToken != ')') - fNextToken++; - - fCurrentLineContainedFlagInfo = TRUE; // handled in PostProcessEndOfLine - fSavedFlagInfo = messageFlags; -} - -/* - resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text -*/ -void TImapServerState::resp_cond_state() -{ - if ((!XP_STRCASECMP(fNextToken, "NO") || - !XP_STRCASECMP(fNextToken, "BAD") ) && - fProcessingTaggedResponse) - fCurrentCommandFailed = TRUE; - - fNextToken = GetNextToken(); - if (ContinueParse()) - resp_text(); -} - -/* - resp_text ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text) - - was changed to in order to enable a one symbol look ahead predictive - parser. - - resp_text ::= ["[" resp_text_code SPACE] (text_mime2 / text) - */ -void TImapServerState::resp_text() -{ - if (ContinueParse() && (*fNextToken == '[')) - resp_text_code(); - - if (ContinueParse()) - { - if (!XP_STRCMP(fNextToken, "=?")) - text_mime2(); - else - text(); - } -} -/* - text_mime2 ::= "=?" <charset> "?" <encoding> "?" - <encoded-text> "?=" - ;; Syntax defined in [MIME-2] -*/ -void TImapServerState::text_mime2() -{ - skip_to_CRLF(); -} - -/* - text ::= 1*TEXT_CHAR - -*/ -void TImapServerState::text() -{ - skip_to_CRLF(); -} - - -/* - resp_text_code ::= "ALERT" / "PARSE" / - "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" / - "READ-ONLY" / "READ-WRITE" / "TRYCREATE" / - "UIDVALIDITY" SPACE nz_number / - "UNSEEN" SPACE nz_number / - atom [SPACE 1*<any TEXT_CHAR except "]">] - - was changed to in order to enable a one symbol look ahead predictive - parser. - - resp_text_code ::= ("ALERT" / "PARSE" / - "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" / - "READ-ONLY" / "READ-WRITE" / "TRYCREATE" / - "UIDVALIDITY" SPACE nz_number / - "UNSEEN" SPACE nz_number / - atom [SPACE 1*<any TEXT_CHAR except "]">] ) - "]" - - -*/ -void TImapServerState::resp_text_code() -{ - // this is a special case way of advancing the token - // strtok won't break up "[ALERT]" into separate tokens - if (XP_STRLEN(fNextToken) > 1) - fNextToken++; - else - fNextToken = GetNextToken(); - - if (ContinueParse()) - { - if (!XP_STRCASECMP(fNextToken,"ALERT]")) - { - char *alertMsg = fCurrentTokenPlaceHolder; // advance past ALERT] - if (alertMsg && *alertMsg && (!fLastAlert || XP_STRCMP(fNextToken, fLastAlert))) - { - fServerConnection.AlertUserEvent(alertMsg); - FREEIF(fLastAlert); - fLastAlert = XP_STRDUP(alertMsg); - } - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken,"PARSE]")) - { - // do nothing for now - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken,"NETSCAPE]")) - { - skip_to_CRLF(); - } - else if (!XP_STRCASECMP(fNextToken,"PERMANENTFLAGS")) - { - // do nothing but eat tokens until we see the ] or CRLF - // we should see the ] but we don't want to go into an - // endless loop if the CRLF is not there -#if 0 - do { - fNextToken = GetNextToken(); - } while (!strcasestr(fNextToken, "]") && - !at_end_of_line() && - ContinueParse()); -#else - fSupportsUserDefinedFlags = FALSE; // assume no unless told - do { - fNextToken = GetNextToken(); - if (!XP_STRNCASECMP(fNextToken, "\\*)]", 4)) - fSupportsUserDefinedFlags = TRUE; - } while (!at_end_of_line() && ContinueParse()); -#endif - } - else if (!XP_STRCASECMP(fNextToken,"READ-ONLY]")) - { - fCurrentFolderReadOnly = TRUE; - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken,"READ-WRITE]")) - { - fCurrentFolderReadOnly = FALSE; - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken,"TRYCREATE]")) - { - // do nothing for now - fNextToken = GetNextToken(); - } - else if (!XP_STRCASECMP(fNextToken,"UIDVALIDITY")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - { - fFolderUIDValidity = atoint32(fNextToken); - fHighestRecordedUID = 0; - fNextToken = GetNextToken(); - } - } - else if (!XP_STRCASECMP(fNextToken,"UNSEEN")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - { - fNumberOfUnseenMessages = atoint32(fNextToken); - fNextToken = GetNextToken(); - } - } - else // just text - { - // do nothing but eat tokens until we see the ] or CRLF - // we should see the ] but we don't want to go into an - // endless loop if the CRLF is not there - do { - fNextToken = GetNextToken(); - } while (!strcasestr(fNextToken, "]") && - !at_end_of_line() && - ContinueParse()); - } - } -} - -/* - response_done ::= response_tagged / response_fatal - */ -void TImapServerState::response_done() -{ - if (ContinueParse()) - { - if (!XP_STRCMP(fCurrentCommandTag, fNextToken)) - response_tagged(); - else - response_fatal(); - } -} - -/* response_tagged ::= tag SPACE resp_cond_state CRLF -*/ -void TImapServerState::response_tagged() -{ - // eat the tag - fNextToken = GetNextToken(); - if (ContinueParse()) - { - fProcessingTaggedResponse = TRUE; - resp_cond_state(); - if (ContinueParse()) - end_of_line(); - } -} - -/* response_fatal ::= "*" SPACE resp_cond_bye CRLF -*/ -void TImapServerState::response_fatal() -{ - // eat the "*" - fNextToken = GetNextToken(); - if (ContinueParse()) - { - resp_cond_bye(); - if (ContinueParse()) - end_of_line(); - } -} -/* -resp_cond_bye ::= "BYE" SPACE resp_text - ;; Server will disconnect condition - */ -void TImapServerState::resp_cond_bye() -{ - SetConnected(FALSE); - fIMAPstate = kNonAuthenticated; - skip_to_CRLF(); -} - - -void TImapServerState::msg_fetch_headers(const char *partNum) -{ - if (GetFillingInShell()) - { - char *headerData = CreateAstring(); - fNextToken = GetNextToken(); - m_shell->AdoptMessageHeaders(headerData, partNum); - } - else - { - msg_fetch_content(FALSE, 0, MESSAGE_RFC822); - } -} - - -/* nstring ::= string / nil -string ::= quoted / literal - nil ::= "NIL" - -*/ -void TImapServerState::msg_fetch_content(XP_Bool chunk, int32 origin, const char *content_type) -{ - // setup the stream for downloading this message. - // Don't do it if we are filling in a shell or downloading a part. - // DO do it if we are downloading a whole message as a result of - // an invalid shell trying to generate. - if ((!chunk || (origin == 0)) && - (GetFillingInShell() ? m_shell->GetGeneratingWholeMessage() : TRUE)) - { - XP_ASSERT(fSizeOfMostRecentMessage > 0); - fServerConnection.BeginMessageDownLoad(fSizeOfMostRecentMessage, - content_type); - } - - if (XP_STRCASECMP(fNextToken, "NIL")) - { - if (*fNextToken == '"') - fLastChunk = msg_fetch_quoted(chunk, origin); - else - fLastChunk = msg_fetch_literal(chunk, origin); - } - else - fNextToken = GetNextToken(); // eat "NIL" - - if (fLastChunk && (GetFillingInShell() ? m_shell->GetGeneratingWholeMessage() : TRUE)) - { - // complete the message download - if (ContinueParse()) - fServerConnection.NormalMessageEndDownload(); - else - fServerConnection.AbortMessageDownLoad(); - } -} - - -/* - quoted ::= <"> *QUOTED_CHAR <"> - - QUOTED_CHAR ::= <any TEXT_CHAR except quoted_specials> / - "\" quoted_specials - - quoted_specials ::= <"> / "\" -*/ -// This algorithm seems gross. Isn't there an easier way? -XP_Bool TImapServerState::msg_fetch_quoted(XP_Bool chunk, int32 origin) -{ - uint32 numberOfCharsInThisChunk = 0; - XP_Bool closeQuoteFound = FALSE; - XP_Bool lastChunk = TRUE; // whether or not this is the last chunk of this message - char *scanLine = fCurrentLine++; // eat the first " - // this won't work! The '"' char does not start - // the line! why would anybody format a message like this! - while (!closeQuoteFound && ContinueParse()) - { - char *quoteSubString = strcasestr(scanLine, "\""); - while (quoteSubString && !closeQuoteFound) - { - if (quoteSubString > scanLine) - { - closeQuoteFound = *(quoteSubString - 1) != '\\'; - if (!closeQuoteFound) - quoteSubString = strcasestr(quoteSubString+1, "\""); - } - else - closeQuoteFound = TRUE; // 1st char is a '"' - } - - // send the string to the connection object so he can display or - // cache or whatever - fServerConnection.HandleMessageDownLoadLine(fCurrentLine, FALSE); - numberOfCharsInThisChunk += XP_STRLEN(fCurrentLine); - AdvanceToNextLine(); - scanLine = fCurrentLine; - } - - lastChunk = !chunk || ((origin + numberOfCharsInThisChunk) >= (unsigned int) fTotalDownloadSize); - return lastChunk; -} -/* msg_obsolete ::= "COPY" / ("STORE" SPACE msg_fetch) - ;; OBSOLETE untagged data responses */ -void TImapServerState::msg_obsolete() -{ - if (!XP_STRCASECMP(fNextToken, "COPY")) - fNextToken = GetNextToken(); - else if (!XP_STRCASECMP(fNextToken, "STORE")) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - msg_fetch(); - } - else - SetSyntaxError(TRUE); - -} -void TImapServerState::capability_data() -{ - fCapabilityFlag = fCapabilityFlag | kCapabilityDefined; - do { - fNextToken = GetNextToken(); - // for now we only care about AUTH=LOGIN - if (fNextToken) { - if(! XP_STRCASECMP(fNextToken, "AUTH=LOGIN")) - fCapabilityFlag |= kHasAuthLoginCapability; - else if (! XP_STRCASECMP(fNextToken, "X-NETSCAPE")) - fCapabilityFlag |= kHasXNetscapeCapability; - else if (! XP_STRCASECMP(fNextToken, "XSENDER")) - fCapabilityFlag |= kHasXSenderCapability; - else if (! XP_STRCASECMP(fNextToken, "IMAP4")) - fCapabilityFlag |= kIMAP4Capability; - else if (! XP_STRCASECMP(fNextToken, "IMAP4rev1")) - fCapabilityFlag |= kIMAP4rev1Capability; - else if (! XP_STRNCASECMP(fNextToken, "IMAP4", 5)) - fCapabilityFlag |= kIMAP4other; - else if (! XP_STRCASECMP(fNextToken, "X-NO-ATOMIC-RENAME")) - fCapabilityFlag |= kNoHierarchyRename; - else if (! XP_STRCASECMP(fNextToken, "X-NON-HIERARCHICAL-RENAME")) - fCapabilityFlag |= kNoHierarchyRename; - else if (! XP_STRCASECMP(fNextToken, "NAMESPACE")) - fCapabilityFlag |= kNamespaceCapability; - else if (! XP_STRCASECMP(fNextToken, "MAILBOXDATA")) - fCapabilityFlag |= kMailboxDataCapability; - else if (! XP_STRCASECMP(fNextToken, "ACL")) - fCapabilityFlag |= kACLCapability; - else if (! XP_STRCASECMP(fNextToken, "XSERVERINFO")) - fCapabilityFlag |= kXServerInfoCapability; - } - } while (fNextToken && - !at_end_of_line() && - ContinueParse()); - - TIMAPHostInfo::SetCapabilityForHost(fServerConnection.GetHostName(), fCapabilityFlag); - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - XP_ASSERT(navCon); // we should always have this - if (navCon) - navCon->CommitCapabilityForHostEvent(); - skip_to_CRLF(); -} - -void TImapServerState::xmailboxinfo_data() -{ - fNextToken = GetNextToken(); - if (!fNextToken) - return; - - char *mailboxName = CreateAstring(); // XP_STRDUP(fNextToken); - if (mailboxName) - { - do - { - fNextToken = GetNextToken(); - if (fNextToken) - { - if (!XP_STRCMP("MANAGEURL", fNextToken)) - { - fNextToken = GetNextToken(); - fFolderAdminUrl = CreateAstring(); - } - else if (!XP_STRCMP("POSTURL", fNextToken)) - { - fNextToken = GetNextToken(); - // ignore this for now... - } - } - } while (fNextToken && !at_end_of_line() && ContinueParse()); - } -} - -void TImapServerState::xserverinfo_data() -{ - do - { - fNextToken = GetNextToken(); - if (!fNextToken) - break; - if (!XP_STRCMP("MANAGEACCOUNTURL", fNextToken)) - { - fNextToken = GetNextToken(); - fMailAccountUrl = CreateAstring(); - } - else if (!XP_STRCMP("MANAGELISTSURL", fNextToken)) - { - fNextToken = GetNextToken(); - fManageListsUrl = CreateAstring(); - } - else if (!XP_STRCMP("MANAGEFILTERSURL", fNextToken)) - { - fNextToken = GetNextToken(); - fManageFiltersUrl = CreateAstring(); - } - } while (fNextToken && !at_end_of_line() && ContinueParse()); -} - - -void TImapServerState::namespace_data() -{ - // flush the old one and create a new one, initialized with no namespaces - TIMAPHostInfo::ClearServerAdvertisedNamespacesForHost(fServerConnection.GetHostName()); - EIMAPNamespaceType namespaceType = kPersonalNamespace; - while ((namespaceType != kUnknownNamespace) && ContinueParse()) - { - fNextToken = GetNextToken(); - while (at_end_of_line() && ContinueParse()) - fNextToken = GetNextToken(); - if (!XP_STRCASECMP(fNextToken,"NIL")) - { - // No namespace for this type. - // Don't add anything to the Namespace object. - } - else if (fNextToken[0] == '(') - { - // There may be multiple namespaces of the same type. - // Go through each of them and add them to our Namespace object. - - fNextToken++; - while (fNextToken[0] == '(' && ContinueParse()) - { - // we have another namespace for this namespace type - fNextToken++; - if (fNextToken[0] != '"') - { - SetSyntaxError(TRUE); - } - else - { - char *namespacePrefix = CreateQuoted(FALSE); - - fNextToken = GetNextToken(); - char *quotedDelimiter = fNextToken; - char namespaceDelimiter = '\0'; - - if (quotedDelimiter[0] == '"') - { - quotedDelimiter++; - namespaceDelimiter = quotedDelimiter[0]; - } - else if (!XP_STRNCASECMP(quotedDelimiter, "NIL", 3)) - { - // NIL hierarchy delimiter. Leave namespace delimiter NULL. - } - else - { - // not quoted or NIL. - SetSyntaxError(TRUE); - } - if (ContinueParse()) - { - TIMAPNamespace *newNamespace = new TIMAPNamespace(namespaceType, namespacePrefix, namespaceDelimiter, FALSE); - if (newNamespace) - TIMAPHostInfo::AddNewNamespaceForHost(fServerConnection.GetHostName(), newNamespace); - - skip_to_close_paren(); // Ignore any extension data - - XP_Bool endOfThisNamespaceType = (fNextToken[0] == ')'); - if (!endOfThisNamespaceType && fNextToken[0] != '(') // no space between namespaces of the same type - { - SetSyntaxError(TRUE); - } - } - } - } - } - else - { - SetSyntaxError(TRUE); - } - switch (namespaceType) - { - case kPersonalNamespace: - namespaceType = kOtherUsersNamespace; - break; - case kOtherUsersNamespace: - namespaceType = kPublicNamespace; - break; - default: - namespaceType = kUnknownNamespace; - break; - } - } - if (ContinueParse()) - { - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - XP_ASSERT(navCon); // we should always have this - if (navCon) - navCon->CommitNamespacesForHostEvent(); - } - skip_to_CRLF(); -} - -void TImapServerState::myrights_data() -{ - fNextToken = GetNextToken(); - if (ContinueParse() && !at_end_of_line()) - { - char *mailboxName = CreateAstring(); // XP_STRDUP(fNextToken); - if (mailboxName) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - { - char *myrights = CreateAstring(); // XP_STRDUP(fNextToken); - if (myrights) - { - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - XP_ASSERT(navCon); // we should always have this - if (navCon) - navCon->AddFolderRightsForUser(mailboxName, NULL /* means "me" */, myrights); - XP_FREE(myrights); - } - else - { - HandleMemoryFailure(); - } - if (ContinueParse()) - fNextToken = GetNextToken(); - } - XP_FREE(mailboxName); - } - else - { - HandleMemoryFailure(); - } - } - else - { - SetSyntaxError(TRUE); - } -} - -void TImapServerState::acl_data() -{ - fNextToken = GetNextToken(); - if (ContinueParse() && !at_end_of_line()) - { - char *mailboxName = CreateAstring(); // XP_STRDUP(fNextToken); - if (mailboxName && ContinueParse()) - { - fNextToken = GetNextToken(); - while (ContinueParse() && !at_end_of_line()) - { - char *userName = CreateAstring(); // XP_STRDUP(fNextToken); - if (userName && ContinueParse()) - { - fNextToken = GetNextToken(); - if (ContinueParse()) - { - char *rights = CreateAstring(); // XP_STRDUP(fNextToken); - if (rights) - { - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - XP_ASSERT(navCon); // we should always have this - if (navCon) - navCon->AddFolderRightsForUser(mailboxName, userName, rights); - XP_FREE(rights); - } - else - HandleMemoryFailure(); - - if (ContinueParse()) - fNextToken = GetNextToken(); - } - XP_FREE(userName); - } - else - HandleMemoryFailure(); - } - } - else - HandleMemoryFailure(); - } -} - - -void TImapServerState::mime_data() -{ - if (XP_STRSTR(fNextToken, "MIME")) - mime_header_data(); - else - mime_part_data(); -} - -// mime_header_data should not be streamed out; rather, it should be -// buffered in the TIMAPBodyShell. -// This is because we are still in the process of generating enough -// information from the server (such as the MIME header's size) so that -// we can construct the final output stream. -void TImapServerState::mime_header_data() -{ - char *partNumber = XP_STRDUP(fNextToken); - if (partNumber) - { - char *start = partNumber+5, *end = partNumber+5; // 5 == XP_STRLEN("BODY[") - while (ContinueParse() && end && *end != 'M' && *end != 'm') - { - end++; - } - if (end && (*end == 'M' || *end == 'm')) - { - *(end-1) = 0; - fNextToken = GetNextToken(); - char *mimeHeaderData = CreateAstring(); // is it really this simple? - fNextToken = GetNextToken(); - if (m_shell) - { - m_shell->AdoptMimeHeader(start, mimeHeaderData); - } - } - else - { - SetSyntaxError(TRUE); - } - XP_FREE(partNumber); // partNumber is not adopted by the body shell. - } - else - { - HandleMemoryFailure(); - } -} - -// Actual mime parts are filled in on demand (either from shell generation -// or from explicit user download), so we need to stream these out. -void TImapServerState::mime_part_data() -{ - char *checkOriginToken = XP_STRDUP(fNextToken); - if (checkOriginToken) - { - uint32 origin = 0; - XP_Bool originFound = FALSE; - char *whereStart = XP_STRCHR(checkOriginToken, '<'); - if (whereStart) - { - char *whereEnd = XP_STRCHR(whereStart, '>'); - if (whereEnd) - { - *whereEnd = 0; - whereStart++; - origin = atoint32(whereStart); - originFound = TRUE; - } - } - XP_FREE(checkOriginToken); - fNextToken = GetNextToken(); - msg_fetch_content(originFound, origin, MESSAGE_RFC822); // keep content type as message/rfc822, even though the - // MIME part might not be, because then libmime will - // still handle and decode it. - } - else - HandleMemoryFailure(); -} - -// FETCH BODYSTRUCTURE parser -// After exit, set fNextToken and fCurrentLine to the right things -void TImapServerState::bodystructure_data() -{ - fNextToken = GetNextToken(); - - // separate it out first - if (fNextToken && *fNextToken == '(') // It has to start with an open paren. - { - char *buf = CreateParenGroup(); - - if (ContinueParse()) - { - if (!buf) - HandleMemoryFailure(); - else - { - // Looks like we have what might be a valid BODYSTRUCTURE response. - // Try building the shell from it here. - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - XP_ASSERT(navCon); - m_shell = new TIMAPBodyShell(navCon, buf, CurrentResponseUID(), GetSelectedMailboxName()); - /* - if (m_shell) - { - if (!m_shell->GetIsValid()) - { - SetSyntaxError(TRUE); - } - } - */ - XP_FREE(buf); - } - } - } - else - SetSyntaxError(TRUE); -} - -XP_Bool TImapServerState::GetFillingInShell() -{ - return (m_shell != NULL); -} - -// Tells the server state parser to use a previously cached shell. -void TImapServerState::UseCachedShell(TIMAPBodyShell *cachedShell) -{ - // We shouldn't already have another shell we're dealing with. - if (m_shell && cachedShell) - { -// PR_LOG(IMAP, out, ("PARSER: Shell Collision")); - XP_ASSERT(FALSE); - } - m_shell = cachedShell; -} - - -void TImapServerState::ResetCapabilityFlag() -{ - TIMAPHostInfo::SetCapabilityForHost(fServerConnection.GetHostName(), kCapabilityUndefined); -} - -/* - literal ::= "{" number "}" CRLF *CHAR8 - ;; Number represents the number of CHAR8 octets -*/ -// returns TRUE if this is the last chunk and we should close the stream -XP_Bool TImapServerState::msg_fetch_literal(XP_Bool chunk, int32 origin) -{ - numberOfCharsInThisChunk = atoint32(fNextToken + 1); // might be the whole message - charsReadSoFar = 0; - static XP_Bool lastCRLFwasCRCRLF = FALSE; - - XP_Bool lastChunk = !chunk || (origin + numberOfCharsInThisChunk >= fTotalDownloadSize); - - TNavigatorImapConnection *navCon = fServerConnection.GetNavigatorConnection(); - if (navCon) - { - if (!lastCRLFwasCRCRLF && navCon->GetIOTunnellingEnabled() && (numberOfCharsInThisChunk > navCon->GetTunnellingThreshold())) - { - // One day maybe we'll make this smarter and know how to handle CR/LF boundaries across tunnels. - // For now, we won't, even though it might not be too hard, because it is very rare and will add - // some complexity. - charsReadSoFar = navCon->OpenTunnel(numberOfCharsInThisChunk); - } - } - - // If we opened a tunnel, finish everything off here. Otherwise, get everything here. - // (just like before) - - while (ContinueParse() && (charsReadSoFar < numberOfCharsInThisChunk)) - { - AdvanceToNextLine(); - if (ContinueParse()) - { - if (lastCRLFwasCRCRLF && (*fCurrentLine == CR)) - { - char *usableCurrentLine = 0; - StrAllocCopy(usableCurrentLine, fCurrentLine + 1); - FREEIF(fCurrentLine); - if (usableCurrentLine) - fCurrentLine = usableCurrentLine; - else - fCurrentLine = 0; - } - - if (ContinueParse()) - { - charsReadSoFar += XP_STRLEN(fCurrentLine); - if (!fDownloadingHeaders && fCurrentCommandIsSingleMessageFetch) - { - fServerConnection.ProgressEventFunction_UsingId(MK_IMAP_DOWNLOADING_MESSAGE); - if (fTotalDownloadSize > 0) - fServerConnection.PercentProgressUpdateEvent(0,(100*(charsReadSoFar + origin))/fTotalDownloadSize); - } - if (charsReadSoFar > numberOfCharsInThisChunk) - { // this is rare. If this msg ends in the middle of a line then only display the actual message. - char *displayEndOfLine = (fCurrentLine + XP_STRLEN(fCurrentLine) - (charsReadSoFar - numberOfCharsInThisChunk)); - char saveit = *displayEndOfLine; - *displayEndOfLine = 0; - fServerConnection.HandleMessageDownLoadLine(fCurrentLine, !lastChunk); - *displayEndOfLine = saveit; - lastCRLFwasCRCRLF = (*(displayEndOfLine - 1) == CR); - } - else - { - lastCRLFwasCRCRLF = (*(fCurrentLine + XP_STRLEN(fCurrentLine) - 1) == CR); - fServerConnection.HandleMessageDownLoadLine(fCurrentLine, !lastChunk && (charsReadSoFar == numberOfCharsInThisChunk)); - } - } - } - } - - // This would be a good thing to log. -// if (lastCRLFwasCRCRLF) -// PR_LOG(IMAP, out, ("PARSER: CR/LF fell on chunk boundary.")); - - if (ContinueParse()) - { - if (charsReadSoFar > numberOfCharsInThisChunk) - { - // move the lexical analyzer state to the end of this message because this message - // fetch ends in the middle of this line. - //fCurrentTokenPlaceHolder = fLineOfTokens + XP_STRLEN(fCurrentLine) - (charsReadSoFar - numberOfCharsInThisChunk); - AdvanceTokenizerStartingPoint(XP_STRLEN(fCurrentLine) - (charsReadSoFar - numberOfCharsInThisChunk)); - fNextToken = GetNextToken(); - } - else - { - skip_to_CRLF(); - fNextToken = GetNextToken(); - } - } - else - { - lastCRLFwasCRCRLF = FALSE; - } - return lastChunk; -} - -XP_Bool TImapServerState::CurrentFolderReadOnly() -{ - return fCurrentFolderReadOnly; -} - -int32 TImapServerState::NumberOfMessages() -{ - return fNumberOfExistingMessages; -} - -int32 TImapServerState::NumberOfRecentMessages() -{ - return fNumberOfRecentMessages; -} - -int32 TImapServerState::NumberOfUnseenMessages() -{ - return fNumberOfUnseenMessages; -} - -int32 TImapServerState::FolderUID() -{ - return fFolderUIDValidity; -} - -uint32 TImapServerState::CurrentResponseUID() -{ - return fCurrentResponseUID; -} - -uint32 TImapServerState::HighestRecordedUID() -{ - return fHighestRecordedUID; -} - - -XP_Bool TImapServerState::IsNumericString(const char *string) -{ - int i; - for(i = 0; i < (int) strlen(string); i++) - { - if (! isdigit(string[i])) - { - return FALSE; - } - } - - return TRUE; -} - -struct mailbox_spec *TImapServerState::CreateCurrentMailboxSpec(const char *mailboxName /* = NULL */) -{ - mailbox_spec *returnSpec = (mailbox_spec *) XP_CALLOC(1, sizeof(mailbox_spec) ); - if (returnSpec) - { - char *convertedMailboxName = NULL; - const char *mailboxNameToConvert = (mailboxName) ? mailboxName : fSelectedMailboxName; - if (mailboxNameToConvert) - { - char *convertedName = fServerConnection.CreateUtf7ConvertedString(mailboxNameToConvert, FALSE); - if (convertedName) - { - convertedMailboxName = fServerConnection.GetNavigatorConnection()->GetCurrentUrl()->AllocateCanonicalPath(convertedName); - XP_FREE(convertedName); - } - } - - returnSpec->folderSelected = TRUE; - returnSpec->folder_UIDVALIDITY = fFolderUIDValidity; - returnSpec->number_of_messages = fNumberOfExistingMessages; - returnSpec->number_of_unseen_messages = fNumberOfUnseenMessages; - returnSpec->number_of_recent_messages = fNumberOfRecentMessages; - - returnSpec->box_flags = kNoFlags; // stub - returnSpec->onlineVerified = FALSE; // we're fabricating this. The flags aren't verified. - returnSpec->allocatedPathName = convertedMailboxName; - returnSpec->connection = fServerConnection.GetNavigatorConnection(); - if (returnSpec->connection) - returnSpec->hostName = returnSpec->connection->GetCurrentUrl()->GetUrlHost(); - else - returnSpec->hostName = NULL; - if (fFlagState) - returnSpec->flagState = fFlagState; //copies flag state - else - returnSpec->flagState = NULL; - } - else - HandleMemoryFailure(); - - return returnSpec; - -} - -// zero stops a list recording of flags and causes the flags for -// each individual message to be sent back to libmsg -void TImapServerState::ResetFlagInfo(int numberOfInterestingMessages) -{ - if (fFlagState) - fFlagState->Reset(numberOfInterestingMessages); -} - - -XP_Bool TImapServerState::GetLastFetchChunkReceived() -{ - return fLastChunk; -} - -void TImapServerState::ClearLastFetchChunkReceived() -{ - fLastChunk = FALSE; -} - - - -//////////////////// TIMAPNamespace ///////////////////////////////////////////////////////////// - - - -TIMAPNamespace::TIMAPNamespace(EIMAPNamespaceType type, const char *prefix, char delimiter, XP_Bool from_prefs) -{ - m_namespaceType = type; - m_prefix = XP_STRDUP(prefix); - m_fromPrefs = from_prefs; - - m_delimiter = delimiter; - m_delimiterFilledIn = !m_fromPrefs; // if it's from the prefs, we can't be sure about the delimiter until we list it. -} - -TIMAPNamespace::~TIMAPNamespace() -{ - FREEIF(m_prefix); -} - -void TIMAPNamespace::SetDelimiter(char delimiter) -{ - m_delimiter = delimiter; - m_delimiterFilledIn = TRUE; -} - -// returns -1 if this box is not part of this namespace, -// or the length of the prefix if it is part of this namespace -int TIMAPNamespace::MailboxMatchesNamespace(const char *boxname) -{ - if (!boxname) return -1; - - // If the namespace is part of the boxname - if (XP_STRSTR(boxname, m_prefix) == boxname) - return XP_STRLEN(m_prefix); - - // If the boxname is part of the prefix - // (Used for matching Personal mailbox with Personal/ namespace, etc.) - if (XP_STRSTR(m_prefix, boxname) == m_prefix) - return XP_STRLEN(boxname); - return -1; -} - - -TIMAPNamespaceList *TIMAPNamespaceList::CreateTIMAPNamespaceList() -{ - TIMAPNamespaceList *rv = new TIMAPNamespaceList(); - if (rv) - { - if (!rv->m_NamespaceList) - { - delete rv; - rv = 0; - } - } - return rv; -} - -TIMAPNamespaceList::TIMAPNamespaceList() -{ - // Create a new list - m_NamespaceList = XP_ListNew(); -} - -int TIMAPNamespaceList::GetNumberOfNamespaces() -{ - return m_NamespaceList ? XP_ListCount(m_NamespaceList) : 0; -} - -int TIMAPNamespaceList::GetNumberOfNamespaces(EIMAPNamespaceType type) -{ - int nodeIndex = 0, count = 0; - for (nodeIndex=XP_ListCount(m_NamespaceList); nodeIndex > 0; nodeIndex--) - { - TIMAPNamespace *nspace = (TIMAPNamespace *)XP_ListGetObjectNum(m_NamespaceList, nodeIndex); - if (nspace->GetType() == type) - { - count++; - } - } - return count; -} - -int TIMAPNamespaceList::AddNewNamespace(TIMAPNamespace *ns) -{ - if (!m_NamespaceList) - return -1; - - // If the namespace is from the NAMESPACE response, then we should see if there - // are any namespaces previously set by the preferences, or the default namespace. If so, remove these. - - if (!ns->GetIsNamespaceFromPrefs()) - { - int nodeIndex = 0; - for (nodeIndex=XP_ListCount(m_NamespaceList); nodeIndex > 0; nodeIndex--) - { - TIMAPNamespace *nspace = (TIMAPNamespace *)XP_ListGetObjectNum(m_NamespaceList, nodeIndex); - if (nspace->GetIsNamespaceFromPrefs()) - { - XP_ListRemoveObject(m_NamespaceList, nspace); - delete nspace; - } - } - } - - // Add the new namespace to the list. This must come after the removing code, - // or else we could never add the initial kDefaultNamespace type to the list. - XP_ListAddObjectToEnd(m_NamespaceList, ns); - - return 0; -} - - -// chrisf - later, fix this to know the real concept of "default" namespace of a given type -TIMAPNamespace *TIMAPNamespaceList::GetDefaultNamespaceOfType(EIMAPNamespaceType type) -{ - TIMAPNamespace *rv = 0, *firstOfType = 0; - if (!m_NamespaceList) - return 0; - - int nodeIndex = 1, count = XP_ListCount(m_NamespaceList); - for (nodeIndex= 1; nodeIndex <= count && !rv; nodeIndex++) - { - TIMAPNamespace *ns = (TIMAPNamespace *)XP_ListGetObjectNum(m_NamespaceList, nodeIndex); - if (ns->GetType() == type) - { - if (!firstOfType) - firstOfType = ns; - if (!(*(ns->GetPrefix()))) - { - // This namespace's prefix is "" - // Therefore it is the default - rv = ns; - } - } - } - if (!rv) - rv = firstOfType; - return rv; -} - -TIMAPNamespaceList::~TIMAPNamespaceList() -{ - ClearNamespaces(TRUE, TRUE); - if (m_NamespaceList) - XP_ListDestroy (m_NamespaceList); -} - -// ClearNamespaces removes and deletes the namespaces specified, and if there are no namespaces left, -void TIMAPNamespaceList::ClearNamespaces(XP_Bool deleteFromPrefsNamespaces, XP_Bool deleteServerAdvertisedNamespaces) -{ - int nodeIndex = 0; - - if (m_NamespaceList) - { - for (nodeIndex=XP_ListCount(m_NamespaceList); nodeIndex > 0; nodeIndex--) - { - TIMAPNamespace *ns = (TIMAPNamespace *) XP_ListGetObjectNum(m_NamespaceList, nodeIndex); - if (ns->GetIsNamespaceFromPrefs()) - { - if (deleteFromPrefsNamespaces) - { - XP_ListRemoveObject(m_NamespaceList, ns); - delete ns; - } - } - else if (deleteServerAdvertisedNamespaces) - { - XP_ListRemoveObject(m_NamespaceList, ns); - delete ns; - } - } - } -} - -TIMAPNamespace *TIMAPNamespaceList::GetNamespaceNumber(int nodeIndex) -{ - int total = GetNumberOfNamespaces(); - XP_ASSERT(nodeIndex >= 1 && nodeIndex <= total); - if (nodeIndex < 1) nodeIndex = 1; - if (nodeIndex > total) nodeIndex = total; - - XP_ASSERT(m_NamespaceList); - if (m_NamespaceList) - { - return (TIMAPNamespace *)XP_ListGetObjectNum(m_NamespaceList, nodeIndex); - } - - return NULL; -} - -TIMAPNamespace *TIMAPNamespaceList::GetNamespaceNumber(int nodeIndex, EIMAPNamespaceType type) -{ - int nodeCount = 0, count = 0; - for (nodeCount=XP_ListCount(m_NamespaceList); nodeCount > 0; nodeCount--) - { - TIMAPNamespace *nspace = (TIMAPNamespace *)XP_ListGetObjectNum(m_NamespaceList, nodeCount); - if (nspace->GetType() == type) - { - count++; - if (count == nodeIndex) - return nspace; - } - } - return NULL; -} - -TIMAPNamespace *TIMAPNamespaceList::GetNamespaceForMailbox(const char *boxname) -{ - // We want to find the LONGEST substring that matches the beginning of this mailbox's path. - // This accounts for nested namespaces (i.e. "Public/" and "Public/Users/") - - // Also, we want to match the namespace's mailbox to that namespace also: - // The Personal box will match the Personal/ namespace, etc. - - // these lists shouldn't be too long (99% chance there won't be more than 3 or 4) - // so just do a linear search - - int lengthMatched = -1; - int currentMatchedLength = -1; - TIMAPNamespace *rv = NULL; - int nodeIndex = 0; - - if (!XP_STRCASECMP(boxname, "INBOX")) - return GetDefaultNamespaceOfType(kPersonalNamespace); - - if (m_NamespaceList) - { - for (nodeIndex=XP_ListCount(m_NamespaceList); nodeIndex > 0; nodeIndex--) - { - TIMAPNamespace *nspace = (TIMAPNamespace *)XP_ListGetObjectNum(m_NamespaceList, nodeIndex); - currentMatchedLength = nspace->MailboxMatchesNamespace(boxname); - if (currentMatchedLength > lengthMatched) - { - rv = nspace; - lengthMatched = currentMatchedLength; - } - } - } - - return rv; -} - - diff --git a/mozilla/network/protocol/imap4/makefile.win b/mozilla/network/protocol/imap4/makefile.win deleted file mode 100644 index 42f8b649c62..00000000000 --- a/mozilla/network/protocol/imap4/makefile.win +++ /dev/null @@ -1,101 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\imap4url.obj \ - .\$(OBJDIR)\imapbody.obj \ - .\$(OBJDIR)\imapearl.obj \ - .\$(OBJDIR)\imaphier.obj \ - .\$(OBJDIR)\imappars.obj \ - .\$(OBJDIR)\mkimap4.obj \ - $(NULL) - -CSRCS = \ - imap4url.c \ - $(NULL) - -CPPSRCS = \ - imapbody.cpp \ - imapearl.cpp \ - imaphier.cpp \ - imappars.cpp \ - mkimap4.cpp \ - $(NULL) - - -LIBRARY_NAME=imap4url -MODULE=imap4url -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= ldap network nspr2 security -EXPORTS= imap4pvt.h imap4url.h imapbody.h imaphier.h mkimap4.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(DEPTH)\lib\libmsg \ - -I$(PUBLIC)\mimetype \ - -I$(PUBLIC)\ldap \ -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/imap4/mkimap4.cpp b/mozilla/network/protocol/imap4/mkimap4.cpp deleted file mode 100644 index 837bf97253c..00000000000 --- a/mozilla/network/protocol/imap4/mkimap4.cpp +++ /dev/null @@ -1,10445 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#define FORCE_PR_LOG /* Allow logging in the release build */ - -#include "rosetta.h" -#include "mkutils.h" - -#include "imap4pvt.h" -#include "imap.h" -#include "imapbody.h" -#include "msgcom.h" -#include "msgnet.h" -#include "xpgetstr.h" -#include "secnav.h" -#include HG26363 -#include "sslerr.h" -#include "prefapi.h" -#include "prlog.h" -#include "libi18n.h" -#include "prtime.h" -#include "netutils.h" -#include "nslocks.h" - -#ifdef XP_MAC -#include "prpriv.h" /* for NewNamedMonitor */ -#else -#include "private/prpriv.h" -#endif - -#define MAX_NEW_IMAP_FOLDER_COUNT 50 -#define IMAP_DB_HEADERS "From To Cc Subject Date Priority X-Priority Message-ID References Newsgroups" - - -#define IMAP_YIELD(A) PR_Sleep(PR_INTERVAL_NO_WAIT) - -extern "C" -{ -extern int MK_OUT_OF_MEMORY; - -/* 45678901234567890123456789012345678901234567890123456789012345678901234567890 -*/ - -extern int XP_ERRNO_EWOULDBLOCK; -extern int XP_ERRNO_ENOTCONN; -extern int MK_TCP_READ_ERROR; -extern int MK_TCP_WRITE_ERROR; -extern int MK_POP3_NO_MESSAGES; -extern int MK_BAD_CONNECT; -extern int XP_FOLDER_RECEIVING_MESSAGE_OF; -extern int XP_RECEIVING_MESSAGE_HEADERS_OF; -extern int XP_RECEIVING_MESSAGE_FLAGS_OF; -extern int XP_IMAP_DELETING_MESSAGES; -extern int XP_IMAP_DELETING_MESSAGE; -extern int XP_IMAP_COPYING_MESSAGES_TO; -extern int XP_IMAP_COPYING_MESSAGE_TO; -extern int XP_IMAP_MOVING_MESSAGES_TO; -extern int XP_IMAP_MOVING_MESSAGE_TO; -extern int MK_MSG_IMAP_SERVER_NOT_IMAP4; -extern int MK_MSG_IMAP_SERVER_SAID; -extern int MK_MSG_TRASH_L10N_NAME; -extern int MK_IMAP_STATUS_CREATING_MAILBOX; -extern int MK_IMAP_STATUS_SELECTING_MAILBOX; -extern int MK_IMAP_STATUS_DELETING_MAILBOX; -extern int MK_IMAP_STATUS_RENAMING_MAILBOX; -extern int MK_IMAP_STATUS_LOOKING_FOR_MAILBOX; -extern int MK_IMAP_STATUS_SUBSCRIBE_TO_MAILBOX; -extern int MK_IMAP_STATUS_UNSUBSCRIBE_MAILBOX; -extern int MK_IMAP_STATUS_SEARCH_MAILBOX; -extern int MK_IMAP_STATUS_MSG_INFO; -extern int MK_IMAP_STATUS_CLOSE_MAILBOX; -extern int MK_IMAP_STATUS_EXPUNGING_MAILBOX; -extern int MK_IMAP_STATUS_LOGGING_OUT; -extern int MK_IMAP_STATUS_CHECK_COMPAT; -extern int MK_IMAP_STATUS_SENDING_LOGIN; -extern int MK_IMAP_STATUS_SENDING_AUTH_LOGIN; -extern int MK_IMAP_CREATE_FOLDER_BUT_NO_SUBSCRIBE; -extern int MK_IMAP_DELETE_FOLDER_BUT_NO_UNSUBSCRIBE; -extern int MK_IMAP_RENAME_FOLDER_BUT_NO_SUBSCRIBE; -extern int MK_IMAP_RENAME_FOLDER_BUT_NO_UNSUBSCRIBE; -extern int MK_IMAP_STATUS_GETTING_NAMESPACE; -extern int MK_IMAP_UPGRADE_NO_PERSONAL_NAMESPACE; -extern int MK_IMAP_UPGRADE_TOO_MANY_FOLDERS; -extern int MK_MSG_IMAP_DISCOVERING_MAILBOX; -extern int MK_IMAP_UPGRADE_PROMPT_USER; -extern int MK_IMAP_UPGRADE_PROMPT_USER_2; -extern int MK_IMAP_UPGRADE_WAIT_WHILE_UPGRADE; -extern int MK_IMAP_UPGRADE_PROMPT_QUESTION; -extern int MK_IMAP_UPGRADE_CUSTOM; -extern int MK_IMAP_UPGRADE_SUCCESSFUL; -extern int MK_MSG_DRAFTS_L10N_NAME; -extern int MK_IMAP_GETTING_ACL_FOR_FOLDER; -extern int MK_IMAP_GETTING_SERVER_INFO; -extern int MK_IMAP_GETTING_MAILBOX_INFO; -extern void NET_SetPopPassword2(const char *password); -extern int XP_PROMPT_ENTER_PASSWORD; -extern int XP_PASSWORD_FOR_POP3_USER; -extern int XP_MSG_IMAP_LOGIN_FAILED; - -extern void net_graceful_shutdown(PRFileDesc* sock, XP_Bool isSecure); -} - -extern PRLogModuleInfo* IMAP; -#define out PR_LOG_ALWAYS - -static int32 gMIMEOnDemandThreshold = 15000; -static XP_Bool gMIMEOnDemand = FALSE; -static XP_Bool gOptimizedHeaders = FALSE; - -static int32 gTunnellingThreshold = 2000; -static XP_Bool gIOTunnelling = FALSE; // off for now - -typedef struct _ImapConData { - TNavigatorImapConnection *netConnection; - - - void *offLineRetrievalData; // really a DisplayOfflineImapState object - - uint32 offLineMsgFlags; - uint32 offLineMsgKey; - - NET_StreamClass *offlineDisplayStream; -} ImapConData; - -typedef struct _GenericInfo { - char *c, *hostName; -} GenericInfo; - -typedef struct _StreamInfo { - uint32 size; - char *content_type; -} StreamInfo; - -typedef struct _ProgressInfo { - char *message; - int percent; -} ProgressInfo; - -typedef struct _FolderQueryInfo { - char *name, *hostName; - XP_Bool rv; -} FolderQueryInfo; - - -typedef struct _StatusMessageInfo { - uint32 msgID; - char * extraInfo; -} StatusMessageInfo; - -typedef struct _UploadMessageInfo { - uint32 newMsgID; - XP_File fileId; - char *dataBuffer; - int32 bytesRemain; -} UploadMessageInfo; - -struct utf_name_struct { - XP_Bool toUtf7Imap; - unsigned char *sourceString; - unsigned char *convertedString; -}; - - -typedef struct _TunnelInfo { - int32 maxSize; - PRFileDesc* ioSocket; - char** inputSocketBuffer; - int32* inputBufferSize; -} TunnelInfo; - -const char *ImapTRASH_FOLDER_NAME = NULL; - -const int32 kImapSleepTime = 1000000; - -int32 atoint32(char *ascii) -{ - char *endptr; - int32 rvalue = XP_STRTOUL(ascii, &endptr, 10); - return rvalue; -} - -XP_Bool IMAP_ContextIsBiff(ActiveEntry *ce) -{ - return (ce->window_id == MSG_GetBiffContext() || ce->window_id->type == MWContextBiff); -} - -XP_Bool IMAP_URLIsBiff(ActiveEntry *ce, TIMAPUrl &currentUrl) -{ - return (IMAP_ContextIsBiff(ce) && currentUrl.GetIMAPurlType() == TIMAPUrl::kSelectFolder); -} - -static void -IMAP_LoadTrashFolderName(void) -{ - if (!ImapTRASH_FOLDER_NAME) - ImapTRASH_FOLDER_NAME = MSG_GetSpecialFolderName(MK_MSG_TRASH_L10N_NAME); -} - -void IMAP_DoNotDownLoadAnyMessageHeadersForMailboxSelect(TNavigatorImapConnection *connection) -{ - if (connection) - connection->NotifyKeyList(NULL,0); -} - -void IMAP_DownLoadMessageBodieForMailboxSelect(TNavigatorImapConnection *connection, - uint32 *messageKeys, /* uint32* is adopted */ - uint32 numberOfKeys) -{ - connection->NotifyKeyList(messageKeys, numberOfKeys); -} - -void IMAP_BodyIdMonitor(TNavigatorImapConnection *connection, XP_Bool enter) -{ - connection->BodyIdMonitor(enter); -} - -void TNavigatorImapConnection::BodyIdMonitor(XP_Bool enter) -{ - if (enter) - PR_EnterMonitor(fWaitForBodyIdsMonitor); - else - PR_ExitMonitor(fWaitForBodyIdsMonitor); -} - -void IMAP_DownLoadMessagesForMailboxSelect(TNavigatorImapConnection *connection, - uint32 *messageKeys, /* uint32* is adopted */ - uint32 numberOfKeys) -{ - connection->NotifyKeyList(messageKeys, numberOfKeys); -} - -char *IMAP_GetCurrentConnectionUrl(TNavigatorImapConnection *connection) -{ - return connection->GetCurrentConnectionURL(); -} - -void IMAP_UploadAppendMessageSize(TNavigatorImapConnection *connection, uint32 msgSize, imapMessageFlagsType flags) -{ - connection->NotifyAppendSize(msgSize, flags); -} - -void IMAP_TerminateConnection (TNavigatorImapConnection *conn) -{ - conn->TellThreadToDie(); -} - -char *IMAP_CreateOnlineSourceFolderNameFromUrl(const char *url) -{ - TIMAPUrl urlObject(url, TRUE); - return urlObject.CreateCanonicalSourceFolderPathString(); -} - -void IMAP_FreeBoxSpec(mailbox_spec *victim) -{ - if (victim) - { - FREEIF(victim->allocatedPathName); - // delete victim->flagState; // not owned by us, leave it alone - XP_FREE(victim); - } -} - -XP_Bool IMAP_CheckNewMail(TNavigatorImapConnection *connection) -{ - return connection->CheckNewMail(); -} - -XP_Bool IMAP_NewMailDetected(TNavigatorImapConnection *connection) -{ - return connection->NewMailDetected(); -} - - -// These C functions implemented here are usually executed as TImapFEEvent's - -static -void SetBiffIndicator(void *biffStateVoid, void *blockingConnectionVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - MSG_BIFF_STATE biffState = (MSG_BIFF_STATE) (uint32) biffStateVoid; - MSG_SetBiffStateAndUpdateFE(biffState); - imapConnection->NotifyEventCompletionMonitor(); - -} - - -#ifndef XP_OS2 -static -#else -extern "OPTLINK" -#endif -void MessageUploadComplete(void *blockingConnectionVoid) // called when upload is complete -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - imapConnection->NotifyMessageUploadMonitor(); -} - -static -void UploadMessageEvent(void *blockingConnectionVoid, void *) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - BeginMessageUpload(imapConnection->GetActiveEntry()->window_id, - imapConnection->GetIOSocket(), - MessageUploadComplete, - imapConnection); -} - -static -void msgSetUserAuthenticated(void *blockingConnectionVoid, void *trueOrFalseVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - XP_Bool authenticated = (XP_Bool) (uint32) trueOrFalseVoid; - if (ce && ce->URL_s->msg_pane) - MSG_SetUserAuthenticated(MSG_GetMaster(ce->URL_s->msg_pane), - authenticated); -} - -static -void LiteSelectEvent(void *blockingConnectionVoid, void * /*unused*/) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - if (ce && ce->URL_s->msg_pane) - ReportLiteSelectUIDVALIDITY(ce->URL_s->msg_pane, - imapConnection->GetServerStateParser().FolderUID()); - imapConnection->NotifyEventCompletionMonitor(); -} - -static -void msgSetMailAccountURL(void *blockingConnectionVoid, void *hostName) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - if (ce && ce->URL_s->msg_pane) - MSG_SetHostMailAccountURL(MSG_GetMaster(ce->URL_s->msg_pane), (const char *) hostName, - imapConnection->GetServerStateParser().GetMailAccountUrl()); -} - -static void msgSetMailServerURLs(void *blockingConnectionVoid, void *hostName) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - if (ce && ce->URL_s->msg_pane) - { - MSG_SetHostMailAccountURL(MSG_GetMaster(ce->URL_s->msg_pane), (const char *) hostName, - imapConnection->GetServerStateParser().GetMailAccountUrl()); - MSG_SetHostManageListsURL(MSG_GetMaster(ce->URL_s->msg_pane), (const char *) hostName, - imapConnection->GetServerStateParser().GetManageListsUrl()); - MSG_SetHostManageFiltersURL(MSG_GetMaster(ce->URL_s->msg_pane), (const char *) hostName, - imapConnection->GetServerStateParser().GetManageFiltersUrl()); - } -} - -static void MOZ_THREADmsgSetFolderURL(void *blockingConnectionVoid, void *folderQueryInfo) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - if (ce && ce->window_id->mailMaster) - { - FolderQueryInfo *queryInfo = (FolderQueryInfo *) folderQueryInfo; - MSG_SetFolderAdminURL(ce->window_id->mailMaster, queryInfo->hostName, queryInfo->name, imapConnection->GetServerStateParser().GetManageFolderUrl()); - } -} - -struct tFlagsKeyStruct { - imapMessageFlagsType flags; - MessageKey key; -}; - -typedef struct tFlagsKeyStruct tFlagsKeyStruct; - -static -void NotifyMessageFlagsEvent( void *blockingConnectionVoid, void *flagsVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - struct tFlagsKeyStruct *flagAndKey = (struct tFlagsKeyStruct *) flagsVoid; - - MSG_RecordImapMessageFlags(imapConnection->GetActiveEntry()->window_id->imapURLPane, - flagAndKey->key, - flagAndKey->flags); - FREEIF( flagAndKey); -} - -struct delete_message_struct { - char *onlineFolderName; - XP_Bool deleteAllMsgs; - char *msgIdString; -}; - -static -void ConvertImapUtf7(void *utf_name_structVoid, - void *blockingConnectionVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - utf_name_struct *names = (utf_name_struct *) utf_name_structVoid; - - // NULL if bad conversion - names->convertedString = NULL; - -#ifdef XP_WIN16 - names->convertedString = (unsigned char *) XP_STRDUP((const char *) names->sourceString); -#else - int16 fromCsid = names->toUtf7Imap ? (INTL_DocToWinCharSetID(INTL_DefaultDocCharSetID(0)) & ~CS_AUTO): CS_IMAP4_UTF7; - int16 toCsid = !names->toUtf7Imap ? (INTL_DocToWinCharSetID(INTL_DefaultDocCharSetID(0)) & ~CS_AUTO): CS_IMAP4_UTF7; - - // convert from whatever to CS_UTF8 - unsigned char *utf8String = INTL_ConvertLineWithoutAutoDetect(fromCsid, CS_UTF8, names->sourceString, XP_STRLEN((const char *) names->sourceString)); - if (utf8String) - { - // convert from CS_UTF8 to whatever - names->convertedString = INTL_ConvertLineWithoutAutoDetect(CS_UTF8, toCsid, utf8String, XP_STRLEN((const char *) utf8String)); - XP_FREE(utf8String); - } - -#endif - if (imapConnection) - imapConnection->NotifyEventCompletionMonitor(); -} - -static -void NotifyMessageDeletedEvent( void *blockingConnectionVoid, void *delete_message_structVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - struct delete_message_struct *msgStruct = (struct delete_message_struct *) delete_message_structVoid; - - if (msgStruct->onlineFolderName) - MSG_ImapMsgsDeleted(imapConnection->GetActiveEntry()->window_id->imapURLPane, - msgStruct->onlineFolderName, imapConnection->GetHostName(), - msgStruct->deleteAllMsgs, - msgStruct->msgIdString); - - FREEIF( msgStruct->onlineFolderName ); - FREEIF( msgStruct->msgIdString); - FREEIF( msgStruct); -} - -static -void AddSearchResultEvent( void *blockingConnectionVoid, void *hitLineVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - MSG_AddImapSearchHit(imapConnection->GetActiveEntry()->window_id, - (const char *) hitLineVoid); - - imapConnection->NotifyEventCompletionMonitor(); -} - - -static -void HeaderFetchCompletedEvent(void *blockingConnectionVoid, void *) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - NotifyHeaderFetchCompleted(imapConnection->GetActiveEntry()->window_id,imapConnection); -} - -#ifdef XP_MAC -// stuff used to measure performance of down loads -// #define MACPERF 1 -#ifdef MACPERF -#include "Events.h" -UInt32 g_StartTimeOfDownLoad; -UInt32 g_TimeSpendInDownLoadFunction; -UInt32 g_NumberOfVisits; -#endif - -#endif - - -/* this function ensures that the msg dislay stream is set up so that - replying to a message causes the compose window to appear with the - correct header info filled in and quoting works. -*/ - -#ifndef XP_OS2 -static -#else -extern "OPTLINK" -#endif -char * imap_mail_generate_html_header_fn (const char* /*dest*/, void *closure, - MimeHeaders *headers) -{ - // This function is only called upon creation of a message pane. - // If this is true then ce->URL_s->msg_pane will be set by - // MSG_Pane::GetURL. - ActiveEntry *ce = (ActiveEntry *) closure; - MSG_Pane *messagepane = ce->URL_s->msg_pane; - - if (!messagepane && ce->window_id) - messagepane = ce->window_id->imapURLPane; - - if (messagepane && (MSG_MESSAGEPANE == MSG_GetPaneType(messagepane))) - MSG_ActivateReplyOptions (messagepane, headers); - return 0; -} - -/* this function generates the correct reference URLs for -IMAP messages */ - -#ifndef XP_OS2 -static -#else -extern "OPTLINK" -#endif -char * imap_mail_generate_reference_url_fn (const char *dest, void *closure, - MimeHeaders*) -{ - ActiveEntry *cur_entry = (ActiveEntry *) closure; - char *addr = cur_entry->URL_s->address; - char *search = (addr ? XP_STRRCHR (addr, '>') + 1 : 0); - char *id2; - char *new_dest = 0; - char *result = 0; - MessageKey key = MSG_MESSAGEKEYNONE; - char *keyStr = 0; - - if (!dest || !*dest) return 0; - id2 = XP_STRDUP (dest); - if (!id2) return 0; - if (id2[XP_STRLEN (id2)-1] == '>') - id2[XP_STRLEN (id2)-1] = 0; - - // convert the Message-ID to a Key - MSG_Pane *pane = cur_entry->window_id->imapURLPane; - if (pane) - { - char *idInDB = id2; - if (id2[0] == '<') - { - new_dest = NET_Escape (id2+1, URL_PATH); - idInDB = id2 + 1; - } - else - { - new_dest = NET_Escape (id2, URL_PATH); - } - - if (0 != MSG_GetKeyFromMessageId(pane, idInDB, &key) || key == MSG_MESSAGEKEYNONE) - goto CLEANUP; - - } - else - { - goto CLEANUP; - } - - - // now convert the message key to a string - keyStr = PR_smprintf ("%ld", (long) key); - - result = (char *) XP_ALLOC ((search ? search - addr : 0) + - (new_dest ? XP_STRLEN (new_dest) : 0) + - 40); - if (result && new_dest) - { - if (search) - { - XP_MEMCPY (result, addr, search - addr); - result[search - addr] = 0; - } - else if (addr) - XP_STRCPY (result, addr); - else - *result = 0; - XP_STRCAT (result, keyStr); - } -CLEANUP: - FREEIF (id2); - FREEIF (new_dest); - FREEIF (keyStr); - return result; -} - -MSG_Pane *IMAP_GetActiveEntryPane(ImapActiveEntry * imap_entry) -{ - ActiveEntry * ce = (ActiveEntry *) imap_entry; - MSG_Pane *returnPane = ce->URL_s->msg_pane; - - if (!returnPane) // can happen when libmime or layout reload a url - returnPane = MSG_FindPaneOfContext(ce->window_id, MSG_ANYPANE); - - return returnPane; -} - -NET_StreamClass *IMAP_CreateDisplayStream(ImapActiveEntry * imap_entry, XP_Bool clearCacheBit, uint32 size, const char *content_type) -{ - ActiveEntry * ce = (ActiveEntry *) imap_entry; - - if (clearCacheBit) - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); // no need to use libnet cache - - if (ce->format_out == FO_PRESENT || ce->format_out == FO_CACHE_AND_PRESENT) - { - IMAP_InitializeImapFeData(ce); - } - - ce->URL_s->content_length = size; - StrAllocCopy(ce->URL_s->content_type, content_type); - NET_StreamClass *displayStream = NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - - return displayStream; -} - - -int -IMAP_InitializeImapFeData (ImapActiveEntry * imap_entry) -{ - ActiveEntry * ce = (ActiveEntry *) imap_entry; - - MimeDisplayOptions *opt; - - { // make sure this is a valid imap url - TIMAPUrl imapurl(ce->URL_s->address, ce->URL_s->internal_url); - if (!imapurl.ValidIMAPUrl()) - { - XP_ASSERT(0); - return -1; - } - } - - if (ce->URL_s->fe_data) - { - XP_ASSERT(0); - return -1; - } - - opt = XP_NEW (MimeDisplayOptions); - if (!opt) return MK_OUT_OF_MEMORY; - XP_MEMSET (opt, 0, sizeof(*opt)); - - opt->generate_reference_url_fn = imap_mail_generate_reference_url_fn; - opt->generate_header_html_fn = imap_mail_generate_html_header_fn; - opt->html_closure = ce; - opt->missing_parts = ce->URL_s->content_modified; - - ce->URL_s->fe_data = opt; - return 0; -} - - -extern "C" void IMAP_PseudoInterruptFetch(MWContext *context) -{ - // OK, we're going to lie and stick the connection object in the context. - TNavigatorImapConnection *imapConnection = context->imapConnection; - - if (imapConnection) - { - imapConnection->PseudoInterrupt(TRUE); - } -} - - - -// This function creates an output stream used to present an RFC822 message or one of its parts -static -void SetupMsgWriteStream(void *blockingConnectionVoid, void *StreamInfoVoid) -{ -#ifdef MACPERF - g_StartTimeOfDownLoad = TickCount(); - g_TimeSpendInDownLoadFunction = 0; - g_NumberOfVisits = 0; -#endif - - PR_LOG(IMAP, out, ("STREAM: Begin Message Download Stream Event")); - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - StreamInfo *si = (StreamInfo *)StreamInfoVoid; - - NET_StreamClass *outputStream = NULL; - - TIMAPUrl currentUrl(ce->URL_s->address, ce->URL_s->internal_url); - if ((currentUrl.GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineCopy) || - (currentUrl.GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineMove)) - MSG_StartImapMessageToOfflineFolderDownload(ce->window_id); - - if (ce->window_id->currentIMAPfolder) - { - outputStream = CreateIMAPDownloadMessageStream(ce, si->size, si->content_type, ce->URL_s->content_modified); - } - else - { - if (ce->format_out == FO_PRESENT || ce->format_out == FO_CACHE_AND_PRESENT) - { - IMAP_InitializeImapFeData(ce); - } - - ce->URL_s->content_length = si->size; - StrAllocCopy(ce->URL_s->content_type, si->content_type); - outputStream = - NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - } - - if (outputStream) - imapConnection->SetOutputStream(outputStream); - else - { - // this should be impossible but be paranoid - imapConnection->SetConnectionStatus(-1); - imapConnection->GetServerStateParser().SetConnected(FALSE); - } - - FREEIF(si->content_type); - XP_FREE(si); - - imapConnection->NotifyEventCompletionMonitor(); -} - - -// report the success of the recent online copy -static -void OnlineCopyReport(void *blockingConnectionVoid, - void *adoptedCopyStateVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ImapOnlineCopyState *copyState = (ImapOnlineCopyState *) adoptedCopyStateVoid; - - ReportSuccessOfOnlineCopy(imapConnection->GetActiveEntry()->window_id, *copyState); - - FREEIF( copyState); -} - -static -void OnlineFolderDelete(void *blockingConnectionVoid, - void *adoptedmailboxNameVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - char *boxNameAdopted = (char *) adoptedmailboxNameVoid; - - ReportSuccessOfOnlineDelete(imapConnection->GetActiveEntry()->window_id, imapConnection->GetHostName(), boxNameAdopted); - - FREEIF( boxNameAdopted); -} - -static -void OnlineFolderCreateFailed(void *blockingConnectionVoid, - void *serverMessageVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - char *serverMessage = (char *) serverMessageVoid; - - ReportFailureOfOnlineCreate(imapConnection->GetActiveEntry()->window_id, serverMessage); - - FREEIF( serverMessage); -} - -static -void OnlineFolderRename(void *blockingConnectionVoid, - void *renameStructVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - folder_rename_struct *renameStruct = (folder_rename_struct *) renameStructVoid; - - ReportSuccessOfOnlineRename(imapConnection->GetActiveEntry()->window_id, renameStruct); - - FREEIF( renameStruct->fOldName); - FREEIF( renameStruct->fNewName); - FREEIF( renameStruct->fHostName); - FREEIF( renameStruct); -} - -static -void MailboxDiscoveryDoneEvent(void *blockingConnectionVoid, void * /*unused*/) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ReportMailboxDiscoveryDone(imapConnection->GetActiveEntry()->window_id, imapConnection->GetActiveEntry()->URL_s); -} - - -// This function tells mail master about a discovered imap mailbox -static -void PossibleIMAPmailbox(void *blockingConnectionVoid, - void *boxSpecVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - MSG_Master *master = NULL; - MWContext *context = imapConnection->GetActiveEntry()->window_id; - if (context) - master = context->mailMaster; - XP_Bool broadcastDiscovery = TRUE; - char *url = imapConnection->GetCurrentConnectionURL(); - if (url) - { - TIMAPUrl urlc(url, TRUE); - if (urlc.GetIMAPurlType() == TIMAPUrl::kCreateFolder) - broadcastDiscovery = FALSE; - XP_FREE(url); - } - - - imapConnection->SetMailboxDiscoveryStatus( - DiscoverIMAPMailbox((mailbox_spec *) boxSpecVoid, - master, - imapConnection->GetActiveEntry()->window_id, - broadcastDiscovery)); - - imapConnection->NotifyEventCompletionMonitor(); -} - -// tell the mail master about the newly selected mailbox -static -void UpdatedIMAPmailbox(void *blockingConnectionVoid, - void *boxSpecVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - UpdateIMAPMailboxInfo((mailbox_spec *) boxSpecVoid, - imapConnection->GetActiveEntry()->window_id); - -} - -// tell the mail master about the newly selected mailbox -static -void UpdatedIMAPmailboxStatus(void *blockingConnectionVoid, - void *boxSpecVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - UpdateIMAPMailboxStatus((mailbox_spec *) boxSpecVoid, - imapConnection->GetActiveEntry()->window_id); - -} - - -struct uid_validity_info { - char *canonical_boxname; - const char *hostName; - int32 returnValidity; -}; - -static -void GetStoredUIDValidity(void *blockingConnectionVoid, - void *ValidityVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - uid_validity_info *info = (uid_validity_info *) ValidityVoid; - - info->returnValidity = GetUIDValidityForSpecifiedImapFolder(info->hostName, info->canonical_boxname, - imapConnection->GetActiveEntry()->window_id); - imapConnection->NotifyEventCompletionMonitor(); -} - - -struct msg_line_info { - char *adoptedMessageLine; - uint32 uidOfMessage; -}; - - -// This function adds one line to current message presentation -static -void ParseAdoptedMsgLine(void *blockingConnectionVoid, - void *adoptedmsg_line_info_Void) -{ -#ifdef MACPERF - UInt32 startTicks = TickCount(); -#endif - - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - msg_line_info *downloadLineDontDelete = (msg_line_info *) adoptedmsg_line_info_Void; - NET_StreamClass *outputStream = imapConnection->GetOutputStream(); - - unsigned int streamBytesMax = (*outputStream->is_write_ready) (outputStream); - char *stringToPut = downloadLineDontDelete->adoptedMessageLine; - XP_Bool allocatedString = FALSE; - - if ( streamBytesMax < (XP_STRLEN(downloadLineDontDelete->adoptedMessageLine) + 2)) - { - // dup the streamBytesMax number of chars, then put the rest of the string back into event queue - if (streamBytesMax != 0) - { - stringToPut = (char *) XP_ALLOC(streamBytesMax + 1); // 1 for \0 - if (stringToPut) - { - XP_MEMCPY(stringToPut, downloadLineDontDelete->adoptedMessageLine, streamBytesMax); - *(stringToPut + streamBytesMax) = 0; - allocatedString = TRUE; - } - - // shift buffer bytes - XP_MEMMOVE(downloadLineDontDelete->adoptedMessageLine, - downloadLineDontDelete->adoptedMessageLine + streamBytesMax, - (XP_STRLEN(downloadLineDontDelete->adoptedMessageLine) + 1) - streamBytesMax); - } - - // the output stream can't handle this event yet! put it back on the - // queue - TImapFEEvent *parseLineEvent = - new TImapFEEvent(ParseAdoptedMsgLine, // function to call - blockingConnectionVoid, // access to current entry - adoptedmsg_line_info_Void, - FALSE); // line to display - if (parseLineEvent) - imapConnection->GetFEEventQueue(). - AdoptEventToBeginning(parseLineEvent); - else - imapConnection->HandleMemoryFailure(); - } - - - if (streamBytesMax != 0) - { - imapConnection->SetBytesMovedSoFarForProgress(imapConnection->GetBytesMovedSoFarForProgress() + - XP_STRLEN(stringToPut)); - - if (!imapConnection->GetPseudoInterrupted()) - { - int bytesPut = 0; - - if (ce->window_id->currentIMAPfolder) - { - // the definition of put_block in net.h defines - // the 3rd parameter as the length of the block, - // but since we are always sending a null terminated - // string, I am able to sent the uid instead - bytesPut = (*outputStream->put_block) (outputStream, - stringToPut, - downloadLineDontDelete->uidOfMessage); - } - else // this is a download for display - { - bytesPut = (*outputStream->put_block) (outputStream, - stringToPut, - XP_STRLEN(stringToPut)); - } - - if (bytesPut < 0) - { - imapConnection->SetConnectionStatus(-1); // something bad happened, stop this url - imapConnection->GetServerStateParser().SetConnected(FALSE); - } - } - } -#ifdef MACPERF - g_TimeSpendInDownLoadFunction += TickCount() - startTicks; - g_NumberOfVisits++; -#endif - - if (allocatedString) - XP_FREE(stringToPut); // event not done yet - else if (streamBytesMax != 0) - imapConnection->NotifyEventCompletionMonitor(); - -} - -// This function closes the message presentation stream -static -void NormalEndMsgWriteStream(void *blockingConnectionVoid, void *) -{ - PR_LOG(IMAP, out, ("STREAM: Normal End Message Download Stream Event")); - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - NET_StreamClass *outputStream = imapConnection->GetOutputStream(); - if (outputStream) - { - if (imapConnection->GetPseudoInterrupted()) - (*outputStream->abort)(outputStream, -1); - else - (*outputStream->complete) (outputStream); - outputStream->data_object = NULL; - } - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - -#ifdef MACPERF - char perfMessage[500]; - sprintf(perfMessage, - (const char *) "Download time = %ld, mkimap4 time = %ld, for %ld visits", - TickCount() - g_StartTimeOfDownLoad, - g_TimeSpendInDownLoadFunction, g_NumberOfVisits); - - DebugStr((const unsigned char *) c2pstr(perfMessage)); -#endif - -} - -// This function aborts the message presentation stream -static -void AbortMsgWriteStream(void *blockingConnectionVoid, void *) -{ - PR_LOG(IMAP, out, ("STREAM: Abort Message Download Stream Event")); - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - NET_StreamClass *outputStream = imapConnection->GetOutputStream(); - if (outputStream && outputStream->data_object) - { - (*outputStream->abort) (outputStream, -1); - outputStream->data_object = NULL; - } - - ActiveEntry *ce = imapConnection->GetActiveEntry(); -#ifdef MACPERF - char perfMessage[500]; - sprintf(perfMessage, - (const char *) "Download time = %ld, mkimap4 time = %ld, for %ld visits", - TickCount() - g_StartTimeOfDownLoad, - g_TimeSpendInDownLoadFunction, g_NumberOfVisits); - - DebugStr((const unsigned char *) c2pstr(perfMessage)); -#endif -} - -// This function displays a modal alert dialog based on -// a XP_GetString of the passed id -static -void AlertEventFunction_UsingId(void *blockingConnectionVoid, - void *errorMessageIdVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - // if this is a biff context, - // don't put up the alert - if (IMAP_ContextIsBiff(ce)) - { - imapConnection->NotifyEventCompletionMonitor(); - return; - } - - uint32 errorId = (uint32) errorMessageIdVoid; - char *errorString = XP_GetString(errorId); - - if (errorString) -#ifdef XP_UNIX - FE_Alert_modal(ce->window_id, errorString); -#else - FE_Alert(ce->window_id, errorString); -#endif - - imapConnection->NotifyEventCompletionMonitor(); -} - -// This function displays a modal alert dialog -static -void AlertEventFunction(void *blockingConnectionVoid, - void *errorMessageVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - // if this is a biff context, - // don't put up the alert - if (IMAP_ContextIsBiff(ce)) - { - imapConnection->NotifyEventCompletionMonitor(); - return; - } - - FE_Alert(ce->window_id, (const char *) errorMessageVoid); - - imapConnection->NotifyEventCompletionMonitor(); -} - -// This function displays a modal alert dialog, appending the -// message to "The IMAP server responded: " -static -void AlertEventFunctionFromServer(void *blockingConnectionVoid, - void *serverSaidVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - // if this is a biff context, - // don't put up the alert - if (IMAP_ContextIsBiff(ce)) - { - imapConnection->NotifyEventCompletionMonitor(); - return; - } - - const char *serverSaid = (const char *) serverSaidVoid; - if (serverSaid) - { - char *whereRealMessage = XP_STRCHR(serverSaid, ' '); - if (whereRealMessage) - whereRealMessage++; - if (whereRealMessage) - whereRealMessage = XP_STRCHR(whereRealMessage, ' '); - if (whereRealMessage) - whereRealMessage++; - - char *message = PR_smprintf(XP_GetString(MK_MSG_IMAP_SERVER_SAID), whereRealMessage ? whereRealMessage : serverSaid); - - if (message) FE_Alert(ce->window_id, message); - FREEIF(message); - } - - imapConnection->NotifyEventCompletionMonitor(); -} - -// until preferences are worked out, save a copy of the password here -static char *gIMAPpassword=NULL; // gross -static XP_Bool preAuthSucceeded = FALSE; - -const char * IMAP_GetPassword() -{ - return gIMAPpassword; -} - -void IMAP_SetPassword(const char *password) -{ - FREEIF(gIMAPpassword); - if (password) - gIMAPpassword = XP_STRDUP(password); -} - -void IMAP_SetPasswordForHost(const char *host, const char *password) -{ - TIMAPHostInfo::SetPasswordForHost(host, password); -} - -void IMAP_ResetAnyCachedConnectionInfo() -{ - if (gIMAPpassword) - { - FREEIF(gIMAPpassword); - gIMAPpassword = NULL; - } - preAuthSucceeded = FALSE; - - TNavigatorImapConnection::ResetCachedConnectionInfo(); -} - -// This function displays a modal alert dialog -static -void GetPasswordEventFunction(void *blockingConnectionVoid, - void *userNameVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - -#if 1 - char* fmt = XP_GetString( XP_PASSWORD_FOR_POP3_USER ); - - if (fmt) - { - const char *host = imapConnection->GetHostName(); - size_t len = (XP_STRLEN(fmt) + - (host ? XP_STRLEN(host) : 0) + 300) - * sizeof(char); - char *prompt = (char*)XP_ALLOC(len); - if (prompt) - { - PR_snprintf(prompt, len, fmt, (char*)userNameVoid, host); - - const char* password = FE_PromptPassword(ce->window_id, prompt); - if (password != NULL) - TIMAPHostInfo::SetPasswordForHost(host, password); - XP_FREE(prompt); - } - } -#else - char *prompt = NULL; - char *promptText = XP_GetString(XP_PROMPT_ENTER_PASSWORD); - - if (promptText) - prompt = PR_smprintf(promptText, (char *) userNameVoid); - - if (prompt) - { - const char *password = FE_PromptPassword(ce->window_id, prompt); - if (password != NULL) - TIMAPHostInfo::SetPasswordForHost(imapConnection->GetHostName(), password); - XP_FREE(prompt); - } -#endif - imapConnection->NotifyEventCompletionMonitor(); -} - - -// This function alerts the FE that we are past the password check -// (The WinFE needs this for progress updates) -static -void PastPasswordCheckFunction(void *blockingConnectionVoid, - void* /*unused*/) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - if (ce->window_id->imapURLPane != NULL && - MSG_GetPaneType(ce->window_id->imapURLPane) != MSG_COMPOSITIONPANE) - FE_PaneChanged (ce->window_id->imapURLPane, FALSE, MSG_PanePastPasswordCheck, 0); - - imapConnection->NotifyEventCompletionMonitor(); -} - -// This function updates the progress message at the bottom of the -// window -static -void ProgressEventFunction(void *blockingConnectionVoid, - void *progressMessageVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - NET_Progress(ce->window_id, (char *)progressMessageVoid); - - imapConnection->NotifyEventCompletionMonitor(); -} - -// This function updates the progress message at the bottom of the -// window based on a XP_GetString of the passed id -static -void ProgressStatusFunction_UsingId(void *blockingConnectionVoid, - void *errorMessageIdVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - uint32 errorId = (uint32) errorMessageIdVoid; - char *errorString = XP_GetString(errorId); - - if (errorString) - NET_Progress(ce->window_id, errorString); - - imapConnection->NotifyEventCompletionMonitor(); -} - -// This function updates the progress message at the bottom of the -// window based on a XP_GetString of the passed id and formats -// it with the passed in string -static -void ProgressStatusFunction_UsingIdWithString(void *blockingConnectionVoid, - void *errorMessageStruct) -{ - char * progressString = NULL; - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - StatusMessageInfo * msgInfo = (StatusMessageInfo *) errorMessageStruct; - if (msgInfo) - progressString = PR_sprintf_append(progressString, XP_GetString(msgInfo->msgID), msgInfo->extraInfo); - - if (progressString) - NET_Progress(ce->window_id, progressString); - - FREEIF(msgInfo->extraInfo); - FREEIF(msgInfo); - FREEIF(progressString); - - imapConnection->NotifyEventCompletionMonitor(); -} - -// This function updates the progress message at the bottom of the -// window, along with setting the percent bar -static -void PercentProgressEventFunction(void *blockingConnectionVoid, - void *progressVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - ProgressInfo *progress = (ProgressInfo *)progressVoid; - - if (progress && progress->message) - NET_Progress(ce->window_id, progress->message); - - FE_SetProgressBarPercent(ce->window_id, progress->percent); - - FREEIF(progress->message); - FREEIF(progress); - - imapConnection->NotifyEventCompletionMonitor(); -} - - - - -// This function uses the existing NET code to establish -// a connection with the IMAP server. -static -void StartIMAPConnection(TNavigatorImapConnection *imapConnection) -{ - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - FE_SetProgressBarPercent(ce->window_id, -1); - - HG83344 - - ce->status = NET_BeginConnect(ce->URL_s->address, - ce->URL_s->IPAddressString, - "IMAP4", - (HG26227 IMAP4_PORT), - &ce->socket, - HG27327, - imapConnection->GetTCPConData(), - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - - imapConnection->SetIOSocket(ce->socket); - if(ce->socket != 0) - NET_TotalNumberOfOpenConnections++; - - if(ce->status == MK_CONNECTED) - { - imapConnection->SetNeedsGreeting(TRUE); - NET_SetReadSelect(ce->window_id, ce->socket); - } - else if(ce->status > -1) - { - ce->con_sock = ce->socket; /* set con sock so we can select on it */ - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - else if(ce->status < 0) - { - /* close and clear the socket here - * so that we don't try and send a RSET - */ - if(ce->socket != 0) - { - NET_TotalNumberOfOpenConnections--; - NET_ClearConnectSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing socket ce->socket: %d", - ce->socket)); - net_graceful_shutdown(ce->socket, HG38373); - PR_Close(ce->socket); - ce->socket = NULL; - imapConnection->SetIOSocket(ce->socket); - } - } - - imapConnection->SetConnectionStatus(ce->status); -} - -// This function uses the existing NET code to establish -// a connection with the IMAP server. -static -void FinishIMAPConnection(void *blockingConnectionVoid, - void* /*unused*/) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - HG83344 - - ce->status = NET_FinishConnect(ce->URL_s->address, - "IMAP4", - (HG72524 IMAP4_PORT), - &ce->socket, - imapConnection->GetTCPConData(), - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - - imapConnection->SetIOSocket(ce->socket); - if(ce->status == MK_CONNECTED) - { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - NET_SetReadSelect(ce->window_id, ce->socket); - } - else if(ce->status > -1) - { - - /* unregister the old CE_SOCK from the select list - * and register the new value in the case that it changes - */ - if(ce->con_sock != ce->socket) - { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = ce->socket; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - } - else if(ce->status < 0) - { - /* close and clear the socket here - * so that we don't try and send a RSET - */ - NET_TotalNumberOfOpenConnections--; - NET_ClearConnectSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing socket ce->socket: %d", ce->socket)); - net_graceful_shutdown(ce->socket, HG73654); - PR_Close(ce->socket); - ce->socket = NULL; - imapConnection->SetIOSocket(ce->socket); - } - - imapConnection->SetConnectionStatus(ce->status); - imapConnection->NotifyEventCompletionMonitor(); -} - - - -// member functions of the TImapFEEvent class -TImapFEEvent::TImapFEEvent(FEEventFunctionPointer *function, - void *arg1, void*arg2, - XP_Bool executeWhenInterrupted) : - fEventFunction(function), - fArg1(arg1), fArg2(arg2), - fExecuteWhenInterrupted(executeWhenInterrupted) -{ - -} - -TImapFEEvent::~TImapFEEvent() -{ -} - -void TImapFEEvent::DoEvent() -{ - (*fEventFunction) (fArg1, fArg2); -} - -// member functions of the TImapFEEventQueue class -TImapFEEventQueue::TImapFEEventQueue() -{ - fEventList = XP_ListNew(); - fListMonitor = PR_NewNamedMonitor("list-monitor"); - fNumberOfEvents = 0; -} - -TImapFEEventQueue *TImapFEEventQueue::CreateFEEventQueue() -{ - TImapFEEventQueue *returnQueue = new TImapFEEventQueue; - if (!returnQueue || - !returnQueue->fEventList || - !returnQueue->fListMonitor) - { - delete returnQueue; - returnQueue = nil; - } - - return returnQueue; -} - -TImapFEEventQueue::~TImapFEEventQueue() -{ - if (fEventList) - XP_ListDestroy(fEventList); - if (fListMonitor) - PR_DestroyMonitor(fListMonitor); -} - -void TImapFEEventQueue::AdoptEventToEnd(TImapFEEvent *event) -{ - PR_EnterMonitor(fListMonitor); - XP_ListAddObjectToEnd(fEventList, event); - fNumberOfEvents++; - PR_ExitMonitor(fListMonitor); -} - -void TImapFEEventQueue::AdoptEventToBeginning(TImapFEEvent *event) -{ - PR_EnterMonitor(fListMonitor); - XP_ListAddObject(fEventList, event); - fNumberOfEvents++; - PR_ExitMonitor(fListMonitor); -} - -TImapFEEvent* TImapFEEventQueue::OrphanFirstEvent() -{ - TImapFEEvent *returnEvent = nil; - PR_EnterMonitor(fListMonitor); - if (fNumberOfEvents) - { - fNumberOfEvents--; - if (fNumberOfEvents == 0) - PR_Notify(fListMonitor); - returnEvent = (TImapFEEvent *) XP_ListRemoveTopObject(fEventList); - } - PR_ExitMonitor(fListMonitor); - - return returnEvent; -} - -int TImapFEEventQueue::NumberOfEventsInQueue() -{ - int returnEvents; - PR_EnterMonitor(fListMonitor); - returnEvents = fNumberOfEvents; - PR_ExitMonitor(fListMonitor); - return returnEvents; -} - - -TIMAP4BlockingConnection::TIMAP4BlockingConnection() : - fConnectionStatus(0), // we want NET_ProcessIMAP4 to continue for now - fServerState(*this), - fBlockedForIO(FALSE), - fCloseNeededBeforeSelect(FALSE), - fCurrentServerCommandTagNumber(0) -{ - fDataMemberMonitor = PR_NewNamedMonitor("data-member-monitor"); - fIOMonitor = PR_NewNamedMonitor("io-monitor"); - - fDeleteModelIsMoveToTrash = FALSE; -} - - -XP_Bool TIMAP4BlockingConnection::ConstructionSuccess() -{ - return (fDataMemberMonitor && fIOMonitor); -} - - - - - - -TIMAP4BlockingConnection::~TIMAP4BlockingConnection() -{ - if (fDataMemberMonitor) - PR_DestroyMonitor(fDataMemberMonitor); - if (fIOMonitor) - PR_DestroyMonitor(fIOMonitor); -} - - -TNavigatorImapConnection *TIMAP4BlockingConnection::GetNavigatorConnection() -{ - return NULL; -} - - -void TIMAP4BlockingConnection::NotifyIOCompletionMonitor() -{ - PR_EnterMonitor(fIOMonitor); - fBlockedForIO = FALSE; - PR_Notify(fIOMonitor); - PR_ExitMonitor(fIOMonitor); -} - - -// escape any backslashes or quotes. Backslashes are used a lot with our NT server -char *TIMAP4BlockingConnection::CreateEscapedMailboxName(const char *rawName) -{ - int numberOfEscapes = 0; - char *escapedName = (char *) XP_ALLOC(XP_STRLEN(rawName) + 20); // enough for 20 deep - if (escapedName) - { - char *currentChar = escapedName; - XP_STRCPY(escapedName,rawName); - - while (*currentChar) - { - if ((*currentChar == '\\') || (*currentChar == '\"')) - { - XP_MEMMOVE(currentChar+1, // destination - currentChar, // source - XP_STRLEN(currentChar) + 1); // remaining string + nil - *currentChar++ = '\\'; - - if (++numberOfEscapes == 20) - { - char *oldString = escapedName; - escapedName = (char *) XP_ALLOC(XP_STRLEN(oldString) + 20); // enough for 20 deep - XP_STRCPY(escapedName,oldString); - currentChar = escapedName + (currentChar - oldString); - FREEIF( oldString); - numberOfEscapes = 0; - } - } - currentChar++; - } - } - - return escapedName; -} - - - -void TIMAP4BlockingConnection::IncrementCommandTagNumber() -{ - sprintf(fCurrentServerCommandTag,"%ld", (long) ++fCurrentServerCommandTagNumber); -} - -#ifdef KMCENTEE_DEBUG -int WaitForIOLoopCount; -int WaitForFEEventLoopCount; -#endif - -void TIMAP4BlockingConnection::WaitForIOCompletion() -{ - PRIntervalTime sleepTime = PR_MicrosecondsToInterval(kImapSleepTime); - - PR_EnterMonitor(fIOMonitor); - fBlockedForIO = TRUE; - -#ifdef KMCENTEE_DEBUG - WaitForIOLoopCount=0; -#endif - - while (fBlockedForIO && !DeathSignalReceived() ) - { - PR_Wait(fIOMonitor, sleepTime); -#ifdef KMCENTEE_DEBUG - WaitForIOLoopCount++; - if (WaitForIOLoopCount == 10) - XP_ASSERT(FALSE); -#endif - } - PR_ExitMonitor(fIOMonitor); -} - -XP_Bool TIMAP4BlockingConnection::BlockedForIO() -{ - XP_Bool returnValue; - - PR_EnterMonitor(fIOMonitor); - returnValue = fBlockedForIO; - PR_ExitMonitor(fIOMonitor); - - return returnValue; -} - - -TImapServerState &TIMAP4BlockingConnection::GetServerStateParser() -{ - return fServerState; -} - - -void TIMAP4BlockingConnection::SetConnectionStatus(int status) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fConnectionStatus = status; - PR_ExitMonitor(GetDataMemberMonitor()); -} - - -int TIMAP4BlockingConnection::GetConnectionStatus() -{ - int returnStatus; - PR_EnterMonitor(GetDataMemberMonitor()); - returnStatus = fConnectionStatus; - PR_ExitMonitor(GetDataMemberMonitor()); - return returnStatus; -} - - -extern "C" void MSG_IMAP_KillConnection(TNavigatorImapConnection *imapConnection) -{ - if (imapConnection) - { - imapConnection->DeathSignalReceived(); // stop anything going on and kill thread - //delete imapConnection; // destroy anything else, not mine to destroy. - } -} - - -void TNavigatorImapConnection::SelectMailbox(const char *mailboxName) -{ - TIMAP4BlockingConnection::SelectMailbox(mailboxName); - - int32 numOfMessagesInFlagState = fFlagState->GetNumberOfMessages(); - TIMAPUrl::EIMAPurlType urlType = fCurrentUrl->GetIMAPurlType(); - // if we've selected a mailbox, and we're not going to do an update because of the - // url type, but don't have the flags, go get them! - if (urlType != TIMAPUrl::kSelectFolder && urlType != TIMAPUrl::kExpungeFolder && urlType != TIMAPUrl::kLiteSelectFolder && - urlType != TIMAPUrl::kDeleteAllMsgs && - ((GetServerStateParser().NumberOfMessages() != numOfMessagesInFlagState) && (numOfMessagesInFlagState == 0))) - ProcessMailboxUpdate(FALSE); - -} - - // authenticated state commands -void TIMAP4BlockingConnection::SelectMailbox(const char *mailboxName) -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_SELECTING_MAILBOX); - IncrementCommandTagNumber(); - - fCloseNeededBeforeSelect = FALSE; // initial value - GetServerStateParser().ResetFlagInfo(0); - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s select \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::CreateMailbox(const char *mailboxName) -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_CREATING_MAILBOX); - - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s create \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -static void setup_message_flags_string(char *flagString, - imapMessageFlagsType flags, XP_Bool userDefined) -{ - XP_ASSERT(flagString); - flagString[0] = '\0'; - if (flags & kImapMsgSeenFlag) - XP_STRCAT(flagString, "\\Seen "); - if (flags & kImapMsgAnsweredFlag) - XP_STRCAT(flagString, "\\Answered "); - if (flags & kImapMsgFlaggedFlag) - XP_STRCAT(flagString, "\\Flagged "); - if (flags & kImapMsgDeletedFlag) - XP_STRCAT(flagString, "\\Deleted "); - if (flags & kImapMsgDraftFlag) - XP_STRCAT(flagString, "\\Draft "); - if (flags & kImapMsgRecentFlag) - XP_STRCAT(flagString, "\\Recent "); - if ((flags & kImapMsgForwardedFlag) && userDefined) - XP_STRCAT(flagString, "Forwarded "); // Not always available - if ((flags & kImapMsgMDNSentFlag) && userDefined) - XP_STRCAT(flagString, "MDNSent "); // Not always available - - // eat the last space - if (*flagString) - *(flagString + XP_STRLEN(flagString) - 1) = '\0'; -} - -void TIMAP4BlockingConnection::AppendMessage(const char *mailboxName, - const char *messageSizeString, - imapMessageFlagsType flags) -{ - //ProgressUpdateEvent("Appending a message..."); - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - // enough room for "\\Seen \\Answered \\Flagged \\Deleted \\Draft \\Recent \\Replied" - char flagString[90]; - - setup_message_flags_string(flagString, flags, SupportsUserDefinedFlags()); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s append \"%s\" (%s) {%s}" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName, - flagString, - messageSizeString); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); - - if (GetServerStateParser().GetIMAPstate() == TImapServerState::kWaitingForMoreClientInput) - { - OnlineCopyCompleted(kReadyForAppendData); - UploadMessage(); - ParseIMAPandCheckForNewMail(); - if (GetServerStateParser().LastCommandSuccessful()) - OnlineCopyCompleted(kInProgress); - else - OnlineCopyCompleted(kFailedAppend); - } -} - - -void TIMAP4BlockingConnection::DeleteMailbox(const char *mailboxName) -{ - ProgressEventFunction_UsingIdWithString (MK_IMAP_STATUS_DELETING_MAILBOX, mailboxName); - - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s delete \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::RenameMailbox(const char *existingName, - const char *newName) -{ - ProgressEventFunction_UsingIdWithString (MK_IMAP_STATUS_RENAMING_MAILBOX, existingName); - - IncrementCommandTagNumber(); - - char *escapedExistingName = CreateEscapedMailboxName(existingName); - char *escapedNewName = CreateEscapedMailboxName(newName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s rename \"%s\" \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedExistingName, - escapedNewName); - - FREEIF( escapedExistingName); - FREEIF( escapedNewName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -int64 TIMAP4BlockingConnection::fgTimeStampOfNonPipelinedList = LL_ZERO; - - -void TIMAP4BlockingConnection::TimeStampListNow() -{ - fgTimeStampOfNonPipelinedList = PR_Now(); -} - -extern "C" { -int64 IMAP_GetTimeStampOfNonPipelinedList() -{ - return TIMAP4BlockingConnection::GetTimeStampOfNonPipelinedList(); -} -} - -void TIMAP4BlockingConnection::List(const char *mailboxPattern, XP_Bool pipeLined /* = FALSE */, XP_Bool dontTimeStamp /* = FALSE */) -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_LOOKING_FOR_MAILBOX); - - IncrementCommandTagNumber(); - - char *escapedPattern = CreateEscapedMailboxName(mailboxPattern); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s list \"\" \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedPattern); - - FREEIF( escapedPattern); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - if (pipeLined) - GetServerStateParser().IncrementNumberOfTaggedResponsesExpected(GetServerCommandTag()); - else - { - if (!dontTimeStamp) - TimeStampListNow(); - ParseIMAPandCheckForNewMail(); - } -} - -void TIMAP4BlockingConnection::Lsub(const char *mailboxPattern, - XP_Bool pipelined) -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_LOOKING_FOR_MAILBOX); - - IncrementCommandTagNumber(); - - char *escapedPattern = CreateEscapedMailboxName(mailboxPattern); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s lsub \"\" \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedPattern); - - FREEIF( escapedPattern); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - if (pipelined) - GetServerStateParser().IncrementNumberOfTaggedResponsesExpected(GetServerCommandTag()); - else - { - TimeStampListNow(); - ParseIMAPandCheckForNewMail(); - } -} - -void TIMAP4BlockingConnection::Subscribe(const char *mailboxName) -{ - ProgressEventFunction_UsingIdWithString (MK_IMAP_STATUS_SUBSCRIBE_TO_MAILBOX, mailboxName); - - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s subscribe \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::Unsubscribe(const char *mailboxName) -{ - ProgressEventFunction_UsingIdWithString (MK_IMAP_STATUS_UNSUBSCRIBE_MAILBOX, mailboxName); - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s unsubscribe \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::Search(const char *searchCriteria, - XP_Bool useUID, - XP_Bool notifyHit /* TRUE */) -{ - fNotifyHit = notifyHit; - ProgressEventFunction_UsingId (MK_IMAP_STATUS_SEARCH_MAILBOX); - IncrementCommandTagNumber(); - - char *formatString; - // the searchCriteria string contains the 'search ....' string - if (useUID) - formatString = "%s uid %s\015\012"; - else - formatString = "%s %s\015\012"; - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - formatString, // format string - GetServerCommandTag(), // command tag - searchCriteria); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::Copy(const char *messageList, - const char *destinationMailbox, - XP_Bool idsAreUid) -{ - IncrementCommandTagNumber(); - - char *escapedDestination = CreateEscapedMailboxName(destinationMailbox); - - char *formatString; - if (idsAreUid) - formatString = "%s uid copy %s \"%s\"\015\012"; - else - formatString = "%s copy %s \"%s\"\015\012"; - - // since messageIds can be infinitely long, use a dynamic buffer rather than the fixed one - const char *commandTag = GetServerCommandTag(); - int protocolStringSize = XP_STRLEN(formatString) + XP_STRLEN(messageList) + XP_STRLEN(commandTag) + XP_STRLEN(escapedDestination) + 1; - char *protocolString = (char *) XP_ALLOC( protocolStringSize ); - - if (protocolString) - { - PR_snprintf(protocolString, // string to create - protocolStringSize, // max size - formatString, // format string - commandTag, // command tag - messageList, - escapedDestination); - - - int ioStatus = WriteLineToSocket(protocolString); - - ParseIMAPandCheckForNewMail(protocolString); - XP_FREE(protocolString); - } - else - HandleMemoryFailure(); - - FREEIF( escapedDestination); -} - -void TIMAP4BlockingConnection::Store(const char *messageList, - const char *messageData, - XP_Bool idsAreUid) -{ - //ProgressUpdateEvent("Saving server message flags..."); - IncrementCommandTagNumber(); - - char *formatString; - if (idsAreUid) - formatString = "%s uid store %s %s\015\012"; - else - formatString = "%s store %s %s\015\012"; - - // we might need to close this mailbox after this - fCloseNeededBeforeSelect = fDeleteModelIsMoveToTrash && (XP_STRCASESTR(messageData, "\\Deleted")); - - const char *commandTag = GetServerCommandTag(); - int protocolStringSize = XP_STRLEN(formatString) + XP_STRLEN(messageList) + XP_STRLEN(messageData) + XP_STRLEN(commandTag) + 1; - char *protocolString = (char *) XP_ALLOC( protocolStringSize ); - - if (protocolString) - { - PR_snprintf(protocolString, // string to create - protocolStringSize, // max size - formatString, // format string - commandTag, // command tag - messageList, - messageData); - - int ioStatus = WriteLineToSocket(protocolString); - - ParseIMAPandCheckForNewMail(protocolString); - XP_FREE(protocolString); - } - else - HandleMemoryFailure(); -} - -void TIMAP4BlockingConnection::Close() -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_CLOSE_MAILBOX); - - IncrementCommandTagNumber(); - GetServerStateParser().ResetFlagInfo(0); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s close" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::Check() -{ - //ProgressUpdateEvent("Checking mailbox..."); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s check" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::Expunge() -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_EXPUNGING_MAILBOX); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s expunge" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -// any state commands -void TIMAP4BlockingConnection::Logout() -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_LOGGING_OUT); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s logout" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - // the socket may be dead before we read the response, so drop it. - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::Noop() -{ - //ProgressUpdateEvent("noop..."); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s noop" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - - -void TIMAP4BlockingConnection::Capability() -{ - - ProgressEventFunction_UsingId (MK_IMAP_STATUS_CHECK_COMPAT); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s capability" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::XServerInfo() -{ - - ProgressEventFunction_UsingId (MK_IMAP_GETTING_SERVER_INFO); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s XSERVERINFO MANAGEACCOUNTURL MANAGELISTSURL MANAGEFILTERSURL" CRLF, - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::XMailboxInfo(const char *mailboxName) -{ - - ProgressEventFunction_UsingId (MK_IMAP_GETTING_MAILBOX_INFO); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s XMAILBOXINFO %s MANAGEURL POSTURL" CRLF, - GetServerCommandTag(), - mailboxName); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - - - - - -void TIMAP4BlockingConnection::Namespace() -{ - - ProgressEventFunction_UsingId (MK_IMAP_STATUS_GETTING_NAMESPACE); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s namespace" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - - -void TIMAP4BlockingConnection::MailboxData() -{ - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s mailboxdata" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - ParseIMAPandCheckForNewMail(); -} - - -void TIMAP4BlockingConnection::GetMyRightsForFolder(const char *mailboxName) -{ - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s myrights \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::GetACLForFolder(const char *mailboxName) -{ - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s getacl \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TIMAP4BlockingConnection::StatusForFolder(const char *mailboxName) -{ - IncrementCommandTagNumber(); - - char *escapedName = CreateEscapedMailboxName(mailboxName); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s STATUS \"%s\" (UIDNEXT MESSAGES UNSEEN)" CRLF, // format string - GetServerCommandTag(), // command tag - escapedName); - - FREEIF( escapedName); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - -void TNavigatorImapConnection::StatusForFolder(const char *mailboxName) -{ - TIMAP4BlockingConnection::StatusForFolder(mailboxName); - mailbox_spec *new_spec = GetServerStateParser().CreateCurrentMailboxSpec(mailboxName); - if (new_spec) - UpdateMailboxStatus(new_spec); -} - -void TIMAP4BlockingConnection::Netscape() -{ - //ProgressUpdateEvent("Netscape..."); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s netscape" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); -} - - -void TIMAP4BlockingConnection::InsecureLogin(const char *userName, - const char *password) -{ - - ProgressEventFunction_UsingId (MK_IMAP_STATUS_SENDING_LOGIN); - IncrementCommandTagNumber(); - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s login \"%s\" \"%s\"" CRLF, // format string - GetServerCommandTag(), // command tag - userName, - password); - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - ParseIMAPandCheckForNewMail(); -} - - -void TIMAP4BlockingConnection::AuthLogin(const char *userName, - const char *password) -{ - ProgressEventFunction_UsingId (MK_IMAP_STATUS_SENDING_AUTH_LOGIN); - IncrementCommandTagNumber(); - - const char *currentTagToken = GetServerCommandTag(); - char *currentCommand = NULL; - - PR_snprintf(GetOutputBuffer(), // string to create - kOutputBufferSize, // max size - "%s authenticate login" CRLF, // format string - GetServerCommandTag()); // command tag - - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - - - StrAllocCopy(currentCommand, GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); - - if (GetServerStateParser().LastCommandSuccessful()) { - char *base64Str = NET_Base64Encode((char*)userName, XP_STRLEN(userName)); - PR_snprintf(GetOutputBuffer(), - kOutputBufferSize, - "%s" CRLF, - base64Str); - XP_FREEIF(base64Str); - ioStatus = WriteLineToSocket(GetOutputBuffer()); - ParseIMAPandCheckForNewMail(currentCommand); - if (GetServerStateParser().LastCommandSuccessful()) { - char *base64Str = NET_Base64Encode((char*)password, XP_STRLEN(password)); - PR_snprintf(GetOutputBuffer(), - kOutputBufferSize, - "%s" CRLF, - base64Str); - XP_FREEIF(base64Str); - ioStatus = WriteLineToSocket(GetOutputBuffer()); - ParseIMAPandCheckForNewMail(currentCommand); - if (GetServerStateParser().LastCommandSuccessful()) - { - FREEIF(currentCommand); - return; - } - } - } - - FREEIF(currentCommand); - // fall back to use InsecureLogin() - InsecureLogin(userName, password); -} - - - -void TIMAP4BlockingConnection::ProcessBIFFRequest() -{ - if (GetConnectionStatus() == MK_WAITING_FOR_CONNECTION) - EstablishServerConnection(); - if (GetConnectionStatus() >= 0) - SetConnectionStatus(-1); // stub! -} - - - -char *TIMAP4BlockingConnection::GetOutputBuffer() -{ - return fOutputBuffer; -} - -char *TIMAP4BlockingConnection::GetServerCommandTag() -{ - return fCurrentServerCommandTag; -} - -PRMonitor *TIMAP4BlockingConnection::GetDataMemberMonitor() -{ - return fDataMemberMonitor; -} - -XP_Bool TIMAP4BlockingConnection::HandlingMultipleMessages(char *messageIdString) -{ - return (XP_STRCHR(messageIdString,',') != NULL || - XP_STRCHR(messageIdString,':') != NULL); -} - - - - -/******************* TNavigatorImapConnection *******************************/ - - -void TNavigatorImapConnection::StartProcessingActiveEntries() -{ - XP_Bool receivedNullEntry = FALSE; - - while (!receivedNullEntry && !DeathSignalReceived()) - { - WaitForNextActiveEntry(); - - if (!DeathSignalReceived()) - { - // while I'm processing this URL nobody can change it! - PR_EnterMonitor(fActiveEntryMonitor); - if (fCurrentEntry) - { - XP_Bool killedEarly = FALSE; - // fCurrentUrl is accessed repeatedly by CurrentConnectionIsMove - // CurrentConnectionIsMove is called from Mozilla thread - LIBNET_LOCK(); - if (!DeathSignalReceived()) - { - delete fCurrentUrl; - fCurrentUrl = new TIMAPUrl(fCurrentEntry->URL_s->address, fCurrentEntry->URL_s->internal_url); - } - else - killedEarly = TRUE; - LIBNET_UNLOCK(); - - if (!fCurrentUrl && !killedEarly) - HandleMemoryFailure(); - else if (!killedEarly) - { - // process the url - ProcessCurrentURL(); - - // wait for the event queue to empty before we trash - // fCurrentEntry. Some of the events reference it. - WaitForEventQueueEmptySignal(); - } - - // this URL is finished so delete it in case - // it is referenced before we create the new one - // the next time through this loop - PR_EnterMonitor(GetDataMemberMonitor()); - delete fCurrentUrl; - fCurrentUrl = NULL; - PR_ExitMonitor(GetDataMemberMonitor()); - - - fCurrentEntry = NULL; - } - else - { - receivedNullEntry = TRUE; - if (GetIOSocket() != 0) - Logout(); - } - PR_ExitMonitor(fActiveEntryMonitor); - } - } - - - - PRIntervalTime sleepTime = PR_MicrosecondsToInterval(kImapSleepTime); - PR_EnterMonitor(fPermissionToDieMonitor); - while (!fIsSafeToDie) - PR_Wait(fPermissionToDieMonitor, sleepTime); - PR_ExitMonitor(fPermissionToDieMonitor); -} - - -XP_Bool TNavigatorImapConnection::BlockedWaitingForActiveEntry() -{ - return !PR_InMonitor(fActiveEntryMonitor); -} - -char *TNavigatorImapConnection::GetCurrentConnectionURL() -{ - PR_EnterMonitor(GetDataMemberMonitor()); - char *rv = fCurrentEntry->URL_s->address ? - XP_STRDUP(fCurrentEntry->URL_s->address) : (char *)NULL; - PR_ExitMonitor(GetDataMemberMonitor()); - return rv; -} - - -void TNavigatorImapConnection::WaitForEventQueueEmptySignal() -{ - // notice that this Wait function is not like the others in that - // it does not wake up and check DeathSignalReceived() - // sometimes it is run after DeathSignalReceived and the thread - // has to drain its final fe events before death. - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fEventQueueEmptySignalMonitor); - while(!fEventQueueEmptySignalHappened) - PR_Wait(fEventQueueEmptySignalMonitor, sleepTime); - fEventQueueEmptySignalHappened = FALSE; - PR_ExitMonitor(fEventQueueEmptySignalMonitor); -} - -void TNavigatorImapConnection::SignalEventQueueEmpty() -{ - PR_EnterMonitor(fEventQueueEmptySignalMonitor); - fEventQueueEmptySignalHappened = TRUE; - PR_Notify(fEventQueueEmptySignalMonitor); - PR_ExitMonitor(fEventQueueEmptySignalMonitor); -} - -void TNavigatorImapConnection::WaitForNextAppendMessageSize() -{ - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fMsgCopyDataMonitor); - while(!fMsgAppendSizeIsNew && !DeathSignalReceived()) - PR_Wait(fMsgCopyDataMonitor, sleepTime); - PR_ExitMonitor(fMsgCopyDataMonitor); -} - - -void TNavigatorImapConnection::WaitForPotentialListOfMsgsToFetch(uint32 **msgIdList, uint32 &msgCount) -{ - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fMsgCopyDataMonitor); - while(!fFetchMsgListIsNew && !DeathSignalReceived()) - PR_Wait(fMsgCopyDataMonitor, sleepTime); - fFetchMsgListIsNew = FALSE; - - *msgIdList = fFetchMsgIdList; - msgCount = fFetchCount; - - PR_ExitMonitor(fMsgCopyDataMonitor); -} - - -void TNavigatorImapConnection::NotifyKeyList(uint32 *keys, uint32 keyCount) -{ - PR_EnterMonitor(fMsgCopyDataMonitor); - fFetchMsgIdList = keys; - fFetchCount = keyCount; - fFetchMsgListIsNew = TRUE; - PR_Notify(fMsgCopyDataMonitor); - PR_ExitMonitor(fMsgCopyDataMonitor); -} - -void TNavigatorImapConnection::WaitForMessageUploadToComplete() -{ - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fMessageUploadMonitor); - while(!fMessageUploadCompleted && !DeathSignalReceived()) - PR_Wait(fMessageUploadMonitor, sleepTime); - fMessageUploadCompleted = FALSE; - PR_ExitMonitor(fMessageUploadMonitor); -} - -void TNavigatorImapConnection::NotifyMessageUploadMonitor() -{ - PR_EnterMonitor(fMessageUploadMonitor); - fMessageUploadCompleted = TRUE; - PR_Notify(fMessageUploadMonitor); - PR_ExitMonitor(fMessageUploadMonitor); -} - -void TNavigatorImapConnection::NotifyAppendSize(uint32 msgSize, imapMessageFlagsType flags) -{ - PR_EnterMonitor(fMsgCopyDataMonitor); - fAppendMessageSize = msgSize; - fAppendMsgFlags = flags & ~kImapMsgRecentFlag; // don't let recent flag through, since we can't store it. - fMsgAppendSizeIsNew = TRUE; - PR_Notify(fMsgCopyDataMonitor); - PR_ExitMonitor(fMsgCopyDataMonitor); -} - -imapMessageFlagsType TNavigatorImapConnection::GetAppendFlags() -{ - imapMessageFlagsType returnValue; - PR_EnterMonitor(fMsgCopyDataMonitor); - returnValue = fAppendMsgFlags; - PR_ExitMonitor(fMsgCopyDataMonitor); - - return returnValue; -} - -uint32 TNavigatorImapConnection::GetAppendSize() -{ - uint32 returnValue; - PR_EnterMonitor(fMsgCopyDataMonitor); - returnValue = fAppendMessageSize; - fMsgAppendSizeIsNew = FALSE; - PR_ExitMonitor(fMsgCopyDataMonitor); - - return returnValue; -} - -void TNavigatorImapConnection::SetFolderInfo(MSG_FolderInfo *folder, XP_Bool folderNeedsSubscribing, - XP_Bool folderNeedsACLRefreshed) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fFolderInfo = folder; - fFolderNeedsSubscribing = folderNeedsSubscribing; - fFolderNeedsACLRefreshed = folderNeedsACLRefreshed; - PR_ExitMonitor(GetDataMemberMonitor()); -} - -void TNavigatorImapConnection::WaitForNextActiveEntry() -{ - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fActiveEntryMonitor); - while(!fNextEntryEventSignalHappened && !DeathSignalReceived()) - PR_Wait(fActiveEntryMonitor, sleepTime); - fNextEntryEventSignalHappened = FALSE; - PR_ExitMonitor(fActiveEntryMonitor); -} - -void TNavigatorImapConnection::SubmitActiveEntry(ActiveEntry * ce, XP_Bool newConnection) -{ - PR_EnterMonitor(fActiveEntryMonitor); - fCurrentEntry = ce; - if (newConnection) - StartIMAPConnection(this); - else - SetConnectionStatus(0); // keep netlib running, connection is reused - fNextEntryEventSignalHappened = TRUE; - PR_Notify(fActiveEntryMonitor); - PR_ExitMonitor(fActiveEntryMonitor); -} - -XPPtrArray *TNavigatorImapConnection::connectionList; - -TNavigatorImapConnection::TNavigatorImapConnection(const char *hostName) : - TIMAP4BlockingConnection(), - fCurrentEntry(nil), - fFEeventCompleted(FALSE), - fTunnelCompleted(FALSE), - fInputBufferSize(0), - fInputSocketBuffer(nil), - fBlockingThread(nil), - fTCPConData(nil), - fIOSocket(NULL), - fCurrentUrl(nil), - fEventQueueEmptySignalHappened(FALSE), - fMessageUploadCompleted(FALSE), - fHierarchyNameState(kNoOperationInProgress), - fHierarchyMover(nil), - fBytesMovedSoFarForProgress(0), - fDeletableChildren(nil), - fOnlineBaseFolderExists(FALSE), - fFetchMsgIdList(NULL), - fFetchCount(0), - fFetchMsgListIsNew(FALSE), - fMsgAppendSizeIsNew(FALSE), - fAppendMessageSize(0), - fNextEntryEventSignalHappened(FALSE), - fThreadShouldDie(FALSE), - fIsSafeToDie(FALSE), - fProgressStringId(0), - fProgressIndex(0), - fNeedGreeting(FALSE), - fNeedNoop(FALSE), - fProgressCount(0), - fOutputStream(nil), - fPseudoInterrupted(FALSE), - fAutoSubscribe(TRUE), - fAutoUnsubscribe(TRUE), - fShouldUpgradeToSubscription(FALSE), - fUpgradeShouldLeaveAlone(FALSE), - fUpgradeShouldSubscribeAll(FALSE), - fFolderInfo(NULL), - fFolderNeedsSubscribing(FALSE), - fFolderNeedsACLRefreshed(FALSE) -{ - fEventCompletionMonitor = PR_NewNamedMonitor("event-completion-monitor"); - fActiveEntryMonitor = PR_NewNamedMonitor("active-entry-monitor"); - fEventQueueEmptySignalMonitor = PR_NewNamedMonitor("event-queue-empty-signal-monitor"); - fMessageUploadMonitor = PR_NewNamedMonitor("message-upload-monitor"); - fMsgCopyDataMonitor = PR_NewNamedMonitor("msg-copy-data-monitor"); - fThreadDeathMonitor = PR_NewNamedMonitor("thread-death-monitor"); - fPermissionToDieMonitor = PR_NewNamedMonitor("die-monitor"); - fPseudoInterruptMonitor = PR_NewNamedMonitor("imap-pseudo-interrupt-monitor"); - fWaitForBodyIdsMonitor = PR_NewNamedMonitor("wait-for-body-ids-monitor"); - fTunnelCompletionMonitor = PR_NewNamedMonitor("imap-io-tunnelling-monitor"); - - fFEEventQueue = TImapFEEventQueue::CreateFEEventQueue(); - fSocketInfo = new TIMAPSocketInfo(); - fListedMailboxList = XP_ListNew(); - fHostName = XP_STRDUP(hostName); - fFlagState = new TImapFlagAndUidState(kFlagEntrySize, FALSE); - fMailToFetch = fGetHeaders = fNewMail = FALSE; - fLastProgressStringId = 0; - fLastPercent = -1; - LL_I2L(fLastProgressTime, 0); - ResetProgressInfo(); - - fActive = fTrackingTime = FALSE; - fStartTime = fEndTime = 0; - fTooFastTime = 2; - fIdealTime = 4; - fChunkAddSize = 2048; - fChunkStartSize = fChunkSize = 10240; - fFetchByChunks = TRUE; - fChunkThreshold = fChunkSize + (fChunkSize / 2); - fMaxChunkSize = 40960; - - connectionList->Add(this); -} - - -void TNavigatorImapConnection::Configure(XP_Bool GetHeaders, int32 TooFastTime, int32 IdealTime, - int32 ChunkAddSize, int32 ChunkSize, int32 ChunkThreshold, - XP_Bool FetchByChunks, int32 MaxChunkSize) -{ - PR_EnterMonitor(fMsgCopyDataMonitor); - fGetHeaders = GetHeaders; - fTooFastTime = TooFastTime; // secs we read too little too fast - fIdealTime = IdealTime; // secs we read enough in good time - fChunkAddSize = ChunkAddSize; // buffer size to add when wasting time - fChunkSize = ChunkSize; - fChunkThreshold = ChunkThreshold; - fFetchByChunks = FetchByChunks; - fMaxChunkSize = MaxChunkSize; - PR_ExitMonitor(fMsgCopyDataMonitor); -} - - -TIMAPHostInfo::TIMAPHostInfo(const char *hostName) -{ - fHostName = XP_STRDUP(hostName); - fNextHost = NULL; - fCachedPassword = NULL; - fCapabilityFlags = kCapabilityUndefined; - fHierarchyDelimiters = NULL; - fHaveWeEverDiscoveredFolders = FALSE; - fCanonicalOnlineSubDir = NULL; - fNamespaceList = TIMAPNamespaceList::CreateTIMAPNamespaceList(); - fUsingSubscription = TRUE; - fOnlineTrashFolderExists = FALSE; - fShouldAlwaysListInbox = TRUE; - fShellCache = TIMAPBodyShellCache::Create(); - fPasswordVerifiedOnline = FALSE; -} - -TIMAPHostInfo::~TIMAPHostInfo() -{ - FREEIF(fHostName); - if (fCachedPassword) - XP_FREE(fCachedPassword); - FREEIF(fHierarchyDelimiters); - delete fNamespaceList; - delete fShellCache; -} - -TIMAPHostInfo *TIMAPHostInfo::FindHost(const char *hostName) -{ - TIMAPHostInfo *host; - - for (host = fHostInfoList; host; host = host->fNextHost) - { - if (!XP_STRCASECMP(hostName, host->fHostName)) - return host; - } - return host; -} - -// reset any cached connection info - delete the lot of 'em -void TIMAPHostInfo::ResetAll() -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *nextHost = NULL; - for (TIMAPHostInfo *host = fHostInfoList; host; host = nextHost) - { - nextHost = host->fNextHost; - delete host; - } - fHostInfoList = NULL; - PR_ExitMonitor(gCachedHostInfoMonitor); -} - -/* static */ XP_Bool TIMAPHostInfo::AddHostToList(const char *hostName) -{ - TIMAPHostInfo *newHost=NULL; - PR_EnterMonitor(gCachedHostInfoMonitor); - if (!FindHost(hostName)) - { - // stick it on the front - newHost = new TIMAPHostInfo(hostName); - if (newHost) - { - newHost->fNextHost = fHostInfoList; - fHostInfoList = newHost; - } - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return newHost != NULL; -} - -XP_Bool IMAP_HostHasACLCapability(const char *hostName) -{ - return (TIMAPHostInfo::GetCapabilityForHost(hostName) & kACLCapability); -} - -uint32 IMAP_GetCapabilityForHost(const char *hostName) -{ - return TIMAPHostInfo::GetCapabilityForHost(hostName); -} - -/* static */ uint32 TIMAPHostInfo::GetCapabilityForHost(const char *hostName) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - - TIMAPHostInfo *host = FindHost(hostName); - uint32 ret = (host) ? host->fCapabilityFlags : 0; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} -/* static */ XP_Bool TIMAPHostInfo::SetCapabilityForHost(const char *hostName, uint32 capability) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fCapabilityFlags = capability; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ char *TIMAPHostInfo::GetPasswordForHost(const char *hostName) -{ - char *ret = NULL; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fCachedPassword; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::SetPasswordForHost(const char *hostName, const char *password) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - FREEIF(host->fCachedPassword); - if (password) - host->fCachedPassword = XP_STRDUP(password); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::SetPasswordVerifiedOnline(const char *hostName) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fPasswordVerifiedOnline = TRUE; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::GetPasswordVerifiedOnline(const char *hostName) -{ - XP_Bool ret = FALSE; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fPasswordVerifiedOnline; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ char *TIMAPHostInfo::GetHierarchyDelimiterStringForHost(const char *hostName) -{ - char *ret = NULL; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fHierarchyDelimiters; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::AddHierarchyDelimiter(const char *hostName, char delimiter) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - if (!host->fHierarchyDelimiters) - { - host->fHierarchyDelimiters = PR_smprintf("%c",delimiter); - } - else if (!XP_STRCHR(host->fHierarchyDelimiters, delimiter)) - { - char *tmpDelimiters = PR_smprintf("%s%c",host->fHierarchyDelimiters,delimiter); - FREEIF(host->fHierarchyDelimiters); - host->fHierarchyDelimiters = tmpDelimiters; - } - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::GetHostIsUsingSubscription(const char *hostName) -{ - XP_Bool ret = FALSE; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fUsingSubscription; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::SetHostIsUsingSubscription(const char *hostName, XP_Bool usingSubscription) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fUsingSubscription = usingSubscription; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::GetHostHasAdminURL(const char *hostName) -{ - XP_Bool ret = FALSE; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fHaveAdminURL; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::SetHostHasAdminURL(const char *hostName, XP_Bool haveAdminURL) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fHaveAdminURL = haveAdminURL; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - - -/* static */ XP_Bool TIMAPHostInfo::GetHaveWeEverDiscoveredFoldersForHost(const char *hostName) -{ - XP_Bool ret = FALSE; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fHaveWeEverDiscoveredFolders; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::SetHaveWeEverDiscoveredFoldersForHost(const char *hostName, XP_Bool discovered) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fHaveWeEverDiscoveredFolders = discovered; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::SetOnlineTrashFolderExistsForHost(const char *hostName, XP_Bool exists) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fOnlineTrashFolderExists = exists; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::GetOnlineTrashFolderExistsForHost(const char *hostName) -{ - XP_Bool ret = FALSE; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fOnlineTrashFolderExists; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::AddNewNamespaceForHost(const char *hostName, TIMAPNamespace *ns) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - host->fNamespaceList->AddNewNamespace(ns); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - - -/* static */ TIMAPNamespace *TIMAPHostInfo::GetNamespaceForMailboxForHost(const char *hostName, const char *mailbox_name) -{ - TIMAPNamespace *ret = 0; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - ret = host->fNamespaceList->GetNamespaceForMailbox(mailbox_name); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - - -/* static */ XP_Bool TIMAPHostInfo::ClearPrefsNamespacesForHost(const char *hostName) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - host->fNamespaceList->ClearNamespaces(TRUE, FALSE); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - - -/* static */ XP_Bool TIMAPHostInfo::ClearServerAdvertisedNamespacesForHost(const char *hostName) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - host->fNamespaceList->ClearNamespaces(FALSE, TRUE); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ TIMAPNamespace *TIMAPHostInfo::GetDefaultNamespaceOfTypeForHost(const char *hostName, EIMAPNamespaceType type) -{ - TIMAPNamespace *ret = NULL; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - ret = host->fNamespaceList->GetDefaultNamespaceOfType(type); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::GetNamespacesOverridableForHost(const char *hostName) -{ - XP_Bool ret = FALSE; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fNamespacesOverridable; - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::SetNamespacesOverridableForHost(const char *hostName, XP_Bool overridable) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fNamespacesOverridable = overridable; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ int TIMAPHostInfo::GetNumberOfNamespacesForHost(const char *hostName) -{ - int ret = 0; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - ret = host->fNamespaceList->GetNumberOfNamespaces(); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - XP_ASSERT(ret > 0); - return ret; -} - -/* static */ TIMAPNamespace *TIMAPHostInfo::GetNamespaceNumberForHost(const char *hostName, int n) -{ - TIMAPNamespace *ret = 0; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - ret = host->fNamespaceList->GetNamespaceNumber(n); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -// Make sure this is running in the Mozilla thread when called -/* static */ XP_Bool TIMAPHostInfo::CommitNamespacesForHost(const char *hostName, MSG_Master *master) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - EIMAPNamespaceType type = kPersonalNamespace; - for (int i = 1; i <= 3; i++) - { - switch(i) - { - case 1: - type = kPersonalNamespace; - break; - case 2: - type = kPublicNamespace; - break; - case 3: - type = kOtherUsersNamespace; - break; - default: - type = kPersonalNamespace; - break; - } - - int32 numInNS = host->fNamespaceList->GetNumberOfNamespaces(type); - if (numInNS == 0) - { - MSG_SetNamespacePrefixes(master, host->fHostName, type, NULL); - } - else if (numInNS >= 1) - { - char *pref = PR_smprintf(""); - for (int count = 1; count <= numInNS; count++) - { - TIMAPNamespace *ns = host->fNamespaceList->GetNamespaceNumber(count, type); - if (ns) - { - if (count > 1) - { - // append the comma - char *tempPref = PR_smprintf("%s,",pref); - FREEIF(pref); - pref = tempPref; - } - char *tempPref = PR_smprintf("%s\"%s\"",pref,ns->GetPrefix()); - FREEIF(pref); - pref = tempPref; - } - } - if (pref) - { - MSG_SetNamespacePrefixes(master, host->fHostName, type, pref); - XP_FREE(pref); - } - } - } - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -// Caller must free the returned string -// Returns NULL if there is no personal namespace on the given host -/* static */ char *TIMAPHostInfo::GetOnlineInboxPathForHost(const char *hostName) -{ - char *ret = NULL; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - TIMAPNamespace *ns = NULL; - ns = host->fNamespaceList->GetDefaultNamespaceOfType(kPersonalNamespace); - if (ns) - { - ret = PR_smprintf("%sINBOX",ns->GetPrefix()); - } - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::GetShouldAlwaysListInboxForHost(const char* /*hostName*/) -{ - XP_Bool ret = TRUE; - - /* - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - ret = host->fShouldAlwaysListInbox; - PR_ExitMonitor(gCachedHostInfoMonitor); - */ - return ret; -} - -/* static */ XP_Bool TIMAPHostInfo::SetShouldAlwaysListInboxForHost(const char *hostName, XP_Bool shouldList) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - host->fShouldAlwaysListInbox = shouldList; - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::SetNamespaceHierarchyDelimiterFromMailboxForHost(const char *hostName, const char *boxName, char delimiter) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - TIMAPNamespace *ns = host->fNamespaceList->GetNamespaceForMailbox(boxName); - if (ns && !ns->GetIsDelimiterFilledIn()) - { - ns->SetDelimiter(delimiter); - } - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ XP_Bool TIMAPHostInfo::AddShellToCacheForHost(const char *hostName, TIMAPBodyShell *shell) -{ - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - if (host->fShellCache) - { - XP_Bool rv = host->fShellCache->AddShellToCache(shell); - PR_ExitMonitor(gCachedHostInfoMonitor); - return rv; - } - else - { - PR_ExitMonitor(gCachedHostInfoMonitor); - return FALSE; - } - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return (host != 0); -} - -/* static */ TIMAPBodyShell *TIMAPHostInfo::FindShellInCacheForHost(const char *hostName, const char *mailboxName, const char *UID) -{ - TIMAPBodyShell *ret = NULL; - - PR_EnterMonitor(gCachedHostInfoMonitor); - TIMAPHostInfo *host = FindHost(hostName); - if (host) - { - if (host->fShellCache) - ret = host->fShellCache->FindShellForUID(UID, mailboxName); - } - PR_ExitMonitor(gCachedHostInfoMonitor); - return ret; -} - - - -extern "C" { - -extern int IMAP_AddIMAPHost(const char *hostName, XP_Bool usingSubscription, XP_Bool overrideNamespaces, - const char *personalNamespacePrefixes, const char *publicNamespacePrefixes, - const char *otherUsersNamespacePrefixes, XP_Bool haveAdminURL) -{ - TIMAPHostInfo::AddHostToList(hostName); - TIMAPHostInfo::SetHostIsUsingSubscription(hostName,usingSubscription); - TIMAPHostInfo::SetNamespacesOverridableForHost(hostName, overrideNamespaces); - TIMAPHostInfo::SetHostHasAdminURL(hostName, haveAdminURL); - - if (personalNamespacePrefixes) - { - int numNamespaces = IMAP_UnserializeNamespaces(personalNamespacePrefixes, NULL, 0); - char **prefixes = (char**) XP_CALLOC(numNamespaces, sizeof(char*)); - if (prefixes) - { - int len = IMAP_UnserializeNamespaces(personalNamespacePrefixes, prefixes, numNamespaces); - for (int i = 0; i < len; i++) - { - char *thisns = prefixes[i]; - char delimiter = '/'; // a guess - if (XP_STRLEN(thisns) >= 1) - delimiter = thisns[XP_STRLEN(thisns)-1]; - TIMAPNamespace *ns = new TIMAPNamespace(kPersonalNamespace, thisns, delimiter, TRUE); - if (ns) - TIMAPHostInfo::AddNewNamespaceForHost(hostName, ns); - FREEIF(thisns); - } - } - } - if (publicNamespacePrefixes) - { - int numNamespaces = IMAP_UnserializeNamespaces(publicNamespacePrefixes, NULL, 0); - char **prefixes = (char**) XP_CALLOC(numNamespaces, sizeof(char*)); - if (prefixes) - { - int len = IMAP_UnserializeNamespaces(publicNamespacePrefixes, prefixes, numNamespaces); - for (int i = 0; i < len; i++) - { - char *thisns = prefixes[i]; - char delimiter = '/'; // a guess - if (XP_STRLEN(thisns) >= 1) - delimiter = thisns[XP_STRLEN(thisns)-1]; - TIMAPNamespace *ns = new TIMAPNamespace(kPublicNamespace, thisns, delimiter, TRUE); - if (ns) - TIMAPHostInfo::AddNewNamespaceForHost(hostName, ns); - FREEIF(thisns); - } - } - } - if (otherUsersNamespacePrefixes) - { - int numNamespaces = IMAP_UnserializeNamespaces(otherUsersNamespacePrefixes, NULL, 0); - char **prefixes = (char**) XP_CALLOC(numNamespaces, sizeof(char*)); - if (prefixes) - { - int len = IMAP_UnserializeNamespaces(otherUsersNamespacePrefixes, prefixes, numNamespaces); - for (int i = 0; i < len; i++) - { - char *thisns = prefixes[i]; - char delimiter = '/'; // a guess - if (XP_STRLEN(thisns) >= 1) - delimiter = thisns[XP_STRLEN(thisns)-1]; - TIMAPNamespace *ns = new TIMAPNamespace(kOtherUsersNamespace, thisns, delimiter, TRUE); - if (ns) - TIMAPHostInfo::AddNewNamespaceForHost(hostName, ns); - FREEIF(thisns); - } - } - } - return 0; -} - -extern void IMAP_SetShouldAlwaysListInboxForHost(const char *hostName, XP_Bool shouldList) -{ - TIMAPHostInfo::SetShouldAlwaysListInboxForHost(hostName, shouldList); -} - -extern int IMAP_GetNumberOfNamespacesForHost(const char *hostName) -{ - return TIMAPHostInfo::GetNumberOfNamespacesForHost(hostName); -} - -extern XP_Bool IMAP_SetHostIsUsingSubscription(const char *hostname, XP_Bool using_subscription) -{ - return TIMAPHostInfo::SetHostIsUsingSubscription(hostname, using_subscription); -} - -#define SERIALIZER_SEPARATORS "," - -/* prefixes is an array of strings; len is the length of that array. - If there is only one string, simply copy it and return it. - Otherwise, put them in quotes and comma-delimit them. - Returns a newly allocated string. */ -extern char *IMAP_SerializeNamespaces(char **prefixes, int len) -{ - char *rv = NULL; - if (len <= 0) - return rv; - if (len == 1) - { - rv = XP_STRDUP(prefixes[0]); - return rv; - } - else - { - for (int i = 0; i < len; i++) - { - char *temp = NULL; - if (i == 0) - temp = PR_smprintf("\"%s\"",prefixes[i]); /* quote the string */ - else - temp = PR_smprintf(",\"%s\"",prefixes[i]); /* comma, then quote the string */ - - char *next = PR_smprintf("%s%s",rv,temp); - FREEIF(rv); - rv = next; - } - return rv; - } -} - -/* str is the string which needs to be unserialized. - If prefixes is NULL, simply returns the number of namespaces in str. (len is ignored) - If prefixes is not NULL, it should be an array of length len which is to be filled in - with newly-allocated string. Returns the number of strings filled in. -*/ -extern int IMAP_UnserializeNamespaces(const char *str, char **prefixes, int len) -{ - if (!str) - return 0; - if (!prefixes) - { - if (str[0] != '"') - return 1; - else - { - int count = 0; - char *ourstr = XP_STRDUP(str); - if (ourstr) - { - char *token = XP_STRTOK( ourstr, SERIALIZER_SEPARATORS ); - while (token != NULL) - { - token = XP_STRTOK( NULL, SERIALIZER_SEPARATORS ); - count++; - } - XP_FREE(ourstr); - } - return count; - } - } - else - { - if ((str[0] != '"') && (len >= 1)) - { - prefixes[0] = XP_STRDUP(str); - return 1; - } - else - { - int count = 0; - char *ourstr = XP_STRDUP(str); - if (ourstr) - { - char *token = XP_STRTOK( ourstr, SERIALIZER_SEPARATORS ); - while ((count < len) && (token != NULL)) - { - char *current = XP_STRDUP(token), *where = current; - if (where[0] == '"') - where++; - if (where[XP_STRLEN(where)-1] == '"') - where[XP_STRLEN(where)-1] = 0; - prefixes[count] = XP_STRDUP(where); - FREEIF(current); - token = XP_STRTOK( NULL, SERIALIZER_SEPARATORS ); - count++; - } - XP_FREE(ourstr); - } - return count; - } - } -} - -} // extern "C" - -///////////////// TNavigatorImapConnection ////////////////////////////// - - - -//static -void TNavigatorImapConnection::ImapStartup() -{ - if (!fFindingMailboxesMonitor) - fFindingMailboxesMonitor = PR_NewNamedMonitor("finding-mailboxes-monitor"); - if (!fUpgradeToSubscriptionMonitor) - fUpgradeToSubscriptionMonitor = PR_NewNamedMonitor("upgrade-to-imap-subscription-monitor"); - if (!TIMAPHostInfo::gCachedHostInfoMonitor) - TIMAPHostInfo::gCachedHostInfoMonitor = PR_NewNamedMonitor("accessing-hostlist-monitor"); -} - -//static -void TNavigatorImapConnection::ImapShutDown() -{ - if (fFindingMailboxesMonitor) - { - PR_DestroyMonitor(fFindingMailboxesMonitor); - fFindingMailboxesMonitor = NULL; - } - if (fUpgradeToSubscriptionMonitor) - { - PR_DestroyMonitor(fUpgradeToSubscriptionMonitor); - fUpgradeToSubscriptionMonitor = NULL; - } - TIMAPHostInfo::ResetAll(); - if (TIMAPHostInfo::gCachedHostInfoMonitor) - { - PR_DestroyMonitor(TIMAPHostInfo::gCachedHostInfoMonitor); - TIMAPHostInfo::gCachedHostInfoMonitor = NULL; - } -} - - -TNavigatorImapConnection * -TNavigatorImapConnection::Create(const char *hostName) -{ - TNavigatorImapConnection *connection = new TNavigatorImapConnection(hostName); - - if (!connection || - !connection->ConstructionSuccess()) - { - delete connection; - connection = nil; - return NULL; - } - connection->fServerState.SetCapabilityFlag(TIMAPHostInfo::GetCapabilityForHost(hostName)); - connection->fServerState.SetFlagState(connection->fFlagState); - - return connection; -} - -XP_Bool TNavigatorImapConnection::ConstructionSuccess() -{ - return (TIMAP4BlockingConnection::ConstructionSuccess() && - fEventCompletionMonitor && - fFEEventQueue && - fActiveEntryMonitor && - fFindingMailboxesMonitor && - fUpgradeToSubscriptionMonitor && - fEventQueueEmptySignalMonitor && - fMessageUploadMonitor && - fMsgCopyDataMonitor && - fThreadDeathMonitor && - fPermissionToDieMonitor && - fPseudoInterruptMonitor && - fTunnelCompletionMonitor && - fSocketInfo && - fFlagState && - fListedMailboxList); -} - -XP_Bool TNavigatorImapConnection::GetPseudoInterrupted() -{ - XP_Bool rv = FALSE; - PR_EnterMonitor(fPseudoInterruptMonitor); - rv = fPseudoInterrupted; - PR_ExitMonitor(fPseudoInterruptMonitor); - return rv; -} - -void TNavigatorImapConnection::PseudoInterrupt(XP_Bool the_interrupt) -{ - PR_EnterMonitor(fPseudoInterruptMonitor); - fPseudoInterrupted = the_interrupt; - if (the_interrupt) - { - Log("CONTROL", NULL, "PSEUDO-Interrupted"); - //PR_LOG(IMAP, out, ("PSEUDO-Interrupted")); - } - PR_ExitMonitor(fPseudoInterruptMonitor); -} - -void TNavigatorImapConnection::SetActive(XP_Bool active) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fActive = active; - PR_ExitMonitor(GetDataMemberMonitor()); -} - -XP_Bool TNavigatorImapConnection::GetActive() -{ - XP_Bool ret; - PR_EnterMonitor(GetDataMemberMonitor()); - ret = fActive; - PR_ExitMonitor(GetDataMemberMonitor()); - return ret; -} - -/* static */ XP_Bool TNavigatorImapConnection::IsConnectionActive(const char *hostName, const char *folderName) -{ - XP_Bool ret = FALSE; - if (!connectionList) - connectionList = new XPPtrArray; - - // go through connection list looking for connection in selected state on folder - for (int32 i = 0; i < connectionList->GetSize() && !ret; i++) - { - TNavigatorImapConnection *curConnection = (TNavigatorImapConnection *) connectionList->GetAt(i); - // we should add semaphores for these variables (state and selectedmailboxname). - PR_EnterMonitor(curConnection->GetDataMemberMonitor()); - char *mailboxName = (curConnection->fCurrentUrl) ? curConnection->fCurrentUrl->CreateServerSourceFolderPathString() : 0; - - if (curConnection->fActive && !XP_STRCMP(hostName, curConnection->fHostName) - && folderName && mailboxName && !XP_STRCMP(folderName, mailboxName/* curConnection->GetServerStateParser().GetSelectedMailboxName() */)) - ret = TRUE; -#ifdef DEBUG_bienvenu - XP_Trace("connection active = %s state = %d selected mailbox name = %s\n", (curConnection->fActive) ? "TRUE" : "FALSE", - curConnection->GetServerStateParser().GetIMAPstate(), (mailboxName) ? mailboxName : "NULL" /* curConnection->GetServerStateParser().GetSelectedMailboxName()*/); -#endif - FREEIF(mailboxName); - PR_ExitMonitor(curConnection->GetDataMemberMonitor()); - } - return ret; -} - -// a thread safe accessor to fCurrentUrl -XP_Bool TNavigatorImapConnection::CurrentConnectionIsMove() -{ - XP_Bool isMove; - PR_EnterMonitor(GetDataMemberMonitor()); - - isMove = (fCurrentUrl != NULL) && - ((fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineCopy) || - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineMove) || - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineCopy) || - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineMove) || - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOfflineToOnlineMove)); - - PR_ExitMonitor(GetDataMemberMonitor()); - - return isMove; -} - - - - -void TNavigatorImapConnection::SetSubscribeParameters(XP_Bool autoSubscribe, - XP_Bool autoUnsubscribe, XP_Bool autoSubscribeOnOpen, XP_Bool autoUnsubscribeFromNoSelect, - XP_Bool shouldUpgrade, XP_Bool upgradeLeaveAlone, XP_Bool upgradeSubscribeAll) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fAutoSubscribe = autoSubscribe; - fAutoUnsubscribe = autoUnsubscribe; - fAutoSubscribeOnOpen = autoSubscribeOnOpen; - fAutoUnsubscribeFromNoSelect = autoUnsubscribeFromNoSelect; - PR_ExitMonitor(GetDataMemberMonitor()); - - PR_EnterMonitor(fUpgradeToSubscriptionMonitor); - fShouldUpgradeToSubscription = shouldUpgrade; - fUpgradeShouldLeaveAlone = upgradeLeaveAlone; - fUpgradeShouldSubscribeAll = upgradeSubscribeAll; - PR_ExitMonitor(fUpgradeToSubscriptionMonitor); -} - - -void TNavigatorImapConnection::TellThreadToDie(XP_Bool isSafeToDie) -{ - if (GetIOSocket() != 0 && (fCurrentEntry && fCurrentEntry->status != - MK_WAITING_FOR_CONNECTION)) - { - char *logoutString = PR_smprintf("xxxx logout\r\n"); - if (logoutString) - { - NET_BlockingWrite(GetIOSocket(), logoutString, - XP_STRLEN(logoutString)); - Log("NET","WR",logoutString); - //PR_LOG(IMAP, out, ("%s",logoutString)); - Log("CONTROL","From TellThreadToDie","LOGOUT"); - //PR_LOG(IMAP, out, ("Logged out from TellThreadToDie")); - XP_FREEIF(logoutString); - } - } - - PR_EnterMonitor(fThreadDeathMonitor); - fThreadShouldDie = TRUE; - PR_ExitMonitor(fThreadDeathMonitor); - - // signal all of the monitors that might be in PR_Wait - // they will wake up and see fThreadShouldDie==TRUE; - PR_EnterMonitor(fEventCompletionMonitor); - PR_Notify(fEventCompletionMonitor); - PR_ExitMonitor(fEventCompletionMonitor); - - PR_EnterMonitor(fTunnelCompletionMonitor); - PR_Notify(fTunnelCompletionMonitor); - PR_ExitMonitor(fTunnelCompletionMonitor); - - PR_EnterMonitor(fMessageUploadMonitor); - PR_Notify(fMessageUploadMonitor); - PR_ExitMonitor(fMessageUploadMonitor); - - PR_EnterMonitor(fMsgCopyDataMonitor); - PR_Notify(fMsgCopyDataMonitor); - PR_ExitMonitor(fMsgCopyDataMonitor); - - PR_EnterMonitor(fIOMonitor); - PR_Notify(fIOMonitor); - PR_ExitMonitor(fIOMonitor); - - if (isSafeToDie) - SetIsSafeToDie(); -} - -XP_Bool TNavigatorImapConnection::DeathSignalReceived() -{ - XP_Bool returnValue; - PR_EnterMonitor(fThreadDeathMonitor); - returnValue = fThreadShouldDie; - PR_ExitMonitor(fThreadDeathMonitor); - - return returnValue; -} - - - -TNavigatorImapConnection::~TNavigatorImapConnection() -{ - // This is either being deleted as the last thing that the - // imap thread does or during a url interrupt, in which case - // the thread was already killed, so don't destroy the thread - // here - - if (GetIOSocket() != 0) - { - // Logout(); *** We still need to close down the socket - net_graceful_shutdown(GetIOSocket(), HG32830); - PR_Close(GetIOSocket()); - SetIOSocket(NULL); // delete connection - if (GetActiveEntry()) - GetActiveEntry()->socket = 0; - } - GetServerStateParser().SetFlagState(NULL); - - if (fEventCompletionMonitor) - PR_DestroyMonitor(fEventCompletionMonitor); - - if (fTunnelCompletionMonitor) - PR_DestroyMonitor(fTunnelCompletionMonitor); - - if (fActiveEntryMonitor) - PR_DestroyMonitor(fActiveEntryMonitor); - - if (fEventQueueEmptySignalMonitor) - PR_DestroyMonitor(fEventQueueEmptySignalMonitor); - - if (fMessageUploadMonitor) - PR_DestroyMonitor(fMessageUploadMonitor); - - if (fMsgCopyDataMonitor) - PR_DestroyMonitor(fMsgCopyDataMonitor); - - if (fThreadDeathMonitor) - PR_DestroyMonitor(fThreadDeathMonitor); - - if (fPermissionToDieMonitor) - PR_DestroyMonitor(fPermissionToDieMonitor); - - if (fPseudoInterruptMonitor) - PR_DestroyMonitor(fPseudoInterruptMonitor); - - if (fWaitForBodyIdsMonitor) - PR_DestroyMonitor(fWaitForBodyIdsMonitor); - if (fFEEventQueue) - delete fFEEventQueue; - - if (fHierarchyMover) - delete fHierarchyMover; - - if (fCurrentUrl) - delete fCurrentUrl; - - if (fSocketInfo) - delete (fSocketInfo); - - if (fFlagState) - delete fFlagState; - - while ((TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList)) - { - } - XP_ListDestroy(fListedMailboxList); - preAuthSucceeded = FALSE; - FREEIF(fInputSocketBuffer); - FREEIF(fHostName); - connectionList->Remove(this); -} - - -TNavigatorImapConnection *TNavigatorImapConnection::GetNavigatorConnection() -{ - return this; -} - - -void TNavigatorImapConnection::HandleMemoryFailure() -{ - PR_EnterMonitor(GetDataMemberMonitor()); - AlertUserEvent(XP_GetString(MK_OUT_OF_MEMORY)); - SetConnectionStatus(-1); // stop this midnight train to crashville - PR_ExitMonitor(GetDataMemberMonitor()); -} - -void TNavigatorImapConnection::SetMailboxDiscoveryStatus(EMailboxDiscoverStatus status) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fDiscoveryStatus = status; - PR_ExitMonitor(GetDataMemberMonitor()); -} - -EMailboxDiscoverStatus TNavigatorImapConnection::GetMailboxDiscoveryStatus( ) -{ - EMailboxDiscoverStatus returnStatus; - PR_EnterMonitor(GetDataMemberMonitor()); - returnStatus = fDiscoveryStatus; - PR_ExitMonitor(GetDataMemberMonitor()); - - return returnStatus; -} - - -void TNavigatorImapConnection::WaitForFEEventCompletion() -{ - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fEventCompletionMonitor); -//#ifdef KMCENTEE_DEBUG -// WaitForFEEventLoopCount=0; -//#endif - - while (!fFEeventCompleted && !DeathSignalReceived()) - { - PR_Wait(fEventCompletionMonitor, sleepTime); -//#ifdef KMCENTEE_DEBUG -// WaitForFEEventLoopCount++; -// if (WaitForFEEventLoopCount == 10) -// XP_ASSERT(FALSE); -//#endif - } - fFEeventCompleted = FALSE; - PR_ExitMonitor(fEventCompletionMonitor); -} - -void TNavigatorImapConnection::WaitForTunnelCompletion() -{ - PRIntervalTime sleepTime = kImapSleepTime; - - PR_EnterMonitor(fTunnelCompletionMonitor); - - while (!fTunnelCompleted && !DeathSignalReceived()) - { - PR_Wait(fTunnelCompletionMonitor, sleepTime); - } - fTunnelCompleted = FALSE; - PR_ExitMonitor(fTunnelCompletionMonitor); -} - - -void TNavigatorImapConnection::NotifyEventCompletionMonitor() -{ - PR_EnterMonitor(fEventCompletionMonitor); - fFEeventCompleted = TRUE; - PR_Notify(fEventCompletionMonitor); - PR_ExitMonitor(fEventCompletionMonitor); -} - -void TNavigatorImapConnection::NotifyTunnelCompletionMonitor() -{ - PR_EnterMonitor(fTunnelCompletionMonitor); - fTunnelCompleted = TRUE; - PR_Notify(fTunnelCompletionMonitor); - PR_ExitMonitor(fTunnelCompletionMonitor); -} - -TImapFEEventQueue &TNavigatorImapConnection::GetFEEventQueue() -{ - return *fFEEventQueue; -} - - -void TNavigatorImapConnection::BeginMessageDownLoad( - uint32 total_message_size, // for user, headers and body - const char *content_type) -{ - char *sizeString = PR_smprintf("OPEN Size: %ld", total_message_size); - Log("STREAM",sizeString,"Begin Message Download Stream"); - FREEIF(sizeString); - //PR_LOG(IMAP, out, ("STREAM: Begin Message Download Stream. Size: %ld", total_message_size)); - StreamInfo *si = (StreamInfo *) XP_ALLOC (sizeof (StreamInfo)); // This will be freed in the event - if (si) - { - si->size = total_message_size; - si->content_type = XP_STRDUP(content_type); - if (si->content_type) - { - TImapFEEvent *setupStreamEvent = - new TImapFEEvent(SetupMsgWriteStream, // function to call - this, // access to current entry - (void *) si, - TRUE); // ok to run when interrupted because si is FREE'd in the event - - if (setupStreamEvent) - { - fFEEventQueue->AdoptEventToEnd(setupStreamEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - fFromHeaderSeen = FALSE; - } - else - HandleMemoryFailure(); - } - else - HandleMemoryFailure(); -} - - -void TNavigatorImapConnection::AddXMozillaStatusLine(uint16 /* flags */) // flags not use now -{ - static char statusLine[] = "X-Mozilla-Status: 0201\r\n"; - HandleMessageDownLoadLine(statusLine, FALSE); -} - - -void TNavigatorImapConnection::HandleMessageDownLoadLine(const char *line, XP_Bool chunkEnd) -{ - // when we duplicate this line, whack it into the native line - // termination. Do not assume that it really ends in CRLF - // to start with, even though it is supposed to be RFC822 - - // If we are fetching by chunks, we can make no assumptions about - // the end-of-line terminator, and we shouldn't mess with it. - - // leave enough room for two more chars. (CR and LF) - char *localMessageLine = (char *) XP_ALLOC(strlen(line) + 3); - if (localMessageLine) - strcpy(localMessageLine,line); - char *endOfLine = localMessageLine + strlen(localMessageLine); - - if (!chunkEnd) - { -#if (LINEBREAK_LEN == 1) - if ((endOfLine - localMessageLine) >= 2 && - endOfLine[-2] == CR && - endOfLine[-1] == LF) - { - /* CRLF -> CR or LF */ - endOfLine[-2] = LINEBREAK[0]; - endOfLine[-1] = '\0'; - } - else if (endOfLine > localMessageLine + 1 && - endOfLine[-1] != LINEBREAK[0] && - ((endOfLine[-1] == CR) || (endOfLine[-1] == LF))) - { - /* CR -> LF or LF -> CR */ - endOfLine[-1] = LINEBREAK[0]; - } - else // no eol characters at all - { - endOfLine[0] = LINEBREAK[0]; // CR or LF - endOfLine[1] = '\0'; - } -#else - if (((endOfLine - localMessageLine) >= 2 && endOfLine[-2] != CR) || - ((endOfLine - localMessageLine) >= 1 && endOfLine[-1] != LF)) - { - if ((endOfLine[-1] == CR) || (endOfLine[-1] == LF)) - { - /* LF -> CRLF or CR -> CRLF */ - endOfLine[-1] = LINEBREAK[0]; - endOfLine[0] = LINEBREAK[1]; - endOfLine[1] = '\0'; - } - else // no eol characters at all - { - endOfLine[0] = LINEBREAK[0]; // CR - endOfLine[1] = LINEBREAK[1]; // LF - endOfLine[2] = '\0'; - } - } -#endif - } - - const char *xSenderInfo = GetServerStateParser().GetXSenderInfo(); - - if (xSenderInfo && *xSenderInfo && !fFromHeaderSeen) - { - if (!XP_STRNCMP("From: ", localMessageLine, 6)) - { - fFromHeaderSeen = TRUE; - if (XP_STRSTR(localMessageLine, xSenderInfo) != NULL) - AddXMozillaStatusLine(0); - GetServerStateParser().FreeXSenderInfo(); - } - } - // if this line is for a different message, or the incoming line is too big - if (((fDownLoadLineCache.CurrentUID() != GetServerStateParser().CurrentResponseUID()) && !fDownLoadLineCache.CacheEmpty()) || - (fDownLoadLineCache.SpaceAvailable() < (strlen(localMessageLine) + 1)) ) - { - if (!fDownLoadLineCache.CacheEmpty()) - { - msg_line_info *downloadLineDontDelete = fDownLoadLineCache.GetCurrentLineInfo(); - PostLineDownLoadEvent(downloadLineDontDelete); - } - fDownLoadLineCache.ResetCache(); - } - - // so now the cache is flushed, but this string might still be to big - if (fDownLoadLineCache.SpaceAvailable() < (strlen(localMessageLine) + 1) ) - { - // has to be dynamic to pass to other win16 thread - msg_line_info *downLoadInfo = (msg_line_info *) XP_ALLOC(sizeof(msg_line_info)); - if (downLoadInfo) - { - downLoadInfo->adoptedMessageLine = localMessageLine; - downLoadInfo->uidOfMessage = GetServerStateParser().CurrentResponseUID(); - PostLineDownLoadEvent(downLoadInfo); - if (!DeathSignalReceived()) - XP_FREE(downLoadInfo); - else - { - // this is very rare, interrupt while waiting to display a huge single line - // Net_InterruptIMAP will read this line so leak the downLoadInfo - - // set localMessageLine to NULL so the FREEIF( localMessageLine) leaks also - localMessageLine = NULL; - } - } - } - else - fDownLoadLineCache.CacheLine(localMessageLine, GetServerStateParser().CurrentResponseUID()); - FREEIF( localMessageLine); -} - -char* TNavigatorImapConnection::CreateUtf7ConvertedString(const char *sourceString, XP_Bool toUtf7Imap) -{ - char *convertedString = NULL; - utf_name_struct *conversion = (utf_name_struct *) XP_ALLOC(sizeof(utf_name_struct)); - if (conversion) - { - conversion->toUtf7Imap = toUtf7Imap; - conversion->sourceString = (unsigned char *) XP_STRDUP(sourceString); - conversion->convertedString = NULL; - } - - TImapFEEvent *convertEvent = - new TImapFEEvent(ConvertImapUtf7, // function to call - conversion, - this, - TRUE); - - if (convertEvent && sourceString && conversion) - { - fFEEventQueue->AdoptEventToEnd(convertEvent); - WaitForFEEventCompletion(); - convertedString = (char *) conversion->convertedString; - } - - if (!DeathSignalReceived()) - { - FREEIF(conversion->sourceString); - FREEIF(conversion); // leak these 8 bytes if we were interrupted here. - } - - return convertedString; -} - - -void TNavigatorImapConnection::PostLineDownLoadEvent(msg_line_info *downloadLineDontDelete) -{ - TImapFEEvent *endEvent = - new TImapFEEvent(ParseAdoptedMsgLine, // function to call - this, // access to current entry - (void *) downloadLineDontDelete, - FALSE); // line/msg info - - if (endEvent && downloadLineDontDelete && downloadLineDontDelete->adoptedMessageLine) - { - fFEEventQueue->AdoptEventToEnd(endEvent); - - // I just put a big buffer in the event queue that I need to reuse, so wait. - // The alternative would be to realloc the buffer each time it gets placed in the - // queue, but I don't want the perf hit a continuously doing an alloc/delete - // of a big buffer. Also, I don't a queue full of huge buffers laying around! - WaitForFEEventCompletion(); - - // we better yield here, dealing with a huge buffer made for a slow fe event. - // because this event was processed, the queue is empty. Yielding here will - // cause NET_ProcessIMAP4 to exit. - if (!DeathSignalReceived()) - PR_Sleep(PR_INTERVAL_NO_WAIT); - } - else - HandleMemoryFailure(); -} - - -// Make sure that we receive data chunks in a size that allows the user to see some -// progress. Dont want to bore them just yet. -// If we received our chunk too fast, ask for more -// if we received our chunk too slow, ask for less, etc - -void TNavigatorImapConnection::AdjustChunkSize() -{ - fEndTime = XP_TIME(); - fTrackingTime = FALSE; - time_t t = fEndTime - fStartTime; - if (t < 0) - return; // bogus for some reason - if (t <= fTooFastTime) { - fChunkSize += fChunkAddSize; - fChunkThreshold = fChunkSize + (fChunkSize / 2); - if (fChunkSize > fMaxChunkSize) - fChunkSize = fMaxChunkSize; - } - else if (t <= fIdealTime) - return; - else { - if (fChunkSize > fChunkStartSize) - fChunkSize = fChunkStartSize; - else if (fChunkSize > (fChunkAddSize * 2)) - fChunkSize -= fChunkAddSize; - fChunkThreshold = fChunkSize + (fChunkSize / 2); - } -} - - - -void TNavigatorImapConnection::NormalMessageEndDownload() -{ - Log("STREAM", "CLOSE", "Normal Message End Download Stream"); - //PR_LOG(IMAP, out, ("STREAM: Normal End Message Download Stream")); - if (fTrackingTime) - AdjustChunkSize(); - if (!fDownLoadLineCache.CacheEmpty()) - { - msg_line_info *downloadLineDontDelete = fDownLoadLineCache.GetCurrentLineInfo(); - PostLineDownLoadEvent(downloadLineDontDelete); - fDownLoadLineCache.ResetCache(); - } - - TImapFEEvent *endEvent = - new TImapFEEvent(NormalEndMsgWriteStream, // function to call - this, // access to current entry - nil, // unused - TRUE); - - if (endEvent) - fFEEventQueue->AdoptEventToEnd(endEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::AbortMessageDownLoad() -{ - Log("STREAM", "CLOSE", "Abort Message Download Stream"); - //PR_LOG(IMAP, out, ("STREAM: Abort Message Download Stream")); - if (fTrackingTime) - AdjustChunkSize(); - if (!fDownLoadLineCache.CacheEmpty()) - { - msg_line_info *downloadLineDontDelete = fDownLoadLineCache.GetCurrentLineInfo(); - PostLineDownLoadEvent(downloadLineDontDelete); - fDownLoadLineCache.ResetCache(); - } - - TImapFEEvent *endEvent = - new TImapFEEvent(AbortMsgWriteStream, // function to call - this, // access to current entry - nil, // unused - TRUE); - - if (endEvent) - fFEEventQueue->AdoptEventToEnd(endEvent); - else - HandleMemoryFailure(); - //MSG_FolderSetGettingMail(fFolderInfo, FALSE); -} - -char *TNavigatorImapConnection::CreatePossibleTrashName(const char *prefix) -{ - IMAP_LoadTrashFolderName(); - - char *returnTrash = (char *) XP_ALLOC(XP_STRLEN(prefix) + XP_STRLEN(ImapTRASH_FOLDER_NAME) + 1); - if (returnTrash) - { - XP_STRCPY(returnTrash, prefix); - XP_STRCAT(returnTrash, ImapTRASH_FOLDER_NAME); - } - return returnTrash; -} - - - -void TNavigatorImapConnection::CanonicalChildList(const char *canonicalPrefix, XP_Bool pipeLined) -{ - char *truncatedPrefix = XP_STRDUP(canonicalPrefix); - if (truncatedPrefix) - { - if (*(truncatedPrefix + XP_STRLEN(truncatedPrefix) - 1) == '/') - *(truncatedPrefix + XP_STRLEN(truncatedPrefix) - 1) = '\0'; - - char *serverPrefix = fCurrentUrl->AllocateServerPath(truncatedPrefix); - if (serverPrefix) - { - char *utf7ListArg = CreateUtf7ConvertedString(serverPrefix,TRUE); - if (utf7ListArg) - { - char *pattern = PR_smprintf("%s%c%c",utf7ListArg, fCurrentUrl->GetOnlineSubDirSeparator(),'%'); - if (pattern) - { - List(pattern,pipeLined); - XP_FREE(pattern); - } - XP_FREE(utf7ListArg); - } - XP_FREE(serverPrefix); - } - XP_FREE(truncatedPrefix); - } -} - -void TNavigatorImapConnection::NthLevelChildList(const char *canonicalPrefix, int depth) -{ - XP_ASSERT(depth >= 0); - if (depth < 0) return; - char *truncatedPrefix = XP_STRDUP(canonicalPrefix); - if (truncatedPrefix) - { - if (*(truncatedPrefix + XP_STRLEN(truncatedPrefix) - 1) == '/') - *(truncatedPrefix + XP_STRLEN(truncatedPrefix) - 1) = '\0'; - - char *serverPrefix = fCurrentUrl->AllocateServerPath(truncatedPrefix); - if (serverPrefix) - { - char *utf7ListArg = CreateUtf7ConvertedString(serverPrefix,TRUE); - if (utf7ListArg) - { - char *pattern = PR_smprintf("%s",utf7ListArg); - int count = 0; - char *suffix = PR_smprintf("%c%c",fCurrentUrl->GetOnlineSubDirSeparator(),'%'); - if (suffix) - { - while (pattern && (count < depth)) - { - StrAllocCat(pattern, suffix); - count++; - } - if (pattern) - { - List(pattern); - } - XP_FREE(suffix); - } - XP_FREEIF(pattern); - XP_FREE(utf7ListArg); - } - XP_FREE(serverPrefix); - } - XP_FREE(truncatedPrefix); - } -} - -static -void MOZTHREAD_ChildDiscoverySucceeded(void *blockingConnectionVoid, - void* /*unused*/) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ReportSuccessOfChildMailboxDiscovery(imapConnection->GetActiveEntry()->window_id); -} - - -void TNavigatorImapConnection::ChildDiscoverySucceeded() -{ - TImapFEEvent *succeedEvent = - new TImapFEEvent(MOZTHREAD_ChildDiscoverySucceeded, // function to call - this, // access to current entry/context - NULL, - TRUE); - - - if (succeedEvent) - fFEEventQueue->AdoptEventToEnd(succeedEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::DiscoverMailboxSpec(mailbox_spec *adoptedBoxSpec) -{ - IMAP_LoadTrashFolderName(); - - TIMAPNamespace *ns = TIMAPHostInfo::GetDefaultNamespaceOfTypeForHost(fCurrentUrl->GetUrlHost(), kPersonalNamespace); - const char *hostDir = ns ? ns->GetPrefix() : 0; - // if (!hostDir) // no personal or default namespaces - only public? or none altogether? - char *canonicalSubDir = NULL; - if (hostDir) - { - canonicalSubDir = XP_STRDUP(hostDir); - if (canonicalSubDir && *canonicalSubDir && (*(canonicalSubDir + XP_STRLEN(canonicalSubDir) - 1) == '/')) - *(canonicalSubDir + XP_STRLEN(canonicalSubDir) - 1) = 0; - } - - switch (fHierarchyNameState) - { - case kNoOperationInProgress: - case kDiscoverTrashFolderInProgress: - case kListingForInfoAndDiscovery: - { - if (canonicalSubDir && XP_STRSTR(adoptedBoxSpec->allocatedPathName, canonicalSubDir)) - fOnlineBaseFolderExists = TRUE; - - if (ns && hostDir) // if no personal namespace, there can be no Trash folder - { - if (!TIMAPHostInfo::GetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost()) && XP_STRSTR(adoptedBoxSpec->allocatedPathName, ImapTRASH_FOLDER_NAME)) - { - XP_Bool trashExists = FALSE; - char *trashMatch = CreatePossibleTrashName(hostDir); - if (trashMatch) - { - trashExists = XP_STRCMP(trashMatch, adoptedBoxSpec->allocatedPathName) == 0; - TIMAPHostInfo::SetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost(), trashExists); - FREEIF(trashMatch); - - // special case check for cmu trash, child of inbox - if (!TIMAPHostInfo::GetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost()) && (ns->GetDelimiter() == '.')) - { - //char *inboxPath = TIMAPHostInfo::GetOnlineInboxPathForHost(fCurrentUrl->GetUrlHost()); - char *inboxPath = PR_smprintf("INBOX"); - if (inboxPath) - { - char *inboxAsParent = PR_smprintf("%s/",inboxPath); - if (inboxAsParent) - { - trashMatch = CreatePossibleTrashName(inboxAsParent); // "INBOX/" - if (trashMatch) - { - trashExists = XP_STRCMP(trashMatch, adoptedBoxSpec->allocatedPathName) == 0; - TIMAPHostInfo::SetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost(), trashExists); - FREEIF(trashMatch); - } - XP_FREE(inboxAsParent); - } - XP_FREE(inboxPath); - } - } - } - - if (trashExists) - adoptedBoxSpec->box_flags |= kImapTrash; - } - } - - // Discover the folder (shuttle over to libmsg, yay) - // Do this only if the folder name is not empty (i.e. the root) - if (*adoptedBoxSpec->allocatedPathName) - { - char *boxNameCopy = XP_STRDUP(adoptedBoxSpec->allocatedPathName); - - TImapFEEvent *endEvent = - new TImapFEEvent(PossibleIMAPmailbox, // function to call - this, // access to current entry/context - (void *) adoptedBoxSpec, - TRUE); - // now owned by msg folder - - if (endEvent) - { - char *listArg = XP_STRDUP(adoptedBoxSpec->allocatedPathName); - fFEEventQueue->AdoptEventToEnd(endEvent); - WaitForFEEventCompletion(); - - if ((GetMailboxDiscoveryStatus() != eContinue) && - (GetMailboxDiscoveryStatus() != eContinueNew) && - (GetMailboxDiscoveryStatus() != eListMyChildren)) - { - SetConnectionStatus(-1); - } - else if (listArg && (GetMailboxDiscoveryStatus() == eListMyChildren) && - (!TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost()) || GetSubscribingNow())) - { - XP_ASSERT(FALSE); // we should never get here anymore. - SetMailboxDiscoveryStatus(eContinue); - if (listArg) - CanonicalChildList(listArg,TRUE); - } - else if (GetMailboxDiscoveryStatus() == eContinueNew) - { - if (fHierarchyNameState == kListingForInfoAndDiscovery && boxNameCopy) - { - // remember the info here also - TIMAPMailboxInfo *mb = new TIMAPMailboxInfo(boxNameCopy); - XP_ListAddObject(fListedMailboxList, mb); - } - SetMailboxDiscoveryStatus(eContinue); - } - FREEIF(listArg); - } - else - HandleMemoryFailure(); - - FREEIF(boxNameCopy); - } - } - break; - case kDiscoverBaseFolderInProgress: - { - if (canonicalSubDir && XP_STRSTR(adoptedBoxSpec->allocatedPathName, canonicalSubDir)) - fOnlineBaseFolderExists = TRUE; - } - break; - case kDeleteSubFoldersInProgress: - { - XP_ListAddObject(fDeletableChildren, adoptedBoxSpec->allocatedPathName); - delete adoptedBoxSpec->flagState; - FREEIF( adoptedBoxSpec); - } - break; - case kListingForInfoOnly: - { - //UpdateProgressWindowForUpgrade(adoptedBoxSpec->allocatedPathName); - ProgressEventFunction_UsingIdWithString(MK_MSG_IMAP_DISCOVERING_MAILBOX, adoptedBoxSpec->allocatedPathName); - TIMAPMailboxInfo *mb = new TIMAPMailboxInfo(adoptedBoxSpec->allocatedPathName); - XP_ListAddObject(fListedMailboxList, mb); - IMAP_FreeBoxSpec(adoptedBoxSpec); - } - break; - case kDiscoveringNamespacesOnly: - { - IMAP_FreeBoxSpec(adoptedBoxSpec); - } - break; - default: - XP_ASSERT(FALSE); - break; - } - FREEIF(canonicalSubDir); -} - -void TNavigatorImapConnection::OnlineCopyCompleted(ImapOnlineCopyState copyState) -{ - ImapOnlineCopyState *orphanedCopyState = (ImapOnlineCopyState *) XP_ALLOC(sizeof(ImapOnlineCopyState)); - if (orphanedCopyState) - *orphanedCopyState = copyState; - - TImapFEEvent *endEvent = - new TImapFEEvent(OnlineCopyReport, // function to call - this, // access to current entry/context - (void *) orphanedCopyState, - TRUE); // storage passed - - - if (endEvent && orphanedCopyState) - fFEEventQueue->AdoptEventToEnd(endEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::FolderDeleted(const char *mailboxName) -{ - char *convertedName = CreateUtf7ConvertedString((char *) mailboxName,FALSE); - char *orphanedMailboxName = convertedName ? fCurrentUrl->AllocateCanonicalPath(convertedName) : 0; - - TImapFEEvent *deleteEvent = - new TImapFEEvent(OnlineFolderDelete, // function to call - this, // access to current entry/context - (void *) orphanedMailboxName, - TRUE); // storage passed - - - if (deleteEvent && orphanedMailboxName) - fFEEventQueue->AdoptEventToEnd(deleteEvent); - else - HandleMemoryFailure(); - - FREEIF(convertedName); -} - -void TNavigatorImapConnection::FolderNotCreated(const char *serverMessageResponse) -{ - char *serverMessage = XP_STRDUP(serverMessageResponse); - - TImapFEEvent *noCreateEvent = - new TImapFEEvent(OnlineFolderCreateFailed, // function to call - this, // access to current entry/context - (void *) serverMessage, - TRUE); // storage passed - - - if (noCreateEvent && serverMessage) - fFEEventQueue->AdoptEventToEnd(noCreateEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::FolderRenamed(const char *oldName, - const char *newName) -{ - if ((fHierarchyNameState == kNoOperationInProgress) || - (fHierarchyNameState == kListingForInfoAndDiscovery)) - - { - char *oldConvertedName = CreateUtf7ConvertedString((char *) oldName,FALSE); - char *newConvertedName = CreateUtf7ConvertedString((char *) newName,FALSE); - - if (oldConvertedName && newConvertedName) - { - folder_rename_struct *orphanRenameStruct = (folder_rename_struct *) XP_ALLOC(sizeof(folder_rename_struct)); - orphanRenameStruct->fHostName = XP_STRDUP(GetHostName()); - orphanRenameStruct->fOldName = fCurrentUrl->AllocateCanonicalPath(oldConvertedName); - orphanRenameStruct->fNewName = fCurrentUrl->AllocateCanonicalPath(newConvertedName); - - - TImapFEEvent *renameEvent = - new TImapFEEvent(OnlineFolderRename, // function to call - this, // access to current entry/context - (void *) orphanRenameStruct, - TRUE); // storage passed - - - if (renameEvent && orphanRenameStruct && - orphanRenameStruct->fOldName && - orphanRenameStruct->fNewName) - fFEEventQueue->AdoptEventToEnd(renameEvent); - else - HandleMemoryFailure(); - } - else - HandleMemoryFailure(); - - FREEIF(oldConvertedName); - FREEIF(newConvertedName); - } -} - -void TNavigatorImapConnection::MailboxDiscoveryFinished() -{ - if (!GetSubscribingNow() && - ((fHierarchyNameState == kNoOperationInProgress) || - (fHierarchyNameState == kListingForInfoAndDiscovery))) - { - TIMAPNamespace *ns = TIMAPHostInfo::GetDefaultNamespaceOfTypeForHost(fCurrentUrl->GetUrlHost(), kPersonalNamespace); - const char *personalDir = ns ? ns->GetPrefix() : 0; - // if (!personalDir) // no personal or default NS - only public folders - if (!TIMAPHostInfo::GetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost()) && - fDeleteModelIsMoveToTrash && TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost())) - { - // maybe we're not subscribed to the Trash folder - if (personalDir) - { - char *originalTrashName = CreatePossibleTrashName(personalDir); - fHierarchyNameState = kDiscoverTrashFolderInProgress; - List(originalTrashName); - fHierarchyNameState = kNoOperationInProgress; - } - } - - // There is no Trash folder (either LIST'd or LSUB'd), and we're using the - // Delete-is-move-to-Trash model, and there is a personal namespace - if (!TIMAPHostInfo::GetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost()) && - fDeleteModelIsMoveToTrash && personalDir) - { - const char *trashPrefix = personalDir; - char *trashName = CreatePossibleTrashName(trashPrefix); - if (trashName) - { - GetServerStateParser().SetReportingErrors(FALSE); - XP_Bool created = CreateMailboxRespectingSubscriptions(trashName); - /* - // we shouldn't need this case anymore, since we're handling namespaces - // the right way, I think. - if (!created && (TIMAPUrl::GetOnlineSubDirSeparator() == '.')) - { - trashPrefix = "INBOX."; - FREEIF(trashName); - trashName = CreatePossibleTrashName(trashPrefix); - if (trashName) - created = CreateMailboxRespectingSubscriptions(trashName); - } - */ - GetServerStateParser().SetReportingErrors(TRUE); - - // force discovery of new trash folder. - if (created) - { - fHierarchyNameState = kDiscoverTrashFolderInProgress; - List(trashName); - fHierarchyNameState = kNoOperationInProgress; - } - else - TIMAPHostInfo::SetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost(), TRUE); // we only try this once, not every time we create any folder. - FREEIF(trashName); - } - } - TIMAPHostInfo::SetHaveWeEverDiscoveredFoldersForHost(fCurrentUrl->GetUrlHost(), TRUE); - SetFolderDiscoveryFinished(); - } -} - - -void TNavigatorImapConnection::SetFolderDiscoveryFinished() -{ - TImapFEEvent *discoveryDoneEvent = - new TImapFEEvent(MailboxDiscoveryDoneEvent, // function to call - this, // access to current entry/context - NULL, - TRUE); - - - if (discoveryDoneEvent) - fFEEventQueue->AdoptEventToEnd(discoveryDoneEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::UpdatedMailboxSpec(mailbox_spec *adoptedBoxSpec) -{ - TImapFEEvent *endEvent = - new TImapFEEvent(UpdatedIMAPmailbox, // function to call - this, // access to current entry/context - (void *) adoptedBoxSpec, - TRUE); // storage passed - // now owned by msg folder - - if (endEvent) - fFEEventQueue->AdoptEventToEnd(endEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::UpdateMailboxStatus(mailbox_spec *adoptedBoxSpec) -{ - TImapFEEvent *endEvent = - new TImapFEEvent(UpdatedIMAPmailboxStatus, // function to call - this, // access to current entry/context - (void *) adoptedBoxSpec, - TRUE); // storage passed - // now owned by msg folder - - if (endEvent) - fFEEventQueue->AdoptEventToEnd(endEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::UploadMessage() -{ - TImapFEEvent *endEvent = - new TImapFEEvent(UploadMessageEvent, // function to call - this, // access to current entry/context - nil, - TRUE); // we are the knights who say nyet! - - if (endEvent) - { - fFEEventQueue->AdoptEventToEnd(endEvent); - WaitForMessageUploadToComplete(); - } - else - HandleMemoryFailure(); -} - - -static void -UploadMessageFileHandler(void *blockingConnectionVoid, void *msgInfo) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - UploadMessageInfo *uploadMsgInfo = (UploadMessageInfo*) msgInfo; - uint32 bytesRead = 0; - int ioStatus = 0; - - if (! uploadMsgInfo->dataBuffer) - { // use 4k buffer - uploadMsgInfo->dataBuffer = - (char *) XP_ALLOC((kOutputBufferSize << 1)+1); - } - - XP_ASSERT(uploadMsgInfo->fileId && uploadMsgInfo->dataBuffer); - - if(!uploadMsgInfo->fileId || !uploadMsgInfo->dataBuffer) - { - if (uploadMsgInfo->fileId) - XP_FileClose(uploadMsgInfo->fileId); - XP_FREEIF(uploadMsgInfo->dataBuffer); - XP_FREEIF(uploadMsgInfo); - XP_InterruptContext(ce->window_id); - return; - } - - XP_ASSERT(uploadMsgInfo->bytesRemain > 0); - - bytesRead = XP_FileRead(uploadMsgInfo->dataBuffer, - (kOutputBufferSize << 1), - uploadMsgInfo->fileId); - *(uploadMsgInfo->dataBuffer+bytesRead) = 0; - ioStatus = NET_BlockingWrite(ce->socket, uploadMsgInfo->dataBuffer, - bytesRead); - // PR_LOG(IMAP, out, ("%s", uploadMsgInfo->dataBuffer)); - - uploadMsgInfo->bytesRemain -= bytesRead; - - if (uploadMsgInfo->bytesRemain <= 0) - { - ioStatus = NET_BlockingWrite(ce->socket, CRLF, XP_STRLEN(CRLF)); - imapConnection->NotifyMessageUploadMonitor(); - } - else - { - TImapFEEvent *uploadMsgFromFileEvent = - new TImapFEEvent(UploadMessageFileHandler, - (void *)imapConnection, - (void *)msgInfo, - TRUE); - if (uploadMsgFromFileEvent) - { - imapConnection->GetFEEventQueue().AdoptEventToEnd(uploadMsgFromFileEvent); - } - else - { - imapConnection->HandleMemoryFailure(); - } - } -} - -XP_Bool TNavigatorImapConnection::NewMailDetected() -{ - return fNewMail; -} - - -void TNavigatorImapConnection::ParseIMAPandCheckForNewMail(char *buff /* = NULL */) -{ - XP_Bool oldMail = fNewMail; - - if (buff) - GetServerStateParser().ParseIMAPServerResponse(buff); - else - GetServerStateParser().ParseIMAPServerResponse(GetOutputBuffer()); - - int32 numOfMessagesInFlagState = fFlagState->GetNumberOfMessages(); - - if ((GetServerStateParser().NumberOfMessages() != numOfMessagesInFlagState) && (numOfMessagesInFlagState > 0)) { - fNewMail = TRUE; - if (!fFlagState->IsLastMessageUnseen()) - fNewMail = FALSE; - } else { - fNewMail = FALSE; - } - if (fNewMail != oldMail) - { - if (fNewMail) - fCurrentBiffState = MSG_BIFF_NewMail; - else - fCurrentBiffState = MSG_BIFF_NoMail; - SendSetBiffIndicatorEvent(fCurrentBiffState); - } -} - - -void TNavigatorImapConnection::UploadMessageFromFile(const char *srcFilePath, - const char *mailboxName, - imapMessageFlagsType flags) -{ - XP_StatStruct st; - - if (-1 != XP_Stat (srcFilePath, &st, xpFileToPost)) - { - char *escapedName = CreateEscapedMailboxName(mailboxName); - - if (!escapedName) - { - XP_FREEIF(escapedName); - HandleMemoryFailure(); - return; - } - /* status command only available on IMAP4rev1 and beyond - * lets try the status first to get the next UID - */ - MessageKey newkey = MSG_MESSAGEKEYNONE; - int ioStatus; - - char flagString[70]; - long bytesRead = 0; - setup_message_flags_string(flagString, flags, SupportsUserDefinedFlags()); - - IncrementCommandTagNumber(); - PR_snprintf (GetOutputBuffer(), kOutputBufferSize, - "%s append \"%s\" (%s) {%ld}" CRLF, - GetServerCommandTag(), - escapedName, - flagString, - (long) st.st_size); - - ioStatus = WriteLineToSocket(GetOutputBuffer()); - - ParseIMAPandCheckForNewMail(); - - UploadMessageInfo *msgInfo = - (UploadMessageInfo*) XP_ALLOC(sizeof(UploadMessageInfo)); - if (!msgInfo) - { - HandleMemoryFailure(); - return; - } - msgInfo->bytesRemain = st.st_size; - msgInfo->newMsgID = newkey; - msgInfo->dataBuffer = 0; - msgInfo->fileId = XP_FileOpen(srcFilePath, xpFileToPost, XP_FILE_READ_BIN); - - TImapFEEvent *uploadMsgFromFileEvent = - new TImapFEEvent(UploadMessageFileHandler, - (void *)this, - (void *)msgInfo, - TRUE); - if (uploadMsgFromFileEvent) - { - fFEEventQueue->AdoptEventToEnd(uploadMsgFromFileEvent); - PR_Sleep(PR_INTERVAL_NO_WAIT); - WaitForMessageUploadToComplete(); - - ParseIMAPandCheckForNewMail(); - - if (GetServerStateParser().LastCommandSuccessful() - && MSG_IsSaveDraftDeliveryState(GetActiveEntry()->URL_s->fe_data)) - { - GetServerStateParser().SetIMAPstate(TImapServerState::kFolderSelected); // *** sucks..... - - if ((GetServerStateParser().GetSelectedMailboxName() && - XP_STRCMP(GetServerStateParser().GetSelectedMailboxName(), - escapedName))) - { - if (fCloseNeededBeforeSelect) - Close(); - SelectMailbox(escapedName); - } - - const char *messageId = NULL; - if (GetActiveEntry()->URL_s->fe_data) - messageId = MSG_GetMessageIdFromState( - GetActiveEntry()->URL_s->fe_data); - if (GetServerStateParser().LastCommandSuccessful() && - messageId) - { - char *tmpBuffer = PR_smprintf ( - "SEARCH SEEN HEADER Message-ID %s", - messageId); - GetServerStateParser().ResetSearchResultSequence(); - Search(tmpBuffer, TRUE, FALSE); - if (GetServerStateParser().LastCommandSuccessful()) - { - TSearchResultIterator *searchResult = - GetServerStateParser().CreateSearchResultIterator(); - newkey = searchResult->GetNextMessageNumber(); - delete searchResult; - if (newkey != MSG_MESSAGEKEYNONE) - MSG_SetIMAPMessageUID(newkey, GetActiveEntry()->URL_s->fe_data); - XP_Bool bSuc = GetServerStateParser().LastCommandSuccessful(); - } - } - } - - XP_FREEIF(msgInfo->dataBuffer); - XP_FileClose(msgInfo->fileId); - XP_FREEIF(msgInfo); - } - else - { - HandleMemoryFailure(); - } - - XP_FREEIF(escapedName); - } -} - - -void TNavigatorImapConnection::NotifyMessageFlags( imapMessageFlagsType flags, MessageKey key) -{ - tFlagsKeyStruct *keyAndFlag = (tFlagsKeyStruct *) XP_ALLOC( sizeof(tFlagsKeyStruct)); - keyAndFlag->flags = flags; - keyAndFlag->key = key; - - TImapFEEvent *flagsEvent = - new TImapFEEvent(NotifyMessageFlagsEvent, // function to call - this, // access to current entry/context - keyAndFlag, - TRUE); // storage passed - - if (flagsEvent) - fFEEventQueue->AdoptEventToEnd(flagsEvent); - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::NotifySearchHit(const char *hitLine) -{ - if (!fNotifyHit) - return; - TImapFEEvent *hitEvent = - new TImapFEEvent(AddSearchResultEvent, // function to call - this, // access to current entry/context - (void *)hitLine, - TRUE); - - if (hitEvent) - { - fFEEventQueue->AdoptEventToEnd(hitEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - -} - -static void -ArbitraryHeadersEvent(void *blockingConnectionVoid, void *valueVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - GenericInfo *value = (GenericInfo *)valueVoid; - - value->c = MSG_GetArbitraryHeadersForHost(ce->window_id->mailMaster, value->hostName); - imapConnection->NotifyEventCompletionMonitor(); -} - -// Returns a newly allocated, space-delimited string of arbitrary headers -// which are used for filters on this host. -char *TNavigatorImapConnection::GetArbitraryHeadersToDownload() -{ - GenericInfo *value = (GenericInfo *)XP_ALLOC(sizeof(GenericInfo)); - if (!value) - return NULL; - - value->c = NULL; - value->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - if (!value->hostName) - { - XP_FREE(value->c); - XP_FREE(value); - return NULL; - } - TImapFEEvent *headerEvent = - new TImapFEEvent(ArbitraryHeadersEvent, // function to call - this, // access to current entry/context - value, - FALSE); - - if (headerEvent) - { - fFEEventQueue->AdoptEventToEnd(headerEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - char *rv = NULL; - if (!DeathSignalReceived()) - rv = value->c; - XP_FREE(value->hostName); - XP_FREE(value); - return rv; -} - -void TNavigatorImapConnection::HeaderFetchCompleted() -{ - TImapFEEvent *endEvent = - new TImapFEEvent(HeaderFetchCompletedEvent, // function to call - this, // access to current entry/context - nil, - TRUE); // we are the knights who say nyet! - - if (endEvent) - fFEEventQueue->AdoptEventToEnd(endEvent); - else - HandleMemoryFailure(); -} - -// Please call only with a single message ID -void TNavigatorImapConnection::Bodystructure(const char *messageId, - XP_Bool idIsUid) -{ - IncrementCommandTagNumber(); - - char commandString[256]; - if (idIsUid) - XP_STRCPY(commandString, "%s UID fetch"); - else - XP_STRCPY(commandString, "%s fetch"); - - XP_STRCAT(commandString, " %s (BODYSTRUCTURE)"); - XP_STRCAT(commandString,CRLF); - - const char *commandTag = GetServerCommandTag(); - int protocolStringSize = XP_STRLEN(commandString) + XP_STRLEN(messageId) + XP_STRLEN(commandTag) + 1; - char *protocolString = (char *) XP_ALLOC( protocolStringSize ); - - if (protocolString) - { - PR_snprintf(protocolString, // string to create - protocolStringSize, // max size - commandString, // format string - commandTag, // command tag - messageId); - - int ioStatus = WriteLineToSocket(protocolString); - - - ParseIMAPandCheckForNewMail(protocolString); - XP_FREE(protocolString); - } - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::PipelinedFetchMessageParts(const char *uid, - TIMAPMessagePartIDArray *parts) -{ - // assumes no chunking - - // build up a string to fetch - char *stringToFetch = NULL, *what = NULL; - int32 currentPartNum = 0; - while ((parts->GetNumParts() > currentPartNum) && !DeathSignalReceived()) - { - TIMAPMessagePartID *currentPart = parts->GetPart(currentPartNum); - if (currentPart) - { - // Do things here depending on the type of message part - // Append it to the fetch string - if (currentPartNum > 0) - StrAllocCat(stringToFetch, " "); - - switch (currentPart->GetFields()) - { - case kMIMEHeader: - what = PR_smprintf("BODY[%s.MIME]",currentPart->GetPartNumberString()); - if (what) - { - StrAllocCat(stringToFetch, what); - XP_FREE(what); - } - else - HandleMemoryFailure(); - break; - case kRFC822HeadersOnly: - if (currentPart->GetPartNumberString()) - { - what = PR_smprintf("BODY[%s.HEADER]", currentPart->GetPartNumberString()); - if (what) - { - StrAllocCat(stringToFetch, what); - XP_FREE(what); - } - else - HandleMemoryFailure(); - } - else - { - // headers for the top-level message - StrAllocCat(stringToFetch, "BODY[HEADER]"); - } - break; - default: - XP_ASSERT(FALSE); // we should only be pipelining MIME headers and Message headers - break; - } - - } - currentPartNum++; - } - - // Run the single, pipelined fetch command - if ((parts->GetNumParts() > 0) && !DeathSignalReceived() && !GetPseudoInterrupted() && stringToFetch) - { - IncrementCommandTagNumber(); - - char *commandString = PR_smprintf("%s UID fetch %s (%s)%s", GetServerCommandTag(), uid, stringToFetch, CRLF); - if (commandString) - { - int ioStatus = WriteLineToSocket(commandString); - ParseIMAPandCheckForNewMail(commandString); - XP_FREE(commandString); - } - else - HandleMemoryFailure(); - XP_FREE(stringToFetch); - } -} - - -void TNavigatorImapConnection::FetchMessage(const char *messageIds, - eFetchFields whatToFetch, - XP_Bool idIsUid, - uint32 startByte, uint32 endByte, - char *part) -{ - IncrementCommandTagNumber(); - - char commandString[350]; - if (idIsUid) - XP_STRCPY(commandString, "%s UID fetch"); - else - XP_STRCPY(commandString, "%s fetch"); - - switch (whatToFetch) { - case kEveryThingRFC822: - if (fTrackingTime) - AdjustChunkSize(); // we started another segment - fStartTime = XP_TIME(); // save start of download time - fTrackingTime = TRUE; - if (GetServerStateParser().ServerHasIMAP4Rev1Capability()) - { - if (GetServerStateParser().GetCapabilityFlag() & kHasXSenderCapability) - XP_STRCAT(commandString, " %s (XSENDER UID RFC822.SIZE BODY[]"); - else - XP_STRCAT(commandString, " %s (UID RFC822.SIZE BODY[]"); - } - else - { - if (GetServerStateParser().GetCapabilityFlag() & kHasXSenderCapability) - XP_STRCAT(commandString, " %s (XSENDER UID RFC822.SIZE RFC822"); - else - XP_STRCAT(commandString, " %s (UID RFC822.SIZE RFC822"); - } - if (endByte > 0) - { - // if we are retrieving chunks - char *byterangeString = PR_smprintf("<%ld.%ld>",startByte,endByte); - if (byterangeString) - { - XP_STRCAT(commandString, byterangeString); - XP_FREE(byterangeString); - } - } - XP_STRCAT(commandString, ")"); - break; - - case kEveryThingRFC822Peek: - { - char *formatString = ""; - uint32 server_capabilityFlags = GetServerStateParser().GetCapabilityFlag(); - - if (server_capabilityFlags & kIMAP4rev1Capability) - { - // use body[].peek since rfc822.peek is not in IMAP4rev1 - if (server_capabilityFlags & kHasXSenderCapability) - formatString = " %s (XSENDER UID RFC822.SIZE BODY.PEEK[])"; - else - formatString = " %s (UID RFC822.SIZE BODY.PEEK[])"; - } - else - { - if (server_capabilityFlags & kHasXSenderCapability) - formatString = " %s (XSENDER UID RFC822.SIZE RFC822.peek)"; - else - formatString = " %s (UID RFC822.SIZE RFC822.peek)"; - } - - XP_STRCAT(commandString, formatString); - } - break; - case kHeadersRFC822andUid: - if (GetServerStateParser().ServerHasIMAP4Rev1Capability()) - { - if (gOptimizedHeaders) - { - char *headersToDL = NULL; - char *arbitraryHeaders = GetArbitraryHeadersToDownload(); - if (arbitraryHeaders) - { - headersToDL = PR_smprintf("%s %s",IMAP_DB_HEADERS,arbitraryHeaders); - XP_FREE(arbitraryHeaders); - } - else - { - headersToDL = PR_smprintf("%s",IMAP_DB_HEADERS); - } - if (headersToDL) - { - char *what = PR_smprintf(" BODY.PEEK[HEADER.FIELDS (%s)])", headersToDL); - if (what) - { - XP_STRCAT(commandString, " %s (UID RFC822.SIZE FLAGS"); - XP_STRCAT(commandString, what); - XP_FREE(what); - } - else - { - XP_STRCAT(commandString, " %s (UID RFC822.SIZE BODY.PEEK[HEADER] FLAGS)"); - } - XP_FREE(headersToDL); - } - else - { - XP_STRCAT(commandString, " %s (UID RFC822.SIZE BODY.PEEK[HEADER] FLAGS)"); - } - } - else - XP_STRCAT(commandString, " %s (UID RFC822.SIZE BODY.PEEK[HEADER] FLAGS)"); - } - else - XP_STRCAT(commandString, " %s (UID RFC822.SIZE RFC822.HEADER FLAGS)"); - break; - case kUid: - XP_STRCAT(commandString, " %s (UID)"); - break; - case kFlags: - XP_STRCAT(commandString, " %s (FLAGS)"); - break; - case kRFC822Size: - XP_STRCAT(commandString, " %s (RFC822.SIZE)"); - break; - case kRFC822HeadersOnly: - if (GetServerStateParser().ServerHasIMAP4Rev1Capability()) - { - if (part) - { - XP_STRCAT(commandString, " %s (BODY["); - char *what = PR_smprintf("%s.HEADER])", part); - if (what) - { - XP_STRCAT(commandString, what); - XP_FREE(what); - } - else - HandleMemoryFailure(); - } - else - { - // headers for the top-level message - XP_STRCAT(commandString, " %s (BODY[HEADER])"); - } - } - else - XP_STRCAT(commandString, " %s (RFC822.HEADER)"); - break; - case kMIMEPart: - XP_STRCAT(commandString, " %s (BODY[%s]"); - if (endByte > 0) - { - // if we are retrieving chunks - char *byterangeString = PR_smprintf("<%ld.%ld>",startByte,endByte); - if (byterangeString) - { - XP_STRCAT(commandString, byterangeString); - XP_FREE(byterangeString); - } - } - XP_STRCAT(commandString, ")"); - break; - case kMIMEHeader: - XP_STRCAT(commandString, " %s (BODY[%s.MIME])"); - break; - }; - - XP_STRCAT(commandString,CRLF); - - // since messageIds can be infinitely long, use a dynamic buffer rather than the fixed one - const char *commandTag = GetServerCommandTag(); - int protocolStringSize = XP_STRLEN(commandString) + XP_STRLEN(messageIds) + XP_STRLEN(commandTag) + 1 + - (part ? XP_STRLEN(part) : 0); - char *protocolString = (char *) XP_ALLOC( protocolStringSize ); - - if (protocolString) - { - if ((whatToFetch == kMIMEPart) || - (whatToFetch == kMIMEHeader)) - { - PR_snprintf(protocolString, // string to create - protocolStringSize, // max size - commandString, // format string - commandTag, // command tag - messageIds, - part); - } - else - { - PR_snprintf(protocolString, // string to create - protocolStringSize, // max size - commandString, // format string - commandTag, // command tag - messageIds); - } - - int ioStatus = WriteLineToSocket(protocolString); - - - ParseIMAPandCheckForNewMail(protocolString); - XP_FREE(protocolString); - } - else - HandleMemoryFailure(); -} - - -void TNavigatorImapConnection::FetchTryChunking(const char *messageIds, - eFetchFields whatToFetch, - XP_Bool idIsUid, - char *part, - uint32 downloadSize) -{ - GetServerStateParser().SetTotalDownloadSize(downloadSize); - if (fFetchByChunks && GetServerStateParser().ServerHasIMAP4Rev1Capability() && - (downloadSize > (uint32) fChunkThreshold)) - { - uint32 startByte = 0; - GetServerStateParser().ClearLastFetchChunkReceived(); - while (!DeathSignalReceived() && !GetPseudoInterrupted() && - !GetServerStateParser().GetLastFetchChunkReceived() && - GetServerStateParser().ContinueParse()) - { - uint32 sizeToFetch = startByte + fChunkSize > downloadSize ? - downloadSize - startByte : fChunkSize; - FetchMessage(messageIds, - whatToFetch, - idIsUid, - startByte, sizeToFetch, - part); - startByte += sizeToFetch; - } - - // Only abort the stream if this is a normal message download - // Otherwise, let the body shell abort the stream. - if ((whatToFetch == TIMAP4BlockingConnection::kEveryThingRFC822) - && - ((startByte > 0 && (startByte < downloadSize) && - (DeathSignalReceived() || GetPseudoInterrupted())) || - !GetServerStateParser().ContinueParse())) - { - AbortMessageDownLoad(); - PseudoInterrupt(FALSE); - } - } - else - { - // small message, or (we're not chunking and not doing bodystructure), - // or the server is not rev1. - // Just fetch the whole thing. - FetchMessage(messageIds, whatToFetch,idIsUid, 0, 0, part); - } -} - - -PRMonitor *TNavigatorImapConnection::fFindingMailboxesMonitor = nil; -PRMonitor *TNavigatorImapConnection::fUpgradeToSubscriptionMonitor = nil; -XP_Bool TNavigatorImapConnection::fHaveWeEverCheckedForSubscriptionUpgrade = FALSE; -MSG_BIFF_STATE TNavigatorImapConnection::fCurrentBiffState = MSG_BIFF_Unknown; -PRMonitor *TIMAPHostInfo::gCachedHostInfoMonitor = nil; -TIMAPHostInfo *TIMAPHostInfo::fHostInfoList = nil; - -void TNavigatorImapConnection::ResetCachedConnectionInfo() -{ - fCurrentBiffState = MSG_BIFF_Unknown; - TIMAPHostInfo::ResetAll(); -} - - - - -static -void WriteLineEvent(void *blockingConnectionVoid, - void *sockInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - TIMAPSocketInfo *sockInfo = (TIMAPSocketInfo *)sockInfoVoid; - - if (sockInfo && sockInfo->writeLine) - { - LIBNET_LOCK(); - sockInfo->writeStatus = (int) NET_BlockingWrite(ce->socket, - sockInfo->writeLine, - XP_STRLEN(sockInfo->writeLine)); - - FREEIF(sockInfo->writeLine); - LIBNET_UNLOCK(); - } - else - { - XP_ASSERT(FALSE); - } - - imapConnection->NotifyEventCompletionMonitor(); -} - - -static -void ReadFirstLineFromSocket(void *blockingConnectionVoid, - void *sockInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - TIMAPSocketInfo *sockInfo = (TIMAPSocketInfo *)sockInfoVoid; - - if (sockInfo) - { - LIBNET_LOCK(); - Bool pause = sockInfo->GetPauseForRead(); - sockInfo->readStatus = NET_BufferedReadLine(sockInfo->GetIOSocket(), - sockInfo->GetNewLineBuffer(), - sockInfo->GetInputSocketBuffer(), - sockInfo->GetInputBufferSize(), - &pause); - - LIBNET_UNLOCK(); - } - else - { - XP_ASSERT(FALSE); - } - - imapConnection->NotifyEventCompletionMonitor(); -} - -#ifndef XP_WIN16 -#define DO_THREADED_IMAP_SOCKET_IO -#endif - -#ifndef DO_THREADED_IMAP_SOCKET_IO // do socket writes in the mozilla thread - -int TNavigatorImapConnection::WriteLineToSocket(char *line) -{ - int returnValue = 0; - - if (!DeathSignalReceived()) - { - if (line) fSocketInfo->writeLine = XP_STRDUP(line); - - fSocketInfo->writeStatus = 0; - TImapFEEvent *feWriteLineEvent = - new TImapFEEvent(WriteLineEvent, // function to call - this, // for access to current - // entry and monitor - fSocketInfo, - TRUE); - - fFEEventQueue->AdoptEventToEnd(feWriteLineEvent); - PR_Sleep(PR_INTERVAL_NO_WAIT); - - // wait here for the read first line io to finish - WaitForFEEventCompletion(); - - int socketError = SOCKET_ERRNO; - Log("NET","WR",line); - //PR_LOG(IMAP, out, ("WR: %s",line)); - int writeStatus = fSocketInfo->writeStatus; - - if(writeStatus <= 0) - { - if (fCurrentEntry && fCurrentEntry->URL_s) - fCurrentEntry->URL_s->error_msg = - NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, socketError); - returnValue = MK_TCP_WRITE_ERROR; - GetServerStateParser().SetConnected(FALSE); - } - else - PR_Sleep(PR_INTERVAL_NO_WAIT); - } - - - return returnValue; -} - - -char *TNavigatorImapConnection::CreateNewLineFromSocket() -{ - Bool pauseForRead = TRUE; - char *newLine = nil; - int socketReadStatus = -1; - - while (pauseForRead && !DeathSignalReceived()) - { - fSocketInfo->SetIOSocket(GetIOSocket()); - fSocketInfo->SetPauseForRead(pauseForRead); - fSocketInfo->SetReadStatus(socketReadStatus); - fSocketInfo->SetInputSocketBuffer(&fInputSocketBuffer); - fSocketInfo->SetInputBufferSize(&fInputBufferSize); - - TImapFEEvent *feReadFirstLineEvent = - new TImapFEEvent(ReadFirstLineFromSocket, // function to call - this, // for access to current - // entry and monitor - fSocketInfo, - TRUE); - - fFEEventQueue->AdoptEventToEnd(feReadFirstLineEvent); - PR_Sleep(PR_INTERVAL_NO_WAIT); - - // wait here for the read first line io to finish - WaitForFEEventCompletion(); - - if (fSocketInfo->newLine) - newLine = XP_STRDUP(fSocketInfo->newLine); - socketReadStatus = fSocketInfo->GetReadStatus(); - //if (*(fSocketInfo->GetNewLineBuffer())) newLine = XP_STRDUP(*(socketStuff->pNewLine)); - //FREEIF(socketStuff->pNewLine); - - int socketError = PR_GetError(); - if (newLine) - Log("NET","RD", newLine); - //PR_LOG(IMAP, out, ("RD: %s",newLine)); - - if (socketReadStatus <= 0) // error - { - -#ifdef KMCENTEE_DEBUG - XP_ASSERT(socketError != PR_NOT_CONNECTED_ERROR); -#endif - if (socketError == PR_WOULD_BLOCK_ERROR - || socketError == PR_NOT_CONNECTED_ERROR) - { - pauseForRead = TRUE; - WaitForIOCompletion(); - } - else - { - LIBNET_LOCK(); - if (fCurrentEntry && fCurrentEntry->URL_s) - fCurrentEntry->URL_s->error_msg = - NET_ExplainErrorDetails(MK_TCP_READ_ERROR, - socketError); - pauseForRead = FALSE; - socketReadStatus = MK_TCP_READ_ERROR; - GetServerStateParser().SetConnected(FALSE); - LIBNET_UNLOCK(); - } - } - else if (pauseForRead && !newLine) - WaitForIOCompletion(); - else - pauseForRead = FALSE; - } - - // the comments for NET_BufferedReadLine say that newLine is allocated - // before it is set. TO me this means that the caller owns the newLine - // storage. But I have seen it stepped on and we have assertion failures - // when we delete it! - char *bogusNewLine = NULL; - if (newLine) - { - bogusNewLine = XP_STRDUP(newLine); - if (bogusNewLine) - StrAllocCat(bogusNewLine, CRLF); - - - if (!bogusNewLine) - HandleMemoryFailure(); - } - - SetConnectionStatus(socketReadStatus); - FREEIF(newLine); - - return bogusNewLine; -} - - -#else // not Win16: do it the usual way - -int TNavigatorImapConnection::WriteLineToSocket(char *line) -{ - int returnValue = 0; - - if (!DeathSignalReceived()) - { - LIBNET_LOCK(); - int writeStatus = 0; - - // check for death signal again inside LIBNET_LOCK because - // we may have locked on LIBNET_LOCK because this context - // was being interrupted and interrupting the context means - // DeathSignalReceived is true and fCurrentEntry was deleted. - if (!DeathSignalReceived()) - writeStatus = (int) NET_BlockingWrite(fCurrentEntry->socket, - line, - XP_STRLEN(line)); - - int socketError = SOCKET_ERRNO; - Log("NET","WR",line); - //PR_LOG(IMAP, out, ("WR: %s",line)); - LIBNET_UNLOCK(); - - if(writeStatus <= 0) - { - LIBNET_LOCK(); - if (!DeathSignalReceived()) - fCurrentEntry->URL_s->error_msg = - NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, socketError); - LIBNET_UNLOCK(); - returnValue = MK_TCP_WRITE_ERROR; - GetServerStateParser().SetConnected(FALSE); - } - else - PR_Sleep(PR_INTERVAL_NO_WAIT); - } - - - return returnValue; -} - -char *TNavigatorImapConnection::CreateNewLineFromSocket() -{ - Bool pauseForRead = TRUE; - char *newLine = nil; - int socketReadStatus = -1; - - while (pauseForRead && !DeathSignalReceived()) - { - LIBNET_LOCK(); - // check for death signal again inside LIBNET_LOCK because - // we may have locked on LIBNET_LOCK because this context - // was being interrupted and interrupting the context means - // DeathSignalReceived is true and fCurrentEntry was deleted. - if (!DeathSignalReceived()) - socketReadStatus = NET_BufferedReadLine(GetIOSocket(), - &newLine, - &fInputSocketBuffer, - &fInputBufferSize, - &pauseForRead); - - int socketError = PR_GetError(); - if (newLine) - Log("NET","RD",newLine); - //PR_LOG(IMAP, out, ("RD: %s",newLine)); - LIBNET_UNLOCK(); - - if (socketReadStatus <= 0) // error - { - -#ifdef KMCENTEE_DEBUG - XP_ASSERT(socketError != PR_NOT_CONNECTED_ERROR); -#endif - if (socketError == PR_WOULD_BLOCK_ERROR - || socketError == PR_NOT_CONNECTED_ERROR) - { - pauseForRead = TRUE; - WaitForIOCompletion(); - } - else - { - LIBNET_LOCK(); - if (!DeathSignalReceived()) - { - fCurrentEntry->URL_s->error_msg = - NET_ExplainErrorDetails(MK_TCP_READ_ERROR, - socketError); - } - pauseForRead = FALSE; - socketReadStatus = MK_TCP_READ_ERROR; - GetServerStateParser().SetConnected(FALSE); - LIBNET_UNLOCK(); - } - } - else if (pauseForRead && !newLine) - WaitForIOCompletion(); - else - pauseForRead = FALSE; - - } - - // the comments for NET_BufferedReadLine say that newLine is allocated - // before it is set. TO me this means that the caller owns the newLine - // storage. But I have seen it stepped on and we have assertion failures - // when we delete it! - char *bogusNewLine = NULL; - if (newLine) - { - bogusNewLine = XP_STRDUP(newLine); - if (bogusNewLine) - StrAllocCat(bogusNewLine, CRLF); - - if (!bogusNewLine) - HandleMemoryFailure(); - } - - SetConnectionStatus(socketReadStatus); - - return bogusNewLine; -} - -#endif // not win16 - - -void TNavigatorImapConnection::SetIOSocket(PRFileDesc *socket) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fIOSocket = socket; - PR_ExitMonitor(GetDataMemberMonitor()); -} - -PRFileDesc * TNavigatorImapConnection::GetIOSocket() -{ - PRFileDesc * returnSocket; - PR_EnterMonitor(GetDataMemberMonitor()); - returnSocket = fIOSocket; - PR_ExitMonitor(GetDataMemberMonitor()); - return returnSocket; -} - -void TNavigatorImapConnection::Logout() -{ - TIMAP4BlockingConnection::Logout(); - SetIOSocket(0); -} - -void TNavigatorImapConnection::SetOutputStream(NET_StreamClass *outputStream) -{ - PR_EnterMonitor(GetDataMemberMonitor()); - fOutputStream = outputStream; - PR_ExitMonitor(GetDataMemberMonitor()); -} - -NET_StreamClass *TNavigatorImapConnection::GetOutputStream() -{ - NET_StreamClass *returnStream; - PR_EnterMonitor(GetDataMemberMonitor()); - returnStream = fOutputStream; - PR_ExitMonitor(GetDataMemberMonitor()); - return returnStream; -} - -void TNavigatorImapConnection::SetIsSafeToDie() // called by TellThreadToDie -{ - PR_EnterMonitor(fPermissionToDieMonitor); - fIsSafeToDie = TRUE; - PR_Notify(fPermissionToDieMonitor); - PR_ExitMonitor(fPermissionToDieMonitor); -} - - -void TNavigatorImapConnection::SetBlockingThread(PRThread *blockingThread) -{ - fBlockingThread = blockingThread; -} - -ActiveEntry *TNavigatorImapConnection::GetActiveEntry() -{ - return fCurrentEntry; -} - -// (Use Get/SetCurrentEntryStatus()) for passing values back to libnet about the currently running ActiveEntry. -void TNavigatorImapConnection::SetCurrentEntryStatus(int status) -{ - // There was a deadlock when the imap thread was waiting for this libnet lock and the mozilla thread - // held this lock, finished the current url and tried to launch another url from the url exit function. - // This caused the mozilla thread to never release the LIBNET_LOCK. - - XP_ASSERT(GetConnectionStatus() >= 0); - - LIBNET_LOCK(); - if (!DeathSignalReceived()) - { - ActiveEntry *ce = GetActiveEntry(); - if (ce) - ce->status = status; - } - LIBNET_UNLOCK(); -} - - -int TNavigatorImapConnection::GetCurrentEntryStatus() -{ - int returnStatus = 0; - LIBNET_LOCK(); - if (!DeathSignalReceived()) - { - ActiveEntry *ce = GetActiveEntry(); - if (ce) - returnStatus = ce->status; - } - LIBNET_UNLOCK(); - return returnStatus; -} - -TCP_ConData **TNavigatorImapConnection::GetTCPConData() -{ - return &fTCPConData; -} - -void TNavigatorImapConnection::EstablishServerConnection() -{ - // let the fe-thread start the connection since we are using - // old non-thread safe functions to do it. - - // call NET_FinishConnect until we are connected or errored out - while (!DeathSignalReceived() && (GetConnectionStatus() == MK_WAITING_FOR_CONNECTION)) - { - TImapFEEvent *feFinishConnectionEvent = - new TImapFEEvent(FinishIMAPConnection, // function to call - this, // for access to current - // entry and monitor - nil, - TRUE); - - fFEEventQueue->AdoptEventToEnd(feFinishConnectionEvent); - PR_Sleep(PR_INTERVAL_NO_WAIT); - - // wait here for the connection finish io to finish - WaitForFEEventCompletion(); - if (!DeathSignalReceived() && (GetConnectionStatus() == MK_WAITING_FOR_CONNECTION)) - WaitForIOCompletion(); - - } - - if (GetConnectionStatus() == MK_CONNECTED) - { - // get the one line response from the IMAP server - char *serverResponse = CreateNewLineFromSocket(); - if (serverResponse) - { - if (!XP_STRNCASECMP(serverResponse, "* OK", 4)) - { - SetConnectionStatus(0); - preAuthSucceeded = FALSE; - //if (!XP_STRNCASECMP(serverResponse, "* OK Netscape IMAP4rev1 Service 3.0", 35)) - // GetServerStateParser().SetServerIsNetscape30Server(); - } - else if (!XP_STRNCASECMP(serverResponse, "* PREAUTH", 9)) - { - // we've been pre-authenticated. - // we can skip the whole password step, right into the - // kAuthenticated state - GetServerStateParser().PreauthSetAuthenticatedState(); - - // tell the master that we're authenticated - XP_Bool loginSucceeded = TRUE; - TImapFEEvent *alertEvent = - new TImapFEEvent(msgSetUserAuthenticated, // function to call - this, // access to current entry - (void *)loginSucceeded, - TRUE); - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - } - else - HandleMemoryFailure(); - - preAuthSucceeded = TRUE; - if (fCurrentBiffState == MSG_BIFF_Unknown) - { - fCurrentBiffState = MSG_BIFF_NoMail; - SendSetBiffIndicatorEvent(fCurrentBiffState); - } - - if (GetServerStateParser().GetCapabilityFlag() == - kCapabilityUndefined) - Capability(); - - if ( !(GetServerStateParser().GetCapabilityFlag() & - (kIMAP4Capability | - kIMAP4rev1Capability | - kIMAP4other) ) ) - { - AlertUserEvent_UsingId(MK_MSG_IMAP_SERVER_NOT_IMAP4); - SetCurrentEntryStatus(-1); - SetConnectionStatus(-1); // stop netlib - preAuthSucceeded = FALSE; - } - else - { - ProcessAfterAuthenticated(); - // the connection was a success - SetConnectionStatus(0); - } - } - else - { - preAuthSucceeded = FALSE; - SetConnectionStatus(MK_BAD_CONNECT); - } - - fNeedGreeting = FALSE; - FREEIF(serverResponse); - } - else - SetConnectionStatus(MK_BAD_CONNECT); - } - - if ((GetConnectionStatus() < 0) && !DeathSignalReceived()) - { - if (!MSG_Biff_Master_NikiCallingGetNewMail()) - AlertUserEvent_UsingId(MK_BAD_CONNECT); - } - -} - - -void TNavigatorImapConnection::ProcessStoreFlags(const char *messageIds, - XP_Bool idsAreUids, - imapMessageFlagsType flags, - XP_Bool addFlags) -{ - if (!flags) - return; - - char *flagString; - XP_Bool userF = GetServerStateParser().SupportsUserFlags(); - - if (!userF && (flags == kImapMsgForwardedFlag || - flags == kImapMsgMDNSentFlag)) // if only flag, and not supported bail out - return; - if (addFlags) - flagString = XP_STRDUP("+Flags ("); - else - flagString = XP_STRDUP("-Flags ("); - - if (flags & kImapMsgSeenFlag) - StrAllocCat(flagString, "\\Seen "); - if (flags & kImapMsgAnsweredFlag) - StrAllocCat(flagString, "\\Answered "); - if (flags & kImapMsgFlaggedFlag) - StrAllocCat(flagString, "\\Flagged "); - if (flags & kImapMsgDeletedFlag) - StrAllocCat(flagString, "\\Deleted "); - if (flags & kImapMsgDraftFlag) - StrAllocCat(flagString, "\\Draft "); - if ((flags & kImapMsgForwardedFlag) && userF) - StrAllocCat(flagString, "Forwarded "); // if supported - if ((flags & kImapMsgMDNSentFlag) && userF) - StrAllocCat(flagString, "MDNSent "); // if supported - - // replace the final space with ')' - *(flagString + XP_STRLEN(flagString) - 1) = ')'; - - Store(messageIds, flagString, idsAreUids); - FREEIF(flagString); -} - - -void TNavigatorImapConnection::ProcessAfterAuthenticated() -{ - // if we're a netscape server, and we haven't got the admin url, get it - if (!TIMAPHostInfo::GetHostHasAdminURL(fCurrentUrl->GetUrlHost())) - { - if (GetServerStateParser().GetCapabilityFlag() & kXServerInfoCapability) - { - XServerInfo(); - if (GetServerStateParser().LastCommandSuccessful()) - { - TImapFEEvent *alertEvent = - new TImapFEEvent(msgSetMailServerURLs, // function to call - this, // access to current entry - (void *) fCurrentUrl->GetUrlHost(), - TRUE); - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - // WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - } - } - else if (GetServerStateParser().GetCapabilityFlag() & kHasXNetscapeCapability) - { - Netscape(); - if (GetServerStateParser().LastCommandSuccessful()) - { - TImapFEEvent *alertEvent = - new TImapFEEvent(msgSetMailAccountURL, // function to call - this, // access to current entry - (void *) fCurrentUrl->GetUrlHost(), - TRUE); - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - // WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - } - } - } - - if (GetServerStateParser().ServerHasNamespaceCapability() && - TIMAPHostInfo::GetNamespacesOverridableForHost(fCurrentUrl->GetUrlHost())) - { - Namespace(); - } -} - -XP_Bool TNavigatorImapConnection::TryToLogon() -{ - - int32 logonTries = 0; - XP_Bool loginSucceeded = FALSE; - - do - { - char *passwordForHost = TIMAPHostInfo::GetPasswordForHost(fCurrentUrl->GetUrlHost()); - XP_Bool imapPasswordIsNew = FALSE; - XP_Bool setUserAuthenticatedIsSafe = FALSE; - ActiveEntry *ce = GetActiveEntry(); - MSG_Master *master = (ce) ? ce->window_id->mailMaster : 0; - - const char *userName = MSG_GetIMAPHostUsername(master, fCurrentUrl->GetUrlHost()); - if (userName && !passwordForHost) - { - TImapFEEvent *fePasswordEvent = - new TImapFEEvent(GetPasswordEventFunction, - this, - (void*) userName, - TRUE); - - if (fePasswordEvent) - { - fFEEventQueue->AdoptEventToEnd(fePasswordEvent); - IMAP_YIELD(PR_INTERVAL_NO_WAIT); - - // wait here password prompt to finish - WaitForFEEventCompletion(); - imapPasswordIsNew = TRUE; - passwordForHost = TIMAPHostInfo::GetPasswordForHost(fCurrentUrl->GetUrlHost()); - } - else - HandleMemoryFailure(); - } - - if (userName && passwordForHost) - { - XP_Bool prefBool = FALSE; - - XP_Bool lastReportingErrors = GetServerStateParser().GetReportingErrors(); - GetServerStateParser().SetReportingErrors(FALSE); // turn off errors - we'll put up our own. - - PREF_GetBoolPref("mail.auth_login", &prefBool); - if (prefBool) { - if (GetServerStateParser().GetCapabilityFlag() == - kCapabilityUndefined) - Capability(); - if (GetServerStateParser().GetCapabilityFlag() & - kHasAuthLoginCapability) - { - AuthLogin (userName, passwordForHost); - logonTries++; // I think this counts against most servers as a logon try - } - else - InsecureLogin(userName, passwordForHost); - } - else - InsecureLogin(userName, passwordForHost); - - if (!GetServerStateParser().LastCommandSuccessful()) - { - // login failed! - // if we failed because of an interrupt, then do not bother the user - if (!DeathSignalReceived()) - { - AlertUserEvent_UsingId(XP_MSG_IMAP_LOGIN_FAILED); - if (passwordForHost != NULL) - { - TIMAPHostInfo::SetPasswordForHost(fCurrentUrl->GetUrlHost(), NULL); - } - fCurrentBiffState = MSG_BIFF_Unknown; - SendSetBiffIndicatorEvent(fCurrentBiffState); - } - - HandleCurrentUrlError(); -// SetConnectionStatus(-1); // stop netlib - } - else // login succeeded - { - MSG_SetIMAPHostPassword(ce->window_id->mailMaster, fCurrentUrl->GetUrlHost(), passwordForHost); - imapPasswordIsNew = !TIMAPHostInfo::GetPasswordVerifiedOnline(fCurrentUrl->GetUrlHost()); - if (imapPasswordIsNew) - TIMAPHostInfo::SetPasswordVerifiedOnline(fCurrentUrl->GetUrlHost()); - NET_SetPopPassword2(passwordForHost); // bug 53380 - if (imapPasswordIsNew) - { - if (fCurrentBiffState == MSG_BIFF_Unknown) - { - fCurrentBiffState = MSG_BIFF_NoMail; - SendSetBiffIndicatorEvent(fCurrentBiffState); - } - LIBNET_LOCK(); - if (!DeathSignalReceived()) - { - setUserAuthenticatedIsSafe = GetActiveEntry()->URL_s->msg_pane != NULL; - MWContext *context = GetActiveEntry()->window_id; - if (context) - FE_RememberPopPassword(context, SECNAV_MungeString(passwordForHost)); - } - LIBNET_UNLOCK(); - } - loginSucceeded = TRUE; - } - GetServerStateParser().SetReportingErrors(lastReportingErrors); // restore it - - if (loginSucceeded && imapPasswordIsNew) - { - TImapFEEvent *alertEvent = - new TImapFEEvent(msgSetUserAuthenticated, // function to call - this, // access to current entry - (void *)loginSucceeded, - TRUE); - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - // WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - } - - if (loginSucceeded) - { - ProcessAfterAuthenticated(); - } - } - else - { - // The user hit "Cancel" on the dialog box - //AlertUserEvent("Login cancelled."); - HandleCurrentUrlError(); - SetCurrentEntryStatus(-1); - SetConnectionStatus(-1); // stop netlib - break; - } - } - - while (!loginSucceeded && ++logonTries < 4); - - if (!loginSucceeded) - { - fCurrentBiffState = MSG_BIFF_Unknown; - SendSetBiffIndicatorEvent(fCurrentBiffState); - HandleCurrentUrlError(); - SetConnectionStatus(-1); // stop netlib - } - - return loginSucceeded; -} - - -void TNavigatorImapConnection::ProcessCurrentURL() -{ - XP_ASSERT(GetFEEventQueue().NumberOfEventsInQueue() == 0); - - if (fCurrentUrl->ValidIMAPUrl()) - { - // Reinitialize the parser - GetServerStateParser().InitializeState(); - - // establish the connection and login - if ((GetConnectionStatus() == MK_WAITING_FOR_CONNECTION) || - fNeedGreeting) - EstablishServerConnection(); - - if (!DeathSignalReceived() && (GetConnectionStatus() >= 0) && - (GetServerStateParser().GetIMAPstate() == - TImapServerState::kNonAuthenticated)) - { - /* if we got here, the server's greeting should not have - been PREAUTH */ - if (GetServerStateParser().GetCapabilityFlag() == - kCapabilityUndefined) - Capability(); - - if ( !(GetServerStateParser().GetCapabilityFlag() & - (kIMAP4Capability | - kIMAP4rev1Capability | - kIMAP4other) ) ) - { - AlertUserEvent_UsingId(MK_MSG_IMAP_SERVER_NOT_IMAP4); - SetCurrentEntryStatus(-1); - SetConnectionStatus(-1); // stop netlib - } - else - { - TryToLogon(); - } - } - - if (!DeathSignalReceived() && (GetConnectionStatus() >= 0)) - { - FindMailboxesIfNecessary(); - - if (fCurrentUrl->GetUrlIMAPstate() == - TIMAPUrl::kAuthenticatedStateURL) - ProcessAuthenticatedStateURL(); - else // must be kSelectedStateURL - ProcessSelectedStateURL(); - - // The URL has now been processed - if (GetConnectionStatus() < 0) - HandleCurrentUrlError(); - if (GetServerStateParser().LastCommandSuccessful()) - SetCurrentEntryStatus(0); - SetConnectionStatus(-1); // stop netlib - - if (DeathSignalReceived()) - HandleCurrentUrlError(); - } - else - HandleCurrentUrlError(); - } - else - { - if (!fCurrentUrl->ValidIMAPUrl()) - AlertUserEvent("Invalid IMAP4 url"); - SetCurrentEntryStatus(-1); - SetConnectionStatus(-1); - } - - PseudoInterrupt(FALSE); // clear this, because we must be done interrupting? - - //ProgressUpdateEvent("Current IMAP Url Completed"); -} - -void TNavigatorImapConnection::FolderHeaderDump(uint32 *msgUids, uint32 msgCount) -{ - FolderMsgDump(msgUids, msgCount, TIMAP4BlockingConnection::kHeadersRFC822andUid); - - if (GetServerStateParser().NumberOfMessages()) - { - HeaderFetchCompleted(); - - // if an INBOX exists on this host - //char *inboxName = TIMAPHostInfo::GetOnlineInboxPathForHost(fCurrentUrl->GetUrlHost()); - char *inboxName = PR_smprintf("INBOX"); - if (inboxName) - { - // if this was the inbox, turn biff off - if (!XP_STRCASECMP(GetServerStateParser().GetSelectedMailboxName(), inboxName)) - { - fCurrentBiffState = MSG_BIFF_NoMail; - SendSetBiffIndicatorEvent(fCurrentBiffState); - } - XP_FREE(inboxName); - } - } -} - -void TNavigatorImapConnection::ShowProgress() -{ - if (fProgressStringId) - { - char *progressString = NULL; - const char *mailboxName = GetServerStateParser().GetSelectedMailboxName(); - progressString = PR_sprintf_append(progressString, XP_GetString(fProgressStringId), (mailboxName) ? mailboxName : "", ++fProgressIndex, fProgressCount); - if (progressString) - PercentProgressUpdateEvent(progressString,(100*(fProgressIndex))/fProgressCount ); - FREEIF(progressString); - } -} - -void TNavigatorImapConnection::FolderMsgDump(uint32 *msgUids, uint32 msgCount, TIMAP4BlockingConnection::eFetchFields fields) -{ - switch (fields) { - case TIMAP4BlockingConnection::kHeadersRFC822andUid: - fProgressStringId = XP_RECEIVING_MESSAGE_HEADERS_OF; - break; - case TIMAP4BlockingConnection::kFlags: - fProgressStringId = XP_RECEIVING_MESSAGE_FLAGS_OF; - break; - default: - fProgressStringId = XP_FOLDER_RECEIVING_MESSAGE_OF; - break; - } - - fProgressIndex = 0; - fProgressCount = msgCount; - - FolderMsgDumpRecurse(msgUids, msgCount, fields); - - fProgressStringId = 0; -} - -uint32 TNavigatorImapConnection::CountMessagesInIdString(const char *idString) -{ - uint32 numberOfMessages = 0; - char *uidString = XP_STRDUP(idString); - - if (uidString) - { - // This is in the form <id>,<id>, or <id1>:<id2> - char curChar = *uidString; - XP_Bool isRange = FALSE; - int32 curToken; - int32 saveStartToken=0; - - for (char *curCharPtr = uidString; curChar && *curCharPtr;) - { - char *currentKeyToken = curCharPtr; - curChar = *curCharPtr; - while (curChar != ':' && curChar != ',' && curChar != '\0') - curChar = *curCharPtr++; - *(curCharPtr - 1) = '\0'; - curToken = atol(currentKeyToken); - if (isRange) - { - while (saveStartToken < curToken) - { - numberOfMessages++; - saveStartToken++; - } - } - - numberOfMessages++; - isRange = (curChar == ':'); - if (isRange) - saveStartToken = curToken + 1; - } - XP_FREE(uidString); - } - return numberOfMessages; -} - -char *IMAP_AllocateImapUidString(uint32 *msgUids, uint32 msgCount) -{ - int blocksAllocated = 1; - char *returnIdString = (char *) XP_ALLOC(256); - if (returnIdString) - { - char *currentidString = returnIdString; - *returnIdString = 0; - - int32 startSequence = (msgCount > 0) ? msgUids[0] : -1; - int32 curSequenceEnd = startSequence; - uint32 total = msgCount; - - for (uint32 keyIndex=0; returnIdString && (keyIndex < total); keyIndex++) - { - int32 curKey = msgUids[keyIndex]; - int32 nextKey = (keyIndex + 1 < total) ? msgUids[keyIndex + 1] : -1; - XP_Bool lastKey = (nextKey == -1); - - if (lastKey) - curSequenceEnd = curKey; - if (nextKey == curSequenceEnd + 1 && !lastKey) - { - curSequenceEnd = nextKey; - continue; - } - else if (curSequenceEnd > startSequence) - { - sprintf(currentidString, "%ld:%ld,", startSequence, curSequenceEnd); - startSequence = nextKey; - curSequenceEnd = startSequence; - } - else - { - startSequence = nextKey; - curSequenceEnd = startSequence; - sprintf(currentidString, "%ld,", msgUids[keyIndex]); - } - currentidString += XP_STRLEN(currentidString); - if ((currentidString + 20) > (returnIdString + (blocksAllocated * 256))) - { - returnIdString = (char *) XP_REALLOC(returnIdString, ++blocksAllocated*256); - if (returnIdString) - currentidString = returnIdString + XP_STRLEN(returnIdString); - } - } - } - - if (returnIdString && *returnIdString) - *(returnIdString + XP_STRLEN(returnIdString) - 1) = 0; // eat the comma - - return returnIdString; -} - - -void TNavigatorImapConnection::FolderMsgDumpRecurse(uint32 *msgUids, uint32 msgCount, TIMAP4BlockingConnection::eFetchFields fields) -{ - PastPasswordCheckEvent(); - - if (msgCount <= 200) - { - char *idString = IMAP_AllocateImapUidString(msgUids, msgCount); // 20 * 200 - if (idString) - { - FetchMessage(idString, - fields, - TRUE); // msg ids are uids - XP_FREE(idString); - } - else - HandleMemoryFailure(); - } - else - { - FolderMsgDumpRecurse(msgUids, 200, fields); - FolderMsgDumpRecurse(msgUids + 200, msgCount - 200, fields); - } -} - - - -void TNavigatorImapConnection::SendSetBiffIndicatorEvent(MSG_BIFF_STATE /*newState*/) -{ - /* TImapFEEvent *biffIndicatorEvent = - new TImapFEEvent(SetBiffIndicator, // function to call - (void *) (unsigned long) newState, - this); - - if (newState == MSG_BIFF_NewMail) - fMailToFetch = TRUE; - else - fMailToFetch = FALSE; - if (biffIndicatorEvent) - { - fFEEventQueue->AdoptEventToEnd(biffIndicatorEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); */ -} - - - -// We get called to see if there is mail waiting for us at the server, even if it may have been -// read elsewhere. We just want to know if we should download headers or not. - -XP_Bool TNavigatorImapConnection::CheckNewMail() -{ - if (!fGetHeaders) - return FALSE; // use biff instead - return TRUE; - /* if (!fMailToFetch && fNewMail) { // This was the old style biff, we don't want this anymore - fMailToFetch = TRUE; - if (fCurrentBiffState != MSG_BIFF_NewMail) - { - fCurrentBiffState = MSG_BIFF_NewMail; - //SendSetBiffIndicatorEvent(fCurrentBiffState); deadlock - } - } - return fMailToFetch; */ -} - - - - -// Use the noop to tell the server we are still here, and therefore we are willing to receive -// status updates. The recent or exists response from the server could tell us that there is -// more mail waiting for us, but we need to check the flags of the mail and the high water mark -// to make sure that we do not tell the user that there is new mail when perhaps they have -// already read it in another machine. - -void TNavigatorImapConnection::PeriodicBiff() -{ - - MSG_BIFF_STATE startingState = fCurrentBiffState; - - //if (fCurrentBiffState == MSG_BIFF_NewMail) // dont do this since another computer could be used to read messages - // return; - if (!fFlagState) - return; - if (GetServerStateParser().GetIMAPstate() == TImapServerState::kFolderSelected) - { - Noop(); // check the latest number of messages - if (GetServerStateParser().NumberOfMessages() != fFlagState->GetNumberOfMessages()) - { - uint32 id = GetServerStateParser().HighestRecordedUID() + 1; - char fetchStr[100]; // only update flags - uint32 added = 0, deleted = 0; - - deleted = fFlagState->GetNumberOfDeletedMessages(); - added = fFlagState->GetNumberOfMessages(); - if (!added || (added == deleted)) // empty keys, get them all - id = 1; - - //sprintf(fetchStr, "%ld:%ld", id, id + GetServerStateParser().NumberOfMessages() - fFlagState->GetNumberOfMessages()); - sprintf(fetchStr, "%ld:*", id); - FetchMessage(fetchStr, TIMAP4BlockingConnection::kFlags, TRUE); - - if (fFlagState && ((uint32) fFlagState->GetHighestNonDeletedUID() >= id) && fFlagState->IsLastMessageUnseen()) - fCurrentBiffState = MSG_BIFF_NewMail; - else - fCurrentBiffState = MSG_BIFF_NoMail; - } - else - fCurrentBiffState = MSG_BIFF_NoMail; - } - else - fCurrentBiffState = MSG_BIFF_Unknown; - - if (startingState != fCurrentBiffState) - SendSetBiffIndicatorEvent(fCurrentBiffState); -} - -void TNavigatorImapConnection::HandleCurrentUrlError() -{ - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kSelectFolder) - { - // let the front end know the select failed so they - // don't leave the view without a database. - mailbox_spec *notSelectedSpec = (mailbox_spec *) XP_CALLOC(1, sizeof( mailbox_spec)); - if (notSelectedSpec) - { - notSelectedSpec->allocatedPathName = fCurrentUrl->CreateCanonicalSourceFolderPathString(); - notSelectedSpec->hostName = fCurrentUrl->GetUrlHost(); - notSelectedSpec->folderSelected = FALSE; - notSelectedSpec->flagState = NULL; - notSelectedSpec->onlineVerified = FALSE; - UpdatedMailboxSpec(notSelectedSpec); - } - } -} - -XP_Bool TNavigatorImapConnection::RenameHierarchyByHand(const char *oldParentMailboxName, const char *newParentMailboxName) -{ - XP_Bool renameSucceeded = TRUE; - fDeletableChildren = XP_ListNew(); - - XP_Bool nonHierarchicalRename = ((GetServerStateParser().GetCapabilityFlag() & kNoHierarchyRename) - || MailboxIsNoSelectMailbox(oldParentMailboxName)); - - if (fDeletableChildren) - { - fHierarchyNameState = kDeleteSubFoldersInProgress; - TIMAPNamespace *ns = TIMAPHostInfo::GetNamespaceForMailboxForHost(fCurrentUrl->GetUrlHost(), oldParentMailboxName); // for delimiter - if (!ns) - { - if (!XP_STRCASECMP(oldParentMailboxName, "INBOX")) - ns = TIMAPHostInfo::GetDefaultNamespaceOfTypeForHost(fCurrentUrl->GetUrlHost(), kPersonalNamespace); - } - if (ns) - { - char *pattern = PR_smprintf("%s%c*", oldParentMailboxName,ns->GetDelimiter()); - if (pattern) - { - if (TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost())) - Lsub(pattern); - else - List(pattern); - XP_FREE(pattern); - } - } - fHierarchyNameState = kNoOperationInProgress; - - if (GetServerStateParser().LastCommandSuccessful()) - renameSucceeded = RenameMailboxRespectingSubscriptions(oldParentMailboxName,newParentMailboxName, TRUE); // rename this, and move subscriptions - - int numberToDelete = XP_ListCount(fDeletableChildren); - - for (int childIndex = 1; (childIndex <= numberToDelete) && renameSucceeded; childIndex++) - { - // the imap parser has already converted to a non UTF7 string in the canonical - // format so convert it back - char *currentName = (char *) XP_ListGetObjectNum(fDeletableChildren, childIndex); - if (currentName) - { - char *serverName = fCurrentUrl->AllocateServerPath(currentName); - char *convertedName = serverName ? CreateUtf7ConvertedString(serverName, TRUE) : (char *)NULL; - FREEIF(serverName); - currentName = convertedName; // currentName not leaked, deleted in XP_ListDestroy - } - - // calculate the new name and do the rename - char *newChildName = (char *) XP_ALLOC(XP_STRLEN(currentName) + XP_STRLEN(newParentMailboxName) + 1); - if (newChildName) - { - XP_STRCPY(newChildName, newParentMailboxName); - XP_STRCAT(newChildName, currentName + XP_STRLEN(oldParentMailboxName)); - RenameMailboxRespectingSubscriptions(currentName,newChildName, nonHierarchicalRename); // pass in xNonHierarchicalRename to - // determine if we should really reanme, - // or just move subscriptions - renameSucceeded = GetServerStateParser().LastCommandSuccessful(); - XP_FREE(newChildName); - } - FREEIF(currentName); - } - - XP_ListDestroy(fDeletableChildren); - fDeletableChildren = NULL; - } - return renameSucceeded; -} - -XP_Bool TNavigatorImapConnection::DeleteSubFolders(const char *selectedMailbox) -{ - XP_Bool deleteSucceeded = TRUE; - fDeletableChildren = XP_ListNew(); - - if (fDeletableChildren) - { - fHierarchyNameState = kDeleteSubFoldersInProgress; - char *pattern = PR_smprintf("%s%c*", selectedMailbox, fCurrentUrl->GetOnlineSubDirSeparator()); - if (pattern) - { - List(pattern); - XP_FREE(pattern); - } - fHierarchyNameState = kNoOperationInProgress; - - // this should be a short list so perform a sequential search for the - // longest name mailbox. Deleting the longest first will hopefully prevent the server - // from having problems about deleting parents - int numberToDelete = XP_ListCount(fDeletableChildren); - - deleteSucceeded = GetServerStateParser().LastCommandSuccessful(); - for (int outerIndex = 1; (outerIndex <= numberToDelete) && deleteSucceeded; outerIndex++) - { - char *longestName = NULL; - for (int innerIndex = 1; innerIndex <= XP_ListCount(fDeletableChildren); innerIndex++) - { - char *currentName = (char *) XP_ListGetObjectNum(fDeletableChildren, innerIndex); - if (!longestName || (XP_STRLEN(longestName) < XP_STRLEN(currentName) ) ) - longestName = currentName; - } - XP_ASSERT(longestName); - XP_ListRemoveObject(fDeletableChildren, longestName); - - // the imap parser has already converted to a non UTF7 string in the canonical - // format so convert it back - if (longestName) - { - char *serverName = fCurrentUrl->AllocateServerPath(longestName); - char *convertedName = serverName ? CreateUtf7ConvertedString(serverName, TRUE) : 0; - FREEIF(serverName); - XP_FREE(longestName); - longestName = convertedName; - } - - // some imap servers include the selectedMailbox in the list of - // subfolders of the selectedMailbox. Check for this so we don't delete - // the selectedMailbox (usually the trash and doing an empty trash) - - // The Cyrus imap server ignores the "INBOX.Trash" constraining string passed - // to the list command. Be defensive and make sure we only delete children of the trash - if (longestName && - XP_STRCMP(selectedMailbox, longestName) && - !XP_STRNCMP(selectedMailbox, longestName, XP_STRLEN(selectedMailbox))) - { - XP_Bool deleted = DeleteMailboxRespectingSubscriptions(longestName); - if (deleted) - FolderDeleted(longestName); - deleteSucceeded = deleted; - } - FREEIF(longestName); - } - - XP_ListDestroy(fDeletableChildren); - fDeletableChildren = NULL; - } - return deleteSucceeded; -} - - -void TNavigatorImapConnection::ProcessMailboxUpdate(XP_Bool handlePossibleUndo, XP_Bool /*fromBiffUpdate*/) -{ - if (DeathSignalReceived()) - return; - // fetch the flags and uids of all existing messages or new ones - if (!DeathSignalReceived() && GetServerStateParser().NumberOfMessages()) - { - if (handlePossibleUndo) - { - // undo any delete flags we may have asked to - char *undoIds = fCurrentUrl->CreateListOfMessageIdsString(); - if (undoIds && *undoIds) - { - // if this string started with a '-', then this is an undo of a delete - // if its a '+' its a redo - if (*undoIds == '-') - Store(undoIds+1, "-FLAGS (\\Deleted)", TRUE); // most servers will fail silently on a failure, deal with it? - else if (*undoIds == '+') - Store(undoIds+1, "+FLAGS (\\Deleted)", TRUE); // most servers will fail silently on a failure, deal with it? - else - XP_ASSERT(FALSE); - } - FREEIF(undoIds); - } - - if (!DeathSignalReceived()) // only expunge if not reading messages manually and before fetching new - { - if (fFlagState && (fFlagState->GetNumberOfDeletedMessages() >= 40) && fDeleteModelIsMoveToTrash) - Expunge(); // might be expensive, test for user cancel - } - - // make the parser record these flags - char fetchStr[100]; - uint32 added = 0, deleted = 0; - - if (fFlagState) - { - added = fFlagState->GetNumberOfMessages(); - deleted = fFlagState->GetNumberOfDeletedMessages(); - } - if (fFlagState && (!added || (added == deleted))) - FetchMessage("1:*", TIMAP4BlockingConnection::kFlags, TRUE); // id string shows uids - else { - sprintf(fetchStr, "%ld:*", GetServerStateParser().HighestRecordedUID() + 1); - FetchMessage(fetchStr, TIMAP4BlockingConnection::kFlags, TRUE); // only new messages please - } - } - else if (!DeathSignalReceived()) - GetServerStateParser().ResetFlagInfo(0); - - mailbox_spec *new_spec = GetServerStateParser().CreateCurrentMailboxSpec(); - if (new_spec && !DeathSignalReceived()) - { - MWContext *ct = NULL; - - LIBNET_LOCK(); - if (!DeathSignalReceived()) - { - // if this is an expunge url, libmsg will not ask for headers - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kExpungeFolder) - new_spec->box_flags |= kJustExpunged; - - ct = new_spec->connection->fCurrentEntry->window_id; - ct->imapURLPane = MSG_FindPane(fCurrentEntry->window_id, MSG_ANYPANE); - } - LIBNET_UNLOCK(); - if (ct) - { - if (!ct->currentIMAPfolder) - ct->currentIMAPfolder = (MSG_IMAPFolderInfoMail *) MSG_FindImapFolder(ct->imapURLPane, fCurrentUrl->GetUrlHost(), "INBOX"); // use real folder name - /* MSG_IMAPFolderInfoMail *imapInbox; - if (urlFolder) - imapInbox = URL_s->msg_pane->GetMaster()->FindImapMailFolder(urlFolder->GetHostName(), "INBOX"); - else - imapInbox = URL_s->msg_pane->GetMaster()->FindImapMailFolder("INBOX"); - if (imapInbox) - imapInbox->NotifyFolderLoaded(URL_s->msg_pane); - */ - PR_EnterMonitor(fWaitForBodyIdsMonitor); - UpdatedMailboxSpec(new_spec); - } - } - else if (!new_spec) - HandleMemoryFailure(); - - // Block until libmsg decides whether to download headers or not. - uint32 *msgIdList; - uint32 msgCount = 0; - - if (!DeathSignalReceived()) - { - WaitForPotentialListOfMsgsToFetch(&msgIdList, msgCount); - - if (new_spec) - PR_ExitMonitor(fWaitForBodyIdsMonitor); - - if (msgIdList && !DeathSignalReceived() && GetServerStateParser().LastCommandSuccessful()) - { - FolderHeaderDump(msgIdList, msgCount); - FREEIF( msgIdList); - } - // this might be bogus, how are we going to do pane notification and stuff when we fetch bodies without - // headers! - } - // wait for a list of bodies to fetch. - if (!DeathSignalReceived() && GetServerStateParser().LastCommandSuccessful()) - { - WaitForPotentialListOfMsgsToFetch(&msgIdList, msgCount); - if ( msgCount && !DeathSignalReceived() && GetServerStateParser().LastCommandSuccessful()) - { - FolderMsgDump(msgIdList, msgCount, TIMAP4BlockingConnection::kEveryThingRFC822Peek); - FREEIF(msgIdList); - } - } - if (DeathSignalReceived()) - GetServerStateParser().ResetFlagInfo(0); -} - - -void TNavigatorImapConnection::ProcessSelectedStateURL() -{ - char *mailboxName = fCurrentUrl->CreateServerSourceFolderPathString(); - if (mailboxName) - { - char *convertedName = CreateUtf7ConvertedString(mailboxName, TRUE); - XP_FREE(mailboxName); - mailboxName = convertedName; - } - - if (mailboxName && !DeathSignalReceived()) - { - //char *inboxName = TIMAPHostInfo::GetOnlineInboxPathForHost(fCurrentUrl->GetUrlHost()); - char *inboxName = PR_smprintf("INBOX"); - TInboxReferenceCount inboxCounter(inboxName ? !XP_STRCASECMP(mailboxName, inboxName) : FALSE); - FREEIF(inboxName); - - if ( (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kBiff) && - (inboxCounter.GetInboxUsageCount() > 1)) - { - FREEIF(mailboxName); - return; - } - - XP_Bool selectIssued = FALSE; - if (GetServerStateParser().GetIMAPstate() == TImapServerState::kFolderSelected) - { - if (GetServerStateParser().GetSelectedMailboxName() && - XP_STRCMP(GetServerStateParser().GetSelectedMailboxName(), - mailboxName)) - { // we are selected in another folder - if (fCloseNeededBeforeSelect) - Close(); - if (GetServerStateParser().LastCommandSuccessful()) - { - selectIssued = TRUE; - AutoSubscribeToMailboxIfNecessary(mailboxName); - SelectMailbox(mailboxName); - } - } - else if (!GetServerStateParser().GetSelectedMailboxName()) - { // why are we in the selected state with no box name? - SelectMailbox(mailboxName); - selectIssued = TRUE; - } - else - { - // get new message counts, if any, from server - ProgressEventFunction_UsingId (MK_IMAP_STATUS_SELECTING_MAILBOX); - if (fNeedNoop) - { - Noop(); // I think this is needed when we're using a cached connection - fNeedNoop = FALSE; - } - } - } - else - { - // go to selected state - AutoSubscribeToMailboxIfNecessary(mailboxName); - SelectMailbox(mailboxName); - selectIssued = TRUE; - } - - if (selectIssued) - { - RefreshACLForFolderIfNecessary(mailboxName); - } - - XP_Bool uidValidityOk = TRUE; - if (GetServerStateParser().LastCommandSuccessful() && selectIssued && - (fCurrentUrl->GetIMAPurlType() != TIMAPUrl::kSelectFolder) && (fCurrentUrl->GetIMAPurlType() != TIMAPUrl::kLiteSelectFolder)) - { - uid_validity_info *uidStruct = (uid_validity_info *) XP_ALLOC(sizeof(uid_validity_info)); - if (uidStruct) - { - uidStruct->returnValidity = kUidUnknown; - uidStruct->hostName = fCurrentUrl->GetUrlHost(); - uidStruct->canonical_boxname = fCurrentUrl->CreateCanonicalSourceFolderPathString(); - TImapFEEvent *endEvent = - new TImapFEEvent(GetStoredUIDValidity, // function to call - this, // access to current entry/context - (void *) uidStruct, - FALSE); // retain storage ownership here - - if (endEvent) - { - fFEEventQueue->AdoptEventToEnd(endEvent); - WaitForFEEventCompletion(); - - // error on the side of caution, if the fe event fails to set uidStruct->returnValidity, then assume that UIDVALIDITY - // did not role. This is a common case event for attachments that are fetched within a browser context. - if (!DeathSignalReceived()) - uidValidityOk = (uidStruct->returnValidity == kUidUnknown) || (uidStruct->returnValidity == GetServerStateParser().FolderUID()); - } - else - HandleMemoryFailure(); - - FREEIF(uidStruct->canonical_boxname); - XP_FREE(uidStruct); - } - else - HandleMemoryFailure(); - } - - if (GetServerStateParser().LastCommandSuccessful() && !DeathSignalReceived() && (uidValidityOk || fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDeleteAllMsgs)) - { - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kLiteSelectFolder) - { - if (GetServerStateParser().LastCommandSuccessful()) - { - TImapFEEvent *liteselectEvent = - new TImapFEEvent(LiteSelectEvent, // function to call - (void *) this, - NULL, TRUE); - - if (liteselectEvent) - { - fFEEventQueue->AdoptEventToEnd(liteselectEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - // need to update the mailbox count - is this a good place? - ProcessMailboxUpdate(FALSE); // handle uidvalidity change - } - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kMsgFetch) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - if (messageIdString) - { - // we dont want to send the flags back in a group - // GetServerStateParser().ResetFlagInfo(0); - if (HandlingMultipleMessages(messageIdString)) - { - // multiple messages, fetch them all - FetchMessage(messageIdString, - TIMAP4BlockingConnection::kEveryThingRFC822Peek, - fCurrentUrl->MessageIdsAreUids()); - } - else - { - // A single message ID - - // First, let's see if we're requesting a specific MIME part - char *imappart = fCurrentUrl->GetIMAPPartToFetch(); - if (imappart) - { - if (fCurrentUrl->MessageIdsAreUids()) - { - // We actually want a specific MIME part of the message. - // The Body Shell will generate it, even though we haven't downloaded it yet. - - TIMAPBodyShell *foundShell = TIMAPHostInfo::FindShellInCacheForHost(fCurrentUrl->GetUrlHost(), - GetServerStateParser().GetSelectedMailboxName(), messageIdString); - if (!foundShell) - { - // The shell wasn't in the cache. Deal with this case later. - Log("SHELL",NULL,"Loading part, shell not found in cache!"); - //PR_LOG(IMAP, out, ("BODYSHELL: Loading part, shell not found in cache!")); - // The parser will extract the part number from the current URL. - Bodystructure(messageIdString, fCurrentUrl->MessageIdsAreUids()); - } - else - { - Log("SHELL", NULL, "Loading Part, using cached shell."); - //PR_LOG(IMAP, out, ("BODYSHELL: Loading part, using cached shell.")); - foundShell->SetConnection(this); - GetServerStateParser().UseCachedShell(foundShell); - foundShell->Generate(imappart); - GetServerStateParser().UseCachedShell(NULL); - } - } - else - { - // Message IDs are not UIDs. - XP_ASSERT(FALSE); - } - XP_FREE(imappart); - } - else - { - // downloading a single message: try to do it by bodystructure, and/or do it by chunks - uint32 messageSize = GetMessageSize(messageIdString, - fCurrentUrl->MessageIdsAreUids()); - - // We need to check the format_out bits to see if we are allowed to leave out parts, - // or if we are required to get the whole thing. Some instances where we are allowed - // to do it by parts: when viewing a message, or its source - // Some times when we're NOT allowed: when forwarding a message, saving it, moving it, etc. - ActiveEntry *ce = GetActiveEntry(); - XP_Bool allowedToBreakApart = (ce && !DeathSignalReceived()) ? ce->URL_s->allow_content_change : FALSE; - - if (gMIMEOnDemand && - allowedToBreakApart && - !GetShouldFetchAllParts() && - GetServerStateParser().ServerHasIMAP4Rev1Capability() && - (messageSize > (uint32) gMIMEOnDemandThreshold) && - !fCurrentUrl->MimePartSelectorDetected()) // if a ?part=, don't do BS. - { - // OK, we're doing bodystructure - - // Before fetching the bodystructure, let's check our body shell cache to see if - // we already have it around. - TIMAPBodyShell *foundShell = NULL; - SetContentModified(TRUE); // This will be looked at by the cache - if (fCurrentUrl->MessageIdsAreUids()) - { - foundShell = TIMAPHostInfo::FindShellInCacheForHost(fCurrentUrl->GetUrlHost(), - GetServerStateParser().GetSelectedMailboxName(), messageIdString); - if (foundShell) - { - Log("SHELL",NULL,"Loading message, using cached shell."); - //PR_LOG(IMAP, out, ("BODYSHELL: Loading message, using cached shell.")); - foundShell->SetConnection(this); - GetServerStateParser().UseCachedShell(foundShell); - foundShell->Generate(NULL); - GetServerStateParser().UseCachedShell(NULL); - } - } - - if (!foundShell) - Bodystructure(messageIdString, fCurrentUrl->MessageIdsAreUids()); - } - else - { - // Not doing bodystructure. Fetch the whole thing, and try to do - // it by parts. - SetContentModified(FALSE); - FetchTryChunking(messageIdString, TIMAP4BlockingConnection::kEveryThingRFC822, - fCurrentUrl->MessageIdsAreUids(), NULL, messageSize); - } - } - - } - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - else if ((fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kSelectFolder) || (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kExpungeFolder)) - { - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kExpungeFolder) - Expunge(); - ProcessMailboxUpdate(TRUE); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kMsgHeader) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - if (messageIdString) - { - // we don't want to send the flags back in a group - // GetServerStateParser().ResetFlagInfo(0); - FetchMessage(messageIdString, - TIMAP4BlockingConnection::kHeadersRFC822andUid, - fCurrentUrl->MessageIdsAreUids()); - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kSearch) - { - char *searchCriteriaString = - fCurrentUrl->CreateSearchCriteriaString(); - if (searchCriteriaString) - { - Search(searchCriteriaString,fCurrentUrl->MessageIdsAreUids()); - // drop the results on the floor for now - FREEIF( searchCriteriaString); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDeleteMsg) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - - if (messageIdString) - { - if (HandlingMultipleMessages(messageIdString)) - ProgressEventFunction_UsingId (XP_IMAP_DELETING_MESSAGES); - else - ProgressEventFunction_UsingId(XP_IMAP_DELETING_MESSAGE); - Store(messageIdString, "+FLAGS (\\Deleted)", - fCurrentUrl->MessageIdsAreUids()); - - if (GetServerStateParser().LastCommandSuccessful()) - { - struct delete_message_struct *deleteMsg = (struct delete_message_struct *) XP_ALLOC (sizeof(struct delete_message_struct)); - - // convert name back from utf7 - utf_name_struct *nameStruct = (utf_name_struct *) XP_ALLOC(sizeof(utf_name_struct)); - char *convertedCanonicalName = NULL; - if (nameStruct) - { - nameStruct->toUtf7Imap = FALSE; - nameStruct->sourceString = (unsigned char *) GetServerStateParser().GetSelectedMailboxName(); - nameStruct->convertedString = NULL; - ConvertImapUtf7(nameStruct, NULL); - if (nameStruct->convertedString) - convertedCanonicalName = fCurrentUrl->AllocateCanonicalPath((char *) nameStruct->convertedString); - } - - deleteMsg->onlineFolderName = convertedCanonicalName; - deleteMsg->deleteAllMsgs = FALSE; - deleteMsg->msgIdString = messageIdString; // storage adopted, do not delete - messageIdString = nil; // deleting nil is ok - - TImapFEEvent *deleteEvent = - new TImapFEEvent(NotifyMessageDeletedEvent, // function to call - (void *) this, - (void *) deleteMsg, TRUE); - - if (deleteEvent) - fFEEventQueue->AdoptEventToEnd(deleteEvent); - else - HandleMemoryFailure(); - } - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDeleteAllMsgs) - { - uint32 numberOfMessages = GetServerStateParser().NumberOfMessages(); - if (numberOfMessages) - { - char messageIdString[100]; // enough for bazillion msgs - sprintf(messageIdString, "1:*"); - - Store(messageIdString, "+FLAGS (\\Deleted)", FALSE); // use sequence #'s - - if (GetServerStateParser().LastCommandSuccessful()) - Expunge(); // expunge messages with deleted flag - if (GetServerStateParser().LastCommandSuccessful()) - { - struct delete_message_struct *deleteMsg = (struct delete_message_struct *) XP_ALLOC (sizeof(struct delete_message_struct)); - - // convert name back from utf7 - utf_name_struct *nameStruct = (utf_name_struct *) XP_ALLOC(sizeof(utf_name_struct)); - char *convertedCanonicalName = NULL; - if (nameStruct) - { - nameStruct->toUtf7Imap = FALSE; - nameStruct->sourceString = (unsigned char *) GetServerStateParser().GetSelectedMailboxName(); - nameStruct->convertedString = NULL; - ConvertImapUtf7(nameStruct, NULL); - if (nameStruct->convertedString) - convertedCanonicalName = fCurrentUrl->AllocateCanonicalPath((char *) nameStruct->convertedString); - } - - deleteMsg->onlineFolderName = convertedCanonicalName; - deleteMsg->deleteAllMsgs = TRUE; - deleteMsg->msgIdString = nil; - - TImapFEEvent *deleteEvent = - new TImapFEEvent(NotifyMessageDeletedEvent, // function to call - (void *) this, - (void *) deleteMsg, TRUE); - - if (deleteEvent) - fFEEventQueue->AdoptEventToEnd(deleteEvent); - else - HandleMemoryFailure(); - } - - } - DeleteSubFolders(mailboxName); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kAppendMsgFromFile) - { - char *sourceMessageFile = - XP_STRDUP(GetActiveEntry()->URL_s->post_data); - char *mailboxName = - fCurrentUrl->CreateServerSourceFolderPathString(); - - if (mailboxName) - { - char *convertedName = CreateUtf7ConvertedString(mailboxName, TRUE); - XP_FREE(mailboxName); - mailboxName = convertedName; - } - if (mailboxName) - { - UploadMessageFromFile(sourceMessageFile, mailboxName, - kImapMsgSeenFlag); - } - else - HandleMemoryFailure(); - FREEIF( sourceMessageFile ); - FREEIF( mailboxName ); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kAddMsgFlags) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - - if (messageIdString) - { - ProcessStoreFlags(messageIdString, fCurrentUrl->MessageIdsAreUids(), - fCurrentUrl->GetMsgFlags(), TRUE); - - FREEIF( messageIdString); - /* - if ( !DeathSignalReceived() && - GetServerStateParser().Connected() && - !GetServerStateParser().SyntaxError()) - { - //if (fCurrentUrl->GetMsgFlags() & kImapMsgDeletedFlag) - // Expunge(); // expunge messages with deleted flag - Check(); // flush servers flag state - } - */ - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kSubtractMsgFlags) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - - if (messageIdString) - { - ProcessStoreFlags(messageIdString, fCurrentUrl->MessageIdsAreUids(), - fCurrentUrl->GetMsgFlags(), FALSE); - - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kSetMsgFlags) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - - if (messageIdString) - { - ProcessStoreFlags(messageIdString, fCurrentUrl->MessageIdsAreUids(), - fCurrentUrl->GetMsgFlags(), TRUE); - ProcessStoreFlags(messageIdString, fCurrentUrl->MessageIdsAreUids(), - ~fCurrentUrl->GetMsgFlags(), FALSE); - - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kBiff) - { - PeriodicBiff(); - } - else if ((fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineCopy) || - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineMove)) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - char *destinationMailbox = - fCurrentUrl->CreateServerDestinationFolderPathString(); - if (destinationMailbox) - { - char *convertedName = CreateUtf7ConvertedString(destinationMailbox, TRUE); - XP_FREE(destinationMailbox); - destinationMailbox = convertedName; - } - - if (messageIdString && destinationMailbox) - { - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineMove) { - if (HandlingMultipleMessages(messageIdString)) - ProgressEventFunction_UsingIdWithString (XP_IMAP_MOVING_MESSAGES_TO, destinationMailbox); - else - ProgressEventFunction_UsingIdWithString (XP_IMAP_MOVING_MESSAGE_TO, destinationMailbox); - } - else { - if (HandlingMultipleMessages(messageIdString)) - ProgressEventFunction_UsingIdWithString (XP_IMAP_COPYING_MESSAGES_TO, destinationMailbox); - else - ProgressEventFunction_UsingIdWithString (XP_IMAP_COPYING_MESSAGE_TO, destinationMailbox); - } - - Copy(messageIdString, destinationMailbox, - fCurrentUrl->MessageIdsAreUids()); - FREEIF( destinationMailbox); - ImapOnlineCopyState copyState; - if (DeathSignalReceived()) - copyState = kInterruptedState; - else - copyState = GetServerStateParser().LastCommandSuccessful() ? - kSuccessfulCopy : kFailedCopy; - OnlineCopyCompleted(copyState); - - if (GetServerStateParser().LastCommandSuccessful() && - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineMove)) - { - Store(messageIdString, "+FLAGS (\\Deleted)", - fCurrentUrl->MessageIdsAreUids()); - - XP_Bool storeSuccessful = GetServerStateParser().LastCommandSuccessful(); - - OnlineCopyCompleted( storeSuccessful ? kSuccessfulDelete : kFailedDelete); - } - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - else if ((fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineCopy) || - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineMove)) - { - char *messageIdString = - fCurrentUrl->CreateListOfMessageIdsString(); - if (messageIdString) - { - fProgressStringId = XP_FOLDER_RECEIVING_MESSAGE_OF; - fProgressIndex = 0; - fProgressCount = CountMessagesInIdString(messageIdString); - - FetchMessage(messageIdString, - TIMAP4BlockingConnection::kEveryThingRFC822Peek, - fCurrentUrl->MessageIdsAreUids()); - - fProgressStringId = 0; - OnlineCopyCompleted( - GetServerStateParser().LastCommandSuccessful() ? - kSuccessfulCopy : kFailedCopy); - - if (GetServerStateParser().LastCommandSuccessful() && - (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOnlineToOfflineMove)) - { - Store(messageIdString, "+FLAGS (\\Deleted)", - fCurrentUrl->MessageIdsAreUids()); - XP_Bool storeSuccessful = GetServerStateParser().LastCommandSuccessful(); - - OnlineCopyCompleted( storeSuccessful ? kSuccessfulDelete : kFailedDelete); - } - - FREEIF( messageIdString); - } - else - HandleMemoryFailure(); - } - } - else if (GetServerStateParser().LastCommandSuccessful() && !uidValidityOk) - ProcessMailboxUpdate(FALSE); // handle uidvalidity change - - FREEIF( mailboxName); - } - else if (!DeathSignalReceived()) - HandleMemoryFailure(); - -} - -void TNavigatorImapConnection::AutoSubscribeToMailboxIfNecessary(const char *mailboxName) -{ - if (fFolderNeedsSubscribing) // we don't know about this folder - we need to subscribe to it / list it. - { - fHierarchyNameState = kListingForInfoOnly; - List(mailboxName); - fHierarchyNameState = kNoOperationInProgress; - - // removing and freeing it as we go. - TIMAPMailboxInfo *mb = NULL; - int total = XP_ListCount(fListedMailboxList); - do - { - mb = (TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList); - delete mb; - } while (mb); - - // if the mailbox exists (it was returned from the LIST response) - if (total > 0) - { - // Subscribe to it, if the pref says so - if (TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost()) && fAutoSubscribeOnOpen) - { - Subscribe(mailboxName); - } - - // Always LIST it anyway, to get it into the folder lists, - // so that we can continue to perform operations on it, at least - // for this session. - fHierarchyNameState = kNoOperationInProgress; - List(mailboxName); - } - - // We should now be subscribed to it, and have it in our folder lists - // and panes. Even if something failed, we don't want to try this again. - fFolderNeedsSubscribing = FALSE; - - } -} - -void TNavigatorImapConnection::FindMailboxesIfNecessary() -{ - PR_EnterMonitor(fFindingMailboxesMonitor); - // biff should not discover mailboxes - XP_Bool foundMailboxesAlready = TIMAPHostInfo::GetHaveWeEverDiscoveredFoldersForHost(fCurrentUrl->GetUrlHost()); - if (!foundMailboxesAlready && - (fCurrentUrl->GetIMAPurlType() != TIMAPUrl::kBiff) && - (fCurrentUrl->GetIMAPurlType() != TIMAPUrl::kDiscoverAllBoxesUrl) && - (fCurrentUrl->GetIMAPurlType() != TIMAPUrl::kUpgradeToSubscription) && - !GetSubscribingNow()) - { - DiscoverMailboxList(); - - // If we decide to do it, here is where we should check to see if - // a namespace exists (personal namespace only?) and possibly - // create it if it doesn't exist. - } - PR_ExitMonitor(fFindingMailboxesMonitor); -} - - -// DiscoverMailboxList() is used to actually do the discovery of folders -// for a host. This is used both when we initially start up (and re-sync) -// and also when the user manually requests a re-sync, by collapsing and -// expanding a host in the folder pane. This is not used for the subscribe -// pane. -// DiscoverMailboxList() also gets the ACLs for each newly discovered folder -void TNavigatorImapConnection::DiscoverMailboxList() -{ - SetMailboxDiscoveryStatus(eContinue); - if (GetServerStateParser().ServerHasACLCapability()) - fHierarchyNameState = kListingForInfoAndDiscovery; - else - fHierarchyNameState = kNoOperationInProgress; - - // Pretend that the Trash folder doesn't exist, so we will rediscover it if we need to. - TIMAPHostInfo::SetOnlineTrashFolderExistsForHost(fCurrentUrl->GetUrlHost(), FALSE); - - // iterate through all namespaces and LSUB them. - for (int i = TIMAPHostInfo::GetNumberOfNamespacesForHost(fCurrentUrl->GetUrlHost()); i >= 1; i-- ) - { - TIMAPNamespace *ns = TIMAPHostInfo::GetNamespaceNumberForHost(fCurrentUrl->GetUrlHost(), i); - if (ns) - { - const char *prefix = ns->GetPrefix(); - if (prefix) - { - - if (*prefix) // only do it for non-empty namespace prefixes - { - // Explicitly discover each Namespace, so that we can create subfolders of them, - mailbox_spec *boxSpec = (mailbox_spec *) XP_CALLOC(1, sizeof(mailbox_spec) ); - if (boxSpec) - { - boxSpec->folderSelected = FALSE; - boxSpec->hostName = fCurrentUrl->GetUrlHost(); - boxSpec->connection = this; - boxSpec->flagState = NULL; - boxSpec->discoveredFromLsub = TRUE; - boxSpec->onlineVerified = TRUE; - boxSpec->box_flags = kNoselect; - boxSpec->hierarchySeparator = ns->GetDelimiter(); - boxSpec->allocatedPathName = fCurrentUrl->AllocateCanonicalPath(ns->GetPrefix()); - - switch (ns->GetType()) - { - case kPersonalNamespace: - boxSpec->box_flags |= kPersonalMailbox; - break; - case kPublicNamespace: - boxSpec->box_flags |= kPublicMailbox; - break; - case kOtherUsersNamespace: - boxSpec->box_flags |= kOtherUsersMailbox; - break; - default: // (kUnknownNamespace) - break; - } - - DiscoverMailboxSpec(boxSpec); - } - else - HandleMemoryFailure(); - } - - // now do the folders within this namespace - char *pattern = NULL, *pattern2 = NULL; - if (TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost())) - pattern = PR_smprintf("%s*", prefix); - else - { - pattern = PR_smprintf("%s%%", prefix); - char delimiter = ns->GetDelimiter(); - if (delimiter) - { - // delimiter might be NIL, in which case there's no hierarchy anyway - pattern2 = PR_smprintf("%s%%%c%%", prefix, delimiter); - } - } - if (pattern) - { - if (TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost())) // && !GetSubscribingNow()) should never get here from subscribe pane - Lsub(pattern); - else - { - List(pattern); - if (pattern2) - { - List(pattern2); - XP_FREE(pattern2); - } - } - XP_FREE(pattern); - } - } - } - } - - // explicitly LIST the INBOX if (a) we're not using subscription, or (b) we are using subscription and - // the user wants us to always show the INBOX. - if (GetServerStateParser().LastCommandSuccessful() && - (!TIMAPHostInfo::GetHostIsUsingSubscription(fCurrentUrl->GetUrlHost()) || - TIMAPHostInfo::GetShouldAlwaysListInboxForHost(fCurrentUrl->GetUrlHost()))) - { - List("INBOX", FALSE, TRUE); - } - fHierarchyNameState = kNoOperationInProgress; - - MailboxDiscoveryFinished(); - - // Get the ACLs for newly discovered folders - if (GetServerStateParser().ServerHasACLCapability()) - { - int total = XP_ListCount(fListedMailboxList), count = 0; - GetServerStateParser().SetReportingErrors(FALSE); - if (total) - { - ProgressEventFunction_UsingId(MK_IMAP_GETTING_ACL_FOR_FOLDER); - TIMAPMailboxInfo *mb = NULL; - do - { - mb = (TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList); - if (mb) - { - if (FolderNeedsACLInitialized(mb->GetMailboxName())) - RefreshACLForFolder(mb->GetMailboxName()); - PercentProgressUpdateEvent(NULL, (count*100)/total); - delete mb; // this is the last time we're using the list, so delete the entries here - count++; - } - } while (mb && !DeathSignalReceived()); - } - } -} - - -void TNavigatorImapConnection::DiscoverAllAndSubscribedBoxes() -{ - // used for subscribe pane - // iterate through all namespaces - for (int i = TIMAPHostInfo::GetNumberOfNamespacesForHost(fCurrentUrl->GetUrlHost()); i >= 1; i-- ) - { - TIMAPNamespace *ns = TIMAPHostInfo::GetNamespaceNumberForHost(fCurrentUrl->GetUrlHost(), i); - if (ns) - { - const char *prefix = ns->GetPrefix(); - if (prefix) - { - // Fills in the hierarchy delimiters for some namespaces, for the case that they - // were filled in manually from the preferences. - if (ns->GetIsDelimiterFilledIn()) - { - fHierarchyNameState = kDiscoveringNamespacesOnly; - List(prefix); - fHierarchyNameState = kNoOperationInProgress; - } - - char *allPattern = PR_smprintf("%s*",prefix); - char *topLevelPattern = PR_smprintf("%s%%",prefix); - char *secondLevelPattern = NULL; - char delimiter = ns->GetDelimiter(); - if (delimiter) - { - // Hierarchy delimiter might be NIL, in which case there's no hierarchy anyway - secondLevelPattern = PR_smprintf("%s%%%c%%",prefix, delimiter); - } - if (allPattern) - { - Lsub(allPattern); // LSUB all the subscribed - XP_FREE(allPattern); - } - if (topLevelPattern) - { - List(topLevelPattern); // LIST the top level - XP_FREE(topLevelPattern); - } - if (secondLevelPattern) - { - List(secondLevelPattern); // LIST the second level - XP_FREE(secondLevelPattern); - } - } - } - } - SetFolderDiscoveryFinished(); -} - - -// report the success of the upgrade to IMAP subscription -static -void MOZTHREAD_SubscribeUpgradeFinished(void *blockingConnectionVoid, - void *endStateVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - EIMAPSubscriptionUpgradeState *endState = (EIMAPSubscriptionUpgradeState *) endStateVoid; - - MSG_ReportSuccessOfUpgradeToIMAPSubscription(imapConnection->GetActiveEntry()->window_id, endState); - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::UpgradeToSubscriptionFinishedEvent(EIMAPSubscriptionUpgradeState endState) -{ - EIMAPSubscriptionUpgradeState *orphanedUpgradeState = (EIMAPSubscriptionUpgradeState *) XP_ALLOC(sizeof(EIMAPSubscriptionUpgradeState)); - if (orphanedUpgradeState) - *orphanedUpgradeState = endState; - - TImapFEEvent *upgradeEvent = - new TImapFEEvent(MOZTHREAD_SubscribeUpgradeFinished, // function to call - this, // access to current entry/context - orphanedUpgradeState, - FALSE); // storage passed - - - if (upgradeEvent) - { - fFEEventQueue->AdoptEventToEnd(upgradeEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -static void -MOZTHREAD_GetOldHostEvent(void *blockingConnectionVoid, - void *pOldHostNameVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - - char **pOldHostName = (char **) pOldHostNameVoid; - // fill in the value - PREF_CopyCharPref("network.hosts.pop_server", pOldHostName); - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::GetOldIMAPHostNameEvent(char **oldHostName) -{ - TImapFEEvent *getHostEvent = - new TImapFEEvent(MOZTHREAD_GetOldHostEvent, // function to call - this, // access to current entry/context - oldHostName, - FALSE); - - if (getHostEvent) - { - fFEEventQueue->AdoptEventToEnd(getHostEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - - -static void -MOZTHREAD_PromptUserForSubscriptionUpgradePath(void *blockingConnectionVoid, void *valueVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - XP_Bool *value = (XP_Bool *)valueVoid; - XP_Bool shouldWeUpgrade = FALSE; - - char *promptString = XP_GetString(MK_IMAP_UPGRADE_PROMPT_USER); - if (promptString) - { - char *promptString2 = XP_GetString(MK_IMAP_UPGRADE_PROMPT_USER_2); - if (promptString2) - { - char *finalPrompt = StrAllocCat(promptString, promptString2); - if (finalPrompt) - { - shouldWeUpgrade = FE_Confirm(ce->window_id, finalPrompt); - } - else - shouldWeUpgrade = FALSE; - } - else - shouldWeUpgrade = FALSE; - } - else - shouldWeUpgrade = FALSE; - - if (!shouldWeUpgrade) - FE_Alert(ce->window_id, XP_GetString(MK_IMAP_UPGRADE_CUSTOM)); - - *value = shouldWeUpgrade; - imapConnection->NotifyEventCompletionMonitor(); -} - -// Returns TRUE if we need to automatically upgrade them, and FALSE if -// they want to do it manually (through the Subscribe UI). -XP_Bool TNavigatorImapConnection::PromptUserForSubscribeUpgradePath() -{ - XP_Bool *value = (XP_Bool *)XP_ALLOC(sizeof(XP_Bool)); - XP_Bool rv = FALSE; - - if (!value) return FALSE; - - TImapFEEvent *getHostEvent = - new TImapFEEvent(MOZTHREAD_PromptUserForSubscriptionUpgradePath, // function to call - this, // access to current entry/context - value, - FALSE); - - if (getHostEvent) - { - fFEEventQueue->AdoptEventToEnd(getHostEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - rv = *value; - XP_FREE(value); - return rv; -} - -// Should only use this for upgrading to subscribe model -void TNavigatorImapConnection::SubscribeToAllFolders() -{ - fHierarchyNameState = kListingForInfoOnly; - TIMAPMailboxInfo *mb = NULL; - - // This will fill in the list - if (!DeathSignalReceived()) - List("*"); - - int total = XP_ListCount(fListedMailboxList), count = 0; - GetServerStateParser().SetReportingErrors(FALSE); - if (!DeathSignalReceived()) do - { - mb = (TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList); - if (mb) - { - Subscribe(mb->GetMailboxName()); - PercentProgressUpdateEvent(NULL, (count*100)/total); - delete mb; - count++; - } - } while (mb && !DeathSignalReceived()); - - PercentProgressUpdateEvent(NULL, 100); - - GetServerStateParser().SetReportingErrors(TRUE); - - fHierarchyNameState = kNoOperationInProgress; -} - -int TNavigatorImapConnection::GetNumberOfListedMailboxesWithUnlistedChildren() -{ - int count = 0, listSize = XP_ListCount(fListedMailboxList), i = 1; - for (i = 1; i <= listSize; i++) - { - TIMAPMailboxInfo *mb = (TIMAPMailboxInfo *)XP_ListGetObjectNum(fListedMailboxList, i); - if (!mb->GetChildrenListed()) - count++; - } - return count; -} - -void TNavigatorImapConnection::UpgradeToSubscription() -{ - EIMAPSubscriptionUpgradeState endState = kEverythingDone; - if (fCurrentUrl->GetShouldSubscribeToAll()) - { - SubscribeToAllFolders(); - } - else - { - TIMAPNamespace *ns = TIMAPHostInfo::GetDefaultNamespaceOfTypeForHost(fCurrentUrl->GetUrlHost(), kPersonalNamespace); - if (ns && ns->GetType()==kPersonalNamespace) - { - // This should handle the case of getting the personal namespace from either the - // prefs or the NAMESPACE extension. - // We will list all the personal folders, and subscribe to them all. - // We can do this, because we know they're personal, and the user said to try - // to subscribe to all. - - fHierarchyNameState = kDiscoveringNamespacesOnly; - List(ns->GetPrefix()); - - fHierarchyNameState = kListingForInfoOnly; - char *pattern = PR_smprintf("%s*",ns->GetPrefix()); - if (pattern && !DeathSignalReceived()) - List(pattern); - fHierarchyNameState = kNoOperationInProgress; - - // removing and freeing it as we go. - - GetServerStateParser().SetReportingErrors(FALSE); - int total = XP_ListCount(fListedMailboxList), count = 0; - TIMAPMailboxInfo *mb = 0; - if (!DeathSignalReceived()) do - { - mb = (TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList); - if (mb) - { - Subscribe(mb->GetMailboxName()); - PercentProgressUpdateEvent(NULL, (count*100)/total); - delete mb; - count++; - } - } while (mb && !DeathSignalReceived()); - PercentProgressUpdateEvent(NULL, 100); - GetServerStateParser().SetReportingErrors(TRUE); - } - else if (!ns) - { - // There is no personal or default namespace. This means that the server - // supports the NAMESPACE extension, and has other namespaces, but explicitly - // has no personal namespace. I would be very surprised if we EVER encounter - // this situation, since the user must have been using Communicator 4.0 on - // a server that supported the NAMESPACE extension and only had, say, - // public folders. Not likely. All we can really do is alert the user - // and bring up the Subscribe UI. - AlertUserEvent_UsingId(MK_IMAP_UPGRADE_NO_PERSONAL_NAMESPACE); - endState = kBringUpSubscribeUI; - } - else if (!GetServerStateParser().ServerHasNamespaceCapability()) - { - // NAMESPACE extension not supported, and we only have a default namespace - // (That is, no explicit personal namespace is specified -- only "") - if ((GetServerStateParser().GetCapabilityFlag() & - kHasXNetscapeCapability) && - !DeathSignalReceived()) - { - Netscape(); - } - if (GetServerStateParser().ServerIsNetscape3xServer()) - { - // Server is a Netscape 3.0 Messaging Server. We know that all the - // folders are personal mail folders, and can subscribe to all (*). - SubscribeToAllFolders(); - } - else - { - // Worst case. It's not a Netscape 3.0 server, NAMESPACE is not supported, - // the user hasn't manually specified a personal namespace prefix, and - // Mission Control hasn't told us anything. Do the best we can. - // Progressively LIST % until either we run out of folders or we encounter - // 50 (MAX_NEW_IMAP_FOLDER_COUNT) - - const char *namespacePrefix = ns->GetPrefix(); // Has to be "", right? - - // List the prefix, to get the hierarchy delimiter. - // We probably shouldn't subscribe to the namespace itself. - fHierarchyNameState = kDiscoveringNamespacesOnly; - if (!DeathSignalReceived()) - List(namespacePrefix); - - // Now, generate the list - // Do it one level at a time, and stop either when nothing comes back or - // we pass the threshold mailbox count (50) - fHierarchyNameState = kListingForInfoOnly; - char *firstPattern = PR_smprintf("%s%%", namespacePrefix); - if (firstPattern && !DeathSignalReceived()) - { - List(firstPattern); - XP_FREE(firstPattern); - } - while ((XP_ListCount(fListedMailboxList) < MAX_NEW_IMAP_FOLDER_COUNT) && - (GetNumberOfListedMailboxesWithUnlistedChildren() > 0)) - { - int listSize = XP_ListCount(fListedMailboxList), i = 1; - for (i = 1; (i <= listSize) && !DeathSignalReceived(); i++) - { - TIMAPMailboxInfo *mb = (TIMAPMailboxInfo *)XP_ListGetObjectNum(fListedMailboxList, i); - if (!mb->GetChildrenListed()) - { - char delimiter = ns->GetDelimiter(); - // If there's a NIL hierarchy delimter, then we don't need to list children - if (delimiter) - { - char *pattern = PR_smprintf("%s%s%c%%",namespacePrefix,mb->GetMailboxName(), ns->GetDelimiter()); - if (pattern && !DeathSignalReceived()) - List(pattern); - } - mb->SetChildrenListed(TRUE); - } - } - } - fHierarchyNameState = kNoOperationInProgress; - - if (XP_ListCount(fListedMailboxList) < MAX_NEW_IMAP_FOLDER_COUNT) - { - // Less than the threshold (50?) - // Iterate through the list and subscribe to each mailbox, - // removing and freeing it as we go. - GetServerStateParser().SetReportingErrors(FALSE); - int total = XP_ListCount(fListedMailboxList), count = 0; - TIMAPMailboxInfo *mb = 0; - if (!DeathSignalReceived()) do - { - mb = (TIMAPMailboxInfo *)XP_ListRemoveTopObject(fListedMailboxList); - if (mb) - { - Subscribe(mb->GetMailboxName()); - PercentProgressUpdateEvent(NULL, (100*count)/total); - delete mb; - count++; - } - } while (mb && !DeathSignalReceived()); - PercentProgressUpdateEvent(NULL, 100); - GetServerStateParser().SetReportingErrors(TRUE); - } - else - { - // More than the threshold. Bring up the subscribe UI. - // We still must free the storage in the list - TIMAPMailboxInfo *mb = 0; - do - { - mb = (TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList); - delete mb; - } while (mb); - AlertUserEvent_UsingId(MK_IMAP_UPGRADE_TOO_MANY_FOLDERS); - endState = kBringUpSubscribeUI; - } - } - } - } - if (!DeathSignalReceived()) // if not interrupted - UpgradeToSubscriptionFinishedEvent(endState); -} - - -void TNavigatorImapConnection::ProcessAuthenticatedStateURL() -{ - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kLsubFolders) - { - //XP_ASSERT(FALSE); // now handled in FindMailboxesIfNecessary - // **** use to find out whether Drafts, Sent, & Templates folder - // exists or not even the user didn't subscribe to it - char *mailboxName = - fCurrentUrl->CreateServerDestinationFolderPathString(); - if (mailboxName) - { - char *convertedName = - CreateUtf7ConvertedString(mailboxName, TRUE); - if (convertedName) - { - FREEIF(mailboxName); - mailboxName = convertedName; - } - ProgressEventFunction_UsingId - (MK_IMAP_STATUS_LOOKING_FOR_MAILBOX); - IncrementCommandTagNumber(); - PR_snprintf(GetOutputBuffer(), kOutputBufferSize, - "%s list \"\" \"%s\"" CRLF, - GetServerCommandTag(), - mailboxName); - int ioStatus = WriteLineToSocket(GetOutputBuffer()); - TimeStampListNow(); - ParseIMAPandCheckForNewMail(); - // send list command to the server; modify - // DiscoverIMAPMailbox to check for the - // existence of the folder - - FREEIF(mailboxName); - } - else - { - HandleMemoryFailure(); - } - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kGetMailAccountUrl) { - if (GetServerStateParser().GetCapabilityFlag() & - kHasXNetscapeCapability) { - Netscape(); - if (GetServerStateParser().LastCommandSuccessful()) { - TImapFEEvent *alertEvent = - new TImapFEEvent(msgSetMailAccountURL, // function to call - this, // access to current entry - (void *) fCurrentUrl->GetUrlHost(), - TRUE); - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - // WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - } - } - } - else - { - // even though we don't have to to be legal protocol, Close any select mailbox - // so we don't miss any info these urls might change for the selected folder - // (e.g. msg count after append) - if (GetServerStateParser().GetIMAPstate() == TImapServerState::kFolderSelected) - { - // now we should be avoiding an implicit Close because it performs an implicit Expunge - // authenticated state urls should not use a cached connection that is in the selected state - XP_ASSERT(FALSE); - //Close(); - } - - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kOfflineToOnlineMove) - { - char *destinationMailbox = - fCurrentUrl->CreateServerDestinationFolderPathString(); - - if (destinationMailbox) - { - char *convertedName = CreateUtf7ConvertedString(destinationMailbox, TRUE); - XP_FREE(destinationMailbox); - destinationMailbox = convertedName; - } - if (destinationMailbox) - { - uint32 appendSize = 0; - do { - WaitForNextAppendMessageSize(); - appendSize = GetAppendSize(); - if (!DeathSignalReceived() && appendSize) - { - char messageSizeString[100]; - sprintf(messageSizeString, "%ld",(long) appendSize); - AppendMessage(destinationMailbox, messageSizeString, GetAppendFlags()); - } - } while (appendSize && GetServerStateParser().LastCommandSuccessful()); - FREEIF( destinationMailbox); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kAppendMsgFromFile) - { - char *sourceMessageFile = - XP_STRDUP(GetActiveEntry()->URL_s->post_data); - char *mailboxName = - fCurrentUrl->CreateServerSourceFolderPathString(); - - if (mailboxName) - { - char *convertedName = CreateUtf7ConvertedString(mailboxName, TRUE); - XP_FREE(mailboxName); - mailboxName = convertedName; - } - if (mailboxName) - { - UploadMessageFromFile(sourceMessageFile, mailboxName, - kImapMsgSeenFlag); - } - else - HandleMemoryFailure(); - FREEIF( sourceMessageFile ); - FREEIF( mailboxName ); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDiscoverAllBoxesUrl) - { - XP_ASSERT(!GetSubscribingNow()); // should not get here from subscribe UI - DiscoverMailboxList(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDiscoverAllAndSubscribedBoxesUrl) - { - XP_ASSERT(GetSubscribingNow()); - DiscoverAllAndSubscribedBoxes(); - } - else - { - char *sourceMailbox = fCurrentUrl->CreateServerSourceFolderPathString(); - if (sourceMailbox) - { - char *convertedName = CreateUtf7ConvertedString(sourceMailbox, TRUE); - XP_FREE(sourceMailbox); - sourceMailbox = convertedName; - } - - if (sourceMailbox) - { - if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kCreateFolder) - { - XP_Bool created = CreateMailboxRespectingSubscriptions(sourceMailbox); - if (created) - { - List(sourceMailbox); - } - else - FolderNotCreated(sourceMailbox); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDiscoverChildrenUrl) - { - char *canonicalParent = fCurrentUrl->CreateCanonicalSourceFolderPathString(); - if (canonicalParent) - { - NthLevelChildList(canonicalParent, 2); - //CanonicalChildList(canonicalParent,FALSE); - XP_FREE(canonicalParent); - } - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDiscoverLevelChildrenUrl) - { - char *canonicalParent = fCurrentUrl->CreateCanonicalSourceFolderPathString(); - int depth = fCurrentUrl->GetChildDiscoveryDepth(); - if (canonicalParent) - { - NthLevelChildList(canonicalParent, depth); - if (GetServerStateParser().LastCommandSuccessful()) - ChildDiscoverySucceeded(); - XP_FREE(canonicalParent); - } - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kSubscribe) - { - Subscribe(sourceMailbox); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kUnsubscribe) - { - Unsubscribe(sourceMailbox); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kRefreshACL) - { - RefreshACLForFolder(sourceMailbox); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kRefreshAllACLs) - { - RefreshAllACLs(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kListFolder) - { - char *folderName = fCurrentUrl->CreateCanonicalSourceFolderPathString(); - List(folderName); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kUpgradeToSubscription) - { - UpgradeToSubscription(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kFolderStatus) - { - StatusForFolder(sourceMailbox); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kRefreshFolderUrls) - { - XMailboxInfo(sourceMailbox); - if (GetServerStateParser().LastCommandSuccessful()) - { - InitializeFolderUrl(sourceMailbox); - } - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kDeleteFolder) - { - XP_Bool deleted = DeleteSubFolders(sourceMailbox); - if (deleted) - deleted = DeleteMailboxRespectingSubscriptions(sourceMailbox); - if (deleted) - FolderDeleted(sourceMailbox); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kRenameFolder) - { - char *destinationMailbox = - fCurrentUrl->CreateServerDestinationFolderPathString(); - if (destinationMailbox) - { - char *convertedName = CreateUtf7ConvertedString(destinationMailbox, TRUE); - XP_FREE(destinationMailbox); - destinationMailbox = convertedName; - } - if (destinationMailbox) - { - XP_Bool renamed = RenameHierarchyByHand(sourceMailbox, destinationMailbox); - if (renamed) - FolderRenamed(sourceMailbox, destinationMailbox); - - FREEIF( destinationMailbox); - } - else - HandleMemoryFailure(); - } - else if (fCurrentUrl->GetIMAPurlType() == TIMAPUrl::kMoveFolderHierarchy) - { - char *destinationMailbox = - fCurrentUrl->CreateServerDestinationFolderPathString(); - if (destinationMailbox) - { - // worst case length - char *newBoxName = (char *) XP_ALLOC(XP_STRLEN(destinationMailbox) + XP_STRLEN(sourceMailbox) + 2); - if (newBoxName) - { - char onlineDirSeparator = fCurrentUrl->GetOnlineSubDirSeparator(); - XP_STRCPY(newBoxName, destinationMailbox); - - char *leafSeparator = XP_STRRCHR(sourceMailbox, onlineDirSeparator); - if (!leafSeparator) - leafSeparator = sourceMailbox; // this is a root level box - else - leafSeparator++; - - if ( *newBoxName && ( *(newBoxName + XP_STRLEN(newBoxName) - 1) != onlineDirSeparator)) - { - char separatorStr[2]; - separatorStr[0] = onlineDirSeparator; - separatorStr[1] = 0; - XP_STRCAT(newBoxName, separatorStr); - } - XP_STRCAT(newBoxName, leafSeparator); - XP_Bool renamed = RenameHierarchyByHand(sourceMailbox, newBoxName); - if (renamed) - FolderRenamed(sourceMailbox, newBoxName); - } - } - } - - - FREEIF( sourceMailbox); - } - else - HandleMemoryFailure(); - } - } -} - -int32 TNavigatorImapConnection::GetMessageSizeForProgress() -{ - return GetServerStateParser().SizeOfMostRecentMessage(); -} - -int32 TNavigatorImapConnection::GetBytesMovedSoFarForProgress() -{ - return fBytesMovedSoFarForProgress; -} - -void TNavigatorImapConnection::SetBytesMovedSoFarForProgress(int32 bytesMoved) -{ - fBytesMovedSoFarForProgress = bytesMoved; -} - - -void TNavigatorImapConnection::AlertUserEvent_UsingId(uint32 msgId) -{ - TImapFEEvent *alertEvent = - new TImapFEEvent(AlertEventFunction_UsingId, // function to call - this, // access to current entry - (void *) msgId, - TRUE); // alert message - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::AlertUserEvent(char *message) -{ - TImapFEEvent *alertEvent = - new TImapFEEvent(AlertEventFunction, // function to call - this, // access to current entry - message, - TRUE); // alert message - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::AlertUserEventFromServer(char *serverSaid) -{ - TImapFEEvent *alertEvent = - new TImapFEEvent(AlertEventFunctionFromServer, // function to call - this, // access to current entry - serverSaid, - TRUE); // alert message - if (alertEvent) - { - fFEEventQueue->AdoptEventToEnd(alertEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::ProgressUpdateEvent(char *message) -{ - TImapFEEvent *progressEvent = - new TImapFEEvent(ProgressEventFunction, // function to call - this, // access to current entry - message, - TRUE); // progress message - - if (progressEvent) - { - fFEEventQueue->AdoptEventToEnd(progressEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -void TNavigatorImapConnection::ProgressEventFunction_UsingId(uint32 msgId) -{ - if (msgId != (uint32) fLastProgressStringId) - { - TImapFEEvent *progressEvent = - new TImapFEEvent(ProgressStatusFunction_UsingId, // function to call - this, // access to current entry - (void *) msgId, - TRUE); // alert message id - if (progressEvent) - { - fFEEventQueue->AdoptEventToEnd(progressEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - fLastProgressStringId = msgId; - } -} - -void TNavigatorImapConnection::ProgressEventFunction_UsingIdWithString(uint32 msgId, const char* extraInfo) -{ - StatusMessageInfo *msgInfo = (StatusMessageInfo *) XP_ALLOC(sizeof(StatusMessageInfo)); // free in event handler - if (msgInfo) { - if (extraInfo) { - msgInfo->msgID = msgId; - msgInfo->extraInfo = XP_STRDUP (extraInfo); // free in event handler - TImapFEEvent *progressEvent = - new TImapFEEvent(ProgressStatusFunction_UsingIdWithString, // function to call - this, // access to current entry - (void *) msgInfo, - TRUE); // alert message info - if (progressEvent) - { - fFEEventQueue->AdoptEventToEnd(progressEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - } - } -} - -void TNavigatorImapConnection::PercentProgressUpdateEvent(char *message, int percent) -{ - int64 nowMS; - if (percent == fLastPercent) - return; // hasn't changed, right? So just return. Do we need to clear this anywhere? - - if (percent < 100) // always need to do 100% - { - int64 minIntervalBetweenProgress; - - LL_I2L(minIntervalBetweenProgress, 250); - int64 diffSinceLastProgress; - LL_I2L(nowMS, PR_IntervalToMilliseconds(PR_IntervalNow())); - LL_SUB(diffSinceLastProgress, nowMS, fLastProgressTime); // r = a - b - LL_SUB(diffSinceLastProgress, diffSinceLastProgress, minIntervalBetweenProgress); // r = a - b - if (!LL_GE_ZERO(diffSinceLastProgress)) - return; - } - - ProgressInfo *progress = (ProgressInfo *) XP_ALLOC(sizeof(ProgressInfo)); // free in event handler - if (progress) - { - // we can do the event without a message - it will set the percent bar - if (message) - progress->message = XP_STRDUP(message); // free in event handler - else - progress->message = 0; - progress->percent = percent; - fLastPercent = percent; - - TImapFEEvent *progressEvent = - new TImapFEEvent(PercentProgressEventFunction, // function to call - this, // access to current entry - progress, - TRUE); // progress message - - fLastProgressTime = nowMS; - if (progressEvent) - { - fFEEventQueue->AdoptEventToEnd(progressEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - } -} - -void TNavigatorImapConnection::PastPasswordCheckEvent() -{ - TImapFEEvent *pwCheckEvent = - new TImapFEEvent(PastPasswordCheckFunction, this, NULL, TRUE); - - if (pwCheckEvent) - { - fFEEventQueue->AdoptEventToEnd(pwCheckEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - - -static void CommitNamespacesFunction(void *blockingConnectionVoid, void *hostNameVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - char *hostName = (char *)hostNameVoid; - - if (hostName) - TIMAPHostInfo::CommitNamespacesForHost(hostName, ce->window_id->mailMaster); - - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::CommitNamespacesForHostEvent() -{ - TImapFEEvent *commitEvent = - new TImapFEEvent(CommitNamespacesFunction,this,(void *)(fCurrentUrl->GetUrlHost()), TRUE); - - if (commitEvent) - { - fFEEventQueue->AdoptEventToEnd(commitEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -static void CommitCapabilityFunction(void *blockingConnectionVoid, void *hostNameVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - char *hostName = (char *)hostNameVoid; - - if (hostName) - MSG_CommitCapabilityForHost(hostName, ce->window_id->mailMaster); - - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::CommitCapabilityForHostEvent() -{ - TImapFEEvent *commitEvent = - new TImapFEEvent(CommitCapabilityFunction,this,(void *)(fCurrentUrl->GetUrlHost()), TRUE); - - if (commitEvent) - { - fFEEventQueue->AdoptEventToEnd(commitEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); -} - -typedef struct _MessageSizeInfo -{ - char *id; - char *folderName; - XP_Bool idIsUid; - uint32 size; -} MessageSizeInfo; - - -// Retrieves the message size given a message UID -// Retrieves the message size given a UID or message sequence number -static -void GetMessageSizeEvent(void *blockingConnectionVoid, - void *sizeInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - MessageSizeInfo *sizeInfo = (MessageSizeInfo *)sizeInfoVoid; - MSG_Pane *masterPane = ce->URL_s->msg_pane; // we need some pane to get to the master - if (!masterPane) - masterPane = MSG_FindPane(ce->window_id, MSG_ANYPANE); // last ditch effort - - sizeInfo->size = MSG_GetIMAPMessageSizeFromDB(masterPane, imapConnection->GetHostName(), sizeInfo->folderName, sizeInfo->id, sizeInfo->idIsUid); - - imapConnection->NotifyEventCompletionMonitor(); -} - - -uint32 TNavigatorImapConnection::GetMessageSize(const char *messageId, XP_Bool idsAreUids) -{ - - MessageSizeInfo *sizeInfo = (MessageSizeInfo *)XP_ALLOC(sizeof(MessageSizeInfo)); - if (sizeInfo) - { - const char *folderFromParser = GetServerStateParser().GetSelectedMailboxName(); - if (folderFromParser) - { - sizeInfo->id = (char *)XP_ALLOC(XP_STRLEN(messageId) + 1); - sizeInfo->folderName = (char *)XP_ALLOC(XP_STRLEN(folderFromParser) + 1); - XP_STRCPY(sizeInfo->id, messageId); - sizeInfo->idIsUid = idsAreUids; - - if (sizeInfo->id && sizeInfo->folderName) - { - XP_STRCPY(sizeInfo->folderName, folderFromParser); - TImapFEEvent *getMessageSizeEvent = new TImapFEEvent(GetMessageSizeEvent, this, sizeInfo, FALSE); - - if (getMessageSizeEvent) - { - fFEEventQueue->AdoptEventToEnd(getMessageSizeEvent); - WaitForFEEventCompletion(); - } - else - { - HandleMemoryFailure(); - return 0; - } - XP_FREE(sizeInfo->id); - XP_FREE(sizeInfo->folderName); - } - else - { - HandleMemoryFailure(); - XP_FREE(sizeInfo); - return 0; - } - - int32 rv = 0; - if (!DeathSignalReceived()) - rv = sizeInfo->size; - XP_FREE(sizeInfo); - return rv; - } - else - { - HandleMemoryFailure(); - return 0; - } - } - else - { - HandleMemoryFailure(); - return 0; - } -} - - - -static void -MOZTHREAD_FolderIsNoSelectEvent(void *blockingConnectionVoid, void *valueVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - FolderQueryInfo *value = (FolderQueryInfo *)valueVoid; - - value->rv = MSG_IsFolderNoSelect(ce->window_id->mailMaster, value->name, value->hostName); - imapConnection->NotifyEventCompletionMonitor(); -} - - - -// Returns TRUE if the mailbox is a NoSelect mailbox. -// If we don't know about it, returns FALSE. -XP_Bool TNavigatorImapConnection::MailboxIsNoSelectMailbox(const char *mailboxName) -{ - FolderQueryInfo *value = (FolderQueryInfo *)XP_ALLOC(sizeof(FolderQueryInfo)); - XP_Bool rv = FALSE; - - if (!value) return FALSE; - - value->name = XP_STRDUP(mailboxName); - if (!value->name) - { - XP_FREE(value); - return FALSE; - } - - value->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - if (!value->hostName) - { - XP_FREE(value->name); - XP_FREE(value); - return FALSE; - } - - TImapFEEvent *theEvent = - new TImapFEEvent(MOZTHREAD_FolderIsNoSelectEvent, // function to call - this, // access to current entry/context - value, - FALSE); - - if (theEvent) - { - fFEEventQueue->AdoptEventToEnd(theEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - rv = value->rv; - XP_FREE(value->hostName); - XP_FREE(value->name); - XP_FREE(value); - return rv; -} - -/////////////////// Begin Subscription Management Functions ///////////////////////////// - - -// returns TRUE is the create succeeded (regardless of subscription changes) -XP_Bool TNavigatorImapConnection::CreateMailboxRespectingSubscriptions(const char *mailboxName) -{ - TIMAP4BlockingConnection::CreateMailbox(mailboxName); - XP_Bool rv = GetServerStateParser().LastCommandSuccessful(); - if (rv) - { - if (fAutoSubscribe) // auto-subscribe is on - { - // create succeeded - let's subscribe to it - XP_Bool reportingErrors = GetServerStateParser().GetReportingErrors(); - GetServerStateParser().SetReportingErrors(FALSE); - Subscribe(mailboxName); - GetServerStateParser().SetReportingErrors(reportingErrors); - } - } - return (rv); -} - -// returns TRUE is the delete succeeded (regardless of subscription changes) -XP_Bool TNavigatorImapConnection::DeleteMailboxRespectingSubscriptions(const char *mailboxName) -{ - XP_Bool rv = TRUE; - if (!MailboxIsNoSelectMailbox(mailboxName)) - { - // Only try to delete it if it really exists - TIMAP4BlockingConnection::DeleteMailbox(mailboxName); - rv = GetServerStateParser().LastCommandSuccessful(); - } - - // We can unsubscribe even if the mailbox doesn't exist. - if (rv && fAutoUnsubscribe) // auto-unsubscribe is on - { - XP_Bool reportingErrors = GetServerStateParser().GetReportingErrors(); - GetServerStateParser().SetReportingErrors(FALSE); - Unsubscribe(mailboxName); - GetServerStateParser().SetReportingErrors(reportingErrors); - - } - return (rv); -} - -// returns TRUE is the rename succeeded (regardless of subscription changes) -// reallyRename tells us if we should really do the rename (TRUE) or if we should just move subscriptions (FALSE) -XP_Bool TNavigatorImapConnection::RenameMailboxRespectingSubscriptions(const char *existingName, const char *newName, XP_Bool reallyRename) -{ - XP_Bool rv = TRUE; - if (reallyRename && !MailboxIsNoSelectMailbox(existingName)) - { - TIMAP4BlockingConnection::RenameMailbox(existingName, newName); - rv = GetServerStateParser().LastCommandSuccessful(); - } - - if (rv) - { - if (fAutoSubscribe) // if auto-subscribe is on - { - XP_Bool reportingErrors = GetServerStateParser().GetReportingErrors(); - GetServerStateParser().SetReportingErrors(FALSE); - Subscribe(newName); - GetServerStateParser().SetReportingErrors(reportingErrors); - } - if (fAutoUnsubscribe) // if auto-unsubscribe is on - { - XP_Bool reportingErrors = GetServerStateParser().GetReportingErrors(); - GetServerStateParser().SetReportingErrors(FALSE); - Unsubscribe(existingName); - GetServerStateParser().SetReportingErrors(reportingErrors); - } - } - return (rv); -} - - -XP_Bool TNavigatorImapConnection::GetSubscribingNow() -{ - return (fCurrentEntry && fCurrentEntry->window_id && fCurrentEntry->window_id->imapURLPane && - (MSG_SUBSCRIBEPANE == MSG_GetPaneType(fCurrentEntry->window_id->imapURLPane))); -} - - -/////////////////// End Subscription Management Functions ///////////////////////////// - -/////////////////// Begin ACL Stuff /////////////////////////////////////////////////// - -void TNavigatorImapConnection::RefreshACLForFolderIfNecessary(const char *mailboxName) -{ - if (fFolderNeedsACLRefreshed && GetServerStateParser().ServerHasACLCapability()) - { - RefreshACLForFolder(mailboxName); - fFolderNeedsACLRefreshed = FALSE; - } -} - -void TNavigatorImapConnection::RefreshACLForFolder(const char *mailboxName) -{ - - TIMAPNamespace *ns = TIMAPHostInfo::GetNamespaceForMailboxForHost(fCurrentUrl->GetUrlHost(), mailboxName); - if (ns) - { - switch (ns->GetType()) - { - case kPersonalNamespace: - // It's a personal folder, most likely. - // I find it hard to imagine a server that supports ACL that doesn't support NAMESPACE, - // so most likely we KNOW that this is a personal, rather than the default, namespace. - - // First, clear what we have. - ClearAllFolderRights(mailboxName); - // Now, get the new one. - GetACLForFolder(mailboxName); - // We're all done, refresh the icon/flags for this folder - RefreshFolderACLView(mailboxName); - break; - default: - // We know it's a public folder or other user's folder. - // We only want our own rights - - // First, clear what we have - ClearAllFolderRights(mailboxName); - // Now, get the new one. - GetMyRightsForFolder(mailboxName); - // We're all done, refresh the icon/flags for this folder - RefreshFolderACLView(mailboxName); - break; - } - } - else - { - // no namespace, not even default... can this happen? - XP_ASSERT(FALSE); - } -} - -void TNavigatorImapConnection::RefreshAllACLs() -{ - fHierarchyNameState = kListingForInfoOnly; - TIMAPMailboxInfo *mb = NULL; - - // This will fill in the list - List("*"); - - int total = XP_ListCount(fListedMailboxList), count = 0; - GetServerStateParser().SetReportingErrors(FALSE); - do - { - mb = (TIMAPMailboxInfo *) XP_ListRemoveTopObject(fListedMailboxList); - if (mb) - { - RefreshACLForFolder(mb->GetMailboxName()); - PercentProgressUpdateEvent(NULL, (count*100)/total); - delete mb; - count++; - } - } while (mb); - - PercentProgressUpdateEvent(NULL, 100); - GetServerStateParser().SetReportingErrors(TRUE); - - fHierarchyNameState = kNoOperationInProgress; -} - -static void ClearFolderRightsEvent(void *blockingConnectionVoid, void *aclRightsInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - TIMAPACLRightsInfo *aclRights = (TIMAPACLRightsInfo *)aclRightsInfoVoid; - - MSG_ClearFolderRightsForFolder(ce->window_id->mailMaster, aclRights->hostName, aclRights->mailboxName); - - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::ClearAllFolderRights(const char *mailboxName) -{ - TIMAPACLRightsInfo *aclRightsInfo = new TIMAPACLRightsInfo(); - if (aclRightsInfo) - { - aclRightsInfo->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - aclRightsInfo->mailboxName = XP_STRDUP(mailboxName); - aclRightsInfo->rights = NULL; - aclRightsInfo->userName = NULL; - - if (aclRightsInfo->hostName && aclRightsInfo->mailboxName) - { - - TImapFEEvent *clearFolderRightsEvent = - new TImapFEEvent(ClearFolderRightsEvent, // function to call - this, // access to current entry/context - aclRightsInfo, - FALSE); - - - if (clearFolderRightsEvent) - { - fFEEventQueue->AdoptEventToEnd(clearFolderRightsEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - XP_FREE(aclRightsInfo->hostName); - XP_FREE(aclRightsInfo->mailboxName); - } - else - HandleMemoryFailure(); - delete aclRightsInfo; - } - else - HandleMemoryFailure(); -} - - -static void AddFolderRightsEvent(void *blockingConnectionVoid, void *aclRightsInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - TIMAPACLRightsInfo *aclRights = (TIMAPACLRightsInfo *)aclRightsInfoVoid; - - MSG_AddFolderRightsForUser(ce->window_id->mailMaster, aclRights->hostName, aclRights->mailboxName, aclRights->userName, aclRights->rights); - - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::AddFolderRightsForUser(const char *mailboxName, const char *userName, const char *rights) -{ - TIMAPACLRightsInfo *aclRightsInfo = new TIMAPACLRightsInfo(); - if (aclRightsInfo) - { - aclRightsInfo->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - aclRightsInfo->mailboxName = XP_STRDUP(mailboxName); - if (userName) - aclRightsInfo->userName = XP_STRDUP(userName); - else - aclRightsInfo->userName = NULL; - aclRightsInfo->rights = XP_STRDUP(rights); - - - if (aclRightsInfo->hostName && aclRightsInfo->mailboxName && aclRightsInfo->rights && - userName ? (aclRightsInfo->userName != NULL) : TRUE) - { - - TImapFEEvent *addFolderRightsEvent = - new TImapFEEvent(AddFolderRightsEvent, // function to call - this, // access to current entry/context - aclRightsInfo, - FALSE); - - - if (addFolderRightsEvent) - { - fFEEventQueue->AdoptEventToEnd(addFolderRightsEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - XP_FREE(aclRightsInfo->hostName); - XP_FREE(aclRightsInfo->mailboxName); - XP_FREE(aclRightsInfo->rights); - if (aclRightsInfo->userName) - XP_FREE(aclRightsInfo->userName); - } - else - HandleMemoryFailure(); - delete aclRightsInfo; - } - else - HandleMemoryFailure(); -} - -static void RefreshFolderRightsEvent(void *blockingConnectionVoid, void *aclRightsInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - TIMAPACLRightsInfo *aclRights = (TIMAPACLRightsInfo *)aclRightsInfoVoid; - - MSG_RefreshFolderRightsViewForFolder(ce->window_id->mailMaster, aclRights->hostName, aclRights->mailboxName); - - imapConnection->NotifyEventCompletionMonitor(); -} - -void TNavigatorImapConnection::RefreshFolderACLView(const char *mailboxName) -{ - TIMAPACLRightsInfo *aclRightsInfo = new TIMAPACLRightsInfo(); - if (aclRightsInfo) - { - aclRightsInfo->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - aclRightsInfo->mailboxName = XP_STRDUP(mailboxName); - aclRightsInfo->rights = NULL; - aclRightsInfo->userName = NULL; - - if (aclRightsInfo->hostName && aclRightsInfo->mailboxName) - { - - TImapFEEvent *refreshFolderRightsEvent = - new TImapFEEvent(RefreshFolderRightsEvent, // function to call - this, // access to current entry/context - aclRightsInfo, - FALSE); - - - if (refreshFolderRightsEvent) - { - fFEEventQueue->AdoptEventToEnd(refreshFolderRightsEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - XP_FREE(aclRightsInfo->hostName); - XP_FREE(aclRightsInfo->mailboxName); - } - else - HandleMemoryFailure(); - delete aclRightsInfo; - } - else - HandleMemoryFailure(); -} - - -static void -MOZTHREAD_FolderNeedsACLInitialized(void *blockingConnectionVoid, void *valueVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - FolderQueryInfo *value = (FolderQueryInfo *)valueVoid; - - value->rv = !MSG_IsFolderACLInitialized(ce->window_id->mailMaster, value->name, value->hostName); - imapConnection->NotifyEventCompletionMonitor(); -} - - -XP_Bool TNavigatorImapConnection::FolderNeedsACLInitialized(const char *folderName) -{ - FolderQueryInfo *value = (FolderQueryInfo *)XP_ALLOC(sizeof(FolderQueryInfo)); - XP_Bool rv = FALSE; - - if (!value) return FALSE; - - value->name = XP_STRDUP(folderName); - if (!value->name) - { - XP_FREE(value); - return FALSE; - } - - value->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - if (!value->hostName) - { - XP_FREE(value->name); - XP_FREE(value); - return FALSE; - } - - TImapFEEvent *folderACLInitEvent = - new TImapFEEvent(MOZTHREAD_FolderNeedsACLInitialized, // function to call - this, // access to current entry/context - value, FALSE); - - if (folderACLInitEvent) - { - fFEEventQueue->AdoptEventToEnd(folderACLInitEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - rv = value->rv; - XP_FREE(value->hostName); - XP_FREE(value->name); - XP_FREE(value); - return rv; -} - -/////////////////// End ACL Stuff ///////////////////////////////////////////////////// - -XP_Bool TNavigatorImapConnection::InitializeFolderUrl(const char *folderName) -{ - FolderQueryInfo *value = (FolderQueryInfo *)XP_ALLOC(sizeof(FolderQueryInfo)); - XP_Bool rv = FALSE; - - if (!value) return FALSE; - - value->name = XP_STRDUP(folderName); - if (!value->name) - { - XP_FREE(value); - return FALSE; - } - - value->hostName = XP_STRDUP(fCurrentUrl->GetUrlHost()); - if (!value->hostName) - { - XP_FREE(value->name); - XP_FREE(value); - return FALSE; - } - - TImapFEEvent *folderURLInitEvent = - new TImapFEEvent(MOZ_THREADmsgSetFolderURL, // function to call - this, // access to current entry/context - value, TRUE); - - if (folderURLInitEvent) - { - fFEEventQueue->AdoptEventToEnd(folderURLInitEvent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - rv = value->rv; - XP_FREE(value->hostName); - XP_FREE(value->name); - XP_FREE(value); - return rv; -} - - -static void -MOZTHREAD_GetShowAttachmentsInline(void *blockingConnectionVoid, void *valueVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - XP_Bool *value = (XP_Bool *)valueVoid; - - PREF_GetBoolPref("mail.inline_attachments", value); - - imapConnection->NotifyEventCompletionMonitor(); -} - -XP_Bool TNavigatorImapConnection::GetShowAttachmentsInline() -{ - XP_Bool *value = (XP_Bool *)XP_ALLOC(sizeof(XP_Bool)); - XP_Bool rv = FALSE; - - if (!value) return FALSE; - - TImapFEEvent *levent = - new TImapFEEvent(MOZTHREAD_GetShowAttachmentsInline, // function to call - this, // access to current entry/context - value, FALSE); - - if (levent) - { - fFEEventQueue->AdoptEventToEnd(levent); - WaitForFEEventCompletion(); - } - else - HandleMemoryFailure(); - - rv = *value; - XP_FREE(value); - return rv; -} - -void TNavigatorImapConnection::SetContentModified(XP_Bool modified) -{ - ActiveEntry *ce = GetActiveEntry(); - if (ce && !DeathSignalReceived()) - ce->URL_s->content_modified = modified; -} - -XP_Bool TNavigatorImapConnection::GetShouldFetchAllParts() -{ - ActiveEntry *ce = GetActiveEntry(); - if (ce && !DeathSignalReceived()) - return ce->URL_s->content_modified; - else - return TRUE; -} - -void TNavigatorImapConnection::Log(const char *logSubName, const char *extraInfo, const char *logData) -{ - static char *nonAuthStateName = "NA"; - static char *authStateName = "A"; - static char *selectedStateName = "S"; - static char *waitingStateName = "W"; - char *stateName = NULL; - - switch (GetServerStateParser().GetIMAPstate()) - { - case TImapServerState::kFolderSelected: - if (fCurrentUrl) - { - if (extraInfo) - PR_LOG(IMAP, out, ("%s:%s-%s:%s:%s: %s", fCurrentUrl->GetUrlHost(),selectedStateName, GetServerStateParser().GetSelectedMailboxName(), logSubName, extraInfo, logData)); - else - PR_LOG(IMAP, out, ("%s:%s-%s:%s: %s", fCurrentUrl->GetUrlHost(),selectedStateName, GetServerStateParser().GetSelectedMailboxName(), logSubName, logData)); - } - return; - break; - case TImapServerState::kNonAuthenticated: - stateName = nonAuthStateName; - break; - case TImapServerState::kAuthenticated: - stateName = authStateName; - break; - case TImapServerState::kWaitingForMoreClientInput: - stateName = waitingStateName; - break; - } - - if (fCurrentUrl) - { - if (extraInfo) - PR_LOG(IMAP, out, ("%s:%s:%s:%s: %s",fCurrentUrl->GetUrlHost(),stateName,logSubName,extraInfo,logData)); - else - PR_LOG(IMAP, out, ("%s:%s:%s: %s",fCurrentUrl->GetUrlHost(),stateName,logSubName,logData)); - } -} - - -// essentially, just a copy of parseadoptedmsgline, except it doesn't notify the eventcompletion monitor -static -void MOZTHREAD_TunnelOutStream(void *blockingConnectionVoid, void *adoptedmsg_line_info_Void) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - ActiveEntry *ce = imapConnection->GetActiveEntry(); - - msg_line_info *downloadLineDontDelete = (msg_line_info *) adoptedmsg_line_info_Void; - NET_StreamClass *outputStream = imapConnection->GetOutputStream(); - - unsigned int streamBytesMax = (*outputStream->is_write_ready) (outputStream); - char *stringToPut = downloadLineDontDelete->adoptedMessageLine; - XP_Bool allocatedString = FALSE; - - if ( streamBytesMax < (XP_STRLEN(downloadLineDontDelete->adoptedMessageLine) + 2)) - { - // dup the streamBytesMax number of chars, then put the rest of the string back into event queue - if (streamBytesMax != 0) - { - stringToPut = (char *) XP_ALLOC(streamBytesMax + 1); // 1 for \0 - if (stringToPut) - { - XP_MEMCPY(stringToPut, downloadLineDontDelete->adoptedMessageLine, streamBytesMax); - *(stringToPut + streamBytesMax) = 0; - allocatedString = TRUE; - } - - // shift buffer bytes - XP_MEMMOVE(downloadLineDontDelete->adoptedMessageLine, - downloadLineDontDelete->adoptedMessageLine + streamBytesMax, - (XP_STRLEN(downloadLineDontDelete->adoptedMessageLine) + 1) - streamBytesMax); - } - - // the output stream can't handle this event yet! put it back on the - // queue - TImapFEEvent *parseLineEvent = - new TImapFEEvent(MOZTHREAD_TunnelOutStream, // function to call - blockingConnectionVoid, // access to current entry - adoptedmsg_line_info_Void, - FALSE); // line to display - if (parseLineEvent) - imapConnection->GetFEEventQueue(). - AdoptEventToBeginning(parseLineEvent); - else - imapConnection->HandleMemoryFailure(); - } - - - if (streamBytesMax != 0) - { - imapConnection->SetBytesMovedSoFarForProgress(imapConnection->GetBytesMovedSoFarForProgress() + - XP_STRLEN(stringToPut)); - - if (!imapConnection->GetPseudoInterrupted()) - { - int bytesPut = 0; - - if (ce->window_id->currentIMAPfolder) - { - // the definition of put_block in net.h defines - // the 3rd parameter as the length of the block, - // but since we are always sending a null terminated - // string, I am able to sent the uid instead - bytesPut = (*outputStream->put_block) (outputStream, - stringToPut, - downloadLineDontDelete->uidOfMessage); - } - else // this is a download for display - { - bytesPut = (*outputStream->put_block) (outputStream, - stringToPut, - XP_STRLEN(stringToPut)); - } - - if (bytesPut < 0) - { - imapConnection->SetConnectionStatus(-1); // something bad happened, stop this url - imapConnection->GetServerStateParser().SetConnected(FALSE); - } - } - } - if (allocatedString) - XP_FREE(stringToPut); // event not done yet -// else if (streamBytesMax != 0) -// imapConnection->NotifyEventCompletionMonitor(); -} - -static void -MOZTHREAD_ProcessTunnel(void *blockingConnectionVoid, void *tunnelInfoVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) blockingConnectionVoid; - TunnelInfo *info = (TunnelInfo *)tunnelInfoVoid; - - if (info->maxSize <= 150) - { - // We want to read less than the size of a line. - // Close the tunnel, and switch back to the IMAP thread - // to do the protocol parsing, etc. - PR_LOG(IMAP, out, ("TUNNEL: Leaving Mozilla Thread with leftover size %ld",info->maxSize)); - imapConnection->NotifyTunnelCompletionMonitor(); - } - else - { - // We know there's enough data to read. So let's do it. - - // Read a line - char *newLine = NULL; - XP_Bool pauseForRead = TRUE; - int socketReadStatus = NET_BufferedReadLine(info->ioSocket, - &newLine, - info->inputSocketBuffer, - info->inputBufferSize, - &pauseForRead); - - if (socketReadStatus > 0) - { - // Set it up to handle reading what's left over - if (newLine) - { - char *lineToStream = PR_smprintf("%s%s",newLine, CRLF); - if (lineToStream) - { - info->maxSize -= XP_STRLEN(lineToStream); - XP_ASSERT(info->maxSize > 0); - TImapFEEvent *event = - new TImapFEEvent(MOZTHREAD_ProcessTunnel, // function to call - blockingConnectionVoid, // access to current entry - tunnelInfoVoid, - FALSE); - if (event) - imapConnection->GetFEEventQueue(). - AdoptEventToBeginning(event); - else - imapConnection->HandleMemoryFailure(); - - - // Finally, stream it out - - msg_line_info *outputStreamInfo = (msg_line_info *) XP_ALLOC(sizeof( msg_line_info)); - if (outputStreamInfo) - { - outputStreamInfo->adoptedMessageLine = lineToStream; - // Whoa, actually call one event from another. - // Let's let it worry about making sure everything is streamed out before we get called here again. - MOZTHREAD_TunnelOutStream(blockingConnectionVoid, outputStreamInfo); - XP_FREE(outputStreamInfo); - } - else - imapConnection->HandleMemoryFailure(); - XP_FREE(lineToStream); - } - else - imapConnection->HandleMemoryFailure(); - } - else - { - // no line yet, but there might have been data read (filling up the buffer) - // Put ourselves back on the queue - TImapFEEvent *event = - new TImapFEEvent(MOZTHREAD_ProcessTunnel, // function to call - blockingConnectionVoid, // access to current entry - tunnelInfoVoid, - FALSE); - if (event) - imapConnection->GetFEEventQueue(). - AdoptEventToBeginning(event); - else - imapConnection->HandleMemoryFailure(); - } - } - else - { - // socketReadStatus <= 0 - int socketError = PR_GetError(); - - // If wouldblock, just put this event back on the queue - if (socketError == XP_ERRNO_EWOULDBLOCK) - { - TImapFEEvent *event = - new TImapFEEvent(MOZTHREAD_ProcessTunnel, // function to call - blockingConnectionVoid, // access to current entry - tunnelInfoVoid, - FALSE); - if (event) - imapConnection->GetFEEventQueue(). - AdoptEventToBeginning(event); - else - imapConnection->HandleMemoryFailure(); - } - else - { - // Some socket error - handle this here - XP_ASSERT(FALSE); - } - } - } -} - -int32 TNavigatorImapConnection::OpenTunnel (int32 maxNumberOfBytesToRead) -{ - char *bytesToRead = PR_smprintf("Max bytes to read: %ld",maxNumberOfBytesToRead); - if (bytesToRead) - { - Log("TUNNEL","Opening Tunnel", bytesToRead); - XP_FREE(bytesToRead); - } - else - { - Log("TUNNEL",NULL,"Opening Tunnel"); - } - TunnelInfo *info = (TunnelInfo *)XP_ALLOC(sizeof(TunnelInfo)); - int32 originalMax = maxNumberOfBytesToRead, rv = 0; - if (info) - { - info->maxSize = maxNumberOfBytesToRead; - info->ioSocket = GetIOSocket(); - info->inputSocketBuffer = &fInputSocketBuffer; - info->inputBufferSize = &fInputBufferSize; - - TImapFEEvent *event = - new TImapFEEvent(MOZTHREAD_ProcessTunnel, // function to call - this, // access to current entry/context - info, // the tunneling info - FALSE); // Interrupts would be bad for this - - if (event) - { - fFEEventQueue->AdoptEventToEnd(event); - //WaitForFEEventCompletion(); - WaitForTunnelCompletion(); - } - else - HandleMemoryFailure(); - - rv = originalMax - info->maxSize; - - XP_FREE(info); - } - char *bytesSoFar = PR_smprintf("Bytes read so far: %ld", rv); - if (bytesSoFar) - { - Log("TUNNEL","Closing Tunnel", bytesSoFar); - XP_FREE(bytesSoFar); - } - else - { - Log("TUNNEL",NULL,"Closing Tunnel"); - } - return rv; -} - -int32 TNavigatorImapConnection::GetTunnellingThreshold() -{ - return gTunnellingThreshold; -} - -XP_Bool TNavigatorImapConnection::GetIOTunnellingEnabled() -{ - return gIOTunnelling; -} - - -PR_STATIC_CALLBACK(void) - -imap_thread_main_function(void *imapConnectionVoid) -{ - TNavigatorImapConnection *imapConnection = - (TNavigatorImapConnection *) imapConnectionVoid; - - imapConnection->StartProcessingActiveEntries(); - - delete imapConnection; -} - - -/* start a imap4 load - */ -extern int MK_POP3_PASSWORD_UNDEFINED; - -//#define KEVIN_DEBUG 1 -#if KEVIN_DEBUG -static int gNumberOfVisits; -static int gNumberOfVisitsProcessingEvents; -static int gNumberOfEventsForCurrentUrl; -#endif - -static -void NotifyOfflineFolderLoad(TIMAPUrl &currentUrl, MWContext *window_id) -{ - mailbox_spec *notSelectedSpec = (mailbox_spec *) XP_CALLOC(1, sizeof( mailbox_spec)); - if (notSelectedSpec) - { - notSelectedSpec->allocatedPathName =currentUrl.CreateCanonicalSourceFolderPathString(); - notSelectedSpec->hostName =currentUrl.GetUrlHost(); - notSelectedSpec->folderSelected = FALSE; - notSelectedSpec->flagState = NULL; - notSelectedSpec->onlineVerified = FALSE; - UpdateIMAPMailboxInfo(notSelectedSpec, window_id); - } -} - -static XP_Bool gotPrefs = FALSE, useLibnetCacheForIMAP4Fetch; -static XP_Bool gotUpgradePrefs = FALSE; -static XP_Bool fTriedSavedPassword = FALSE; -static XP_Bool triedUpgradingToSubscription = FALSE; -static XP_Bool autoSubscribe = TRUE, autoUnsubscribe = TRUE, autoSubscribeOnOpen = TRUE, autoUnsubscribeFromNoSelect = TRUE; -static XP_Bool allowMultipleFolderConnections = TRUE; -static XP_Bool gGetHeaders = FALSE; -static int32 gTooFastTime = 2; -static int32 gIdealTime = 4; -static int32 gChunkAddSize = 2048; -static int32 gChunkSize = 10240; -static int32 gChunkThreshold = 10240 + 4096; -static XP_Bool gFetchByChunks = TRUE; -static int32 gMaxChunkSize = 40960; - -/* static */ int -TNavigatorImapConnection::SetupConnection(ActiveEntry * ce, MSG_Master *master, XP_Bool loadingURL) -{ - int32 returnValue = MK_WAITING_FOR_CONNECTION; - TIMAPUrl currentUrl(ce->URL_s->address, ce->URL_s->internal_url); - XP_Bool thisHostUsingSubscription = FALSE; - XP_Bool shouldUpgradeToSubscription = FALSE, upgradeLeaveAlone = FALSE, upgradeSubscribeAll = FALSE; - - if (!gotUpgradePrefs) - { - shouldUpgradeToSubscription = MSG_ShouldUpgradeToIMAPSubscription(master); - - PREF_GetBoolPref("mail.imap.upgrade.leave_subscriptions_alone", &upgradeLeaveAlone); - PREF_GetBoolPref("mail.imap.upgrade.auto_subscribe_to_all", &upgradeSubscribeAll); - - gotUpgradePrefs = TRUE; - } - - char *serverMailboxPath = (currentUrl.GetUrlIMAPstate() == - TIMAPUrl::kAuthenticatedStateURL) ? 0 : - currentUrl.CreateCanonicalSourceFolderPathString(); - - // if we are appending message even though it is in - // TIMAPUrl::kAuthenticatedStateURL we should try to reuse the cached - // connection. The reason for that is that the user might already have the - // folder opened using a new connection to append message can cause the - // thread window view out of sync. - if (!serverMailboxPath && currentUrl.GetIMAPurlType() == - TIMAPUrl::kAppendMsgFromFile) - serverMailboxPath = - currentUrl.CreateCanonicalSourceFolderPathString(); - - XP_Bool waitingForCachedConnection = FALSE; - XP_Bool newConnection = FALSE; - TNavigatorImapConnection *blockingConnection = NULL; - if (master) - { - blockingConnection = MSG_UnCacheImapConnection(master, currentUrl.GetUrlHost(), serverMailboxPath); - // if it's in the cache, by definition, it's not in use, I believe. - // this code doesn't work if you don't have remember password turned on, because we never make a connection! - if (!blockingConnection && IMAP_URLIsBiff(ce, currentUrl) - && TNavigatorImapConnection::IsConnectionActive(currentUrl.GetUrlHost(), serverMailboxPath)) - { - PR_LOG(IMAP, out, ("URL: Biff blocking on active connection %s", ce->URL_s->address)); - return -1; // we didn't have a cached connection but the inbox is busy, so biff should wait - } - } - - - if (blockingConnection && (currentUrl.GetIMAPurlType() == TIMAPUrl::kSelectFolder || currentUrl.GetIMAPurlType() == TIMAPUrl::kDeleteAllMsgs)) - blockingConnection->SetNeedsNoop(TRUE); - if (blockingConnection && - (blockingConnection->GetServerStateParser().GetIMAPstate() == TImapServerState::kFolderSelected) && - (currentUrl.GetUrlIMAPstate() == TIMAPUrl::kAuthenticatedStateURL) ) - { - // We dont want to be in the selected state in case we operate on the selected mailbox - // and we do not want an implicit Close() so shut this connection down - IMAP_TerminateConnection(blockingConnection); - blockingConnection = NULL; - } - ImapConData *newConnectionData = (ImapConData *) ce->con_data; - - if (blockingConnection) - { - MSG_SetFolderRunningIMAPUrl(ce->URL_s->msg_pane, currentUrl.GetUrlHost(), serverMailboxPath, MSG_RunningOnline); - // let's use the cached connection - newConnectionData->netConnection = blockingConnection; - ce->socket = blockingConnection->GetIOSocket(); - ce->con_sock = ce->socket; - - ce->local_file = FALSE; - NET_TotalNumberOfOpenConnections++; - NET_SetReadSelect(ce->window_id, ce->socket); - FE_SetProgressBarPercent(ce->window_id, -1); - // I don't think I need to call FE_SetConnectSelect since we are already connected - } - else - { - if (!allowMultipleFolderConnections) - { - XP_Bool folderActive = TNavigatorImapConnection::IsConnectionActive(currentUrl.GetUrlHost(), serverMailboxPath); - if (folderActive) - { - waitingForCachedConnection = TRUE; - if (loadingURL) - PR_LOG(IMAP, out, ("URL: Blocking on active connection %s", ce->URL_s->address)); - - ce->local_file = TRUE; - // Note: Chrisf: This needs to be a PRFileDesc, we're not sure how to do this so we'll leave it for you - // to fix when you get back... -// ce->socket = 1; - if (loadingURL) - NET_SetCallNetlibAllTheTime(ce->window_id, "mkimap4"); - } - } - // create the blocking connection object - if (!waitingForCachedConnection) - { - HG73299 - blockingConnection = TNavigatorImapConnection::Create(currentUrl.GetUrlHost()); - } - if (blockingConnection) - { - MSG_FolderInfo *folder = MSG_SetFolderRunningIMAPUrl(ce->URL_s->msg_pane, currentUrl.GetUrlHost(), serverMailboxPath, MSG_RunningOnline); - // Find out if delete is move-to-trash - XP_Bool deleteIsMoveToTrash = MSG_GetIMAPHostDeleteIsMoveToTrash(master, currentUrl.GetUrlHost()); - int threadPriority = 31; // medium priority was 15, but that may have slowed down thru-put -#ifdef XP_UNIX - threadPriority = 31; // highest priority for unix, especially SSL -#endif - - - newConnection = TRUE; - // start the imap thread - PRThread *imapThread = PR_CreateThread(PR_USER_THREAD, imap_thread_main_function, blockingConnection, - PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, - 0); // standard stack - // save the thread object so an IMAP interrupt will - // cause the TIMAP4BlockingConnection destructor to - // destroy it. - blockingConnection->SetBlockingThread(imapThread); - newConnectionData->netConnection = blockingConnection; - - XP_Bool folderNeedsSubscribing = FALSE; - XP_Bool folderNeedsACLRefreshed = FALSE; - if (folder) - { - folderNeedsSubscribing = MSG_GetFolderNeedsSubscribing(folder); - folderNeedsACLRefreshed = MSG_GetFolderNeedsACLListed(folder); - } - blockingConnection->SetFolderInfo(folder, folderNeedsSubscribing, folderNeedsACLRefreshed); - - blockingConnection->SetSubscribeParameters(autoSubscribe, autoUnsubscribe, - autoSubscribeOnOpen, autoUnsubscribeFromNoSelect, shouldUpgradeToSubscription, upgradeLeaveAlone, upgradeSubscribeAll); - blockingConnection->SetDeleteIsMoveToTrash(deleteIsMoveToTrash); - blockingConnection->Configure(gGetHeaders, gTooFastTime, gIdealTime, gChunkAddSize, gChunkSize, - gChunkThreshold, gFetchByChunks, gMaxChunkSize); - } - } - - if (blockingConnection) - { - blockingConnection->SetActive(TRUE); - if (ce->window_id && - ((ce->window_id->type == MWContextMail) || - (ce->window_id->type == MWContextNews))) - { - FE_UpdateStopState(ce->window_id); - } - PR_Sleep(PR_INTERVAL_NO_WAIT); - blockingConnection->SubmitActiveEntry(ce, newConnection); - - // force netlib to be called all the time, whether there is IO - // or not. This enables us to process the fe event queue. - // net_call_all_the_time_count is a global used by the existing netlib - //if(net_call_all_the_time_count < 1) - if (loadingURL) - NET_SetCallNetlibAllTheTime(ce->window_id, "mkimap4"); - blockingConnection->SetCallingNetlibAllTheTime(TRUE); - - // msg copy code has to use the TNavigatorImapConnection 'C' interface - if (ce->window_id->msgCopyInfo) - MSG_StoreNavigatorIMAPConnectionInMoveState(ce->window_id, blockingConnection); - ce->window_id->imapConnection = blockingConnection; - - -#if KEVIN_DEBUG - gNumberOfVisits=0; - gNumberOfVisitsProcessingEvents=0; - gNumberOfEventsForCurrentUrl=0; -#endif - returnValue = NET_ProcessIMAP4(ce); - } - else if (!waitingForCachedConnection) - { - FE_Alert(ce->window_id, XP_GetString(MK_OUT_OF_MEMORY)); - returnValue = -1; - } - FREEIF(serverMailboxPath); - return returnValue; -} - -MODULE_PRIVATE int32 -NET_IMAP4Load (ActiveEntry * ce) -{ - int returnValue=0; - - PR_LOG(IMAP, out, ("URL: Loading %s",ce->URL_s->address)); - - // Get the master and a master Pane. We will need them a few times later. - MSG_Pane *masterPane = ce->URL_s->msg_pane; // we need some pane to get to the master, libimg will run fetch urls to get mime parts - if (!masterPane) - masterPane = MSG_FindPane(ce->window_id, MSG_ANYPANE); // last ditch effort, GROSS! - MSG_Master *master = ce->window_id->mailMaster; - if (!master) - { - master = MSG_GetMaster(masterPane); - ce->window_id->mailMaster = master; - } - XP_ASSERT(master); - - // check to see if we have all the prefs we need for this load - if (!gotPrefs) - { - // cacheing pref - PREF_GetBoolPref("mail.imap.cache_fetch_responses",&useLibnetCacheForIMAP4Fetch); - - PREF_GetBoolPref("mail.imap.allow_multiple_folder_connections", &allowMultipleFolderConnections); - - // subscription prefs - PREF_GetBoolPref("mail.imap.auto_subscribe",&autoSubscribe); - PREF_GetBoolPref("mail.imap.auto_unsubscribe", &autoUnsubscribe); - PREF_GetBoolPref("mail.imap.auto_subscribe_on_open",&autoSubscribeOnOpen); - PREF_GetBoolPref("mail.imap.auto_unsubscribe_from_noselect_folders",&autoUnsubscribeFromNoSelect); - - // chunk size and header prefs - PREF_GetBoolPref("mail.imap.new_mail_get_headers", &gGetHeaders); - PREF_GetIntPref("mail.imap.chunk_fast", &gTooFastTime); // secs we read too little too fast - PREF_GetIntPref("mail.imap.chunk_ideal", &gIdealTime); // secs we read enough in good time - PREF_GetIntPref("mail.imap.chunk_add", &gChunkAddSize); // buffer size to add when wasting time - PREF_GetIntPref("mail.imap.chunk_size", &gChunkSize); - PREF_GetIntPref("mail.imap.min_chunk_size_threshold", &gChunkThreshold); - PREF_GetBoolPref("mail.imap.fetch_by_chunks", &gFetchByChunks); - PREF_GetIntPref("mail.imap.max_chunk_size", &gMaxChunkSize); - - // bodystructure prefs - PREF_GetBoolPref("mail.imap.mime_parts_on_demand", &gMIMEOnDemand); - PREF_GetIntPref("mail.imap.mime_parts_on_demand_threshold", &gMIMEOnDemandThreshold); - PREF_GetBoolPref("mail.imap.optimize_header_dl", &gOptimizedHeaders); - - PREF_GetIntPref("mail.imap.tunnelling_threshold", &gTunnellingThreshold); - PREF_GetBoolPref("mail.imap.io_tunnelling", &gIOTunnelling); - - gotPrefs = TRUE; - } - - ce->window_id->imapConnection = NULL; - // this might be simple note that the filtering is done - if (!XP_STRCMP(ce->URL_s->address, kImapFilteringCompleteURL)) - { - MSG_ImapInboxFilteringComplete(ce->URL_s->msg_pane); - return -1; - } - - // this might be simple note that the on/off synch is done - if (!XP_STRCMP(ce->URL_s->address, kImapOnOffSynchCompleteURL)) - { - MSG_ImapOnOffLineSynchComplete(ce->URL_s->msg_pane); - return -1; - } - - // if this url is bogus, be defensive and leave before we make a connection - TIMAPUrl currentUrl(ce->URL_s->address, ce->URL_s->internal_url); - if (!currentUrl.ValidIMAPUrl()) - return -1; - - const char *password = NULL; - - TIMAPHostInfo::AddHostToList(currentUrl.GetUrlHost()); - - // try cached password for this host; if this fails, ask libmsg. - XP_Bool savePassword = FALSE; - password = TIMAPHostInfo::GetPasswordForHost(currentUrl.GetUrlHost()) ; - if (!password) - { - savePassword = TRUE; - password = MSG_GetIMAPHostPassword(ce->window_id->mailMaster, currentUrl.GetUrlHost()); - } -/* if (!fTriedSavedPassword) */ { - // Try getting the password from the prefs, if it was saved - if (savePassword && password && (XP_STRLEN(password) > 0)) { // make sure we actually have one in the prefs - TIMAPHostInfo::SetPasswordForHost(currentUrl.GetUrlHost(), password); - } - fTriedSavedPassword = TRUE; - } - - // if this is a biff and we have no valid password, then bail before we make a connection - if (IMAP_URLIsBiff(ce, currentUrl)) - { - if (!MSG_GetIMAPHostIsSecure(master, currentUrl.GetUrlHost()) && !password) - return -1; - } - - // if we want to use the libnet cache: - // if this is not a message fetch, make sure this url is not cached. How can - // libnet cache a load mailbox command? duh. - if (!useLibnetCacheForIMAP4Fetch || - ((currentUrl.GetIMAPurlType() != TIMAPUrl::kMsgFetch) || - currentUrl.MimePartSelectorDetected())) - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); - - // If this is a message fetch URL - // See if it is a force-reload-all-attachments URL. If so, strip off the - int whereStart = XP_STRLEN(ce->URL_s->address) - 9; // 9 == XP_STRLEN("&allparts") - if (whereStart > 0) - { - if (!XP_STRNCASECMP(ce->URL_s->address + whereStart, "&allparts", 9)) - { - // It is a force reload all - strip off the "&allparts" - *(ce->URL_s->address+whereStart) = 0; - ce->URL_s->content_modified = TRUE; // tiny hack. Set this bit to mean this is a - // forced reload. - } - } - - ImapConData *newConnectionData = (ImapConData *) XP_CALLOC(sizeof(ImapConData), 1); - if (!newConnectionData) - { - FE_Alert(ce->window_id, XP_GetString(MK_OUT_OF_MEMORY)); - return -1; - } - ce->con_data = newConnectionData; - newConnectionData->offLineRetrievalData = NULL; - newConnectionData->offlineDisplayStream = NULL; - - if ((currentUrl.GetIMAPurlType() == TIMAPUrl::kMsgFetch) && (currentUrl.MessageIdsAreUids()) ) - { - char *serverMailboxPath = currentUrl.CreateCanonicalSourceFolderPathString(); - char *msgIdString = currentUrl.CreateListOfMessageIdsString(); - - MSG_Pane *masterPane = ce->URL_s->msg_pane; // we need some pane to get to the master, libimg will run fetch urls to get mime parts - if (!masterPane) - masterPane = MSG_FindPane(ce->window_id, MSG_ANYPANE); // last ditch effort, GROSS! - - newConnectionData->offLineMsgKey = atoint32(msgIdString); - newConnectionData->offLineMsgFlags = MSG_GetImapMessageFlags(masterPane, currentUrl.GetUrlHost(), serverMailboxPath, newConnectionData->offLineMsgKey ); - - if ((newConnectionData->offLineMsgFlags & MSG_FLAG_OFFLINE) || NET_IsOffline()) - { - MSG_SetFolderRunningIMAPUrl(masterPane, currentUrl.GetUrlHost(), serverMailboxPath, MSG_RunningOffline); - ce->local_file = TRUE; - ce->socket = NULL; - NET_SetCallNetlibAllTheTime(ce->window_id, "mkimap4"); - /// do not cache this url since its already local - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); - - MSG_StartOfflineImapRetrieval(masterPane, - currentUrl.GetUrlHost(), serverMailboxPath, - newConnectionData->offLineMsgKey, - &newConnectionData->offLineRetrievalData); - - returnValue = NET_ProcessIMAP4(ce); - } - - FREEIF(serverMailboxPath); - FREEIF(msgIdString); - } - - if (!newConnectionData->offLineRetrievalData && !NET_IsOffline()) - { - returnValue = TNavigatorImapConnection::SetupConnection(ce, master, TRUE); - } - else if (!newConnectionData->offLineRetrievalData && NET_IsOffline()) - { - // we handled offline fetch earlier, now handle offline select - if (currentUrl.GetIMAPurlType() == TIMAPUrl::kSelectFolder) - NotifyOfflineFolderLoad(currentUrl, ce->window_id); - returnValue = MK_OFFLINE; - } - - - return returnValue; -} - -// this is called from the memory cache to notify us that a cached imap message has finished loading -void IMAP_URLFinished(URL_Struct *URL_s) -{ - TIMAPUrl currentUrl(URL_s->address, URL_s->internal_url); - char *serverMailboxPath = currentUrl.CreateCanonicalSourceFolderPathString(); - MSG_FolderInfo *folder = MSG_SetFolderRunningIMAPUrl(URL_s->msg_pane, currentUrl.GetUrlHost(), serverMailboxPath, MSG_NotRunning); - FREEIF(serverMailboxPath); - MSG_IMAPUrlFinished(folder, URL_s); -} - -static MSG_FolderInfo *imap_clear_running_imap_url(ActiveEntry *ce) -{ - TIMAPUrl currentUrl(ce->URL_s->address, ce->URL_s->internal_url); - char *serverMailboxPath = currentUrl.CreateCanonicalSourceFolderPathString(); - MSG_FolderInfo *folder = MSG_SetFolderRunningIMAPUrl(ce->URL_s->msg_pane, currentUrl.GetUrlHost(), serverMailboxPath, MSG_NotRunning); - FREEIF(serverMailboxPath); - return folder; -} - - -/* NET_ProcessOfflineIMAP4 will control the state machine that - * loads messages from a imap db - * - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -static int -NET_ProcessOfflineIMAP4 (ActiveEntry *ce, ImapConData *cd) -{ - int keepCallingMe = 1; - - if (!cd->offlineDisplayStream) - { - if (ce->format_out == FO_PRESENT || ce->format_out == FO_CACHE_AND_PRESENT) - { - IMAP_InitializeImapFeData(ce); - } - - ce->URL_s->content_length = MSG_GetOfflineMessageSize(cd->offLineRetrievalData); - StrAllocCopy(ce->URL_s->content_type, ce->URL_s->content_length ? MESSAGE_RFC822 : TEXT_HTML); - cd->offlineDisplayStream = NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - if (!cd->offlineDisplayStream) - ce->status = -1; - } - - if (ce->status >= 0) - { - int32 read_size = (*cd->offlineDisplayStream->is_write_ready) (cd->offlineDisplayStream); - if(!read_size) - return(0); /* wait until we are ready to write */ - else - read_size = MIN(read_size, NET_Socket_Buffer_Size); - - ce->status = MSG_ProcessOfflineImap(cd->offLineRetrievalData, NET_Socket_Buffer, read_size); - if(ce->status > 0) - { - ce->bytes_received += ce->status; - (*cd->offlineDisplayStream->put_block) (cd->offlineDisplayStream, NET_Socket_Buffer, ce->status); - } - - if (ce->status == 0) - { - if (cd->offlineDisplayStream) - (*cd->offlineDisplayStream->complete) (cd->offlineDisplayStream); - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkimap4"); - - // clean up the offline info, in case we need to mark read online - ce->local_file = FALSE; - ce->socket = 0; - cd->offLineRetrievalData = NULL; - keepCallingMe = -1; - } - } - - if (ce->status < 0) - keepCallingMe = -1; - - // here we need to check if we have offline events saved up while we were running this url - // (and not plain old offline events getting played back). And we need to figure out how to run - // them from here...because we will interrupt current url if not careful. - if (keepCallingMe < 0) - { - // tell libmsg that we're not running an imap url for this folder anymore - MSG_FolderInfo *folder = imap_clear_running_imap_url(ce); - MSG_IMAPUrlFinished(folder, ce->URL_s); - } - - return keepCallingMe; -} - - - - -static void imap_interrupt_possible_libmsg_select(ActiveEntry *ce) -{ - // if this was a folder load then tell libmsg it was interrupted - TIMAPUrl interruptedURL(ce->URL_s->address, ce->URL_s->internal_url); - if (interruptedURL.GetIMAPurlType() == TIMAPUrl::kSelectFolder) - { - char *folderName = interruptedURL.CreateCanonicalSourceFolderPathString(); - MSG_InterruptImapFolderLoad( MSG_FindPaneOfContext(ce->window_id, MSG_ANYPANE), - interruptedURL.GetUrlHost(), folderName); - FREEIF(folderName); - } -} - -void TNavigatorImapConnection::ResetProgressInfo() -{ - LL_I2L(fLastProgressTime, 0); - fLastPercent = -1; - fLastProgressStringId = -1; -} - -/* NET_ProcessIMAP4 will control the state machine that - * loads messages from a imap4 server - * - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -MODULE_PRIVATE int32 -NET_ProcessIMAP4 (ActiveEntry *ce) -{ -#if KEVIN_DEBUG - gNumberOfVisits++; -#endif - MSG_Master *currentMaster = ce->window_id->mailMaster; - if (!currentMaster && ce->URL_s->msg_pane) // if there is no pane or master, then I can't find the master where the cache is - currentMaster = MSG_GetMaster(ce->URL_s->msg_pane); - - ImapConData *cd = (ImapConData *) ce->con_data; - XP_Bool shouldDieAtEnd = FALSE; - - if (cd->offLineRetrievalData) - { - return NET_ProcessOfflineIMAP4(ce, cd); - } - - TNavigatorImapConnection *imapConnection = cd->netConnection; - if (!imapConnection) - { - TNavigatorImapConnection::SetupConnection(ce, currentMaster, FALSE); - return MK_WAITING_FOR_CONNECTION; - } - assert(imapConnection); - - // if this is a move/copy operation, be sure to let libmsg do its thing. - if (imapConnection->CurrentConnectionIsMove() && ce->window_id->msgCopyInfo && - !MSG_IsMessageCopyFinished(ce->window_id->msgCopyInfo)) - { - int finishReturn = MSG_FinishCopyingMessages(ce->window_id); - - if (finishReturn < 0) - { - // handled in ReportSuccessOfOnlineCopy - - } - } - - // NotifyIOCompletionMonitor even if we end up here because we are calling netlib all of the time. - // an extra NotifyIOCompletionMonitor will cause one extra poll of the port. - // This can happen after we finish processing a bunch of fe events and go - // into a BlockedForIO state. So, we might randomly do one extra poll per - // blocked io read. After this poll, calling netlib off the time will - // be turned off if we are still blocked on io. - if (imapConnection->BlockedForIO()) - { - // we entered NET_ProcessIMAP4 because a net read is finished - imapConnection->NotifyIOCompletionMonitor(); // will give time to imap thread - } - else - PR_Sleep(PR_INTERVAL_NO_WAIT); // give the imap thread some time. - - int connectionStatus = imapConnection->GetConnectionStatus(); - - int eventLimitNotReached = 2; // if we don't limit the events, then huge downloads - // are effectively synchronous - -#if KEVIN_DEBUG - if (imapConnection->GetFEEventQueue().NumberOfEventsInQueue()) - gNumberOfVisitsProcessingEvents++; -#endif - - while (eventLimitNotReached-- && (connectionStatus >= 0) && - imapConnection->GetFEEventQueue().NumberOfEventsInQueue()) - { - if (imapConnection->GetFEEventQueue().NumberOfEventsInQueue()) - { - TImapFEEvent *event = - imapConnection->GetFEEventQueue().OrphanFirstEvent(); - event->DoEvent(); - delete event; -#if KEVIN_DEBUG - gNumberOfEventsForCurrentUrl++; -#endif - } - - // PR_Sleep(PR_INTERVAL_NO_WAIT); // when this yield was here, a huge message download, - // now that it is buffered, always caused an event - // in the queue but never tripped eventLimitNotReached. - // Since each buffered event is relatively slow, (e.g. - // html parsing 1500 bytes) the effect was to cause - // synchronous downloads - connectionStatus = imapConnection->GetConnectionStatus(); - } - - //if (eventLimitNotReached == -1) - // DebugStr("\pTouch the sky"); - - - if (connectionStatus < 0) - { - // we are done or errored out - ce->window_id->imapConnection = NULL; - XP_Bool diedWhileCallingNetlibSet = imapConnection->GetCallingNetlibAllTheTime(); - - // some events can fail and put another event in the queue - // this is rare and catastrophic anyway so only process the number - // of events we know about when we start this loop - int numberOfEventsToProcess = imapConnection->GetFEEventQueue().NumberOfEventsInQueue(); - while (numberOfEventsToProcess-- && imapConnection->GetFEEventQueue().NumberOfEventsInQueue()) - { - TImapFEEvent *event = - imapConnection->GetFEEventQueue().OrphanFirstEvent(); - event->DoEvent(); - delete event; -#if KEVIN_DEBUG - gNumberOfEventsForCurrentUrl++; -#endif - } - imapConnection->SignalEventQueueEmpty(); - - // tell libmsg that we're not running an imap url for this folder anymore - MSG_FolderInfo *folder = imap_clear_running_imap_url(ce); - - FREEIF(ce->con_data); - if (ce->socket != 0) - { - // stop calling me, i am finished - NET_ClearReadSelect(ce->window_id, ce->socket); - NET_ClearConnectSelect(ce->window_id, ce->socket); - NET_TotalNumberOfOpenConnections--; - - // maybe we can cache this connection - XP_Bool wasCached = FALSE; - - if (currentMaster && // do not cache a non-authenticated or disconnected connection. - (imapConnection->GetServerStateParser().GetIMAPstate() != TImapServerState::kNonAuthenticated) && - (imapConnection->GetServerStateParser().Connected()) && - !imapConnection->GetServerStateParser().SyntaxError()) - { - TIMAPUrl currentUrl(ce->URL_s->address, ce->URL_s->internal_url); - imapConnection->ResetProgressInfo(); - - wasCached = MSG_TryToCacheImapConnection(currentMaster, currentUrl.GetUrlHost(), - imapConnection->GetServerStateParser().GetSelectedMailboxName(), - imapConnection); - } - if (!wasCached) - { - char *logoutString = PR_smprintf("xxxx logout\r\n"); - - if (logoutString) - { - PR_LOG(IMAP, out, ("%s",logoutString)); - PR_LOG(IMAP, out, ("Logged out from NET_ProcessIMAP4")); - NET_BlockingWrite(ce->socket, logoutString, XP_STRLEN(logoutString)); - XP_FREEIF(logoutString); - } - - if (!imapConnection->GetServerStateParser().Connected()) - { - imap_interrupt_possible_libmsg_select(ce); - } - - shouldDieAtEnd = TRUE; - imapConnection->SetIOSocket(NULL); // delete connection - net_graceful_shutdown(ce->socket, HG87263); - PR_Close(ce->socket); - } - else - { - imapConnection->SetActive(FALSE); - } - - ce->socket = 0; - } - else - shouldDieAtEnd = TRUE; - - - // Whoa! - // net_call_all_the_time_count is a global used by the existing netlib - //net_call_all_the_time_count--; - //if(net_call_all_the_time_count < 1) - if (diedWhileCallingNetlibSet) - { - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkimap4"); - imapConnection->SetCallingNetlibAllTheTime(FALSE); - } -#if KEVIN_DEBUG - char debugString[250]; - sprintf(debugString, "visits = %ld, usefull visits = %ld, # of events = %ld", - gNumberOfVisits, - gNumberOfVisitsProcessingEvents, - gNumberOfEventsForCurrentUrl); - DebugStr(c2pstr(debugString)); -#endif - // here we need to check if we have offline events saved up while we were running this url - // (and not plain old offline events getting played back). And we need to figure out how to run - // them from here...because we will interrupt current url if not careful. - MSG_IMAPUrlFinished(folder, ce->URL_s); - } - else - { - if (imapConnection->BlockedForIO() && !imapConnection->GetFEEventQueue().NumberOfEventsInQueue()) - { - // if we are blocked and there are no events to process - // then stop calling me until io completes - if (imapConnection->GetCallingNetlibAllTheTime()) - { - imapConnection->SetCallingNetlibAllTheTime(FALSE); - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkimap4"); - } - } - else if (!imapConnection->GetCallingNetlibAllTheTime()) - { - // the thread might need to process events, keep entering - imapConnection->SetCallingNetlibAllTheTime(TRUE); - NET_SetCallNetlibAllTheTime(ce->window_id, "mkimap4"); - } - } - if (shouldDieAtEnd) - imapConnection->TellThreadToDie(); - // the imapConnection may now be deleted, so don't use it! - return connectionStatus; -} - - -/* abort the connection in progress - */ -MODULE_PRIVATE int32 -NET_InterruptIMAP4(ActiveEntry * ce) -{ - PR_LOG(IMAP, out, ("INTERRUPT Entered")); - ImapConData *cd = (ImapConData *) ce->con_data; - - TNavigatorImapConnection *imapConnection = cd->netConnection; - - if (!imapConnection || cd->offLineRetrievalData) - { - void *offLineRetrievalData = cd->offLineRetrievalData; - ce->status = MK_INTERRUPTED; - ce->window_id->imapConnection = NULL; - FREEIF(cd); - return MSG_InterruptOfflineImap(offLineRetrievalData); - } - - // Whoa! - // net_call_all_the_time_count is a global used by the existing netlib - if (imapConnection->GetCallingNetlibAllTheTime()) - { - imapConnection->SetCallingNetlibAllTheTime(FALSE); - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkimap4"); - } - - // tell libmsg that we're not running an imap url for this folder anymore - imap_clear_running_imap_url(ce); - - // tell the imap thread that we are shutting down - // pass FALSE and call SetIsSafeToDie later - imapConnection->TellThreadToDie(FALSE); - - // some events can fail and put another event in the queue - // this is rare and catastrophic anyway so only process the number - // of events we know about when we start this loop - int numberOfEventsToProcess = imapConnection->GetFEEventQueue().NumberOfEventsInQueue(); - while (numberOfEventsToProcess-- && imapConnection->GetFEEventQueue().NumberOfEventsInQueue()) - { - TImapFEEvent *event = - imapConnection->GetFEEventQueue().OrphanFirstEvent(); - if (event->ShouldExecuteWhenInterrupted()) - { - if (event->GetEventFunction() == NormalEndMsgWriteStream) - event->SetEventFunction(AbortMsgWriteStream); - event->DoEvent(); - } - delete event; - } - imapConnection->SignalEventQueueEmpty(); - - imap_interrupt_possible_libmsg_select(ce); - - FREEIF(ce->con_data); - ce->status = MK_INTERRUPTED; - if (ce->socket != 0) - { - /* *** imapConnection->TellThreadToDie(FALSE) sends out the - * logout command string already - * - char *logoutString = PR_smprintf("xxxx logout\r\n"); - if (logoutString) - { - PR_LOG(IMAP, out, ("%s",logoutString)); - PR_LOG(IMAP, out, ("Logged out from NET_InterruptIMAP4")); - NET_BlockingWrite(ce->socket, logoutString, XP_STRLEN(logoutString)); - XP_FREEIF(logoutString); - } - * - */ - NET_ClearReadSelect(ce->window_id, ce->socket); - NET_ClearConnectSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing socket ce->socket: %d", - ce->socket)); - imapConnection->SetIOSocket(NULL); - net_graceful_shutdown(ce->socket, HG83733); - PR_Close(ce->socket); - imapConnection->SetIOSocket(NULL); - NET_TotalNumberOfOpenConnections--; - ce->socket = 0; - } - - // tell it to stop - imapConnection->SetIsSafeToDie(); - // the imapConnection may now be deleted, so don't use it! - - ce->window_id->imapConnection = NULL; - - return MK_INTERRUPTED; -} - -/* called on shutdown to clean up */ -extern "C" void net_CleanupIMAP4(void); -extern "C" void -net_CleanupIMAP4(void) -{ -} - -extern "C" void -NET_InitIMAP4Protocol(void) -{ - static NET_ProtoImpl imap4_proto_impl; - - imap4_proto_impl.init = NET_IMAP4Load; - imap4_proto_impl.process = NET_ProcessIMAP4; - imap4_proto_impl.interrupt = NET_InterruptIMAP4; - imap4_proto_impl.resume = NULL; - imap4_proto_impl.cleanup = net_CleanupIMAP4; - - NET_RegisterProtocolImplementation(&imap4_proto_impl, IMAP_TYPE_URL); -} - -TLineDownloadCache::TLineDownloadCache() -{ - fLineInfo = (msg_line_info *) XP_ALLOC(sizeof( msg_line_info)); - fLineInfo->adoptedMessageLine = fLineCache; - fLineInfo->uidOfMessage = 0; - fBytesUsed = 0; -} - -TLineDownloadCache::~TLineDownloadCache() -{ - FREEIF( fLineInfo); -} - -uint32 TLineDownloadCache::CurrentUID() -{ - return fLineInfo->uidOfMessage; -} - -uint32 TLineDownloadCache::SpaceAvailable() -{ - return kDownLoadCacheSize - fBytesUsed; -} - -msg_line_info *TLineDownloadCache::GetCurrentLineInfo() -{ - return fLineInfo; -} - -void TLineDownloadCache::ResetCache() -{ - fBytesUsed = 0; -} - -XP_Bool TLineDownloadCache::CacheEmpty() -{ - return fBytesUsed == 0; -} - -void TLineDownloadCache::CacheLine(const char *line, uint32 uid) -{ - uint32 lineLength = XP_STRLEN(line); - XP_ASSERT((lineLength + 1) <= SpaceAvailable()); - - fLineInfo->uidOfMessage = uid; - - XP_STRCPY(fLineInfo->adoptedMessageLine + fBytesUsed, line); - fBytesUsed += lineLength; -} - -HG00374 - - -TIMAPSocketInfo::TIMAPSocketInfo() : -fIOSocket(0), -pInputSocketBuffer(nil), -pInputBufferSize(nil), -newLine(nil), -pauseForRead(FALSE), -readStatus(-1) -{ -} - -// TInboxReferenceCount functions - -PRMonitor *TInboxReferenceCount::fgDataSafeMonitor = nil; -int TInboxReferenceCount::fgInboxUsageCount = 0; - -TInboxReferenceCount::TInboxReferenceCount(XP_Bool bumpInboxCount) -{ - if (fgDataSafeMonitor) - { - PR_EnterMonitor(fgDataSafeMonitor); - fInboxCountWasBumped = bumpInboxCount; - if (fInboxCountWasBumped) - fgInboxUsageCount++; - PR_ExitMonitor(fgDataSafeMonitor); - } - else - fInboxCountWasBumped = FALSE; -} - -TInboxReferenceCount::~TInboxReferenceCount() -{ - if (fInboxCountWasBumped && fgDataSafeMonitor) - { - PR_EnterMonitor(fgDataSafeMonitor); - fgInboxUsageCount--; - PR_ExitMonitor(fgDataSafeMonitor); - } -} - -int TInboxReferenceCount::GetInboxUsageCount() -{ - int returnCount = 0; - - if (fgDataSafeMonitor) - { - PR_EnterMonitor(fgDataSafeMonitor); - returnCount = fgInboxUsageCount; - PR_ExitMonitor(fgDataSafeMonitor); - } - - return returnCount; -} - -//static -void TInboxReferenceCount::ImapStartup() -{ - if (!fgDataSafeMonitor) - fgDataSafeMonitor = PR_NewNamedMonitor("inbox-data-safe-monitor"); -} - -//static -void TInboxReferenceCount::ImapShutDown() -{ - if (fgDataSafeMonitor) - { - PR_DestroyMonitor(fgDataSafeMonitor); - fgDataSafeMonitor = NULL; - } -} - - -TIMAPMailboxInfo::TIMAPMailboxInfo(const char *name) -{ - m_mailboxName = XP_STRDUP(name); - m_childrenListed = FALSE; -} - -TIMAPMailboxInfo::~TIMAPMailboxInfo() -{ - FREEIF(m_mailboxName); -} - -void IMAP_StartupImap() -{ - TInboxReferenceCount::ImapStartup(); - TNavigatorImapConnection::ImapStartup(); -} - -void IMAP_ShutdownImap() -{ - TInboxReferenceCount::ImapShutDown(); - TNavigatorImapConnection::ImapShutDown(); -} - -XP_Bool IMAP_HaveWeBeenAuthenticated() -{ - return (gIMAPpassword || preAuthSucceeded); -} diff --git a/mozilla/network/protocol/imap4/mkimap4.h b/mozilla/network/protocol/imap4/mkimap4.h deleted file mode 100644 index ec9850584a0..00000000000 --- a/mozilla/network/protocol/imap4/mkimap4.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKIMAP4_H -#define MKIMAP4_H - -#include "mkgeturl.h" - -XP_BEGIN_PROTOS - -extern int32 NET_IMAP4Load (ActiveEntry *ce); - -/* NET_ProcessIMAP4 will control the state machine that - * loads messages from a imap4 server - * - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -extern int32 NET_ProcessIMAP4 (ActiveEntry *ce); - -/* abort the connection in progress - */ -MODULE_PRIVATE int32 NET_InterruptIMAP4(ActiveEntry * ce); - -extern void NET_InitIMAP4Protocol(void); - -XP_END_PROTOS - - -#endif /* MKIMAP4_H */ diff --git a/mozilla/network/protocol/js/MANIFEST b/mozilla/network/protocol/js/MANIFEST deleted file mode 100644 index a36fb83989a..00000000000 --- a/mozilla/network/protocol/js/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -jsurl.h diff --git a/mozilla/network/protocol/js/Makefile.in b/mozilla/network/protocol/js/Makefile.in deleted file mode 100644 index a270192f540..00000000000 --- a/mozilla/network/protocol/js/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = jsurl -LIBRARY_NAME = jsurl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl lay parse style - -CSRCS = mkmocha.c - -EXPORTS = $(srcdir)/jsurl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/js/jsurl.h b/mozilla/network/protocol/js/jsurl.h deleted file mode 100644 index 66db8e36f5f..00000000000 --- a/mozilla/network/protocol/js/jsurl.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKMOCHA_H -#define MKMOCHA_H - -/* - * Mocha netlib-specific stuff. - */ -extern void NET_InitMochaProtocol(void); - -#endif /* MKMOCHA_H */ diff --git a/mozilla/network/protocol/js/makefile.win b/mozilla/network/protocol/js/makefile.win deleted file mode 100644 index 4d47b0d56eb..00000000000 --- a/mozilla/network/protocol/js/makefile.win +++ /dev/null @@ -1,87 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkmocha.obj \ - $(NULL) - - -CSRCS = \ - mkmocha.c \ - $(NULL) - - -LIBRARY_NAME=jsurl -MODULE=jsurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= jsurl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\lay \ - -I$(XPDIST)\public\parse \ - -I$(XPDIST)\public\style \ - -I$(XPDIST)\public\network -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/js/mkmocha.c b/mozilla/network/protocol/js/mkmocha.c deleted file mode 100644 index dcd2b99fa72..00000000000 --- a/mozilla/network/protocol/js/mkmocha.c +++ /dev/null @@ -1,756 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* Please leave at the top for windows precompiled headers */ -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" - -#include <stddef.h> -#include <memory.h> -#include <time.h> -#include "net.h" -#include "libmocha.h" -#include "jsurl.h" -#include "libevent.h" -#include "fe_proto.h" -#include "pa_tags.h" /* included via -I../libparse */ -#include "libi18n.h" /* unicode */ -#include "layout.h" /* for lo_ContextToCell only */ - -extern char lm_unknown_origin_str[]; - -extern int MK_OUT_OF_MEMORY; -extern int MK_MALFORMED_URL_ERROR; - -typedef struct { - char * buffer; - size_t offset; - size_t length; - MWContext * context; - char * content_type; - int16 char_set; -} MochaStream; - -typedef struct { - int32 ref_count; - ActiveEntry * active_entry; - PRPackedBool is_valid; - PRPackedBool eval_what; - PRPackedBool single_shot; - PRPackedBool polling; - char * str; - size_t len; - MWContext * context; - int status; - char * wysiwyg_url; - char * base_href; - NET_StreamClass * stream; -} MochaConData; - -#define HOLD_CON_DATA(con_data) ((con_data)->ref_count++) -#define DROP_CON_DATA(con_data) { \ - if (--(con_data)->ref_count == 0) \ - free_con_data(con_data); \ -} - -static void -free_con_data(MochaConData * con_data) -{ - PR_FREEIF(con_data->str); - PR_FREEIF(con_data->wysiwyg_url); - PR_FREEIF(con_data->base_href); - PR_Free(con_data); -} - -#define START_POLLING(ae, con_data) { \ - (con_data)->polling = TRUE; \ - NET_SetCallNetlibAllTheTime((ae)->window_id, "mkmocha"); \ -} - -#define STOP_POLLING(ae, con_data) { \ - NET_ClearCallNetlibAllTheTime((ae)->window_id, "mkmocha"); \ - (con_data)->polling = FALSE; \ -} - -/* forward decl */ -PRIVATE int32 net_ProcessMocha(ActiveEntry * ae); - -/* - * Add the new bits to our buffer - */ -PRIVATE int -mocha_process(NET_StreamClass *stream, const char *str, int32 len) -{ - MochaStream * mocha_stream = (MochaStream *) stream->data_object; - - mocha_stream->length += len; - if (!mocha_stream->buffer) { - mocha_stream->buffer = (char *)PR_Malloc(mocha_stream->length); - } - else { - mocha_stream->buffer = (char *)PR_Realloc(mocha_stream->buffer, - mocha_stream->length); - } - if (!mocha_stream->buffer) { - return MK_OUT_OF_MEMORY; - } - memcpy(mocha_stream->buffer + mocha_stream->offset, str, len); - mocha_stream->offset += len; - return len; -} - -PRIVATE unsigned int -mocha_ready(NET_StreamClass *stream) -{ - return MAX_WRITE_READY; /* always ready for writing */ -} - - -/* - * All of the processing for this needs to be done in the mocha thread - */ -PRIVATE void -mocha_complete(NET_StreamClass *stream) -{ - void * data; - JSBool isUnicode = JS_FALSE; - - MochaStream * mocha_stream = (MochaStream *) stream->data_object; - - if (mocha_stream->char_set != CS_DEFAULT) { - uint32 len; - INTL_Unicode * unicode; - - /* find out how many unicode characters we'll end up with */ - len = INTL_TextToUnicodeLen(mocha_stream->char_set, - (unsigned char *) mocha_stream->buffer, - mocha_stream->length); - unicode = PR_Malloc(sizeof(INTL_Unicode) * len); - if (!unicode) - return; - - /* do the conversion */ - mocha_stream->length = INTL_TextToUnicode(mocha_stream->char_set, - (unsigned char *) mocha_stream->buffer, - mocha_stream->length, - unicode, - len); - - data = unicode; - isUnicode = JS_TRUE; - - PR_Free(mocha_stream->buffer); - mocha_stream->buffer = NULL; - } - else { - data = mocha_stream->buffer; - } - - /* this will grab ownership of data */ - ET_MochaStreamComplete(mocha_stream->context, data, - mocha_stream->length, - mocha_stream->content_type, - isUnicode); - - PR_FREEIF(mocha_stream->content_type); - PR_Free(mocha_stream); - -} - -PRIVATE void -mocha_abort(NET_StreamClass *stream, int status) -{ - MochaStream * mocha_stream = (MochaStream *) stream->data_object; - - ET_MochaStreamAbort(mocha_stream->context, status); - PR_Free(mocha_stream->buffer); - PR_FREEIF(mocha_stream->content_type); - PR_Free(mocha_stream); -} - -int16 -net_check_for_charset(URL_Struct *url_struct) -{ - int i, max; - char *key, *value; - static char charset[] = "charset="; - int len = PL_strlen(charset); - - max = url_struct->all_headers.empty_index; - - for (i = 0; i < max; i++) { - key = url_struct->all_headers.key[i]; - - /* keep looking until we find the content type one */ - if (PL_strcasecmp(key, "Content-type")) - continue; - - value = url_struct->all_headers.value[i]; - - value = strtok(value, ";"); - while (value) { - value = XP_StripLine(value); - - if (!PL_strncasecmp(value, charset, len)) { - value += len; - value = XP_StripLine(value); - return (INTL_CharSetNameToID(value)); - } - - /* move to next arg */ - value = strtok(NULL, ";"); - - } - - /* found content-type but no charset */ - return CS_DEFAULT; - - } - - /* didn't find content-type */ - return CS_DEFAULT; -} - -static char * -getOriginFromURLStruct(MWContext *context, URL_Struct *url_struct) -{ - char *referer; - /* - * Look in url_struct->origin_url for this javascript: URL's - * original referrer. - * - * In the basis case, a javascript: or *.js URL targets a context - * from a (the same, or not) context loaded with a non-javascript URL. - * The referring document's URL is in url_struct->referer and we - * duplicate it as origin_url. If we find a non-null origin_url - * later, we know by induction where it came from. - */ - referer = url_struct->origin_url; - if (referer == NULL) { - /* - * url_struct->referer (sic) tells the URL of the page in - * which a javascript: or *.js link or form was clicked or submitted. - * If it's non-null, but the context is a frame cell that's - * being (re-)created for this load, don't use referer as the - * decoder's source URL for the evaluation, because the FE has - * arbitrarily set it to the top frameset's URL. Instead, use - * the immediate parent frameset context's wysiwyg URL to get - * the origin of the generator (or the parent's address URL if - * not wysiwyg). - * - * If referer is null, the user typed this javascript: URL or - * its frameset's URL directly into the Location toolbar. - */ - referer = url_struct->referer; - if (referer) { - lo_GridRec *grid = NULL; - - if (context->is_grid_cell && - !lo_ContextToCell(context, FALSE, &grid)) { - /* - * Context is a frame being (re)created: veto referer. - * The javascript: or *.js URL can't be a LAYER SRC= URL in a - * frame because the frame's cell must point to its - * context by the time the first tag (even LAYER) is - * processed by layout. - */ - referer = NULL; - } - } - if (!referer) { - History_entry *he; - - if (context->grid_parent) { - /* - * If grid parent, use its history entry to get the - * wysiwyg or real URL, which tells the subject origin - * of (any code in it that may have generated) this - * javascript: or *.js URL open. If no grid parent, this must - * be a javascript: or *.js URL that was typed directly into - * Location. - */ - context = context->grid_parent; - } - he = SHIST_GetCurrent(&context->hist); - if (!he) { - referer = lm_unknown_origin_str; - } else { - referer = he->wysiwyg_url; - if (!referer) - referer = he->address; - } - } - } - - PR_ASSERT(referer); - referer = PL_strdup(referer); - if (!referer) { - return NULL; - } - url_struct->origin_url = referer; - return referer; -} - -NET_StreamClass * -NET_CreateMochaConverter(FO_Present_Types format_out, - void *data_object, - URL_Struct *url_struct, - MWContext *context) -{ - MochaStream * mocha_stream; - NET_StreamClass *stream; - char *origin; - - mocha_stream = (MochaStream *) PR_NEWZAP(MochaStream); - if (!mocha_stream) - return NULL; - - mocha_stream->context = context; - mocha_stream->content_type = PL_strdup(url_struct->content_type); - mocha_stream->char_set = net_check_for_charset(url_struct); - - /* Get the origin from the URL struct. We don't have to free origin - * here because url_struct->origin_url owns it. - */ - origin = getOriginFromURLStruct(context, url_struct); - if (origin == NULL) - return NULL; - - if (NET_URL_Type(url_struct->address) == FILE_TYPE_URL && - NET_URL_Type(origin) != FILE_TYPE_URL) - { - /* - * Don't allow loading a file: URL from a non-file URL to - * prevent privacy attacks against the local machine from - * web pages. - */ - return NULL; - } - - stream = NET_NewStream("mocha", mocha_process, mocha_complete, - mocha_abort, mocha_ready, mocha_stream, - context); - return stream; -} - -PRIVATE void -mk_mocha_eval_exit_fn(void * data, char * str, size_t len, char * wysiwyg_url, - char * base_href, Bool valid) -{ - MochaConData * con_data = (MochaConData *) data; - - if (!valid) { - con_data->status = MK_MALFORMED_URL_ERROR; - con_data->is_valid = TRUE; - return; - } - if (str == NULL) { - con_data->status = MK_DATA_LOADED; - con_data->is_valid = TRUE; - return; - } - - con_data->base_href = base_href; - con_data->wysiwyg_url = wysiwyg_url; - con_data->str = str; - con_data->len = len; - con_data->is_valid = TRUE; - -} - -/* - * Handle both 'mocha:<stuff>' urls and the mocha type-in widget - */ -MODULE_PRIVATE int32 -net_MochaLoad(ActiveEntry *ae) -{ - MWContext *context; - URL_Struct *url_struct; - char *what; - Bool eval_what, single_shot; - MochaConData * con_data; - - context = ae->window_id; - url_struct = ae->URL_s; - what = PL_strchr(url_struct->address, ':'); - PR_ASSERT(what); - what++; - eval_what = FALSE; - single_shot = (*what != '?'); - - if (single_shot) { - /* Don't use an existing Mocha output window's stream. */ - if (*what == '\0') { - /* Generate two grid cells, one for output and one for input. */ - what = PR_smprintf("<frameset rows=\"75%%,25%%\">\n" - "<frame name=MochaOutput src=about:blank>\n" - "<frame name=MochaInput src=%.*s#input>\n" - "</frameset>", - what - url_struct->address, - url_struct->address); - } else if (!PL_strcmp(what, "#input")) { - /* The input cell contains a form with one magic isindex field. */ - what = PR_smprintf("<b>%.*s typein</b>\n" - "<form action=%.*s target=MochaOutput" - " onsubmit='this.isindex.focus()'>\n" - "<input name=isindex size=60>\n" - "</form>", - what - url_struct->address - 1, - url_struct->address, - what - url_struct->address, - url_struct->address); - url_struct->internal_url = TRUE; - } else { - eval_what = TRUE; - } - } else { - /* Use the Mocha output window if it exists. */ - url_struct->auto_scroll = 1000; - - /* Skip the leading question-mark and clean up the string. */ - what++; - NET_PlusToSpace(what); - NET_UnEscape(what); - eval_what = TRUE; - } - - /* something got hosed. bail */ - if (!what) { - ae->status = MK_OUT_OF_MEMORY; - return -1; - } - - /* make space for the connection data */ - con_data = PR_NEWZAP(MochaConData); - if (!con_data) { - ae->status = MK_OUT_OF_MEMORY; - return -1; - } - - /* remember for next time */ - con_data->ref_count = 1; - con_data->active_entry = ae; - ae->con_data = con_data; - - /* set up some state so we remember where we are */ - con_data->eval_what = eval_what; - con_data->single_shot = single_shot; - con_data->context = context; - - /* fake out netlib so we don't select on the socket id */ - ae->socket = NULL; - ae->local_file = TRUE; - - if (eval_what) { - char *referer; - JSPrincipals *principals; - ETEvalStuff *stuff; - - referer = getOriginFromURLStruct(context, url_struct); - if (!referer) { - ae->status = MK_OUT_OF_MEMORY; - return -1; - } - - principals = LM_NewJSPrincipals(NULL, NULL, referer); - if (!principals) { - ae->status = MK_OUT_OF_MEMORY; - return -1; - } - - /* - * send the buffer off to be evaluated - */ - stuff = (ETEvalStuff *) PR_NEWZAP(ETEvalStuff); - if (!stuff) { - ae->status = MK_OUT_OF_MEMORY; - return -1; - } - - stuff->len = PL_strlen(what); - stuff->line_no = 0; - stuff->scope_to = NULL; - stuff->want_result = JS_TRUE; - stuff->data = con_data; - stuff->version = JSVERSION_UNKNOWN; - stuff->principals = principals; - - ET_EvaluateScript(context, what, stuff, mk_mocha_eval_exit_fn); - - } - else { - - /* allocated above, don't need to free */ - con_data->str = what; - con_data->len = PL_strlen(what); - con_data->is_valid = TRUE; - - } - - /* make sure netlib gets called so we know when our data gets back */ - START_POLLING(ae, con_data); - - /* ya'll come back now, ya'hear? */ - return net_ProcessMocha(ae); - -} - -PRIVATE int -net_process_mocha(MochaConData * con_data) -{ - int32 ref_count; - - ref_count = con_data->ref_count; - DROP_CON_DATA(con_data); - if (ref_count == 1 || !con_data->active_entry) - return -1; - return net_ProcessMocha(con_data->active_entry); -} - -static char nscp_open_tag[] = "<" PT_NSCP_OPEN ">"; - -/* - * If the mocha has finished evaluation shove the result - * down the stream and continue else just wait - */ -PRIVATE int32 -net_ProcessMocha(ActiveEntry * ae) -{ - FO_Present_Types output_format; - Bool to_layout; - Bool first_time; - NET_StreamClass *stream = NULL; - MochaConData * con_data = (MochaConData *) ae->con_data; - MWContext * context; - int status; - - /* if we haven't gotten our data yet just return and wait */ - if (!con_data || !con_data->is_valid) - return 0; - - context = ae->window_id; - - /* - * Race with the mocha thread until we can grab the JSLock - */ - if (!con_data->single_shot) { - MochaDecoder * decoder; - - HOLD_CON_DATA(con_data); - if (!LM_AttemptLockJS(context, - (JSLockReleaseFunc)net_process_mocha, con_data)) - return 0; - DROP_CON_DATA(con_data); - decoder = LM_GetMochaDecoder(context); - if (!decoder) { - LM_UnlockJS(context); - ae->status = MK_OUT_OF_MEMORY; - goto done; - } - stream = decoder->stream; - LM_PutMochaDecoder(decoder); - LM_UnlockJS(context); - } - else { - stream = con_data->stream; - } - - /* we've gotten valid data, clear the callme all the time flag */ - STOP_POLLING(ae, con_data); - - /* see if there were any problems */ - if (con_data->status < 0 || con_data->str == NULL) { - ET_SendLoadEvent(context, EVENT_LOAD, NULL, NULL, - LO_DOCUMENT_LAYER_ID, FALSE); - ae->status = con_data->status; - goto done; - } - - /* - * If we don't already have a stream to take our output create one now - */ - first_time = !stream; - if (first_time) { - StrAllocCopy(ae->URL_s->content_type, TEXT_HTML); - ae->format_out = CLEAR_CACHE_BIT(ae->format_out); - - stream = NET_StreamBuilder(ae->format_out, ae->URL_s, ae->window_id); - if (!stream) { - ae->status = MK_UNABLE_TO_CONVERT; - goto done; - } - } - - /* - * If the stream we just created isn't ready for writing just - * hold onto the stream and try again later - */ - if (!stream->is_write_ready(stream)) { - con_data->stream = stream; - START_POLLING(ae, con_data); - return 0; - } - - /* XXX this condition is fairly bogus */ - output_format = CLEAR_CACHE_BIT(ae->format_out); - to_layout = (output_format != FO_INTERNAL_IMAGE && - output_format != FO_MULTIPART_IMAGE && - output_format != FO_EMBED && - output_format != FO_PLUGIN); - - if (to_layout) { - /* The string must end in a newline so the parser will flush it. */ - if (con_data->len != 0 && con_data->str[con_data->len-1] != '\n') { - size_t new_len = con_data->len + 1; - char * new_str = PR_Malloc((new_len + 1) * sizeof(char)); - - if (!new_str) { - ae->status = MK_OUT_OF_MEMORY; - goto done; - } - memcpy(new_str, con_data->str, con_data->len); - new_str[new_len-1] = '\n'; - new_str[new_len] = '\0'; - con_data->str = new_str; - con_data->len = new_len; - } - } - - - /* - * If this is the first time do some initial setup. We'll set - * the window title and maybe shove out a <BASE> tag - */ - status = 0; - if (to_layout && first_time && con_data->eval_what) { - - /* Feed layout an internal tag so it will create a new top state. */ - stream->put_block(stream, nscp_open_tag, - sizeof nscp_open_tag - 1); - - (void) LM_WysiwygCacheConverter(context, ae->URL_s, - con_data->wysiwyg_url, - con_data->base_href); - - if (*con_data->str != '<') { - char * prefix = NULL; - StrAllocCopy(prefix, "<TITLE>"); - StrAllocCat(prefix, ae->URL_s->address); - StrAllocCat(prefix, "</TITLE><PLAINTEXT>"); - if (!prefix) { - ae->status = MK_OUT_OF_MEMORY; - goto done; - } - status = (*stream->put_block)(stream, prefix, - PL_strlen(prefix)); - PR_Free(prefix); - } - else { - if (con_data->base_href) { - status = (*stream->put_block)(stream, - con_data->base_href, - PL_strlen(con_data->base_href)); - } - } - } - - if (status >= 0) { - status = (*stream->put_block)(stream, con_data->str, - (int32)con_data->len); - } - - if (con_data->single_shot && status >= 0) - (*stream->complete)(stream); - - if (!con_data->single_shot && status >= 0) { - if (first_time) { - ET_SetDecoderStream(context, stream, ae->URL_s, JS_TRUE); - goto done; - } - } else { - if (status < 0) - (*stream->abort)(stream, status); - if (first_time) - PR_Free(stream); - } - - ae->status = MK_DATA_LOADED; - -done: - ae->con_data = NULL; - con_data->active_entry = NULL; - DROP_CON_DATA(con_data); - return -1; - -} - -PRIVATE int32 -net_InterruptMocha(ActiveEntry *ae) -{ - MochaConData * con_data = (MochaConData *) ae->con_data; - - if (!con_data) - return MK_INTERRUPTED; - - /* do we need to decrement the callme all the time flag? */ - if (con_data->polling) { - STOP_POLLING(ae, con_data); - } - - /* ae is about to go away, break its connection with con_data */ - ae->con_data = NULL; - con_data->active_entry = NULL; - - /* ae is about to go away, better get it off the JS lock waiters list */ - if (LM_ClearAttemptLockJS(con_data->context, - (JSLockReleaseFunc)net_process_mocha, con_data)) - DROP_CON_DATA(con_data); - - return ae->status = MK_INTERRUPTED; -} - -PRIVATE void -net_CleanupMocha(void) -{ - /* nothing so far needs freeing */ - return; -} - -MODULE_PRIVATE void -NET_InitMochaProtocol(void) -{ - static NET_ProtoImpl mocha_proto_impl; - - mocha_proto_impl.init = net_MochaLoad; - mocha_proto_impl.process = net_ProcessMocha; - mocha_proto_impl.interrupt = net_InterruptMocha; - mocha_proto_impl.resume = NULL; - mocha_proto_impl.cleanup = net_CleanupMocha; - - NET_RegisterProtocolImplementation(&mocha_proto_impl, MOCHA_TYPE_URL); -} - diff --git a/mozilla/network/protocol/ldap/MANIFEST b/mozilla/network/protocol/ldap/MANIFEST deleted file mode 100644 index c49665fd5f2..00000000000 --- a/mozilla/network/protocol/ldap/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mkldap.h diff --git a/mozilla/network/protocol/ldap/Makefile.in b/mozilla/network/protocol/ldap/Makefile.in deleted file mode 100644 index c2905dba5e4..00000000000 --- a/mozilla/network/protocol/ldap/Makefile.in +++ /dev/null @@ -1,43 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = ldapurl -LIBRARY_NAME = ldapurl - -REQUIRES = ldap progress netcache network dbm util pref js java fileurl security layer img httpurl mimetype htmldlgs - -CSRCS = mkldap.c - -EXPORTS = $(srcdir)/mkldap.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - -INCLUDES += -I$(topsrcdir)/lib/libmsg - diff --git a/mozilla/network/protocol/ldap/makefile.win b/mozilla/network/protocol/ldap/makefile.win deleted file mode 100644 index 80c2c78929d..00000000000 --- a/mozilla/network/protocol/ldap/makefile.win +++ /dev/null @@ -1,89 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkldap.obj \ - $(NULL) - -CSRCS = \ - mkldap.c \ - $(NULL) - - -LIBRARY_NAME=ldapurl -MODULE=ldapurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= progress network ldap -EXPORTS= mkldap.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\progress \ - -I$(DEPTH)\lib\libmsg \ - -I$(PUBLIC)\mimetype \ -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/ldap/mkldap.cpp b/mozilla/network/protocol/ldap/mkldap.cpp deleted file mode 100644 index f2a80c6c752..00000000000 --- a/mozilla/network/protocol/ldap/mkldap.cpp +++ /dev/null @@ -1,3317 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -// -// mkldap.cpp -- Handles LDAP-related URLs for the core Navigator, without -// requiring libmsg. mkldap is responsible for -// 1. basic async searching of LDAP servers, including authentication, -// capability negotiation with the server, and parsing results -// 2. Reading LDAP entries and converting them into HTML for display -// in the browsers -// 3. Reading an LDAP entry and converting it for use in the local -// Address Book -// 4. Replicating a large section of an LDAP directory into a local -// Address Book using changelog deltas -// - -#include "rosetta.h" -#include "mkutils.h" - -#include "mkgeturl.h" -#include "mkldap.h" -#include "xpgetstr.h" -#include "abcom.h" -#include "addrbook.h" -#include "msgcom.h" -#include "msgnet.h" -#if 0 -#include "msgpane.h" -#include "msgurlq.h" -#endif -#include "dirprefs.h" -#include "net.h" -#include "xp_str.h" -#include HG87373 -#include "secnav.h" -#include "libi18n.h" -#include "intl_csi.h" -#if 0 -#include "pw_public.h" -#endif - -#ifdef MOZ_LDAP - #ifdef MOZ_LI - #include "LILDAPAllOps.h" - #endif - - #define NEEDPROTOS - #define LDAP_REFERRALS - #include "lber.h" - #include "ldap.h" -#endif - - -extern "C" -{ - extern int MK_OUT_OF_MEMORY; - extern int MK_MSG_SEARCH_FAILED; - - extern int MK_LDAP_COMMON_NAME; - extern int MK_LDAP_FAX_NUMBER; - extern int MK_LDAP_GIVEN_NAME; - extern int MK_LDAP_LOCALITY; - extern int MK_LDAP_PHOTOGRAPH; - extern int MK_LDAP_EMAIL_ADDRESS; - extern int MK_LDAP_MANAGER; - extern int MK_LDAP_ORGANIZATION; - extern int MK_LDAP_OBJECT_CLASS; - extern int MK_LDAP_ORG_UNIT; - extern int MK_LDAP_POSTAL_ADDRESS; - extern int MK_LDAP_SECRETARY; - extern int MK_LDAP_SURNAME; - extern int MK_LDAP_STREET; - extern int MK_LDAP_PHONE_NUMBER; - extern int MK_LDAP_CAR_LICENSE; - extern int MK_LDAP_BUSINESS_CAT; - extern int MK_LDAP_DEPT_NUMBER; - extern int MK_LDAP_DESCRIPTION; - extern int MK_LDAP_EMPLOYEE_TYPE; - extern int MK_LDAP_POSTAL_CODE; - extern int MK_LDAP_TITLE; - - extern int MK_LDAP_ADD_SERVER_TO_PREFS; - extern int MK_MALFORMED_URL_ERROR; - HG73226 - extern int MK_LDAP_HTML_TITLE; - - extern int MK_LDAP_AUTH_PROMPT; - - extern int XP_LDAP_OPEN_SERVER_FAILED; - extern int XP_LDAP_BIND_FAILED; - extern int XP_LDAP_SEARCH_FAILED; -} - - -#ifdef MOZ_LDAP - -//***************************************************************************** -// -// net_LdapConnectionData is the base class which knows how to run -// ldap URLs asynchronously and pull out search results. -// -// If you want to do something special with the results of an LDAP -// search, you probably want to derive from this class and use/make -// virtual functions. -// - -class net_LdapConnectionData -{ -public: - net_LdapConnectionData (ActiveEntry*, XP_Bool bInitLdap = TRUE); - virtual ~net_LdapConnectionData (); - - virtual int Load (ActiveEntry *ce); - virtual int Process (); - virtual int Interrupt (); - -protected: - typedef enum _LdapConnectionType - { - kBaseConnection, - kHtmlConnection, - kReplicatorConnection, - kAddressBookConnection, - kLIConnection - } LdapConnectionType; - - virtual int Unbind (); - virtual int OnBindCompleted () { return 0; } - virtual int OnEntryFound (LDAPMessage *) { return 0; } - virtual int OnSearchCompleted () { return MK_CONNECTED; } - virtual XP_Bool OnError(int err) { return TRUE; } - virtual int16 GetLocalCharSet (); - virtual LdapConnectionType GetConnectionType() { return kBaseConnection; } - - void AddLdapServerToPrefs (LDAPURLDesc* pDesc); - - char *ConvertFromServerCharSet (char *s); - char *ConvertToServerCharSet (char *s); - // sub classes may have strings prefixed to the url...We need to filter them out here. - virtual char * ExtractLDAPEncoding(char * s); - - XP_Bool ShouldAddUrlDescToPrefs (MWContext *context, XP_List *serverList, LDAPURLDesc *pDesc); - void ConvertUrlDescToDirServer (LDAPURLDesc *pDesc, DIR_Server **pServer); - - const char *GetHostDescription (); - char *GetAttributeFromDN (char *dn, const char *name); - const char *GetAttributeString (DIR_AttributeId id); - - void DisplayError (int templateId, const char *contextString, int ldapErrorId); - - int16 m_csid; - LDAP *m_ldap; - int m_messageId; - ActiveEntry *m_ce; - DIR_Server *m_server; -}; - -net_LdapConnectionData::net_LdapConnectionData (ActiveEntry *ce, XP_Bool bInitLdap) -{ - // We init LDAP with no server name and port since we expect all - // such information to be spedified by URLs in our case. - // - if (bInitLdap) - m_ldap = ldap_init(NULL,0); - else - m_ldap = NULL; - - m_messageId = -1; // Init to an illegal value so we can detect errors - - m_server = NULL; - - m_csid = -1; - m_ce = ce; - m_ce->socket = NULL; - - // Netlib magic so we get a timeslice without waiting for a read-ready socket. - // It would be nice to ditch this, but the LDAP SDK manages the sockets. - NET_SetCallNetlibAllTheTime(m_ce->window_id, "mkldap"); -} - - -net_LdapConnectionData::~net_LdapConnectionData () -{ - // This is the normal-termination case to let go of the connection - Unbind(); - - // Netlib magic so we won't get called anymore for this URL - // It would be nice to ditch this, but the LDAP SDK manages the sockets. - NET_ClearCallNetlibAllTheTime(m_ce->window_id, "mkldap"); -} - -int16 net_LdapConnectionData::GetLocalCharSet () -{ - if (m_csid == -1) - m_csid = INTL_DefaultDocCharSetID(0); - return m_csid; -} - -void net_LdapConnectionData::AddLdapServerToPrefs (LDAPURLDesc* pDesc) -{ - // Takes an ActiveEntry from the current operation, a url descriptor from ldap_url_parse, - // determines (by asking the user) if we should add it to our LDAP prefs, and adds it if necessary. - - // Do we want to add the server specified by the URL to our LDAP prefs? - XP_List *serverList = FE_GetDirServers(); - if (serverList && ShouldAddUrlDescToPrefs(m_ce->window_id, serverList, pDesc)) - { - ConvertUrlDescToDirServer (pDesc, &m_server); - if (m_server) - { - XP_ListAddObjectToEnd (serverList, m_server); - DIR_SaveServerPreferences (serverList); - } - } -} - - -int net_LdapConnectionData::Load (ActiveEntry *ce) -{ - int ldapErr = 0; - LDAPURLDesc *pDesc = NULL; - - XP_ASSERT(ce); - XP_ASSERT(ce->URL_s); - XP_ASSERT(ce->URL_s->address); - - if (m_ldap) - { - // addbook and html have prefixes in front of them (i.e. addbook-ldap). We now want - // to parse that out of the utf8 encoding string that will be sent to the server. - // In addition, we want to convert the resulting encoding to utf8 - - // we do not need to free encoding because it is a part of the url passed in.... - char * encoding = ExtractLDAPEncoding(ce->URL_s->address); - - // now take the ldap encoding and convert to the server char set. - char *utf8Encoding = utf8Encoding = ConvertToServerCharSet (encoding); - - if (utf8Encoding) - { - ldapErr = ldap_url_parse (utf8Encoding, &pDesc); - - if (!pDesc || ldapErr != LDAP_SUCCESS) - ldapErr = MK_MALFORMED_URL_ERROR; - - if (ldapErr == 0) - { - // RFC 1959 allows this syntax, but we don't really have a way - // to infer an LDAP server, and it's a pretty strange X.500-ism anyway - if (!pDesc->lud_host) - ldapErr = MK_MALFORMED_URL_ERROR; - - AddLdapServerToPrefs (pDesc); - - HG29237 - if (ldapErr == 0) - { - // Initiate the search on the server - int msgId = ldap_url_search (m_ldap, utf8Encoding, 0); - if (msgId != -1) - m_messageId = msgId; - else - ldapErr = -1; - } - } - else - ldapErr = MK_MALFORMED_URL_ERROR; - - XP_FREE(utf8Encoding); - } - else - ldapErr = -1; - } - else - XP_ASSERT(pDesc); - ldapErr = -1; - - if (pDesc) - ldap_free_urldesc (pDesc); - - return ldapErr; -} - - -// Interpret all data we get from the server as being UTF-8 -char *net_LdapConnectionData::ConvertFromServerCharSet (char *s) -{ - char *converted = NULL; - XP_ASSERT(s); - if (s) - { - // Use the win_csid for browsers but the GUI csid for the AB - int16 destCsid = GetLocalCharSet(); - converted = DIR_ConvertFromServerCharSet (m_server, s, destCsid); - } - return converted; -} - -char * net_LdapConnectionData::ExtractLDAPEncoding(char * url) -{ - // for the base class, we don't know about stripping any prefixes off... - return url; -} - -// Send all data to the server in UTF-8 -char *net_LdapConnectionData::ConvertToServerCharSet (char *s) -{ - char *converted = NULL; - XP_ASSERT(s); - if (s) - { - // Use the win_csid for browsers but the GUI csid for the AB - int16 srcCsid = GetLocalCharSet(); - converted = DIR_ConvertToServerCharSet (m_server, s, srcCsid); - } - return converted; -} - -const char *net_LdapConnectionData::GetHostDescription() -{ - // since the description is optional, it might be null, so pick up - // the server's DNS name if necessary - return m_server->description ? m_server->description : m_server->serverName; -} - -char *net_LdapConnectionData::GetAttributeFromDN (char *dn, const char *name) -{ - // Pull an attribute out of the distinguished name - // e.g. the cn attribute from cn=John Smith,o=Netscape Communications Corp.,c=US - - char *result = NULL; - char **explodedDn = ldap_explode_dn (dn, FALSE /* suppress types? */); - if (explodedDn) - { - int i = 0; - while (explodedDn[i] && !result) - { - const char *nameFromDn = XP_STRTOK (explodedDn[i], "="); - if (!XP_STRCASECMP(name, nameFromDn)) - { - char *tmpResult = XP_STRDUP(explodedDn[i] + XP_STRLEN(nameFromDn) + 1); - result = ConvertFromServerCharSet (tmpResult); - XP_FREE(tmpResult); - } - i++; - } - ldap_value_free (explodedDn); - } - return result; -} - - -const char *net_LdapConnectionData::GetAttributeString (DIR_AttributeId id) -{ - // This function is a bottleneck for DIR_GetAttributeName. I think most - // of the time we'll have a DIR_Server, but I think it can also be NULL - // if the user clicked on an ldap: URL for which there's no server in - // the preferences - - return DIR_GetFirstAttributeString (m_server, id); -} - -void net_LdapConnectionData::DisplayError (int templateId, const char *contextString, int ldapErrorId) -{ - // This builds up error dialogs which look like: - // "Failed to open connection to 'ldap.mcom.com' due to LDAP error 'bad DN name' (0x22)" - - char *templateString = XP_GetString (templateId); - char *ldapErrString = NULL; - - if (ldapErrorId != 0) - ldapErrString = ldap_err2string (ldapErrorId); - if (templateString && contextString && (ldapErrorId == 0 || ldapErrString)) - { - int len = XP_STRLEN(templateString) + XP_STRLEN(contextString) + 10; - if (ldapErrString) - len += XP_STRLEN(ldapErrString); - char *theBigString = (char*) XP_ALLOC (len); - if (theBigString) - { - if (ldapErrorId) - PR_snprintf (theBigString, len, templateString, contextString, ldapErrString, ldapErrorId); - else - PR_snprintf (theBigString, len, templateString, contextString); - FE_Alert (m_ce->window_id, theBigString); - XP_FREE(theBigString); - } - } -} - - -XP_Bool net_LdapConnectionData::ShouldAddUrlDescToPrefs (MWContext *context, XP_List *serverList, LDAPURLDesc *pDesc) -{ - XP_Bool shouldAdd = TRUE; - - // First look through the prefs to see if the server already exists there - for (int i = 1; i <= XP_ListCount(serverList) && shouldAdd; i++) - { - DIR_Server *server = (DIR_Server*) XP_ListGetObjectNum (serverList, i); - if (server && server->serverName && pDesc->lud_host) - { - if (!XP_STRCASECMP(pDesc->lud_host, server->serverName)) - { - // The server does exist -- don't ask to add it again - shouldAdd = FALSE; - if (!m_server) - m_server = server; - } - } - } - - // If the server doesn't exist, ask the user if they want to add it to their prefs - if (shouldAdd) - { - char *prompt = PR_smprintf (XP_GetString(MK_LDAP_ADD_SERVER_TO_PREFS), pDesc->lud_host); - if (prompt) - { - shouldAdd = FE_Confirm (context, prompt); - XP_FREE(prompt); - } - else - shouldAdd = FALSE; - } - - return shouldAdd; -} - - -void net_LdapConnectionData::ConvertUrlDescToDirServer (LDAPURLDesc *pDesc, DIR_Server **ppServer) -{ - *ppServer = (DIR_Server*) XP_ALLOC (sizeof(DIR_Server)); - if (*ppServer) - { - XP_BZERO(*ppServer, sizeof(DIR_Server)); - - // These fields just map right over - (*ppServer)->serverName = XP_STRDUP (pDesc->lud_host); - (*ppServer)->searchBase = XP_STRDUP (pDesc->lud_dn ? pDesc->lud_dn : ""); - (*ppServer)->port = pDesc->lud_port; - - // These could probably be in a generic DIR_Server initializer. Do we need that? - (*ppServer)->efficientWildcards = TRUE; - (*ppServer)->saveResults = TRUE; - (*ppServer)->maxHits = 100; - - // The address book needs a valid filename. Use the hostname to derive one. - char *fileName = XP_STRTOK(pDesc->lud_host, "."); - if (fileName) - (*ppServer)->fileName = WH_FileName (fileName, xpAddrBook); - else - (*ppServer)->fileName = WH_FileName (pDesc->lud_host, xpAddrBook); - - // Try to derive a reasonable name for DIR_Server.description by looking - // at the distinguished name and picking out the most specific RDN - // (i.e. the last OU, or any OU, or any O, or any C). - if (pDesc->lud_dn) - { - char **explodedDn = ldap_explode_dn (pDesc->lud_dn, TRUE /*suppress types? */); - if (explodedDn) - { - if (explodedDn[0]) - (*ppServer)->description = XP_STRDUP (explodedDn[0]); - - ldap_value_free (explodedDn); - } - } - - // If we couldn't find any reasonable-looking DN component, just use the host name - if (NULL == (*ppServer)->description) - (*ppServer)->description = XP_STRDUP ((*ppServer)->serverName); - } -} - - -int net_LdapConnectionData::Process () -{ - LDAPMessage *message = NULL; - struct timeval timeout; - XP_BZERO (&timeout, sizeof(timeout)); - int result = ldap_result (m_ldap, m_messageId, 0, &timeout, &message); - - switch (result) - { - case LDAP_RES_SEARCH_ENTRY: - result = OnEntryFound (message); - break; - case LDAP_RES_SEARCH_RESULT: - result = OnSearchCompleted (); - break; - case LDAP_RES_BIND: - result = OnBindCompleted (); - break; - case LDAP_TIMEOUT: - result = 0; - break; - case 0: - break; - default: - if (result > 0) - { - int err = ldap_result2error (m_ldap, message, 0); - result = ((err != 0) ? err : result); - } - - if (OnError(result)) - { - DisplayError (XP_LDAP_OPEN_SERVER_FAILED, GetHostDescription(), result); - result = -1; - } - break; - } - - if (message != NULL) - ldap_msgfree (message); - return result; -} - - -int net_LdapConnectionData::Interrupt () -{ - // The destructor will unbind. - int ldapErr = ldap_abandon (m_ldap, m_messageId); - return ldapErr; -} - - -int net_LdapConnectionData::Unbind () -{ - int ldapErr = 0; - if (m_ldap) - { - ldapErr = ldap_unbind(m_ldap); - m_ldap = NULL; - } - return ldapErr; -} - - -//***************************************************************************** -// -// net_LdapToHtml does the work of converting LDAP entries into HTML -// which can be displayed in a browser window -// - -const int kNumAttributeNames = 24; - -class net_LdapToHtml : public net_LdapConnectionData -{ -public: - net_LdapToHtml (ActiveEntry*); - - virtual int OnEntryFound (LDAPMessage *entry); - virtual int OnSearchCompleted(); - virtual int16 GetLocalCharSet (); - - typedef struct - { - char *attributeName; - int resourceId; - } AttributeName; - -protected: - virtual LdapConnectionType GetConnectionType() { return kHtmlConnection; } - - int OpenStream (); - int CloseStream (); - int WriteLineToStream (const char *line, XP_Bool bold, XP_Bool lineBreak, XP_Bool isMailto = FALSE, - XP_Bool isUri = FALSE, XP_Bool aligntop = FALSE, XP_Bool isCell = FALSE); - NET_StreamClass *m_stream; - - const char *LookupAttributeName (const char *attrib); - char *GetTableCaption (LDAPMessage*); - - int WriteEntryToStream (LDAPMessage*); - int WriteValue (const char *, XP_Bool isMailto = FALSE, XP_Bool isUri = FALSE); - int WriteAttribute (const char *); - int WritePlainLine (const char *); - - - XP_Bool IsMailtoAttribute (const char *); - XP_Bool IsUriAttribute (const char *); - - char *ConvertDnToUri (const char *); - char *EscapeSpaces (const char *); - char *InferUrlBase (); - - static AttributeName m_names[kNumAttributeNames]; -}; - - -// Note that these are sorted. Someday I'll match attribs by binary search -// -// These are initialized to zero instead of their real resource IDs because -// the HP/UX compiler seems not to be capable of doing that - -net_LdapToHtml::AttributeName net_LdapToHtml::m_names[kNumAttributeNames] = { - { "carlicense", 0 }, - { "cn", 0 }, - { "businesscategory", 0 }, - { "departmentnumber", 0 }, - { "description", 0 }, - { "employeetype", 0 }, - { "facsimiletelephonenumber", 0 }, - { "givenname", 0 }, - { "l", 0 }, - { "jpegPhoto", 0 }, - { "mail", 0 }, - { "manager", 0 }, - { "o", 0 }, - { "objectclass", 0 }, - { "ou", 0 }, - { "postaladdress", 0 }, - { "postalcode", 0 }, - { "secretary", 0 }, - { "sn", 0 }, - { "street", 0 }, - { "telephonenumber", 0 }, - { "title", 0 } - HG38731 -}; - - -net_LdapToHtml::net_LdapToHtml (ActiveEntry *ce) : net_LdapConnectionData (ce) -{ - m_stream = NULL; -} - - -int net_LdapToHtml::OnEntryFound (LDAPMessage *message) -{ - int status = 0; - if (!m_stream) - status = OpenStream(); - if (0 == status) - status = WriteEntryToStream (message); - return status; -} - -int net_LdapToHtml::OnSearchCompleted () -{ - CloseStream(); - return net_LdapConnectionData::OnSearchCompleted(); -} - - -int16 net_LdapToHtml::GetLocalCharSet () -{ - if (m_csid == -1) - { - INTL_CharSetInfo c = LO_GetDocumentCharacterSetInfo(m_ce->window_id); - m_csid = INTL_GetCSIWinCSID(c); - if (CS_DEFAULT == m_csid) - m_csid = INTL_DefaultWinCharSetID (0); - } - return m_csid; -} - - -int net_LdapToHtml::OpenStream () -{ - int err = 0; - - if (NULL != m_stream) - return err; - - if (!m_ce->URL_s->content_type) - StrAllocCopy(m_ce->URL_s->content_type, TEXT_HTML); - m_stream = NET_StreamBuilder(m_ce->format_out, m_ce->URL_s, m_ce->window_id); - if (!m_stream) - return MK_OUT_OF_MEMORY; - - // Scribble HTML-starting stuff into the stream - char *htmlHeaders = PR_smprintf ("<HTML><HEAD><TITLE>%s</TITLE></HEAD>%s<BODY>%s", XP_GetString(MK_LDAP_HTML_TITLE), LINEBREAK, LINEBREAK); - if (htmlHeaders) - err = (*(m_stream)->put_block)(m_stream, htmlHeaders, XP_STRLEN(htmlHeaders)); - else - err = MK_OUT_OF_MEMORY; - - if (1 == err) - err = 0; //### which is it: 1 for success or 0 for success? - - return err; -} - - -int net_LdapToHtml::CloseStream () -{ - int err = 0; - - // Never got any hits for this operation - if (!m_stream) - { - if (((err = OpenStream()) == 0) && m_stream) - { - char *noMatches = PR_smprintf ("<H1>%s</H1>", XP_GetString(MK_MSG_SEARCH_FAILED)); - if (noMatches) - { - err = (*(m_stream)->put_block)(m_stream, noMatches, XP_STRLEN(noMatches)); - XP_FREE(noMatches); - } - } - } - - // Scribble HTML-ending stuff into the stream - if (m_stream) - { - char htmlFooters[32]; - PR_snprintf (htmlFooters, sizeof(htmlFooters), "</BODY>%s</HTML>%s", LINEBREAK, LINEBREAK); - err = (*(m_stream)->put_block)(m_stream, htmlFooters, XP_STRLEN(htmlFooters)); - if (1 == err) - err = 0; //### which is it: 1 for success or 0 for success? - - // complete the stream - (*m_stream->complete) (m_stream); - XP_FREE(m_stream); - } - - return err; -} - - -const char *net_LdapToHtml::LookupAttributeName (const char *attrib) -{ - // If we know about this attribute (it has a DIR_AttributeId and we - // have a DIR_Server to ask, get the name from the DIR_Server - DIR_AttributeId id; - if (0 == DIR_AttributeNameToId (attrib, &id) && m_server) - return DIR_GetAttributeName (m_server, id); - - // If we didn't get the name from LDAP prefs, get it using our - // own hacky internal table. ### This should really move into the LDAP SDK. - - // Fill these resource IDs in here since the HP/UX compiler can't do it - // in the initializer for the static array. - if (m_names[0].resourceId == 0) - { - m_names[0].resourceId = MK_LDAP_CAR_LICENSE; - m_names[1].resourceId = MK_LDAP_COMMON_NAME; - m_names[2].resourceId = MK_LDAP_BUSINESS_CAT; - m_names[3].resourceId = MK_LDAP_DEPT_NUMBER; - m_names[4].resourceId = MK_LDAP_DESCRIPTION; - m_names[5].resourceId = MK_LDAP_EMPLOYEE_TYPE; - m_names[6].resourceId = MK_LDAP_FAX_NUMBER; - m_names[7].resourceId = MK_LDAP_GIVEN_NAME; - m_names[8].resourceId = MK_LDAP_LOCALITY; - m_names[9].resourceId = MK_LDAP_PHOTOGRAPH; - m_names[10].resourceId = MK_LDAP_EMAIL_ADDRESS; - m_names[11].resourceId = MK_LDAP_MANAGER; - m_names[12].resourceId = MK_LDAP_ORGANIZATION; - m_names[13].resourceId = MK_LDAP_OBJECT_CLASS; - m_names[14].resourceId = MK_LDAP_ORG_UNIT; - m_names[15].resourceId = MK_LDAP_POSTAL_ADDRESS; - m_names[16].resourceId = MK_LDAP_POSTAL_CODE; - m_names[17].resourceId = MK_LDAP_SECRETARY; - m_names[18].resourceId = MK_LDAP_SURNAME; - m_names[19].resourceId = MK_LDAP_STREET; - m_names[20].resourceId = MK_LDAP_PHONE_NUMBER; - m_names[21].resourceId = MK_LDAP_TITLE; - m_names[22].resourceId = HG87272; - m_names[23].resourceId = HG73272; - } - - for (int i = 0; i < kNumAttributeNames; i++) - { - if (!XP_STRCASECMP(attrib, m_names[i].attributeName)) - return XP_GetString (m_names[i].resourceId); - } - - // ### Boy, is this hacky. Maybe we can push this into default prefs now that we have excluded attributes - if (XP_STRCASECMP(attrib, "userpassword") && XP_STRCMP(attrib, "objectclass") && - XP_STRCASECMP(attrib, "subtreeaci")) - return attrib; - return NULL; -} - - -int net_LdapToHtml::WriteLineToStream (const char *line, XP_Bool bold, XP_Bool lineBreak, XP_Bool isMailto, XP_Bool isUri, XP_Bool aligntop, XP_Bool isCell) -{ -#define kMailtoTemplate "<A HREF=\"mailto:%s\">%s</A>" -#define kUriTemplate "<A HREF=\"%s\">%s</A>" - - int err = 0; - int htmlLen = XP_STRLEN(line) + XP_STRLEN("<TD VALIGN=TOP></TD>"); - if (bold) - htmlLen += XP_STRLEN ("<B></B>"); - if (lineBreak) - htmlLen += XP_STRLEN(LINEBREAK); - if (isMailto) - htmlLen += XP_STRLEN(kMailtoTemplate) + XP_STRLEN(line); - if (isUri) - htmlLen += XP_STRLEN(kUriTemplate) + XP_STRLEN(line); - - char *htmlLine = (char *) XP_ALLOC(htmlLen + 1); - if (htmlLine) - { - htmlLine[0] = '\0'; - if (isCell) - { - if (aligntop) - XP_STRCAT (htmlLine, "<TD VALIGN=TOP>"); - else - XP_STRCAT (htmlLine, "<TD>"); - } - - if (bold) - XP_STRCAT (htmlLine, "<B>"); - - if (isMailto) - { - char *mailtoHtml = PR_smprintf (kMailtoTemplate, line, line); - if (mailtoHtml) - { - XP_STRCAT(htmlLine, mailtoHtml); - XP_FREE(mailtoHtml); - } - } - else if (isUri) - { - // RFC 2079 sez the URL comes first, then zero or more spaces, then an optional label - char *label = NULL; - char *url = XP_STRDUP(line); - if (url) - { - int i = 0; - while (url[i] && url[i] != ' ') - i++; - if (url[i] == ' ') - { - url[i] = '\0'; - - int j = i + 1; - while (url[j] == ' ') - j++; - - label = &url[j]; - } - } - - char *uriHtml = PR_smprintf (kUriTemplate, url ? url : line, label ? label : line); - if (uriHtml) - { - XP_STRCAT(htmlLine, uriHtml); - XP_FREE(uriHtml); - } - XP_FREEIF(url); - } - else - XP_STRCAT (htmlLine, line); - - if (bold) - XP_STRCAT (htmlLine, "</B> "); - if (isCell) - XP_STRCAT (htmlLine, "</TD>"); - if (lineBreak) - XP_STRCAT (htmlLine, LINEBREAK); - err = (*(m_stream)->put_block)(m_stream, htmlLine, XP_STRLEN(htmlLine)); - XP_FREE (htmlLine); - } - else - err = MK_OUT_OF_MEMORY; - return err; -} - - -int net_LdapToHtml::WriteAttribute (const char *attrib) -{ - return WriteLineToStream (attrib, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE); -} - - -int net_LdapToHtml::WriteValue (const char *value, XP_Bool isMailto, XP_Bool isUri) -{ - return WriteLineToStream (value, TRUE, TRUE, isMailto, isUri, FALSE, TRUE); -} - - -int net_LdapToHtml::WritePlainLine (const char *line) -{ - return WriteLineToStream (line, FALSE, TRUE); -} - - -XP_Bool net_LdapToHtml::IsMailtoAttribute (const char *attrib) -{ - if (m_server) - { - const char **strings = DIR_GetAttributeStrings (m_server, mail); - if (strings) - { - int i = 0; - while (strings[i]) - { - if (!XP_STRCASECMP(attrib, strings[i])) - return TRUE; - i++; - } - } - } - else - if (!XP_STRCASECMP(attrib, "mail")) - return TRUE; - - return FALSE; -} - - -XP_Bool net_LdapToHtml::IsUriAttribute (const char *attrib) -{ - switch (XP_TO_LOWER(attrib[0])) - { - case 'l': - if (!XP_STRCASECMP(attrib, "labeleduri") || // preferred - !XP_STRCASECMP(attrib, "labeledurl")) // old-style - return TRUE; - break; - case 'u': - if (!XP_STRCASECMP(attrib, "url")) // apparently some servers do this. be lenient in what we accept - return TRUE; - break; - } - return FALSE; -} - - -char *net_LdapToHtml::InferUrlBase () -{ - // Look in Netlib's data structures to find the URL we're running right now - // and assume that new URLs have the same host, port, etc - - // I'm guessing we can just look for everything up to the third slash. If this - // turns out to be not true, we can do the more expensive thing of running it - // through ldap_url_parse and then reforming it from the ldap_url_desc - - char *url = m_ce->URL_s->address; - - // Small memory wastage here, but this buf is so short-lived, it's probably - // not worth figuring out the real right size - char *urlBase = (char*) XP_ALLOC (XP_STRLEN(url)); - - if (urlBase) - { - char *tmpSrc = url; - char *tmpDst = urlBase; - int slashCount = 0; - - while (*tmpSrc) - { - if (*tmpSrc == '/') - slashCount++; - if (slashCount == 3) - { - *tmpDst = '\0'; - break; - } - else - *tmpDst++ = *tmpSrc; - tmpSrc++; - } - - } - return urlBase; - -} - - -char *net_LdapToHtml::EscapeSpaces (const char *string) -{ - int length = XP_STRLEN (string) + 1; // +1 for trailing null - const char *tmp = string; - while (*tmp) - { - if (*tmp == 0x20) - length += 2; // From " " to "%20" - tmp++; - } - - char *result = (char*) XP_ALLOC (length); - if (result) - { - tmp = string; - char *tmp2 = result; - - while (*tmp) - { - if (*tmp == 0x20) - { - *tmp2++ = '%'; - *tmp2++ = '2'; - *tmp2++ = '0'; - } - else - *tmp2++ = *tmp; - *tmp++; - } - *tmp2 = '\0'; - } - - return result; -} - - -char *net_LdapToHtml::ConvertDnToUri (const char *dn) -{ - char *uri = NULL; - char **explodedDn = ldap_explode_dn (dn, TRUE /* suppress types? */); - if (explodedDn) - { - char *urlBase = InferUrlBase(); - if (urlBase) - { - char *unescapedUrl = PR_smprintf ("%s/%s", urlBase, dn); - if (unescapedUrl) - { - char *escapedUrl = EscapeSpaces (unescapedUrl); - if (escapedUrl) - { - uri = PR_smprintf ("%s %s", escapedUrl, explodedDn[0]); - XP_FREE(escapedUrl); - } - XP_FREE(unescapedUrl); - } - XP_FREE(urlBase); - } - ldap_value_free (explodedDn); - } - - return uri; -} - - -char *net_LdapToHtml::GetTableCaption (LDAPMessage *message) -{ - // Here's a somewhat arbitrary way to decide what the table caption for an entry should be - - char *caption = NULL; - - // Look first for a "cn" attribute. - const char *cnAttrName = GetAttributeString (cn); - if (cnAttrName) - { - char **cnValues = ldap_get_values (m_ldap, message, cnAttrName); - if (cnValues) - { - if (cnValues[0]) - caption = ConvertFromServerCharSet (cnValues[0]); - ldap_value_free (cnValues); - } - } - - if (!caption) - { - // Use the left-most (most specific) component of the DN - char *dn = ldap_get_dn (m_ldap, message); - if (dn) - { - char **explodedDn = ldap_explode_dn (dn, TRUE /* suppress types? */); - if (explodedDn && explodedDn[0]) - caption = ConvertFromServerCharSet (explodedDn[0]); - ldap_value_free (explodedDn); - ldap_memfree(dn); - } - } - - return caption; -} - - -int net_LdapToHtml::WriteEntryToStream (LDAPMessage *message) -{ - // Write an LDAP directory entry to the HTML stream - - XP_ASSERT(message && m_stream); - if (!message || !m_stream) - return -1; - - WritePlainLine ("<TABLE ALIGN=CENTER>"); - - char *caption = GetTableCaption (message); - if (caption) - { - char *captionHtml = PR_smprintf ("<TD><CAPTION><FONT COLOR=\"#1908B9\"><FONT SIZE=+2>%s</FONT></FONT> </CAPTION></TD>", caption); - if (captionHtml) - { - WritePlainLine (captionHtml); - XP_FREE(captionHtml); - } - XP_FREE(caption); - } - - BerElement *ber; - char *attrib = ldap_first_attribute (m_ldap, message, &ber); - while (attrib) - { - const char *attribName = LookupAttributeName (attrib); - if (attribName && !DIR_IsAttributeExcludedFromHtml (m_server, attrib)) - { - int valueIndex = 0; - - HG73211 - if (XP_STRCASECMP(attrib, "jpegPhoto") == 0 || XP_STRCASECMP(attrib, "audio") == 0) - { - struct berval **berImages = ldap_get_values_len (m_ldap, message, attrib); - while (berImages[valueIndex]) - { - WritePlainLine ("<TR>"); - if (valueIndex == 0) - WriteAttribute (attribName); - else - WritePlainLine("<TD></TD>"); - - // ### There are Win16 problems with this strategy. We could use libmime - // to stream the base64 bits one line at a time, but we'd still need to get the - // LDAP SDK to do something similar, or to use huge pointers. - - char *base64Encoding = NET_Base64Encode ( - berImages[valueIndex]->bv_val, - berImages[valueIndex]->bv_len); - if (base64Encoding) - { - char *htmlLine = NULL; - if (XP_STRCASECMP(attrib, "jpegPhoto") == 0) - htmlLine = PR_smprintf ("<TD><IMG SRC=\"data:image/jpeg;base64,%s\"></TD>", base64Encoding); - else - htmlLine = PR_smprintf ("<TD><A HREF=\"data:audio/basic;base64,%s\"><IMG SRC=\"/ns-icons/sound.gif\"></A></TD>", base64Encoding); - if (htmlLine) - { - WritePlainLine (htmlLine); - XP_FREE (htmlLine); - } - XP_FREE(base64Encoding); - } - WritePlainLine ("</TR>"); - valueIndex++; - } - ldap_value_free_len (berImages); - } - else - { - char **values = ldap_get_values (m_ldap, message, attrib); - if (values) - { - XP_Bool isMailtoAttribute = IsMailtoAttribute (attrib); - XP_Bool isUriAttribute = IsUriAttribute (attrib); - XP_Bool isDnAttribute = DIR_IsDnAttribute (m_server, attrib); - XP_Bool isEscapedAttribute = DIR_IsEscapedAttribute (m_server, attrib); - - while (values[valueIndex]) - { - char *decodedUtf8 = ConvertFromServerCharSet (values[valueIndex]); - if (decodedUtf8) - { - WritePlainLine ("<TR>"); - if (valueIndex == 0) - WriteAttribute (attribName); - else - WritePlainLine("<TD></TD>"); - - // This unescaping code is mandated by. DNs are one class of thing, and - // attributes which are "productions" of strings are another class of thing - // and plain old string attributes get left alone. - if (isDnAttribute) - { - // Here's some special code to make values which look like DNs into - // links to LDAP URLs. Cool, huh? - char *tmp = ConvertDnToUri (decodedUtf8); - if (tmp) - { - XP_FREE(decodedUtf8); - decodedUtf8 = tmp; - isUriAttribute = TRUE; - } - } - else if (isEscapedAttribute) - { - // Some attributes which are "productions" of a couple of strings have - // special encoding rules. Decode 'em into something useful here. - char *tmp = DIR_Unescape (decodedUtf8, TRUE /*makeHtml?*/); - if (tmp) - { - XP_FREE(decodedUtf8); - decodedUtf8 = tmp; - } - } - - WriteValue (decodedUtf8, isMailtoAttribute, isUriAttribute); - XP_FREE(decodedUtf8); - WritePlainLine ("</TR>"); - } - valueIndex++; - } - ldap_value_free (values); - } - } - } - ldap_memfree (attrib); - attrib = ldap_next_attribute (m_ldap, message, ber); - } - - WritePlainLine ("</TABLE>"); - WritePlainLine ("<HR>"); - - return 0; -} - - -//***************************************************************************** -// -// net_LdapReplicator is the class which knows how to read replication entries -// from the LDAP server to the local Address Book using the "change log" format -// specified in: -// http://ds.internic.net/internet-drafts/draft-good-ldap-changelog-00.txt -// - -#include "garray.h" - -extern "C" -{ - extern int MK_OUT_OF_MEMORY; - extern int MK_LDAP_REPL_CANT_SYNC_REPLICA; - extern int MK_LDAP_REPL_DSE_BOGUS; - extern int MK_LDAP_REPL_CHANGELOG_BOGUS; - extern int MK_LDAP_REPL_PROGRESS_TITLE; - extern int MK_LDAP_REPL_CONNECTING; - extern int MK_LDAP_REPL_CHANGE_ENTRY; - extern int MK_LDAP_REPL_NEW_ENTRY; - extern int MK_LDAP_AUTHDN_LOOKUP_FAILED; -} - -#define LDAP_REPL_CHUNK_SIZE 50 - - -static void CancelReplication(void *closure) -{ - MWContext *progressContext = (MWContext *)closure; - if (progressContext) - XP_InterruptContext(progressContext); -} - - -class net_LdapReplicator : public net_LdapConnectionData -{ -public: - net_LdapReplicator(ActiveEntry *ce); - virtual ~net_LdapReplicator(); - - virtual int Interrupt (); - - virtual int OnBindCompleted (); - virtual int OnEntryFound (LDAPMessage *message); - virtual int OnSearchCompleted (); - virtual XP_Bool OnError(int err); - -protected: - - typedef enum _LdapReplicationState - { - kInitializing, - kAuthorizing, - kBinding, - kParsingRootDSE, - kReplicatingChanges, - kReplicatingAdditions, - kReplicatingEntries - } LdapReplicationState; - - virtual LdapConnectionType GetConnectionType() { return kReplicatorConnection; } - - XP_Bool CollectUserCredentials (); - void SaveCredentialsToPrefs (); - void UpdateProgress (); - - int Load (ActiveEntry *); - int Process (); - int Initialize (); - int Authorize (); - int Bind (); - int SearchRootDSE (); - int Replicate (XP_Bool initial = FALSE); - int ProcessAdditions (); - - int ParseAuthorizationEntry (LDAPMessage *); - int ParseRootDSE (LDAPMessage *); - int ParseChangelogEntry (LDAPMessage *); - int ParseInitialEntry (LDAPMessage *); - void ParseReplicationUrl(const char *); - - XP_Bool m_initialReplicationOkay; - XP_Bool m_changesReturned; - char *m_authDn; - char *m_authPwd; - char *m_valueUsedToFindDn; - char *m_dnOfChangelog; // Root DSE's setting for the DN suffix of changelog entries - char *m_dataVersion; // Root DSE's setting to scope change numbers. The data version - int32 m_firstChangeNumber; // Root DSE's setting for oldest change it knows - int32 m_lastChangeNumber; // Root DSE's setting for newest change it knows - // gets reset whenever the server's DB gets reloaded from LDIF - - int32 m_progressEntry; - int32 m_progressTotal; - MWContext *m_progressContext; - pw_ptr m_progressWindow; - - LdapReplicationState m_replState; - CXP_GrowableArray m_dnsToAdd; - - AB_ContainerInfo *m_container; - - static char *m_rootReplicationAttribs[5]; - static char *m_entryReplicationAttribs[3]; -}; - -char *net_LdapReplicator::m_rootReplicationAttribs[5] = - { "changelog", "firstChangeNumber", "lastChangeNumber", "dataVersion", NULL }; -char *net_LdapReplicator::m_entryReplicationAttribs[3] = - { "targetdn", "changetype", NULL }; - - -net_LdapReplicator::net_LdapReplicator (ActiveEntry *ce) : net_LdapConnectionData (ce, FALSE) -{ - m_replState = kInitializing; - - m_initialReplicationOkay = FALSE; - m_changesReturned = FALSE; - m_authDn = NULL; - m_authPwd = NULL; - m_valueUsedToFindDn = NULL; - m_dnOfChangelog = NULL; - m_dataVersion = NULL; - m_firstChangeNumber = 0; - m_lastChangeNumber = 0; - - m_progressEntry = 0; - m_progressTotal = 0; - m_progressContext = NULL; - m_progressWindow = NULL; - - m_container = NULL; -} - -net_LdapReplicator::~net_LdapReplicator () -{ - int size; - - XP_FREEIF(m_authDn); - XP_FREEIF(m_authPwd); - XP_FREEIF(m_dnOfChangelog); - XP_FREEIF(m_dataVersion); - - size = m_dnsToAdd.Size(); - if (size > 0) - { - while (--size >= 0) - XP_FREE(m_dnsToAdd[size]); - } - - if (m_container) - { - AB_EndReplication(m_container); - m_container = NULL; - } - - if (m_progressWindow) - { - PW_Hide(m_progressWindow); - PW_Destroy(m_progressWindow); - - if (m_progressContext) - PW_DestroyProgressContext(m_progressContext); - } -} - - -int net_LdapReplicator::OnBindCompleted () -{ - return SearchRootDSE(); -} - -int net_LdapReplicator::OnEntryFound (LDAPMessage *message) -{ - int status = 0; - - switch (m_replState) - { - case kAuthorizing: - status = ParseAuthorizationEntry (message); - break; - case kParsingRootDSE: - status = ParseRootDSE (message); - break; - case kReplicatingChanges: - status = ParseChangelogEntry (message); - break; - case kReplicatingAdditions: - case kReplicatingEntries: - status = ParseInitialEntry (message); - break; - default: - XP_ASSERT(FALSE); - } - - return status; -} - -int net_LdapReplicator::OnSearchCompleted () -{ - int status = 0; - - switch (m_replState) - { - case kAuthorizing: - status = Bind(); - break; - case kParsingRootDSE: - status = Replicate (TRUE); - break; - case kReplicatingAdditions: - m_server->replInfo->lastChangeNumber++; - /* fall-through */ - case kReplicatingChanges: - status = ProcessAdditions (); - break; - case kReplicatingEntries: - if (m_initialReplicationOkay) - m_server->replInfo->lastChangeNumber = m_lastChangeNumber; - if (m_server->replInfo->lastChangeNumber >= 0) - { - SaveCredentialsToPrefs (); - DIR_SaveServerPreferences (FE_GetDirServers()); - } - status = MK_CONNECTED; - break; - default: - XP_ASSERT(FALSE); - } - - return status; -} - -XP_Bool net_LdapReplicator::OnError(int err) -{ - /* If we were performing the initial replication, destroy the subset of - * entries that we had replicated so far. - */ - if (m_server->replInfo->lastChangeNumber < 0) - AB_RemoveReplicaEntries(m_container); - - /* Because replication can be very expensive, we must try to save the data - * we have already replicated even in the event of an error. - */ - DIR_SaveServerPreferences (FE_GetDirServers()); - - return TRUE; -} - -XP_Bool net_LdapReplicator::CollectUserCredentials () -{ - /* First look in the DIR_Server we read out of the prefs. If it already - * knows the user's credentials, there's no need to ask again here. - */ - if (m_server->authDn && XP_STRLEN(m_server->authDn)) - m_authDn = XP_STRDUP (m_server->authDn); - if (m_server->savePassword && m_server->password && XP_STRLEN(m_server->password)) - m_authPwd = XP_STRDUP (m_server->password); - if (m_authDn && m_authPwd) - return TRUE; - - XP_Bool rc = FALSE; - char *prompt = PR_smprintf (XP_GetString(MK_LDAP_AUTH_PROMPT), - DIR_GetAttributeName (m_server, auth), - m_server->description); - if (prompt) - { - /* TBD: Only prompt for password if we already have the DN - */ - char *username = NULL, *password = NULL; - if (m_authDn) - { - password = FE_PromptPassword (m_ce->window_id, prompt); - rc = (password != NULL); - } - else - rc = FE_PromptUsernameAndPassword (m_ce->window_id, prompt, &username, &password); - - if (rc) - { - if (username) - m_valueUsedToFindDn = username; - if (password) - { - m_authPwd = SECNAV_MungeString (password); - XP_FREE(password); - } - } - - XP_FREE(prompt); - } - - return rc; -} - -void net_LdapReplicator::SaveCredentialsToPrefs () -{ - if (m_authDn) - DIR_SetAuthDN (m_server, m_authDn); - - if (m_server->savePassword && m_authPwd) - DIR_SetPassword (m_server, m_authPwd); -} - -void net_LdapReplicator::UpdateProgress () -{ - ++m_progressEntry; - - if (!m_progressContext) - return; - - if (m_replState == kReplicatingAdditions) - { - int percent = (m_progressEntry * 100) / m_progressTotal; - FE_SetProgressBarPercent (m_progressContext, percent); - } - - if ((m_progressEntry % MAX(1, m_progressEntry / 10)) == 0) - { - char *status; - - if (m_replState == kReplicatingAdditions) - status = PR_smprintf (XP_GetString(MK_LDAP_REPL_CHANGE_ENTRY), m_progressEntry); - else - status = PR_smprintf (XP_GetString(MK_LDAP_REPL_NEW_ENTRY), m_progressEntry); - - if (status) - { - FE_Progress (m_progressContext, status); - XP_FREE(status); - } - } -} - - -int net_LdapReplicator::Load (ActiveEntry *ce) -{ - XP_ASSERT(ce); - XP_ASSERT(ce->URL_s); - XP_ASSERT(ce->URL_s->address); - - /* If this URL was not started via NET_ReplicateDirectory, we need to - * create a progress window for it. - */ - if (!ce->URL_s->internal_url) - { - m_progressContext = PW_CreateProgressContext(); - if (m_progressContext) - { - m_progressWindow = PW_Create(NULL, pwStandard); - if (m_progressWindow) - { - PW_AssociateWindowWithContext(m_progressContext, m_progressWindow); - PW_SetWindowTitle(m_progressWindow, XP_GetString(MK_LDAP_REPL_PROGRESS_TITLE)); - PW_SetLine1(m_progressWindow, NULL); - PW_SetLine2(m_progressWindow, NULL); - PW_SetProgressRange(m_progressWindow, 0, 0); - PW_SetCancelCallback(m_progressWindow, CancelReplication, m_progressContext); - PW_Show(m_progressWindow); - } - else - { - PW_DestroyProgressContext(m_progressContext); - m_progressContext = NULL; - } - } - } - else - m_progressContext = ce->window_id; - - if (m_progressContext) - { - FE_Progress (m_progressContext, XP_GetString(MK_LDAP_REPL_CONNECTING)); - FE_SetProgressBarPercent (m_progressContext, 0); - } - - /* Get the DIR_Server that matches the hostname in the URL. - */ - ParseReplicationUrl (ce->URL_s->address); - if (m_server == NULL) - return -1; - - /* Initialize the LDAP structure - * - * TBD: need to account for the case where one host name corresponds to - * more than one machine (e.g. directory.netscape.com). - */ - m_ldap = ldap_init(m_server->serverName, m_server->port); - if (!m_ldap) - return MK_OUT_OF_MEMORY; - - return 0; -} - -int net_LdapReplicator::Process () -{ - int status = 0; - - if (m_replState == kInitializing) - status = Initialize (); - else - status = net_LdapConnectionData::Process (); - - return status; -} - -int net_LdapReplicator::Initialize () -{ - int status = 0; - - /* If we are supposed to authenticate with the server, attempt to bind to - * the server using authentication info from the prefs or the user. - */ - if (m_server->enableAuth) - { - if (CollectUserCredentials()) - { - /* If we don't have an authorization DN but we have an email id, - * then try to look up the authorization DN. - */ - if (!m_authDn && m_valueUsedToFindDn) - return Authorize(); - else - return Bind(); - } - } - - return SearchRootDSE(); -} - -int net_LdapReplicator::Authorize () -{ - int status = 0; - - char *attribs[2]; - attribs[0] = XP_STRDUP(DIR_GetFirstAttributeString (m_server, cn)); - attribs[1] = NULL; - - char *filter = PR_smprintf ("(%s=%s)", DIR_GetFirstAttributeString (m_server, auth), m_valueUsedToFindDn); - - int msgId = -1; - if (attribs[0] && filter) - msgId = ldap_search (m_ldap, m_server->searchBase, LDAP_SCOPE_SUBTREE, filter, &attribs[0], 0); - else - status = MK_OUT_OF_MEMORY; - - XP_FREEIF(attribs[0]); - XP_FREEIF(filter); - - if (msgId != -1) - { - m_replState = kAuthorizing; - m_messageId = msgId; - } - else if (status == 0) - { - DisplayError (XP_LDAP_SEARCH_FAILED, GetHostDescription(), ldap_get_lderrno(m_ldap,NULL,NULL)); - status = -1; - } - - return status; -} - -int net_LdapReplicator::Bind () -{ - char *upwd = SECNAV_UnMungeString (m_authPwd); - if (upwd) - { - int msgId = ldap_simple_bind(m_ldap, m_authDn, upwd); - XP_FREE(upwd); - - if (msgId != -1) - { - m_replState = kBinding; - m_messageId = msgId; - } - else - { - DisplayError (XP_LDAP_BIND_FAILED, GetHostDescription(), ldap_get_lderrno(m_ldap,NULL,NULL)); - return -1; - } - } - else - return MK_OUT_OF_MEMORY; - - return 0; -} - -int net_LdapReplicator::SearchRootDSE () -{ - /* Kick things off with a search of the Root DSE for the replication data. - */ - int msgId = ldap_search(m_ldap, "", LDAP_SCOPE_BASE, "objectclass=*", - m_rootReplicationAttribs, 0); - if (msgId != -1) - { - m_replState = kParsingRootDSE; - m_messageId = msgId; - } - else - { - DisplayError (XP_LDAP_SEARCH_FAILED, GetHostDescription(), ldap_get_lderrno(m_ldap,NULL,NULL)); - return -1; - } - - return 0; -} - -int net_LdapReplicator::Replicate (XP_Bool initial) -{ - int msgId = -1; - - /* If the last completed change is -1, we need to perform an initial - * replication. - */ - if (m_server->replInfo->lastChangeNumber == -1) - { - /* We're going to replicate every entry. - */ - m_replState = kReplicatingEntries; - - /* Delete the old replica database and start a fresh one. - */ - AB_RemoveReplicaEntries(m_container); - - /* Try to do a search which will return every entry (limited by the - * filter preference) on the server. - * - * TBD: This fails even on thehole unless Directory Manager is used. - * We must have a special replication dn or find some other way - * to initialize the database. - */ - msgId = ldap_search(m_ldap, m_server->searchBase, LDAP_SCOPE_SUBTREE, - DIR_GetReplicationFilter(m_server), AB_GetReplicaAttributeNames(m_container), 0); - } - else if (m_lastChangeNumber > m_server->replInfo->lastChangeNumber) - { - /* We're going to replicate only the changes. - */ - m_replState = kReplicatingChanges; - - if (initial) - m_progressTotal = m_lastChangeNumber - m_server->replInfo->lastChangeNumber; - - char *filter = PR_smprintf ("(&(changenumber>=%d)(changenumber<=%d))", - m_server->replInfo->lastChangeNumber + 1, - MIN(m_lastChangeNumber, - m_server->replInfo->lastChangeNumber + LDAP_REPL_CHUNK_SIZE)); - if (filter) - { - msgId = ldap_search(m_ldap, m_dnOfChangelog, LDAP_SCOPE_ONELEVEL, - filter, m_entryReplicationAttribs, 0); - XP_FREE(filter); - } - } - else - { - if (!initial) - { - SaveCredentialsToPrefs (); - DIR_SaveServerPreferences (FE_GetDirServers()); - } - return MK_CONNECTED; - } - - if (msgId != -1) - m_messageId = msgId; - else - { - DisplayError (XP_LDAP_SEARCH_FAILED, GetHostDescription(), ldap_get_lderrno(m_ldap,NULL,NULL)); - return -1; - } - - return 0; -} - - -int net_LdapReplicator::ProcessAdditions() -{ - int size = m_dnsToAdd.Size(); - if (size > 0) - { - int msgId = -1; - char *targetDn = (char *)(m_dnsToAdd[size - 1]); - - msgId = ldap_search(m_ldap, targetDn, LDAP_SCOPE_SUBTREE, - DIR_GetReplicationFilter(m_server), AB_GetReplicaAttributeNames(m_container), 0); - - XP_FREE(targetDn); - m_dnsToAdd.SetSize(size - 1); - - if (msgId != -1) - { - m_messageId = msgId; - m_replState = kReplicatingAdditions; - } - else - { - DisplayError (XP_LDAP_SEARCH_FAILED, GetHostDescription(), ldap_get_lderrno(m_ldap,NULL,NULL)); - return -1; - } - } - else - { - /* We must verify that the changelog search returned at least one - * entry. It may return none if the user has insufficient access. - * If so, we must abort the replication; otherwise, we will get stuck - * in an infinite loop. - */ - if (m_changesReturned) - { - return Replicate(); - } - else - { - DisplayError (XP_LDAP_SEARCH_FAILED, GetHostDescription(), LDAP_INSUFFICIENT_ACCESS); - return -1; - } - } - - return 0; -} - -int net_LdapReplicator::Interrupt () -{ - /* Put the last processed change number into prefs - */ - if (m_server->replInfo && m_server->replInfo->lastChangeNumber >= 0) - DIR_SaveServerPreferences (FE_GetDirServers()); - - /* If we were performing the initial replication, destroy the subset of - * entries that we had replicated so far. - */ - else - AB_RemoveReplicaEntries(m_container); - - if (m_ldap) - ldap_abandon (m_ldap, m_messageId); - - return net_LdapConnectionData::Interrupt(); // base class will unbind -} - - -void net_LdapReplicator::ParseReplicationUrl(const char *ldap_url) -{ - char *url = XP_STRDUP(ldap_url); - LDAPURLDesc *desc = (LDAPURLDesc *)XP_CALLOC(1, sizeof(LDAPURLDesc)); - if (desc && url) - { - char *next; - char *fullurl = url; - - /* Pull out the connection type (and fill in the default port numbers). - */ - if (XP_STRCASECMP(url, "repl-ldaps://") == 0) - { - url += 13; - desc->lud_options |= LDAP_URL_OPT_SECURE; - desc->lud_port = LDAPS_PORT; - } - else - { - url += 12; - desc->lud_port = LDAP_PORT; - } - - /* Pull out the authorized DN and password if they are present and - * requested. - */ - char *authDn=NULL, *authPwd=NULL; - next = XP_STRCHR(url, '@'); - if (next) - { - next[0] = '\0'; - - char *pwd = XP_STRCHR(url, ':'); - if (pwd) - { - pwd[0] = '\0'; - authPwd = pwd + 1; - } - authDn = url; - - url = next + 1; - } - - /* Pull out the host name, the port number and the base dn. - */ - next = XP_STRCHR(url, ':'); - if (!next) - next = XP_STRCHR(url, '/'); - if (!next) - desc->lud_host = url; - else - { - if (next[0] == ':') - desc->lud_port = 0; - next[0] = '\0'; - - desc->lud_host = url; - url = next + 1; - - if (desc->lud_port == 0) - { - next = XP_STRCHR(url, '/'); - if (next) - next[0] = '\0'; - desc->lud_port = XP_ATOI(url); - } - - if (next) - desc->lud_dn = next + 1; - } - - /* The host name, port number and base dn must be present and valid. - */ - if (desc->lud_host && desc->lud_port != 0 && desc->lud_dn) - { - AddLdapServerToPrefs(desc); - - if (m_server) - { - if (!m_server->authDn && authDn) - m_server->authDn = XP_STRDUP(authDn); - if (!m_server->password && authPwd) - m_server->password = XP_STRDUP(authPwd); - } - } - - url = fullurl; - } - - XP_FREEIF(desc); - XP_FREEIF(url); -} - - -int net_LdapReplicator::ParseAuthorizationEntry (LDAPMessage *message) -{ - if (!m_authDn) - { - char *authDn = ldap_get_dn (m_ldap, message); - m_authDn = XP_STRDUP(authDn); - ldap_memfree(authDn); - } - else - { - /* Better not have more than one hit for this search. - * We don't have a way for the user to choose which "phil" they are. - */ - DisplayError (MK_LDAP_AUTHDN_LOOKUP_FAILED, GetHostDescription(), 0); - return -1; - } - - return 0; -} - -int net_LdapReplicator::ParseRootDSE (LDAPMessage *message) -{ - int i; - char **values = NULL; - - for (i = 0; i < 4; i++) - { - values = ldap_get_values (m_ldap, message, m_rootReplicationAttribs[i]); - if (values && values[0]) - { - switch (i) { - case 0: - m_dnOfChangelog = XP_STRDUP (values[0]); - break; - case 1: - m_firstChangeNumber = XP_ATOI (values[0]); - break; - case 2: - m_lastChangeNumber = XP_ATOI (values[0]); - break; - case 3: - m_dataVersion = XP_STRDUP (values[0]); - break; - } - - ldap_value_free (values); - } - else - { - DisplayError (MK_LDAP_REPL_DSE_BOGUS, GetHostDescription(), 0); - return -1; - } - } - - /* Parse the root DSE. DIR_ValidateRootDSE can return three different - * types of values; - * <0 - There is no replication information available for this server; - * we should abort replication. - * 0 - Either our replication data matches what the server returned or - * we have never replicated. In the former case, perform an - * incremental update. In the later case, generate the replica - * from scratch. - * >0 - The server's replication data does not match ours; reinitialize - * our replica from scratch. - */ - int rc = DIR_ValidateRootDSE (m_server, m_dataVersion, m_firstChangeNumber, m_lastChangeNumber); - if (rc < 0) - { - DisplayError (MK_LDAP_REPL_DSE_BOGUS, GetHostDescription(), 0); - return -1; - } - - /* Get access to the container info that will manage the interaction - * between ldap server connection and the replica database. - * - * NOTE: This must be called after DIR_ValidateRootDSE, because the later - * is what sets up the replication information in the DIR_Server - * which in turn is required by the container to replicate. - */ - m_container = AB_BeginReplication(m_progressContext, m_server); - if (m_container == NULL) - { - DisplayError (MK_LDAP_REPL_CANT_SYNC_REPLICA, GetHostDescription(), 0); - return -1; - } - - return 0; -} - - -// Here we get an entry from the changelog and try to figure out what kind of -// change happened to the entry given by the targetdn. -int net_LdapReplicator::ParseChangelogEntry (LDAPMessage *message) -{ - char **values = NULL; - char *targetDn = NULL; - - values = ldap_get_values (m_ldap, message, "targetdn"); - if (values && values[0]) - { - targetDn = XP_STRDUP(values[0]); - ldap_value_free (values); - } - else - { - DisplayError (MK_LDAP_REPL_CHANGELOG_BOGUS, GetHostDescription(), 0); - return -1; - } - - values = ldap_get_values (m_ldap, message, "changetype"); - if (values && values[0]) - { - if (!XP_STRCASECMP(values[0], "add")) - { - m_dnsToAdd.Add (targetDn); - } - else if (!XP_STRCASECMP(values[0], "mod")) - { - AB_DeleteReplicaEntry (m_container,targetDn); - m_dnsToAdd.Add (targetDn); - } - else if (!XP_STRCASECMP(values[0], "del")) - { - AB_DeleteReplicaEntry (m_container,targetDn); - UpdateProgress(); - } - ldap_value_free (values); - } - else - { - DisplayError (MK_LDAP_REPL_CHANGELOG_BOGUS, GetHostDescription(), 0); - return -1; - } - - m_changesReturned = TRUE; - return 0; -} - -/* ParseInitialEntry - * - * Method for adding an entry to the replication database. - */ -int net_LdapReplicator::ParseInitialEntry (LDAPMessage *message) -{ - message = ldap_first_entry (m_ldap, message); - if (message) - { - int mapSize = AB_GetNumReplicaAttributes(m_container); - char **mapNames = AB_GetReplicaAttributeNames(m_container); - char **valueList = (char **)XP_ALLOC(sizeof(char *) * mapSize); - if (!valueList) - { - m_initialReplicationOkay = FALSE; - return MK_OUT_OF_MEMORY; - } - - /* Copy each of the attribute values from the LDAP result into the index - * in the value array that corresponds to the same index in the attribute - * mapping structure. - */ - int i, indexCn = -1, indexOrg = -1; - char **scratchArray = NULL; - for (i = 0; i < mapSize; i++) - { - scratchArray = ldap_get_values (m_ldap, message, mapNames[i]); - if (scratchArray && scratchArray[0]) - { - valueList[i] = DIR_ConvertFromServerCharSet (m_server, scratchArray[0], GetLocalCharSet()); - ldap_value_free (scratchArray); - } - else - { - if (AB_ReplicaAttributeMatchesId(m_container, i, cn)) - indexCn = i; - else if (AB_ReplicaAttributeMatchesId(m_container, i, o)) - indexOrg = i; - - valueList[i] = NULL; - } - } - - /* If we didn't get some attributes we wanted, try to pick them up from the DN - */ - if (indexOrg != -1 || indexCn != -1) - { - char *scratch; - if (scratch = ldap_get_dn (m_ldap, message)) - { - if ((scratchArray = ldap_explode_dn (scratch, FALSE)) != NULL) - { - char *dnComponent = NULL; - for (i = 0; (dnComponent = scratchArray[i]) != NULL; i++) - { - if (indexOrg != -1 && !XP_STRNCASECMP (dnComponent, "o=", 2)) - { - valueList[indexOrg] = DIR_ConvertFromServerCharSet (m_server, dnComponent+2, GetLocalCharSet()); - indexOrg = -1; - } - if (indexCn != -1 && !XP_STRNCASECMP (dnComponent, "cn=", 3)) - { - valueList[indexCn] = DIR_ConvertFromServerCharSet (m_server, dnComponent+3, GetLocalCharSet()); - indexCn = -1; - } - } - ldap_value_free (scratchArray); - } - ldap_memfree (scratch); - } - } - - /* If the entry is valid, add it to the replica database. Also set the - * initial replication okay flag to true in case we are performing an - * initial replication. Finally, update the progress window. - */ - if (indexCn == -1 && AB_AddReplicaEntry (m_container, valueList) == AB_SUCCESS) - { - m_initialReplicationOkay = TRUE; - UpdateProgress(); - } - - for (i = 0; i < mapSize; i++) - XP_FREEIF(valueList[i]); - XP_FREE(valueList); - } - - return 0; -} - - -//***************************************************************************** -// -// net_OfflineLdapReplicator is the class which knows which directory replicas -// should be updated and how to replicate them in succession. -// - -class net_OfflineLdapReplicator -{ -public: - net_OfflineLdapReplicator(MSG_Pane *, DIR_Server *server = NULL); - ~net_OfflineLdapReplicator(); - - XP_Bool ReplicateDirectory(); - - static void ReplicateNextDirectory(URL_Struct *, int, MWContext *); - -protected: - MSG_Pane *m_pane; - XP_List *m_serverList; - MWContext *m_progressContext; - pw_ptr m_progressWindow; -}; - - -net_OfflineLdapReplicator::net_OfflineLdapReplicator(MSG_Pane *pane, DIR_Server *server) -{ - m_pane = pane; - - m_progressContext = NULL; - m_progressWindow = NULL; - - m_serverList = XP_ListNew(); - if (m_serverList) - { - if (server) - { - if (DIR_TestFlag(server, DIR_REPLICATION_ENABLED)) - { - /* Create a progress window. - */ - m_progressContext = PW_CreateProgressContext(); - if (m_progressContext) - { - m_progressWindow = PW_Create(NULL, pwStandard); - if (m_progressWindow) - { - PW_AssociateWindowWithContext(m_progressContext, m_progressWindow); - PW_SetWindowTitle(m_progressWindow, XP_GetString(MK_LDAP_REPL_PROGRESS_TITLE)); - PW_SetLine1(m_progressWindow, NULL); - PW_SetLine2(m_progressWindow, NULL); - PW_SetProgressRange(m_progressWindow, 0, 0); - PW_SetCancelCallback(m_progressWindow, CancelReplication, m_progressContext); - PW_Show(m_progressWindow); - } - else - { - PW_DestroyProgressContext(m_progressContext); - } - } - - XP_ListAddObjectToEnd(m_serverList, server); - } - - } - else - { - XP_ASSERT(m_pane); - m_progressContext = m_pane->GetContext(); - - XP_List *serverList = FE_GetDirServers(); - for (int i = 1; i <= XP_ListCount(serverList); i++) - { - server = (DIR_Server *)XP_ListGetObjectNum(serverList, i); - if (DIR_TestFlag(server, DIR_REPLICATION_ENABLED)) - XP_ListAddObjectToEnd(m_serverList, server); - } - } - - if (XP_ListCount(m_serverList) == 0) - { - XP_ListDestroy(m_serverList); - m_serverList = NULL; - } - } -} - -net_OfflineLdapReplicator::~net_OfflineLdapReplicator() -{ - if (m_serverList) - XP_ListDestroy(m_serverList); - - /* We destroy the progress window, but the pane destroys the context? - * This seems kind of weird, but it's the way things work. - */ - if (m_progressWindow) - { - PW_Hide(m_progressWindow); - PW_Destroy(m_progressWindow); - } -} - - -XP_Bool net_OfflineLdapReplicator::ReplicateDirectory() -{ - /* Return FALSE iff there are no more servers to replicate. - */ - DIR_Server *server = (DIR_Server *)XP_ListRemoveTopObject(m_serverList); - if (!server) - return FALSE; - - char *auth = NULL; - if (server->enableAuth && server->authDn) - { - if (server->password) - auth = PR_smprintf("%s:%s@", server->authDn, server->password); - else - auth = PR_smprintf("%s@", server->authDn); - } - - char *url = PR_smprintf("repl-ldap%s://%s%s:%d/%s", server->isSecure ? "s" : "", - auth ? auth : "", server->serverName, server->port, server->searchBase); - if (url) - { - URL_Struct *URL_s = NET_CreateURLStruct(url, NET_DONT_RELOAD); - if(URL_s) - { - URL_s->owner_data = this; - URL_s->internal_url = TRUE; - URL_s->msg_pane = m_pane; - if (m_pane) - MSG_UrlQueue::AddUrlToPane(URL_s, net_OfflineLdapReplicator::ReplicateNextDirectory, m_pane, TRUE, FO_PRESENT); - else - NET_GetURL(URL_s, FO_PRESENT, m_progressContext, net_OfflineLdapReplicator::ReplicateNextDirectory); - } - XP_FREE(url); - } - XP_FREEIF(auth); - - return TRUE; -} - - -void net_OfflineLdapReplicator::ReplicateNextDirectory(URL_Struct *URL_s, int, MWContext *) -{ - net_OfflineLdapReplicator *replicator = (net_OfflineLdapReplicator *)(URL_s->owner_data); - if (replicator) - { - /* ReplicateDirectory returns FALSE if there are no more directories - * left to replicate. It is our job to clean up the replicator object - * when we're done. - */ - if (!replicator->ReplicateDirectory()) - delete replicator; - } -} - - -//***************************************************************************** -// -// net_LdapToAddressBook does the work of converting LDAP entries into a format -// that can be stored in the local Address Book database. -// -class net_LdapToAddressBook : public net_LdapConnectionData -{ -public: - net_LdapToAddressBook (ActiveEntry*); - virtual ~net_LdapToAddressBook(); - - // Base class overrides - virtual int OnEntryFound (LDAPMessage*); - - // Address Book specific stuff - void ConvertEntryToPerson (LDAPMessage *, PersonEntry &); - void ConvertEntryToPerson (LDAPMessage *message, AB_AttributeValue ** valuesArray, uint16 * numItems); // new version for new AB - int WriteEntryToAddressBook (LDAPMessage*); - virtual char * ExtractLDAPEncoding(char * url); - -protected: - virtual LdapConnectionType GetConnectionType() { return kAddressBookConnection; } - - // used to take an ldap attribute, value pair and conver it to one or more address book attribute - // values, adding those values to the abAttributes list. - int AddLDAPAttribute(const char * dirAttrib, const char * dirValue, XP_List * abAttributes); - - AB_AddressBookCopyInfo * m_abCopyInfo; // used for new address book... -}; - -// prototypes fo net_LdapToAddressBook helper functions... -AB_AttributeValue * findAttributeInList(AB_AttribID attrib, XP_List * abAttributes); - -net_LdapToAddressBook::net_LdapToAddressBook (ActiveEntry *ce) : net_LdapConnectionData(ce) -{ - if (ce && ce->URL_s) - m_abCopyInfo = (AB_AddressBookCopyInfo *) ce->URL_s->owner_data; - else - m_abCopyInfo = NULL; -} - -net_LdapToAddressBook::~net_LdapToAddressBook() -{ - // copy info freed by url exit function... -// if (m_abCopyInfo) -// AB_FreeAddressBookCopyInfo(m_abCopyInfo); // also destroys allocated memory.. - m_abCopyInfo = NULL; -} - -char * net_LdapToAddressBook::ExtractLDAPEncoding(char * url) -{ - // we want to strip off the addbook- part for the LDAP encoding... - // caller should not be freeing this return string because it is part of the url.. - return url+8; // 8 for "addbook-" -} - -// helper function used to find an attribute in the list -AB_AttributeValue * findAttributeInList(AB_AttribID attrib, XP_List * abAttributes) -{ - if (abAttributes) - { - for (int i = 1; i <= XP_ListCount(abAttributes); i++) - { - AB_AttributeValue *v = (AB_AttributeValue*) XP_ListGetObjectNum (abAttributes, i); - if (v && v->attrib == attrib) - return v; - } - } - - return NULL; -} - -int net_LdapToAddressBook::AddLDAPAttribute(const char * attrib, const char * dirValue, XP_List * abAttributes) -{ - int status = 0; - AB_AttributeValue * value = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue)); - if (value) - { - status = -1; - // we can make a minor hack to optmize this...since all of - // them are string attributes, we only need to set the - // value->attrib field in the if statements...then if - // we found a match, set the value->u.string outside the - // if statements... - - if (!XP_STRCASECMP(attrib, GetAttributeString(cn))) - { - value->attrib = AB_attribDisplayName; - status = 0; - } - if (!XP_STRCASECMP(attrib, GetAttributeString (givenname))) - { - value->attrib = AB_attribGivenName; - status = 0; - } - else if (!XP_STRCASECMP(attrib, GetAttributeString(sn))) - { - value->attrib = AB_attribFamilyName; - status = 0; - } - else if (!XP_STRCASECMP(attrib, GetAttributeString(o))) - { - value->attrib = AB_attribCompanyName; - status = 0; - } - else if (!XP_STRCASECMP(attrib, GetAttributeString(l))) - { - value->attrib = AB_attribLocality; - status = 0; - } - else if (!XP_STRCASECMP(attrib, GetAttributeString(mail))) - { - value->attrib = AB_attribEmailAddress; - status = 0; - } - else if (!XP_STRCASECMP(attrib, "title")) - { - value->attrib = AB_attribTitle; - status = 0; - } - else if (!XP_STRCASECMP(attrib, "postaladdress")) - { - value->attrib = AB_attribPOAddress; - status = 0; - } - else if (!XP_STRCASECMP(attrib, "st")) - { - value->attrib = AB_attribRegion; - status = 0; - } - else if (!XP_STRCASECMP(attrib, "postalcode")) - { - value->attrib = AB_attribZipCode; - status = 0; - } - else if (!XP_STRCASECMP(attrib, GetAttributeString(telephonenumber))) - { - value->attrib = AB_attribWorkPhone; - status = 0; - } - else if (!XP_STRCASECMP(attrib, "facsimiletelephonenumber")) - { - value->attrib = AB_attribFaxPhone; - status = 0; - } - else if (!XP_STRCASECMP(attrib, "dlshost")) - { - value->attrib = AB_attribCoolAddress; - // we also need to set the use server... - AB_AttributeValue * nextValue = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue)); - if (nextValue) - { - nextValue->attrib = AB_attribUseServer; - nextValue->u.shortValue = kSpecificDLS; - XP_ListAddObjectToEnd(abAttributes, (void *) nextValue); - } - } - else if (!XP_STRCASECMP(attrib, "host")) - { - value->attrib = AB_attribCoolAddress; - // we also need to set the use server... - AB_AttributeValue * nextValue = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue)); - if (nextValue) - { - nextValue->attrib = AB_attribUseServer; - nextValue->u.shortValue = kHostOrIPAddress; - XP_ListAddObjectToEnd(abAttributes, (void *) nextValue); - } - } - - if (status == 0) // we found a match - { - value->u.string = XP_STRDUP(dirValue); - XP_ListAddObjectToEnd(abAttributes, (void *) value); - } - - else // we didn't find a match.... - XP_FREEIF(value); - } - else - status = MK_OUT_OF_MEMORY; - - return status; -} - - -void net_LdapToAddressBook::ConvertEntryToPerson (LDAPMessage *message, AB_AttributeValue ** valuesArray, uint16 * numItems) -{ - XP_List * abAttributes = XP_ListNew(); - AB_AttributeValue * values = NULL; - uint16 numAttributes = 0; - - if (abAttributes) - { - // loop over each attribute in the entry, and pick out the ones the address book - // is interested in. We are ignoring the case where the same attribute has multiple - // values. The AB doesn't have a way to deal with that. - - char *tmpCn = NULL; - BerElement *ber; - char *attrib = ldap_first_attribute (m_ldap, message, &ber); - while (attrib) - { - char ** values = ldap_get_values(m_ldap, message, attrib); - if (m_server && values && values[0]) - { - char *decodedUtf8 = ConvertFromServerCharSet (values[0]); - if (decodedUtf8) - { - AddLDAPAttribute(attrib, decodedUtf8, abAttributes); - if (!XP_STRCASECMP(attrib, GetAttributeString (cn))) - tmpCn = XP_STRDUP(decodedUtf8); // hang on to cn in case we need it later - } - - XP_FREEIF (decodedUtf8); - } - if (values) - ldap_value_free (values); - ldap_memfree (attrib); - attrib = ldap_next_attribute (m_ldap, message, ber); - } // add the next attribute.... - - // now we have some fixing up to do...adding CSID, - AB_AttributeValue * abValue = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue)); - if (abValue) - { - abValue->attrib = AB_attribWinCSID; - abValue->u.shortValue = INTL_GetCSIWinCSID(LO_GetDocumentCharacterSetInfo(m_ce->window_id)); - XP_ListAddObjectToEnd(abAttributes, (void *) abValue); - } - - // If the entry doesn't have an 'o', get it from the DN - char *dn = NULL; - AB_AttributeValue * company = findAttributeInList(AB_attribCompanyName, abAttributes); - if (!company) - { - if (!dn) - dn = ldap_get_dn (m_ldap, message); - if (dn) - { - const char *oAttribName = GetAttributeString (o); - AB_AttributeValue * abValue = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue)); - if (abValue) - { - abValue->attrib = AB_attribCompanyName; - abValue->u.string = GetAttributeFromDN (dn, oAttribName); - XP_ListAddObjectToEnd(abAttributes, (void *) abValue); - } - } - } - - // If the entry doesn't have 'givenname' or 'sn' try to use 'cn' - AB_AttributeValue * givenName = findAttributeInList(AB_attribGivenName, abAttributes); - AB_AttributeValue * familyName = findAttributeInList(AB_attribFamilyName, abAttributes); - if (!givenName /* || !familyName */) - { - char * useThisForGivenName = NULL; - // prefer CN as attribute to CN from dist name - if (tmpCn) - { - useThisForGivenName = tmpCn; - tmpCn = NULL; - } - else - { - if (!dn) - dn = ldap_get_dn (m_ldap, message); - if (dn) - { - const char *cnAttribName = GetAttributeString (cn); - useThisForGivenName = GetAttributeFromDN (dn, cnAttribName); - } - } - - if (useThisForGivenName) - { - AB_AttributeValue * abValue = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue)); - if (abValue) - { - abValue->attrib = AB_attribGivenName; - abValue->u.string = useThisForGivenName; - XP_ListAddObjectToEnd(abAttributes, (void *) abValue); - } - } - } // !givenName - - if (dn) - ldap_memfree(dn); - if (tmpCn) - XP_FREE(tmpCn); - - // our last step is to turn the XP_List into an array of attribute values... - numAttributes = XP_ListCount(abAttributes); - if (numAttributes) - { - values = (AB_AttributeValue *) XP_ALLOC(sizeof(AB_AttributeValue) * numAttributes); - if (valuesArray) - { - // iterate through the list adding each attribute to our static array - for (uint16 index = 1; index <= numAttributes; index++) - { - AB_AttributeValue * value = (AB_AttributeValue *) XP_ListGetObjectNum(abAttributes, index); - AB_CopyEntryAttributeValue(value, &values[index-1]); - } - } - } - - // free the list attributes... - for (int i = 1; i <= XP_ListCount(abAttributes); i++) - { - AB_AttributeValue * value = (AB_AttributeValue *) XP_ListGetObjectNum(abAttributes, i); - AB_FreeEntryAttributeValue(value); - - } - - XP_ListDestroy (abAttributes); - - } // if abAttributes - - // set up the return values... - if (numItems) - *numItems = numAttributes; - if (valuesArray) - *valuesArray = values; - else - AB_FreeEntryAttributeValues(values, numAttributes); -} - - -#ifdef MOZ_NEWADDR -int net_LdapToAddressBook::WriteEntryToAddressBook (LDAPMessage *message) -{ - int status = 0; - if (m_abCopyInfo && m_abCopyInfo->destContainer) - { - AB_AttributeValue * valuesArray = NULL; - uint16 numItems = 0; - ConvertEntryToPerson(message, &valuesArray, &numItems); - if (valuesArray) - { - // If there is only one URL in the queue, we bring up the UI, but - // if there is more than one, we add them silently. There could be - // a ton of URLs, and we don't have a Yes/No/All dialog - status = AB_AddUserAB2(m_abCopyInfo->destContainer, valuesArray, numItems, NULL /* we don't care about the entry id...*/); - AB_FreeEntryAttributeValues(valuesArray, numItems); - } - } - else - status = ABError_NullPointer; - - return status; -} -#else -int net_LdapToAddressBook::WriteEntryToAddressBook (LDAPMessage *message) -{ - // Add an entry we found on an LDAP directory into the local AB DB - - int err = 0; - PersonEntry person; - person.Initialize (); - ConvertEntryToPerson (message, person); - - XP_List *dirServers = FE_GetDirServers (); - XP_ASSERT(dirServers); - if (dirServers) - { - DIR_Server *pab = NULL; - DIR_GetPersonalAddressBook (dirServers, &pab); - XP_ASSERT(pab); - if (pab) - { - ABook *ab = FE_GetAddressBook (NULL /* don't have a pane? */); - AB_BreakApartFirstName (ab, &person); - - // If there is only one URL in the queue, we bring up the UI, but - // if there is more than one, we add them silently. There could be - // a ton of URLs, and we don't have a Yes/No/All dialog - - if (MSG_GetUrlQueueSize (m_ce->URL_s->address, m_ce->window_id) <= 1) - err = AB_AddUserWithUI (m_ce->window_id, &person, pab, TRUE); - else - { - // Don't allow any external URLs to add batches of people to the AB - if (m_ce->URL_s->internal_url) - { - ABID unusedId; - err = AB_AddUser (pab, ab, &person, &unusedId); - } - } - } - } - - person.CleanUp(); - return err; -} -#endif - -int net_LdapToAddressBook::OnEntryFound (LDAPMessage *message) -{ - return WriteEntryToAddressBook (message); -} - -void net_LdapToAddressBook::ConvertEntryToPerson (LDAPMessage *message, PersonEntry &person) -{ - // Loop over each attribute in the entry, and pick out the ones the - // Address Book is interested in. Note that we're ignoring cases where - // the same attribute has multiple values. The AB doesn't have a way to - // deal with that. - - char *tmpCn = NULL; - BerElement *ber; - char *attrib = ldap_first_attribute (m_ldap, message, &ber); - while (attrib) - { - char **values = ldap_get_values (m_ldap, message, attrib); - - // We better have a DIR_Server for this, otherwise GetAttributeString - // will crash. Since the only way to get to this code is through the Search - // Directory dialog, I think this is an ok restriction. We could certainly - // add default names in dirprefs.c if necessary. - XP_ASSERT(m_server && values && values[0]); - if (!m_server || !values || !values[0]) - return; - - char *decodedUtf8 = ConvertFromServerCharSet (values[0]); - if (!decodedUtf8) - return; - - // ### maybe it would be nice to have a few more of these - // expressed as DIR_Prefs attributeIds??? - - if (!XP_STRCASECMP(attrib, GetAttributeString (cn))) - tmpCn = XP_STRDUP(decodedUtf8); // hang on to cn in case we need it later - if (!XP_STRCASECMP(attrib, GetAttributeString (givenname))) - person.pGivenName = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, GetAttributeString(sn))) - person.pFamilyName = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, GetAttributeString(o))) - person.pCompanyName = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, GetAttributeString(l))) - person.pLocality = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, GetAttributeString(mail))) - person.pEmailAddress = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, "title")) - person.pTitle = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, "postaladdress")) - person.pPOAddress = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, "st")) - person.pRegion = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, "postalcode")) - person.pZipCode = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, GetAttributeString(telephonenumber))) - person.pWorkPhone = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, "facsimiletelephonenumber")) - person.pFaxPhone = XP_STRDUP(decodedUtf8); - else if (!XP_STRCASECMP(attrib, "dlshost")) - { - person.UseServer = kSpecificDLS; - person.pCoolAddress = XP_STRDUP(decodedUtf8); - } - else if (!XP_STRCASECMP(attrib, "host")) - { - person.UseServer = kHostOrIPAddress; - person.pCoolAddress = XP_STRDUP(decodedUtf8); - } - - - ldap_value_free (values); - XP_FREE (decodedUtf8); - ldap_memfree (attrib); - - attrib = ldap_next_attribute (m_ldap, message, ber); - } - - // If the entry doesn't have an 'o', get it from the DN - char *dn = NULL; - if (!person.pCompanyName) - { - if (!dn) - dn = ldap_get_dn (m_ldap, message); - if (dn) - { - const char *oAttribName = GetAttributeString (o); - person.pCompanyName = GetAttributeFromDN (dn, oAttribName); - } - } - - // If the entry doesn't have 'givenname' or 'sn' try to use 'cn' - if (!person.pGivenName || !person.pFamilyName) - { - // prefer CN as attribute to CN from dist name - if (tmpCn) - { - person.pGivenName = tmpCn; - tmpCn = NULL; // PersonEntry now owns that memory, so don't free it - } - else - { - if (!dn) - dn = ldap_get_dn (m_ldap, message); - if (dn) - { - const char *cnAttribName = GetAttributeString (cn); - person.pGivenName = GetAttributeFromDN (dn, cnAttribName); - } - } - } - - if (dn) - ldap_memfree(dn); - if (tmpCn) - XP_FREE(tmpCn); - - person.WinCSID = INTL_GetCSIWinCSID(LO_GetDocumentCharacterSetInfo(m_ce->window_id)); -} - -#ifdef MOZ_LI - -/* - * Class net_LdapLIConnectionData - * ============================== - * This class is used for LI LDAP operations. It expects a LDAPOperation* to be - * passed in via the URL_s->owner_data. The operation to be performed is determined - * by URL_s->method. The results of the operations are returned in the LDAPOperation; - * the caller is responsible for creating and deleting the operation object. - */ -class net_LdapLIConnectionData : public net_LdapConnectionData -{ -public: - net_LdapLIConnectionData(ActiveEntry *ce); - virtual ~net_LdapLIConnectionData (); // The base class handles it correctly. - - virtual int Load (ActiveEntry *ce); - virtual int Process (); - virtual int Interrupt (); - - virtual int Unbind (); - - -protected: - virtual LdapConnectionType GetConnectionType() { return kLIConnection; } - -private: - XP_Bool m_bCallerProvidedConnection; // Did the caller provide the m_ldap connection? - LDAPOperation* m_pParams; // Parameters. -}; - -/* net_LdapLIConnectionData Constructor - * ==================================== - * Create a connection data object class for an LI operation; set up a connection if - * the caller didn't provide one. We tell the base class not to initialize m_ldap since - * a LDAP* may be passed in to us. - */ -net_LdapLIConnectionData::net_LdapLIConnectionData(ActiveEntry *ce) : net_LdapConnectionData(ce,FALSE) -{ - m_pParams = (LDAPOperation*)ce->URL_s->owner_data; - - if(m_pParams && (m_pParams->getConnection() || (m_pParams->getURLMethod() == LDAP_LI_BIND_METHOD))) - { - // Set the connection in the base class. - // Free the LDAP* struct if created by the base class. - m_ldap = m_pParams->getConnection(); - m_bCallerProvidedConnection = TRUE; - } - else - { - m_ldap = ldap_init(m_pParams->getURL()->getHost(),m_pParams->getURL()->getPort()); - m_bCallerProvidedConnection = FALSE; - } - -} - -/* net_LdapLIConnectionData Destructor - * ==================================== - * Remember not to unbind if the caller provided the connection. - */ -net_LdapLIConnectionData::~net_LdapLIConnectionData() -{ - // Base class destructor will try to unbind, so we have to prevent that if - // the caller provided the connection. - if(m_bCallerProvidedConnection) - m_ldap = NULL; -} - -/* Load() - * ====== - * Called by netlib when starting an LI operation. This function is responsible to starting - * the LDAP operations. - */ -int net_LdapLIConnectionData::Load(ActiveEntry *ce) -{ - int ldapErr = 0; - int msgId = -1; - char *attrs[2] = { "modifyTimeStamp" , NULL }; - const LDAPURL* url = m_pParams->getURL(); - char *utf8Encoding = NULL; - - if(url->getParseError() != LDAP_SUCCESS) - { - ldapErr = MK_MALFORMED_URL_ERROR; - goto net_LdapLIConnectionDataLoadExit; - } - - if(m_pParams->started()) - { - ldapErr = LI_LDAP_ALREADY_STARTED; - goto net_LdapLIConnectionDataLoadExit; - } - - XP_ASSERT(m_ce); - XP_ASSERT(m_ce->URL_s); - XP_ASSERT(m_ce->URL_s->address); - XP_ASSERT(m_ldap); - - /* Convert the URL to UTF8 */ - utf8Encoding = ConvertToServerCharSet (ce->URL_s->address); - - if(!utf8Encoding) - return LI_LDAP_MEMORY_ERROR; - - /* The URL is assumed to be valid (checked by - * LDAPOperation before calling NET_GetURL) - */ - - /* This is where the real work begins */ - - // let the world know what we are doing. - FE_GraphProgressInit(ce->window_id, NULL, 1); - - // Initiate the operation on the server - switch(m_pParams->getURLMethod()) - { - case LDAP_LI_BIND_METHOD: - // Bind operation is not really async yet, the initial IP stuff is still synchronous in the LDAP API. - msgId = ldap_simple_bind(m_ldap,m_pParams->getURL()->getDN(),((LDAPBindOperation*)m_pParams)->getPassword()); - break; - case LDAP_LI_SEARCH_METHOD: - msgId = ldap_search(m_ldap, - url->getDN(), - url->getScope(), - url->getFilter(), - url->getAttrs(), - ((LDAPSearchOperation*)m_pParams)->getAttrsOnly()); - break; - case LDAP_LI_ADD_METHOD: - case LDAP_LI_ADDGLM_METHOD: - // Note that since we take apart the URL, we end up ignoring everything but the DN. - msgId = ldap_add(m_ldap, url->getDN(), ((LDAPAddOperation*)m_pParams)->getLDAPModArray()->getLDAPModStarStar()); - break; - case LDAP_LI_MOD_METHOD: - case LDAP_LI_MODGLM_METHOD: - // Note that since we take apart the URL, we end up ignoring everything but the DN. - msgId = ldap_modify(m_ldap, url->getDN(), ((LDAPModOperation*)m_pParams)->getLDAPModArray()->getLDAPModStarStar()); - break; - case LDAP_LI_DEL_METHOD: - msgId = ldap_delete(m_ldap, url->getDN()); - break; - case LDAP_LI_GETLASTMOD_METHOD: - { - msgId = ldap_search(m_ldap, - url->getDN(), - url->getScope(), - url->getFilter(), - attrs, - ((LDAPSearchOperation*)m_pParams)->getAttrsOnly()); - } - break; - case LDAP_SUCCESS: - break; - } - - if (msgId != -1) - { - m_messageId = msgId; - } else { - m_pParams->setErrNo(ldap_get_lderrno(m_ldap,NULL,NULL)); - ldapErr = LI_LDAP_ERROR; - } - -net_LdapLIConnectionDataLoadExit: - - XP_FREEIF(utf8Encoding); - - return ldapErr; -} - -/* Process() - * ========= - * Process LI Gets/Puts, etc. Only one entry can be gotten/put at a time. - * The result of the process is a LDAPMessage* put into the LDAPOperation* - * in the URL_s->owner_data in the ActiveEntry. - * The caller of NET_GetURL is required to free this data via ldap_msgfree() - * if it is non-NULL in the LDAPOperation object. - */ -int net_LdapLIConnectionData::Process() -{ - LDAPMessage *message = NULL; - struct timeval timeout; - - // REMIND: put in the timeout stuff. - - XP_BZERO (&timeout, sizeof(timeout)); - int ldapErr = ldap_result (m_ldap, m_messageId, 1, &timeout, &message); - - XP_ASSERT(m_pParams); - - /* Check for network error */ - // We don't set result to NULL here because it may have already been set to - // something, e.g. by the LDAP_LI_ADDGLM or LDAP_LI_MODGLM methods. - if(ldapErr == -1) - { - m_pParams->setErrNo(ldap_get_lderrno(m_ldap,NULL,NULL)); - return LI_LDAP_ERROR; - } - - switch (ldapErr) - { - /* - * We can only get one entry at a time in the current implementation, so we - * terminate when we have at least one. - */ - case LDAP_RES_SEARCH_ENTRY: - case LDAP_RES_SEARCH_RESULT: - case LDAP_RES_MODIFY: - case LDAP_RES_DELETE: - case LDAP_RES_ADD: - FE_GraphProgress(m_ce->window_id, NULL, 0, 1, -2); // -2 specifies that we want items not bytes - case LDAP_RES_BIND: - m_pParams->setResults(message); - ldapErr = LI_LDAP_DONE; /* Special value to indicate to netlib that we're done. */ - /* We don't use -1 here so we can differentiate between */ - /* a valid result and an ldap error */ - m_pParams->setErrNo(ldap_result2error(m_ldap,message,0)); - break; - case LDAP_SUCCESS: - break; - default: - if(message) - m_pParams->setResults(message); - m_pParams->setErrNo(ldap_result2error(m_ldap,message,0)); - ldapErr = LI_LDAP_ERROR; - break; - } - - /* If the ldapErr is -2, it means we're done and we've gotten something */ - if(ldapErr == LI_LDAP_DONE) { - - char *utf8Encoding = NULL; - - // the last modified time is given by the modifyTimeStamp attribute. - char *attrs[2] = { "modifyTimeStamp" , NULL }; - int msgID; - const LDAPURL* url = m_pParams->getURL(); - - // For LDAP_LI_MODGLM_METHOD and LDAP_LI_ADDGLM_METHOD, we have to - // do another search to get the last modified time if the first - // search completes successfully. To this, we simply start the search - // and don't return -1 so netlib will keep calling process(). We also - // change m_method to LDAP_LI_SEARCH_METHOD so that we won't end up in this - // if statement again. Note that we don't change it in m_ce->URL_s->method - // This is mainly to avoid netlib weirdness. - switch(m_pParams->getURLMethod()) { - case LDAP_LI_ADDGLM_METHOD: - case LDAP_LI_MODGLM_METHOD: - - // Determine if the ADD part succeeded. We don't free the result because - // it's the policy of the URL handler to always return the result when - // it's available. We'll have to free if it the ADD/MOD succeed so that - // the GLM result can be returned. - if(m_pParams-> getErrNo() != LDAP_SUCCESS) { - // m_pParams->result and param->status already set above. - ((LDAPModGLMOperation*)m_pParams)->setModSucceeded(FALSE); - break; // exit the ADDGLM and MODGLM stuff. - } - - // setResults will free message, since setResults(message) was called earlier. - m_pParams->setResults(NULL); - message = NULL; - ((LDAPModGLMOperation*)m_pParams)->setModSucceeded(TRUE); - - msgID = ldap_search(m_ldap,url->getDN(),url->getScope(),"(objectclass=*)",attrs,0); - - // each time we initiate a new ldap operation we need to increase the count - FE_GraphProgressInit(m_ce->window_id, NULL, 1); - - // If msgID == -1, then there was a network error; so we set the error condition and - // leave ldapErr = -1 so netlib will exit the url handler. - if(msgID == -1) { - m_pParams->setErrNo(ldap_get_lderrno(m_ldap,NULL,NULL)); - ldapErr = LI_LDAP_ERROR; - } else { - ldapErr = 1; // >0 indicates to netlib to continue processing - m_messageId = msgID; - ((LDAPModGLMOperation*)m_pParams)->changeModToGLM(); - } - break; - } // switch - FE_GraphProgressDestroy(m_ce->window_id, NULL, 1, 1); - } // if - - return ldapErr; -} - -/* Unbind() - * ======== - * Unbind from the server if the caller didn't provide a connection. - */ -int net_LdapLIConnectionData::Unbind() -{ - // If the caller did not provide the connection, we do the standard unbind. - // If the caller did provide the connection, we have a sticky situation - // because net_LdapConnectionData::Unbind() is called in the base class' - // destructor, and that destructor is guaranteed to be called. To avoid - // unbinding a caller provided connection, we just set m_ldap to NULL so that - // the base class' Unbind() won't do anything. - if(!m_bCallerProvidedConnection) - return net_LdapConnectionData::Unbind(); - else - m_ldap = NULL; - - return 0; // Don't know what else we can return. -} - -/* Interrupt() - * =========== - * netlib wants to interrupt this connect; we rely on the base class to do most of - * the work and just set the appropriate error. - */ -int net_LdapLIConnectionData::Interrupt() -{ - return net_LdapConnectionData::Interrupt(); -} - -#endif // MOZ_LI -#endif // MOZ_LDAP - - -//**************************************************************************** -// -// Callbacks from NET_GetURL -// - -extern "C" int32 net_LoadLdap (ActiveEntry *ce) -{ -#ifdef MOZ_LDAP - if (NET_IsOffline()) - return MK_OFFLINE; - - net_LdapConnectionData *cd = NULL; - switch (NET_URL_Type (ce->URL_s->address)) - { - case LDAP_TYPE_URL: - case SECURE_LDAP_TYPE_URL: -#ifdef MOZ_LI - // If we're doing an LDAP operation, we - // have to figure out if it's an LI operation - // and instantiate the right connection data object. - if((LDAP_SEARCH_METHOD < ce->URL_s->method) && (LDAP_LI_BIND_METHOD >= ce->URL_s->method)) - cd = new net_LdapLIConnectionData(ce); - else -#endif - cd = new net_LdapToHtml (ce); - break; - case LDAP_QUERY_DSE_TYPE_URL: // I think we need to query the DSE for any operation, so this is in the base class - cd = new net_LdapToHtml (ce); - break; - case ADDRESS_BOOK_LDAP_TYPE_URL: - cd = new net_LdapToAddressBook (ce); - break; - case LDAP_REPLICATION_TYPE_URL: - cd = new net_LdapReplicator (ce); - break; - default: - XP_ASSERT(FALSE); - return MK_MALFORMED_URL_ERROR; - } - if (!cd) - return MK_OUT_OF_MEMORY; - - ce->con_data = cd; - int err = cd->Load (ce); - if (err) - { - ce->status = err; - delete cd; - ce->con_data = NULL; - } - - return err; -#else - return MK_MALFORMED_URL_ERROR; -#endif -} - -extern "C" int32 net_ProcessLdap (ActiveEntry *ce) -{ -#ifdef MOZ_LDAP - net_LdapConnectionData *cd = (net_LdapConnectionData*) ce->con_data; - - int err = cd->Process(); - if (err < 0 || err == MK_CONNECTED) - { - delete cd; - ce->con_data = NULL; - } - - if(err == MK_CONNECTED) - err = -1; - - return err; -#else - return MK_MALFORMED_URL_ERROR; -#endif -} - - -extern "C" int32 net_InterruptLdap (ActiveEntry * ce) -{ -#ifdef MOZ_LDAP - net_LdapConnectionData *cd = (net_LdapConnectionData*) ce->con_data; - - int err = cd->Interrupt (); - delete cd; - ce->con_data = NULL; - ce->status = MK_INTERRUPTED; - - return err; -#else - return -1; -#endif -} - -extern "C" void -net_CleanupLdap(void) -{ -} - -extern "C" void -NET_InitLDAPProtocol(void) -{ - static NET_ProtoImpl ldap_proto_impl; - - ldap_proto_impl.init = net_LoadLdap; - ldap_proto_impl.process = net_ProcessLdap; - ldap_proto_impl.interrupt = net_InterruptLdap; - ldap_proto_impl.resume = NULL; - ldap_proto_impl.cleanup = net_CleanupLdap; - - NET_RegisterProtocolImplementation(&ldap_proto_impl, LDAP_TYPE_URL); - NET_RegisterProtocolImplementation(&ldap_proto_impl, SECURE_LDAP_TYPE_URL); - NET_RegisterProtocolImplementation(&ldap_proto_impl, ADDRESS_BOOK_LDAP_TYPE_URL); -} - - -//**************************************************************************** -// -// Helper APIs -// - -extern "C" XP_Bool NET_ReplicateDirectory (MSG_Pane *pane, DIR_Server *server) -{ -#ifdef MOZ_LDAP - net_OfflineLdapReplicator *replicator = new net_OfflineLdapReplicator(pane, server); - - if (replicator->ReplicateDirectory()) - return TRUE; - - delete replicator; -#endif - return FALSE; -} diff --git a/mozilla/network/protocol/ldap/mkldap.h b/mozilla/network/protocol/ldap/mkldap.h deleted file mode 100644 index e2aa24086e0..00000000000 --- a/mozilla/network/protocol/ldap/mkldap.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKLDAP_H -#define MKLDAP_H - -PR_BEGIN_EXTERN_C - -void NET_InitLDAPProtocol(void); - -PR_END_EXTERN_C - -#endif diff --git a/mozilla/network/protocol/mailbox/MANIFEST b/mozilla/network/protocol/mailbox/MANIFEST deleted file mode 100644 index 49bf077dd1f..00000000000 --- a/mozilla/network/protocol/mailbox/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mkmailbx.h diff --git a/mozilla/network/protocol/mailbox/Makefile.in b/mozilla/network/protocol/mailbox/Makefile.in deleted file mode 100644 index c112e0dced0..00000000000 --- a/mozilla/network/protocol/mailbox/Makefile.in +++ /dev/null @@ -1,43 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = mailbxurl -LIBRARY_NAME = mailbxurl - -REQUIRES = imap4url netcache network dbm util pref js java fileurl security layer img httpurl mimetype htmldlgs - -CSRCS = mkmailbx.c - -EXPORTS = $(srcdir)/mkmailbx.h - -LOCAL_INCLUDES = -I$(topsrcdir)/network/protocol/imap4 - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/mailbox/makefile.win b/mozilla/network/protocol/mailbox/makefile.win deleted file mode 100644 index 851b6c61b90..00000000000 --- a/mozilla/network/protocol/mailbox/makefile.win +++ /dev/null @@ -1,88 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkmailbx.obj \ - $(NULL) - -CSRCS = \ - mkmailbx.c \ - $(NULL) - - -LIBRARY_NAME=mailbxurl -MODULE=mailbxurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network ldap imap4url -EXPORTS= mkmailbx.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\imap4url \ - -I$(PUBLIC)\mimetype \ -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/mailbox/mkmailbx.c b/mozilla/network/protocol/mailbox/mkmailbx.c deleted file mode 100644 index c72b4eda31a..00000000000 --- a/mozilla/network/protocol/mailbox/mkmailbx.c +++ /dev/null @@ -1,879 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * state machine to handle mailbox URL - */ - -#include "mkutils.h" -#include "mkgeturl.h" -#include "mktcp.h" -#include "mkparse.h" -#include "mkmailbx.h" -#include "msgcom.h" -#include "msgnet.h" -#include "msg_srch.h" -#include "libmime.h" -#include "merrors.h" -#include "mkimap4.h" -#include "netutils.h" -#ifdef XP_MAC -#include "msg_srch.h" -#endif - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_MAIL_READING_FOLDER; -extern int XP_MAIL_READING_MESSAGE; -extern int XP_COMPRESSING_FOLDER; -extern int XP_MAIL_DELIVERING_QUEUED_MESSAGES; -extern int XP_READING_MESSAGE_DONE; -extern int XP_MAIL_READING_FOLDER_DONE; -extern int XP_MAIL_COMPRESSING_FOLDER_DONE; -extern int XP_MAIL_DELIVERING_QUEUED_MESSAGES_DONE; -extern int XP_MAIL_SEARCHING; - - -extern int MK_OUT_OF_MEMORY; - -/* definitions of states for the state machine design - */ -typedef enum _MailboxStates { - MAILBOX_OPEN_FOLDER, - MAILBOX_FINISH_OPEN_FOLDER, - MAILBOX_OPEN_MESSAGE, - MAILBOX_OPEN_STREAM, - MAILBOX_READ_MESSAGE, - MAILBOX_COMPRESS_FOLDER, - MAILBOX_FINISH_COMPRESS_FOLDER, - MAILBOX_BACKGROUND, - MAILBOX_NULL, - MAILBOX_NULL2, - MAILBOX_DELIVER_QUEUED, - MAILBOX_FINISH_DELIVER_QUEUED, - MAILBOX_DONE, - MAILBOX_ERROR_DONE, - MAILBOX_FREE, - MAILBOX_COPY_MESSAGES, - MAILBOX_FINISH_COPY_MESSAGES -} MailboxStates; - - - -/* structure to hold data pertaining to the active state of - * a transfer in progress. - * - */ -typedef struct _MailboxConData { - MSG_Pane *pane; - - int next_state; /* the next state or action to be taken */ - int initial_state; /* why we are here */ - Bool pause_for_read; /* Pause now for next read? */ - void *folder_ptr; - void *msg_ptr; - void *compress_folder_ptr; - void *deliver_queued_ptr; - void *mailbox_search_ptr; - char *folder_name; - char *msg_id; - int32 msgnum; /* -1 if none specified. */ - NET_StreamClass *stream; - - XP_Bool destroy_graph_progress; /* do we need to destroy - * graph progress? */ - int32 original_content_length; /* the content length at the time of - * calling graph progress */ - char *input_buffer; - int32 input_buffer_size; - -} MailboxConData; - -#define COMPLETE_STREAM (*cd->stream->complete)(cd->stream) -#define ABORT_STREAM(s) (*cd->stream->abort)(cd->stream, s) -#define PUT_STREAM(buf, size) (*cd->stream->put_block) \ - (cd->stream, buf, size) - -/* forward decl */ -PRIVATE int32 net_ProcessMailbox (ActiveEntry *ce); - -PRIVATE int32 -net_MailboxLoad (ActiveEntry * ce) -{ - /* get memory for Connection Data */ - MailboxConData * cd; - char *path; - char *search; - char *part; - char *wholeUrl; - - /* temp, until imap urls have their own identifier */ - if (!XP_STRNCASECMP(ce->URL_s->address, "IMAP://", 7) ) - return NET_IMAP4Load(ce); - - if (XP_STRCASECMP(ce->URL_s->address, "mailbox:displayattachments") == 0) { - MIME_DisplayAttachmentPane(ce->window_id); - return -1; - } - - - cd = XP_NEW(MailboxConData); - path = NET_ParseURL(ce->URL_s->address, GET_PATH_PART); - search = NET_ParseURL(ce->URL_s->address, GET_SEARCH_PART); - part = search; - - ce->con_data = cd; - if(!ce->con_data) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - ce->status = MK_OUT_OF_MEMORY; - return (ce->status); - } - - /* init */ - XP_MEMSET(cd, 0, sizeof(MailboxConData)); - cd->msgnum = -1; - - wholeUrl = XP_STRDUP(ce->URL_s->address); - -#ifndef XP_MAC /* #### Fix Mac Pathname */ - NET_UnEscape (path); - NET_UnEscape (wholeUrl); -#endif /* !XP_MAC */ - - cd->pane = ce->URL_s->msg_pane; - if (!cd->pane) - { -#ifdef DEBUG_phil - XP_Trace ("NET_MailboxLoad: url->msg_pane NULL for URL: %s\n", ce->URL_s->address); -#endif - /* If we're displaying a message, there'll be a '?' in the url */ - if (XP_STRCHR(wholeUrl, '?')) - { - if (XP_STRSTR(wholeUrl, "?compress-folder") || XP_STRSTR(wholeUrl, "?deliver-queued")) - cd->pane = MSG_FindPane(ce->window_id, MSG_FOLDERPANE); /* ###phil tar to the tarpit */ - else - { - /* find a pane, just to get back to the MSG_Master */ - MSG_Pane *someRandomPane = MSG_FindPane (ce->window_id, MSG_ANYPANE); - if (someRandomPane) - { - cd->pane = MSG_FindPaneFromUrl(someRandomPane, wholeUrl, MSG_MESSAGEPANE); - /* - ** jrm and dmb, 97/02/06: temporary fix, because we MUST have a thread pane - ** in order for certain operations to succeed. The macintosh UI can - ** forward from the thread pane, with no message pane available, and this - ** routine was setting cd->pane to a folderpane, which is a kind of - ** pane that really doesn't work. The permanent fix will be to change the - ** behavior of MSG_FindPane. - */ - if (!cd->pane) - cd->pane = MSG_FindPaneFromUrl(someRandomPane, wholeUrl, MSG_THREADPANE); - } - } - } - else - cd->pane = MSG_FindPane(ce->window_id, MSG_FOLDERPANE); - - if (cd->pane == NULL) - { - /* find a pane, just to get back to the MSG_Master */ - MSG_Pane *someRandomPane = MSG_FindPane (ce->window_id, MSG_ANYPANE); - if (someRandomPane) - cd->pane = MSG_FindPaneFromUrl (someRandomPane, wholeUrl, MSG_MESSAGEPANE); - } - - /* ###dmb so there! This whole FindPane stuff is too adhoc. */ - if (cd->pane == NULL) - cd->pane = MSG_FindPane(ce->window_id, MSG_FOLDERPANE); - /* km! I agree! */ - if (cd->pane == NULL) - cd->pane = MSG_FindPane(ce->window_id, MSG_THREADPANE); - /* ###whs this isn't really true the way things are set up. */ - /* XP_ASSERT(cd->pane && MSG_GetContext(cd->pane) == ce->window_id); */ - } - if (cd->pane == NULL) - { - FREEIF(wholeUrl); - return -1; /* ### */ - } - - if (XP_STRCASECMP(wholeUrl, "mailbox:copymessages") == 0) - cd->next_state = MAILBOX_COPY_MESSAGES; - else - { - cd->folder_name = path; - cd->next_state = MAILBOX_OPEN_FOLDER; - } - - if (part && *part == '?') part++; - while (part) { - char* amp = XP_STRCHR(part, '&'); - if (amp) *amp++ = '\0'; - if (XP_STRNCMP(part, "id=", 3) == 0) { - cd->msg_id = XP_STRDUP (NET_UnEscape (part+3)); - } else if (XP_STRNCMP(part, "number=", 7) == 0) { - cd->msgnum = atol(part + 7); - if (cd->msgnum == 0 && part[7] != '0') cd->msgnum = -1; - } else if (XP_STRNCMP(part, "uidl=", 5) == 0) { - /* ### Vile hack time. If a UIDL was specified, then tell libmsg about - it, giving it a chance to arrange so that when this URL is all done, - MSG_GetNewMail gets called. */ - MSG_PrepareToIncUIDL(cd->pane, ce->URL_s, NET_UnEscape(part + 5)); - } else if (ce->URL_s->internal_url && - XP_STRNCMP(part, "compress-folder", 15) == 0) { - cd->next_state = MAILBOX_COMPRESS_FOLDER; - } else if (ce->URL_s->internal_url && - XP_STRNCMP(part, "deliver-queued", 14) == 0) { - cd->next_state = MAILBOX_DELIVER_QUEUED; - } else if (ce->URL_s->internal_url && - XP_STRNCMP(part, "background", 10) == 0) { - cd->next_state = MAILBOX_BACKGROUND; - } else if (ce->URL_s->internal_url && - XP_STRNCMP(part, "null", 10) == 0) { - cd->next_state = MAILBOX_NULL; - } - part = amp; - } - FREEIF(search); - FREEIF(wholeUrl); - - cd->initial_state = cd->next_state; - - /* don't cache mailbox url's */ - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); - - ce->local_file = TRUE; - ce->socket = NULL; - NET_SetCallNetlibAllTheTime(ce->window_id, "mkmailbx"); - - return(net_ProcessMailbox(ce)); -} - - -/* This doesn't actually generate HTML - but it is our hook into the - message display code, so that we can get some values out of it - after the headers-to-be-displayed have been parsed. - */ -static char * -mail_generate_html_header_fn (const char *dest, void *closure, - MimeHeaders *headers) -{ - ActiveEntry *ce = (ActiveEntry *) closure; - MailboxConData * cd = (MailboxConData *)ce->con_data; - MSG_ActivateReplyOptions (cd->pane, headers); - return 0; -} - - -static char * -mail_generate_html_footer_fn (const char *dest, void *closure, - MimeHeaders *headers) -{ - ActiveEntry *cur_entry = (ActiveEntry *) closure; - MailboxConData * cd = (MailboxConData *)cur_entry->con_data; - - char *uidl = (headers - ? MimeHeaders_get(headers, HEADER_X_UIDL, FALSE, FALSE) - : 0); - if (uidl) - { - XP_FREE(uidl); - return MSG_GeneratePartialMessageBlurb (cd->pane, - cur_entry->URL_s, - closure, headers); - } - return 0; -} - - -static char * -mail_generate_reference_url_fn (const char *dest, void *closure, - MimeHeaders *headers) -{ - ActiveEntry *cur_entry = (ActiveEntry *) closure; - char *addr = cur_entry->URL_s->address; - char *search = (addr ? XP_STRCHR (addr, '?') : 0); - char *id2; - char *new_dest; - char *result; - - if (!dest || !*dest) return 0; - id2 = XP_STRDUP (dest); - if (!id2) return 0; - if (id2[XP_STRLEN (id2)-1] == '>') - id2[XP_STRLEN (id2)-1] = 0; - if (id2[0] == '<') - new_dest = NET_Escape (id2+1, URL_PATH); - else - new_dest = NET_Escape (id2, URL_PATH); - - FREEIF (id2); - result = (char *) XP_ALLOC ((search ? search - addr : 0) + - (new_dest ? XP_STRLEN (new_dest) : 0) + - 40); - if (result && new_dest) - { - if (search) - { - XP_MEMCPY (result, addr, search - addr); - result[search - addr] = 0; - } - else if (addr) - XP_STRCPY (result, addr); - else - *result = 0; - XP_STRCAT (result, "?id="); - XP_STRCAT (result, new_dest); - - if (search && XP_STRSTR (search, "&headers=all")) - XP_STRCAT (result, "&headers=all"); - } - FREEIF (new_dest); - return result; -} - - -static int -net_make_mail_msg_stream (ActiveEntry *ce) -{ - MailboxConData * cd = (MailboxConData *)ce->con_data; - - StrAllocCopy(ce->URL_s->content_type, MESSAGE_RFC822); - - if (ce->format_out == FO_PRESENT || ce->format_out == FO_CACHE_AND_PRESENT) - { - MimeDisplayOptions *opt = XP_NEW (MimeDisplayOptions); - if (!opt) return MK_OUT_OF_MEMORY; - XP_MEMSET (opt, 0, sizeof(*opt)); - - opt->generate_reference_url_fn = mail_generate_reference_url_fn; - opt->generate_header_html_fn = 0; - opt->generate_post_header_html_fn = mail_generate_html_header_fn; - opt->generate_footer_html_fn = mail_generate_html_footer_fn; - opt->html_closure = ce; - ce->URL_s->fe_data = opt; - } - cd->stream = NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - if (!cd->stream) - return MK_UNABLE_TO_CONVERT; - else - return 0; -} - - -/* - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -PRIVATE int32 -net_ProcessMailbox (ActiveEntry *ce) -{ - MailboxConData * cd = (MailboxConData *)ce->con_data; - - /* temp, until imap urls have their own identifier */ - if ((!XP_STRNCASECMP(ce->URL_s->address, "IMAP://", 7) ) || - (!XP_STRNCASECMP(ce->URL_s->address, "view-source:IMAP://",19))) - return NET_ProcessIMAP4(ce); - - cd->pause_for_read = FALSE; /* already paused; reset */ - - while(!cd->pause_for_read) - { -#ifdef DEBUG_username - XP_Trace("NET_ProcessMailbox: at top of loop, state %d, status %d", cd->next_state, ce->status); -#endif - - switch(cd->next_state) { - - case MAILBOX_OPEN_FOLDER: - if (!ce->URL_s->load_background) { - char *fmt = XP_GetString( XP_MAIL_READING_FOLDER ); - char *folder = cd->folder_name; - char *s = XP_STRRCHR (folder, '/'); - if (s) - folder = s+1; - s = (char *) XP_ALLOC(XP_STRLEN(fmt) + XP_STRLEN(folder) + 20); - if (s) - { - XP_SPRINTF (s, fmt, folder); - NET_Progress(ce->window_id, s); - XP_FREE(s); - } - } - ce->status = MSG_BeginOpenFolderSock(cd->pane, - cd->folder_name, - cd->msg_id, - cd->msgnum, - &cd->folder_ptr); - - if(ce->status == MK_CONNECTED) - { -#ifdef DEBUG_username - XP_Trace ("NET_ProcessMailBox: next state is MAILBOX_OPEN_MESSAGE"); -#endif - cd->next_state = MAILBOX_OPEN_MESSAGE; - } - else if(ce->status > -1) - { -#ifdef DEBUG_username - XP_Trace ("NET_ProcessMailBox: next state is MAILBOX_FINISH_OPEN_FOLDER"); -#endif - cd->pause_for_read = TRUE; - cd->next_state = MAILBOX_FINISH_OPEN_FOLDER; - } -#ifdef DEBUG_username - XP_Trace ("NET_ProcessMailBox: MAILBOX_OPEN_FOLDER got error %d", ce->status); -#endif - break; - - case MAILBOX_FINISH_OPEN_FOLDER: - ce->status = MSG_FinishOpenFolderSock(cd->pane, - cd->folder_name, - cd->msg_id, - cd->msgnum, - &cd->folder_ptr); - - if(ce->status == MK_CONNECTED) - { - cd->next_state = MAILBOX_OPEN_MESSAGE; - } - else - { - cd->pause_for_read = TRUE; - } - break; - - case MAILBOX_OPEN_MESSAGE: - if(cd->msg_id == NULL && cd->msgnum < 0) - { - /* only open the message if we are actuall - * asking for a message - */ - cd->next_state = MAILBOX_DONE; - NET_Progress(ce->window_id, XP_GetString( XP_MAIL_READING_FOLDER_DONE ) ); - } - else - { - if (!ce->URL_s->load_background) - NET_Progress(ce->window_id, - XP_GetString( XP_MAIL_READING_MESSAGE ) ); - ce->status = MSG_OpenMessageSock(cd->pane, - cd->folder_name, - cd->msg_id, - cd->msgnum, - cd->folder_ptr, - &cd->msg_ptr, - &ce->URL_s->content_length); - cd->next_state = MAILBOX_OPEN_STREAM; - } - break; - - case MAILBOX_OPEN_STREAM: - { - ce->status = net_make_mail_msg_stream (ce); - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(ce->status); - return(ce->status); - } - else - { - XP_ASSERT (cd->stream); - cd->next_state = MAILBOX_READ_MESSAGE; - } - - if (!ce->URL_s->load_background) { - FE_GraphProgressInit(ce->window_id, ce->URL_s, - ce->URL_s->content_length); - cd->destroy_graph_progress = TRUE; - } - cd->original_content_length = ce->URL_s->content_length; - } - break; - - case MAILBOX_READ_MESSAGE: - { - int32 read_size; - - cd->pause_for_read = TRUE; - read_size = (*cd->stream->is_write_ready) - (cd->stream); - - if (cd->input_buffer == NULL) { - cd->input_buffer_size = 10240; -#ifdef DEBUG_ricardob - cd->input_buffer_size *= 2; -#endif - while (cd->input_buffer == NULL) { - cd->input_buffer = - (char*) XP_ALLOC(cd->input_buffer_size); - if (!cd->input_buffer) { - cd->input_buffer_size /= 2; - if (cd->input_buffer_size < 512) { - ce->status = MK_OUT_OF_MEMORY; - break; - } - } - } - if (cd->input_buffer == NULL) break; - } - - if(!read_size) - { - return(0); /* wait until we are ready to write */ - } - else - { - read_size = MIN(read_size, cd->input_buffer_size); - } - - ce->status = MSG_ReadMessageSock(cd->pane, - cd->folder_name, - cd->msg_ptr, - cd->msg_id, - cd->msgnum, - cd->input_buffer, - read_size); - - if(ce->status > 0) - { - ce->bytes_received += ce->status; - if (!ce->URL_s->load_background) - FE_GraphProgress(ce->window_id, ce->URL_s, - ce->bytes_received, ce->status, - ce->URL_s->content_length); - - ce->status = PUT_STREAM(cd->input_buffer, ce->status); - } - else if(ce->status == 0) - cd->next_state = MAILBOX_DONE; - } - break; - - case MAILBOX_COMPRESS_FOLDER: - if ((cd->initial_state == MAILBOX_COMPRESS_FOLDER) && - (!ce->URL_s->load_background)) { - char *fmt= XP_GetString( XP_COMPRESSING_FOLDER ); - char *folder = cd->folder_name; - char *s = XP_STRRCHR (folder, '/'); - if (s) - folder = s+1; - s = (char *)XP_ALLOC (XP_STRLEN(fmt) + XP_STRLEN(folder) + 20); - if (s) - { - XP_SPRINTF (s, fmt, folder); - NET_Progress(ce->window_id, s); - XP_FREE(s); - } - } - ce->status = MSG_BeginCompressFolder(cd->pane, ce->URL_s, - cd->folder_name, - &cd->compress_folder_ptr); - if (ce->status == MK_CONNECTED) { - cd->next_state = MAILBOX_DONE; - } else { - cd->pause_for_read = TRUE; - cd->next_state = MAILBOX_FINISH_COMPRESS_FOLDER; - } - break; - - case MAILBOX_FINISH_COMPRESS_FOLDER: - ce->status = MSG_FinishCompressFolder(cd->pane, ce->URL_s, - cd->folder_name, - cd->compress_folder_ptr); - if (ce->status == MK_CONNECTED) { - cd->next_state = MAILBOX_DONE; - } else { - cd->pause_for_read = TRUE; - } - break; - - case MAILBOX_BACKGROUND: - ce->status = MSG_ProcessBackground(ce->URL_s); - if (ce->status == MK_CONNECTED) { - cd->next_state = MAILBOX_DONE; - } else { - cd->pause_for_read = TRUE; - } - break; - - case MAILBOX_NULL: - ce->status = MK_WAITING_FOR_CONNECTION; - cd->next_state = MAILBOX_NULL2; - cd->pause_for_read = TRUE; - break; - case MAILBOX_NULL2: - ce->status = MK_CONNECTED; - cd->next_state = MAILBOX_DONE; - break; - - case MAILBOX_DELIVER_QUEUED: - if (!ce->URL_s->load_background) - NET_Progress(ce->window_id, - XP_GetString( XP_MAIL_DELIVERING_QUEUED_MESSAGES ) ); - ce->status = MSG_BeginDeliverQueued(cd->pane, ce->URL_s, - &cd->deliver_queued_ptr); - if (ce->status == MK_CONNECTED) { - cd->next_state = MAILBOX_DONE; - } else { - cd->pause_for_read = TRUE; - cd->next_state = MAILBOX_FINISH_DELIVER_QUEUED; - } - break; - - case MAILBOX_FINISH_DELIVER_QUEUED: - ce->status = MSG_FinishDeliverQueued(cd->pane, ce->URL_s, - cd->deliver_queued_ptr); - if (ce->status == MK_CONNECTED) { - cd->next_state = MAILBOX_DONE; - } else { - cd->pause_for_read = TRUE; - } - break; - - case MAILBOX_COPY_MESSAGES: - ce->status = MSG_BeginCopyingMessages(ce->window_id); - if (ce->status == MK_CONNECTED) - cd->next_state = MAILBOX_DONE; - else - { - cd->pause_for_read = TRUE; - cd->next_state = MAILBOX_FINISH_COPY_MESSAGES; - } - break; - - case MAILBOX_FINISH_COPY_MESSAGES: - ce->status = MSG_FinishCopyingMessages(ce->window_id); - if (ce->status == MK_CONNECTED) - cd->next_state = MAILBOX_DONE; - else - cd->pause_for_read = TRUE; - break; - - case MAILBOX_DONE: - if(cd->stream) - { - COMPLETE_STREAM; - FREE(cd->stream); - } - cd->next_state = MAILBOX_FREE; - break; - - case MAILBOX_ERROR_DONE: - if(cd->stream) - { - ABORT_STREAM(ce->status); - FREE(cd->stream); - } - cd->next_state = MAILBOX_FREE; - - if (ce->status < -1 && !ce->URL_s->error_msg) - ce->URL_s->error_msg = NET_ExplainErrorDetails(ce->status); - - break; - - case MAILBOX_FREE: - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkmailbx"); - - if (cd->input_buffer) { - XP_FREE(cd->input_buffer); - cd->input_buffer = NULL; - } - - if(cd->destroy_graph_progress) - FE_GraphProgressDestroy(ce->window_id, - ce->URL_s, - cd->original_content_length, - ce->bytes_received); - - if(cd->msg_ptr) - { - MSG_CloseMessageSock(cd->pane, cd->folder_name, - cd->msg_id, cd->msgnum, cd->msg_ptr); - cd->msg_ptr = NULL; - if (!ce->URL_s->load_background) - NET_Progress(ce->window_id, - XP_GetString( XP_READING_MESSAGE_DONE ) ); - } - - if(cd->folder_ptr) - { - MSG_CloseFolderSock(cd->pane, cd->folder_name, - cd->msg_id, cd->msgnum, cd->folder_ptr); - if ((cd->msg_id == NULL && cd->msgnum < 0) && - (!ce->URL_s->load_background)) - /* If we read a message, don't hide the previous message - with this one. */ - NET_Progress(ce->window_id, - XP_GetString( XP_MAIL_READING_FOLDER_DONE ) ); - } - - if(cd->compress_folder_ptr) - { - MSG_CloseCompressFolderSock(cd->pane, ce->URL_s, - cd->compress_folder_ptr); - cd->compress_folder_ptr = NULL; - if ((cd->initial_state == MAILBOX_COMPRESS_FOLDER) && - (!ce->URL_s->load_background)) - NET_Progress(ce->window_id, - XP_GetString( XP_MAIL_COMPRESSING_FOLDER_DONE ) ); - } - if(cd->deliver_queued_ptr) - { - MSG_CloseDeliverQueuedSock(cd->pane, ce->URL_s, - cd->deliver_queued_ptr); - cd->deliver_queued_ptr = NULL; - if (!ce->URL_s->load_background) - NET_Progress(ce->window_id, - XP_GetString( XP_MAIL_DELIVERING_QUEUED_MESSAGES_DONE ) ); - } - FREEIF(cd->folder_name); - FREEIF(cd->msg_id); - FREE(cd); - - return(-1); /* final end */ - - default: /* should never happen !!! */ - TRACEMSG(("MAILBOX: BAD STATE!")); - XP_ASSERT(0); - cd->next_state = MAILBOX_ERROR_DONE; - break; - } - - /* check for errors during load and call error - * state if found - */ - if(ce->status < 0 && cd->next_state != MAILBOX_FREE) - { - cd->next_state = MAILBOX_ERROR_DONE; - /* don't exit! loop around again and do the free case */ - cd->pause_for_read = FALSE; - } - } /* while(!cd->pause_for_read) */ - -#ifdef DEBUG_username - XP_Trace ("Leaving NET_ProcessMailbox with status %d", ce->status); -#endif - - return(ce->status); -} - -/* abort the connection in progress - */ -PRIVATE int32 -net_InterruptMailbox(ActiveEntry * ce) -{ - MailboxConData * cd = (MailboxConData *)ce->con_data; - - /* temp until imap urls have their own identifier */ - if (!XP_STRNCASECMP(ce->URL_s->address, "IMAP://", 7) ) - return NET_InterruptIMAP4(ce); - - cd->next_state = MAILBOX_ERROR_DONE; - ce->status = MK_INTERRUPTED; - - return(net_ProcessMailbox(ce)); -} - -/* Free any memory that might be used in caching etc. - */ -PRIVATE void -net_CleanupMailbox(void) -{ - /* nothing so far needs freeing */ - return; -} - -MODULE_PRIVATE void -NET_InitMailboxProtocol(void) -{ - static NET_ProtoImpl mailbox_proto_impl; - - mailbox_proto_impl.init = net_MailboxLoad; - mailbox_proto_impl.process = net_ProcessMailbox; - mailbox_proto_impl.interrupt = net_InterruptMailbox; - mailbox_proto_impl.resume = NULL; - mailbox_proto_impl.cleanup = net_CleanupMailbox; - - NET_RegisterProtocolImplementation(&mailbox_proto_impl, MAILBOX_TYPE_URL); -} - -/* Since each search may be composed of multiple distinct URLs to - * process, use a "search:" URL as a meta-URL which schedules the - * subparts for processing - */ -PRIVATE int32 -net_ProcessMsgSearch (ActiveEntry *ce) -{ -/* MailboxConData *cd = (MailboxConData *) ce->con_data;*/ - int retVal = MSG_ProcessSearch (ce->window_id); - ce->status = 0; - - if (0 != retVal) - { - /* stop this crazy thing */ - NET_ClearCallNetlibAllTheTime(ce->window_id, "mkmailbx"); - } - return retVal; -} - -PRIVATE int32 -net_MsgSearchLoad (ActiveEntry *ce) -{ - /* don't cache search urls */ - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); - - ce->local_file = TRUE; - ce->socket = NULL; - NET_SetCallNetlibAllTheTime(ce->window_id, "mkmailbx"); - return 0; -} - -PRIVATE int32 -net_InterruptMsgSearch (ActiveEntry *ce) -{ - return MSG_InterruptSearch (ce->window_id); -} - -/* Free any memory that might be used in caching etc. - */ -PRIVATE void -net_CleanupMsgSearch(void) -{ - /* nothing so far needs freeing */ - return; -} - -MODULE_PRIVATE void -NET_InitMsgSearchProtocol(void) -{ - static NET_ProtoImpl msgsearch_proto_impl; - - msgsearch_proto_impl.init = net_MsgSearchLoad; - msgsearch_proto_impl.process = net_ProcessMsgSearch; - msgsearch_proto_impl.interrupt = net_InterruptMsgSearch; - msgsearch_proto_impl.resume = NULL; - msgsearch_proto_impl.cleanup = net_CleanupMsgSearch; - - NET_RegisterProtocolImplementation(&msgsearch_proto_impl, MSG_SEARCH_TYPE_URL); -} diff --git a/mozilla/network/protocol/mailbox/mkmailbx.h b/mozilla/network/protocol/mailbox/mkmailbx.h deleted file mode 100644 index bb692941452..00000000000 --- a/mozilla/network/protocol/mailbox/mkmailbx.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MK_MAILBX_H -#define MK_MAILBX_H - -extern void NET_InitMailboxProtocol(void); - -extern void NET_InitMsgSearchProtocol(void); - -#endif /* MK_MAILBX_H */ diff --git a/mozilla/network/protocol/makefile.win b/mozilla/network/protocol/makefile.win deleted file mode 100644 index 10724c17460..00000000000 --- a/mozilla/network/protocol/makefile.win +++ /dev/null @@ -1,60 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network protocols -# -#------------------------------------------------------------------------ - - -DEPTH=..\.. -include <$(DEPTH)\config\config.mak> -DIRS= \ - about \ - file \ - ftp \ - gopher \ - http \ - remote \ - sockstub \ -!if defined(SMART_MAIL) - pop3 \ -!endif -!if defined(MOZ_MAIL_NEWS) - smtp \ -!endif -!ifdef MOZ_MAIL_NEWS - nntp \ - mailbox \ - certld \ - imap4 \ -!endif -!ifdef MOZ_LDAP - ldap \ -!endif - $(NULL) - -include <$(DEPTH)\config\rules.mak> - diff --git a/mozilla/network/protocol/marimba/MANIFEST b/mozilla/network/protocol/marimba/MANIFEST deleted file mode 100644 index c11fc50175c..00000000000 --- a/mozilla/network/protocol/marimba/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -marimurl.h diff --git a/mozilla/network/protocol/marimba/Makefile.in b/mozilla/network/protocol/marimba/Makefile.in deleted file mode 100644 index ea9e093fadf..00000000000 --- a/mozilla/network/protocol/marimba/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = marimurl -LIBRARY_NAME = marimurl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl - -CPPSRCS = mkmarimb.cpp - -EXPORTS = $(srcdir)/marimurl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/marimba/makefile.win b/mozilla/network/protocol/marimba/makefile.win deleted file mode 100644 index 49aa971f559..00000000000 --- a/mozilla/network/protocol/marimba/makefile.win +++ /dev/null @@ -1,84 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkmarimb.obj \ - $(NULL) - - -CSRCS = \ - mkmarimb.c \ - $(NULL) - - -LIBRARY_NAME=marimurl -MODULE=marimurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= marimurl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\network -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/marimba/marimurl.h b/mozilla/network/protocol/marimba/marimurl.h deleted file mode 100644 index 890cf409c7b..00000000000 --- a/mozilla/network/protocol/marimba/marimurl.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef MKMARIMBA_H -#define MKMARIMBA_H - -PR_BEGIN_EXTERN_C - -extern void NET_InitMarimbaProtocol(void); - -/* MIME Stuff */ - -typedef struct _NET_AppMarimbaStruct { - MWContext *context; - int32 content_length; - int32 bytes_read; - int32 bytes_alloc; - char *channelData; -} NET_ApplicationMarimbaStruct; - - -NET_StreamClass * NET_DoMarimbaApplication(int format_out, - void *data_obj, - URL_Struct *url_struct, - MWContext *context); - - -PR_END_EXTERN_C - -#endif - - diff --git a/mozilla/network/protocol/marimba/mkmarimb.cpp b/mozilla/network/protocol/marimba/mkmarimb.cpp deleted file mode 100644 index 9c8ce9f5248..00000000000 --- a/mozilla/network/protocol/marimba/mkmarimb.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -// mkmarimb.cpp -- Handles "castanet:" URLs for core Navigator, without -// requiring libmsg. -// - -#include "xp.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" - -#include "marimurl.h" -#include "xpgetstr.h" -#include "net.h" -#include "xp_str.h" -#include "client.h" - -/* a stub */ - -MODULE_PRIVATE void -NET_InitMarimbaProtocol(void) -{ - return; -} - - -/* this is a stub converter - - */ -PUBLIC NET_StreamClass * -NET_DoMarimbaApplication(int format_out, - void *data_obj, - URL_Struct *url_struct, - MWContext *context) -{ - return(NULL); - -} - diff --git a/mozilla/network/protocol/nntp/MANIFEST b/mozilla/network/protocol/nntp/MANIFEST deleted file mode 100644 index 51fc96dd9c1..00000000000 --- a/mozilla/network/protocol/nntp/MANIFEST +++ /dev/null @@ -1,4 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - diff --git a/mozilla/network/protocol/nntp/Makefile.in b/mozilla/network/protocol/nntp/Makefile.in deleted file mode 100644 index 95ca70f0163..00000000000 --- a/mozilla/network/protocol/nntp/Makefile.in +++ /dev/null @@ -1,45 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = nntpurl -LIBRARY_NAME = nntpurl - -REQUIRES = netcache network dbm util pref js java fileurl security layer img httpurl mimetype htmldlgs - -CPPSRCS = \ - mknews.cpp \ - mknewsgr.cpp \ - $(NULL) - -EXPORTS = mknews.h mknewsgr.h -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/nntp/makefile.win b/mozilla/network/protocol/nntp/makefile.win deleted file mode 100644 index 2e764e1c4a4..00000000000 --- a/mozilla/network/protocol/nntp/makefile.win +++ /dev/null @@ -1,90 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mknews.obj \ - .\$(OBJDIR)\mknewsgr.obj \ - $(NULL) - -CSRCS = \ - mknews.c \ - mknewsgr.c \ - $(NULL) - - -LIBRARY_NAME=nntpurl -MODULE=nntpurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= ldap network httpurl -EXPORTS= mknews.h mknewsgr.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\httpurl \ - -I$(PUBLIC)\mimetype \ -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/nntp/mknews.cpp b/mozilla/network/protocol/nntp/mknews.cpp deleted file mode 100644 index dd011eef154..00000000000 --- a/mozilla/network/protocol/nntp/mknews.cpp +++ /dev/null @@ -1,5967 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * NNTP protocol implementation. Maintains some state and sends most - * data to messenger backend. - */ - -/* Please leave outside of ifdef for windows precompiled headers */ -#define FORCE_PR_LOG /* Allow logging in the release build (sorry this breaks the PCH) */ -extern "C" { -#include "mkutils.h" -#include "netutils.h" -} - -#ifdef MOZILLA_CLIENT - -#include "merrors.h" - -#include "mime.h" -#include "shist.h" -#include "glhist.h" - -#include "mknews.h" -#include "mktcp.h" -#include "mkparse.h" -#include "mkformat.h" -#include "mkstream.h" -#include "mkaccess.h" -#include "mksort.h" -#include "netcache.h" -#include "libi18n.h" -#include "gui.h" - -#include "rosetta.h" -#include HG40855 -#include "mknews.h" - -#include "msgcom.h" -#include "msgnet.h" -#include "msg_srch.h" -#include "libmime.h" - -#include "prtime.h" -#include "prlog.h" -#include "prerror.h" - -#include "xp_error.h" -#include HG09893 -#include "prefapi.h" -#include "xplocale.h" - -/* start turning on XPCOM interfaces here. - * when they are all turned on, PLEASE remove dead code */ -#define XPCOM_XOVER -#define XPCOM_NEWSPARSE -#define XPCOM_NEWSHOST -#define XPCOM_NEWSGROUP -#define XPCOM_OFFLINE - -#ifdef XPCOM_XOVER -#include "nsIMsgXOVERParser.h" -#endif - -#ifdef XPCOM_NEWSPARSE -#include "nsIMsgNewsArticleList.h" -#endif - -#ifdef XPCOM_NEWSHOST -#include "nsIMsgNewsHost.h" -#endif - -#ifdef XPCOM_NEWSGROUP -#include "nsIMsgNewsgroup.h" -#endif - -#ifdef XPCOM_OFFLINE -#include "nsIMsgOfflineNewsState.h" -#endif - -#include "nsIMsgRFC822Parser.h" -#include "nsMsgRFC822Parser.h" /* for the factory */ - -/*#define CACHE_NEWSGRP_PASSWORD*/ - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int MK_MALFORMED_URL_ERROR; -extern int MK_NEWS_ERROR_FMT; -extern int MK_NNTP_CANCEL_CONFIRM; -extern int MK_NNTP_CANCEL_DISALLOWED; -extern int MK_NNTP_NOT_CANCELLED; -extern int MK_OUT_OF_MEMORY; -extern int XP_CONFIRM_SAVE_NEWSGROUPS; -extern int XP_HTML_ARTICLE_EXPIRED; -extern int XP_HTML_NEWS_ERROR; -extern int XP_PROGRESS_READ_NEWSGROUPINFO; -extern int XP_PROGRESS_RECEIVE_ARTICLE; -extern int XP_PROGRESS_RECEIVE_LISTARTICLES; -extern int XP_PROGRESS_RECEIVE_NEWSGROUP; -extern int XP_PROGRESS_SORT_ARTICLES; -extern int XP_PROGRESS_READ_NEWSGROUP_COUNTS; -extern int XP_THERMO_PERCENT_FORM; -extern int XP_PROMPT_ENTER_USERNAME; -extern int MK_BAD_NNTP_CONNECTION; -extern int MK_NNTP_AUTH_FAILED; -extern int MK_NNTP_ERROR_MESSAGE; -extern int MK_NNTP_NEWSGROUP_SCAN_ERROR; -extern int MK_NNTP_SERVER_ERROR; -extern int MK_NNTP_SERVER_NOT_CONFIGURED; -HG25431 -extern int MK_TCP_READ_ERROR; -extern int MK_TCP_WRITE_ERROR; -extern int MK_NNTP_CANCEL_ERROR; -extern int XP_CONNECT_NEWS_HOST_CONTACTED_WAITING_FOR_REPLY; -extern int XP_PLEASE_ENTER_A_PASSWORD_FOR_NEWS_SERVER_ACCESS; -extern int XP_GARBAGE_COLLECTING; -extern int XP_MESSAGE_SENT_WAITING_NEWS_REPLY; -extern int MK_MSG_DELIV_NEWS; -extern int MK_MSG_COLLABRA_DISABLED; -extern int MK_MSG_EXPIRE_NEWS_ARTICLES; -extern int MK_MSG_HTML_IMAP_NO_CACHED_BODY; - -/* Logging stuff */ - -PRLogModuleInfo* NNTP = NULL; -#define out PR_LOG_ALWAYS - -#define NNTP_LOG_READ(buf) \ -if (NNTP==NULL) \ - NNTP = PR_NewLogModule("NNTP"); \ -PR_LOG(NNTP, out, ("Receiving: %s", buf)) ; - -#define NNTP_LOG_WRITE(buf) \ -if (NNTP==NULL) \ - NNTP = PR_NewLogModule("NNTP"); \ -PR_LOG(NNTP, out, ("Sending: %s", buf)) ; - -#define NNTP_LOG_NOTE(buf) \ -if (NNTP==NULL) \ - NNTP = PR_NewLogModule("NNTP"); \ -PR_LOG(NNTP, out, buf) ; - - -/* end logging */ - -/* Forward declarations */ -static int net_xpat_send (ActiveEntry*); -static int net_list_pretty_names(ActiveEntry*); - -int net_ProcessNews(ActiveEntry *cur_entry); - -#ifdef PROFILE -#pragma profile on -#endif - -#define LIST_WANTED 0 -#define ARTICLE_WANTED 1 -#define CANCEL_WANTED 2 -#define GROUP_WANTED 3 -#define NEWS_POST 4 -#define READ_NEWS_RC 5 -#define NEW_GROUPS 6 -#define SEARCH_WANTED 7 -#define PRETTY_NAMES_WANTED 8 -#define PROFILE_WANTED 9 -#define IDS_WANTED 10 - -/* the output_buffer_size must be larger than the largest possible line - * 2000 seems good for news - * - * jwz: I increased this to 4k since it must be big enough to hold the - * entire button-bar HTML, and with the new "mailto" format, that can - * contain arbitrarily long header fields like "references". - * - * fortezza: proxy auth is huge, buffer increased to 8k (sigh). - */ -#define OUTPUT_BUFFER_SIZE (4096*2) - -/* the amount of time to subtract from the machine time - * for the newgroup command sent to the nntp server - */ -#define NEWGROUPS_TIME_OFFSET 60L*60L*12L /* 12 hours */ - -/* Allow the user to open at most this many connections to one news host*/ -#define kMaxConnectionsPerHost 3 - -/* Keep this many connections cached. The cache is global, not per host */ -#define kMaxCachedConnections 2 - -/* globals - */ -PRIVATE XP_List * nntp_connection_list=0; - -PRIVATE XP_Bool net_news_last_username_probably_valid=FALSE; -PRIVATE int32 net_NewsChunkSize=-1; /* default */ - -PRIVATE int32 net_news_timeout = 170; /* seconds that an idle NNTP conn can live */ - -#define PUTSTRING(s) (*cd->stream->put_block) \ - (cd->stream, s, PL_strlen(s)) -#define COMPLETE_STREAM (*cd->stream->complete) \ - (cd->stream) -#define ABORT_STREAM(s) (*cd->stream->abort) \ - (cd->stream, s) -#define PUT_STREAM(buf, size) (*cd->stream->put_block) \ - (cd->stream, buf, size) - -/* states of the machine - */ -typedef enum _StatesEnum { -NNTP_RESPONSE, -#ifdef BLOCK_UNTIL_AVAILABLE_CONNECTION -NNTP_BLOCK_UNTIL_CONNECTIONS_ARE_AVAILABLE, -NNTP_CONNECTIONS_ARE_AVAILABLE, -#endif -NNTP_CONNECT, -NNTP_CONNECT_WAIT, -HG07711 -NNTP_LOGIN_RESPONSE, -NNTP_SEND_MODE_READER, -NNTP_SEND_MODE_READER_RESPONSE, -SEND_LIST_EXTENSIONS, -SEND_LIST_EXTENSIONS_RESPONSE, -SEND_LIST_SEARCHES, -SEND_LIST_SEARCHES_RESPONSE, -NNTP_LIST_SEARCH_HEADERS, -NNTP_LIST_SEARCH_HEADERS_RESPONSE, -NNTP_GET_PROPERTIES, -NNTP_GET_PROPERTIES_RESPONSE, -SEND_LIST_SUBSCRIPTIONS, -SEND_LIST_SUBSCRIPTIONS_RESPONSE, -SEND_FIRST_NNTP_COMMAND, -SEND_FIRST_NNTP_COMMAND_RESPONSE, -SETUP_NEWS_STREAM, -NNTP_BEGIN_AUTHORIZE, -NNTP_AUTHORIZE_RESPONSE, -NNTP_PASSWORD_RESPONSE, -NNTP_READ_LIST_BEGIN, -NNTP_READ_LIST, -DISPLAY_NEWSGROUPS, -NNTP_NEWGROUPS_BEGIN, -NNTP_NEWGROUPS, -NNTP_BEGIN_ARTICLE, -NNTP_READ_ARTICLE, -NNTP_XOVER_BEGIN, -NNTP_FIGURE_NEXT_CHUNK, -NNTP_XOVER_SEND, -NNTP_XOVER_RESPONSE, -NNTP_XOVER, -NEWS_PROCESS_XOVER, -NNTP_READ_GROUP, -NNTP_READ_GROUP_RESPONSE, -NNTP_READ_GROUP_BODY, -NNTP_SEND_GROUP_FOR_ARTICLE, -NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE, -NNTP_PROFILE_ADD, -NNTP_PROFILE_ADD_RESPONSE, -NNTP_PROFILE_DELETE, -NNTP_PROFILE_DELETE_RESPONSE, -NNTP_SEND_ARTICLE_NUMBER, -NEWS_PROCESS_BODIES, -NNTP_PRINT_ARTICLE_HEADERS, -NNTP_SEND_POST_DATA, -NNTP_SEND_POST_DATA_RESPONSE, -NNTP_CHECK_FOR_MESSAGE, -NEWS_NEWS_RC_POST, -NEWS_DISPLAY_NEWS_RC, -NEWS_DISPLAY_NEWS_RC_RESPONSE, -NEWS_START_CANCEL, -NEWS_DO_CANCEL, -NNTP_XPAT_SEND, -NNTP_XPAT_RESPONSE, -NNTP_SEARCH, -NNTP_SEARCH_RESPONSE, -NNTP_SEARCH_RESULTS, -NNTP_LIST_PRETTY_NAMES, -NNTP_LIST_PRETTY_NAMES_RESPONSE, -NNTP_LIST_XACTIVE, -NNTP_LIST_XACTIVE_RESPONSE, -NNTP_LIST_GROUP, -NNTP_LIST_GROUP_RESPONSE, -NEWS_DONE, -NEWS_ERROR, -NNTP_ERROR, -NEWS_FREE -} StatesEnum; - -#ifdef DEBUG -char *stateLabels[] = { -"NNTP_RESPONSE", -#ifdef BLOCK_UNTIL_AVAILABLE_CONNECTION -"NNTP_BLOCK_UNTIL_CONNECTIONS_ARE_AVAILABLE", -"NNTP_CONNECTIONS_ARE_AVAILABLE", -#endif -"NNTP_CONNECT", -"NNTP_CONNECT_WAIT", -HG25430 -"NNTP_LOGIN_RESPONSE", -"NNTP_SEND_MODE_READER", -"NNTP_SEND_MODE_READER_RESPONSE", -"SEND_LIST_EXTENSIONS", -"SEND_LIST_EXTENSIONS_RESPONSE", -"SEND_LIST_SEARCHES", -"SEND_LIST_SEARCHES_RESPONSE", -"NNTP_LIST_SEARCH_HEADERS", -"NNTP_LIST_SEARCH_HEADERS_RESPONSE", -"NNTP_GET_PROPERTIES", -"NNTP_GET_PROPERTIES_RESPONSE", -"SEND_LIST_SUBSCRIPTIONS", -"SEND_LIST_SUBSCRIPTIONS_RESPONSE", -"SEND_FIRST_NNTP_COMMAND", -"SEND_FIRST_NNTP_COMMAND_RESPONSE", -"SETUP_NEWS_STREAM", -"NNTP_BEGIN_AUTHORIZE", -"NNTP_AUTHORIZE_RESPONSE", -"NNTP_PASSWORD_RESPONSE", -"NNTP_READ_LIST_BEGIN", -"NNTP_READ_LIST", -"DISPLAY_NEWSGROUPS", -"NNTP_NEWGROUPS_BEGIN", -"NNTP_NEWGROUPS", -"NNTP_BEGIN_ARTICLE", -"NNTP_READ_ARTICLE", -"NNTP_XOVER_BEGIN", -"NNTP_FIGURE_NEXT_CHUNK", -"NNTP_XOVER_SEND", -"NNTP_XOVER_RESPONSE", -"NNTP_XOVER", -"NEWS_PROCESS_XOVER", -"NNTP_READ_GROUP", -"NNTP_READ_GROUP_RESPONSE", -"NNTP_READ_GROUP_BODY", -"NNTP_SEND_GROUP_FOR_ARTICLE", -"NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE", -"NNTP_PROFILE_ADD", -"NNTP_PROFILE_ADD_RESPONSE", -"NNTP_PROFILE_DELETE", -"NNTP_PROFILE_DELETE_RESPONSE", -"NNTP_SEND_ARTICLE_NUMBER", -"NEWS_PROCESS_BODIES", -"NNTP_PRINT_ARTICLE_HEADERS", -"NNTP_SEND_POST_DATA", -"NNTP_SEND_POST_DATA_RESPONSE", -"NNTP_CHECK_FOR_MESSAGE", -"NEWS_NEWS_RC_POST", -"NEWS_DISPLAY_NEWS_RC", -"NEWS_DISPLAY_NEWS_RC_RESPONSE", -"NEWS_START_CANCEL", -"NEWS_DO_CANCEL", -"NNTP_XPAT_SEND", -"NNTP_XPAT_RESPONSE", -"NNTP_SEARCH", -"NNTP_SEARCH_RESPONSE", -"NNTP_SEARCH_RESULTS", -"NNTP_LIST_PRETTY_NAMES", -"NNTP_LIST_PRETTY_NAMES_RESPONSE", -"NNTP_LIST_XACTIVE_RESPONSE", -"NNTP_LIST_XACTIVE", -"NNTP_LIST_GROUP", -"NNTP_LIST_GROUP_RESPONSE", -"NEWS_DONE", -"NEWS_ERROR", -"NNTP_ERROR", -"NEWS_FREE" -}; - -#endif - -/* structure to hold data about a tcp connection - * to a news host - */ -typedef struct _NNTPConnection { - char *hostname; /* hostname string (may contain :port) */ - PRFileDesc *csock; /* control socket */ - XP_Bool busy; /* is the connection in use already? */ - XP_Bool prev_cache; /* did this connection come from the cache? */ - XP_Bool posting_allowed;/* does this server allow posting */ - XP_Bool default_host; - XP_Bool no_xover; /* xover command is not supported here */ - HG55785 - char *current_group; /* last GROUP command sent on this connection */ - PRTime last_used_time; /* last time this conn was used, for conn aging purposes */ -} NNTPConnection; - - -/* structure to hold all the state and data - * for the state machine - */ -typedef struct _NewsConData { - MSG_Pane *pane; -#ifdef XPCOM_NEWSHOST - nsIMsgNewsHost *news_host; -#else - MSG_NewsHost *host; -#endif - - StatesEnum next_state; - StatesEnum next_state_after_response; - int type_wanted; /* Article, List, or Group */ - int response_code; /* code returned from NNTP server */ - char *response_txt; /* text returned from NNTP server */ - Bool pause_for_read; /* should we pause for the next read? */ - - char *proxy_server; /* @#$ proxy server hostname */ - XP_Bool proxy_auth_required; /* is auth required */ - XP_Bool sent_proxy_auth; /* have we sent a proxy auth? */ - - XP_Bool newsrc_performed; /* have we done a newsrc update? */ - XP_Bool mode_reader_performed; /* have we sent any cmds to the server yet? */ - -#ifdef XP_WIN - XP_Bool calling_netlib_all_the_time; -#endif - NET_StreamClass * stream; - - NNTPConnection * control_con; /* all the info about a connection */ - - char *data_buf; - int32 data_buf_size; - - /* for group command */ - char *path; /* message id */ - -#ifdef XPCOM_NEWSGROUP - nsIMsgNewsgroup *newsgroup; -#else - char *group_name; -#endif - - int32 first_art; - int32 last_art; - int32 first_possible_art; - int32 last_possible_art; - - int32 num_loaded; /* How many articles we got XOVER lines for. */ - int32 num_wanted; /* How many articles we wanted to get XOVER - lines for. */ - - /* for cancellation: the headers to be used */ - char *cancel_from; - char *cancel_newsgroups; - char *cancel_distribution; - char *cancel_id; - char *cancel_msg_file; - int cancel_status; - - /* variables for ReadNewsRC */ - int32 newsrc_list_index; - int32 newsrc_list_count; - - XP_Bool use_fancy_newsgroup_listing; /* use LIST XACTIVE or LIST */ - XP_Bool destroy_graph_progress; /* do we need to destroy - * graph progress? - */ - - char *output_buffer; /* use it to write out lines */ - - int32 article_num; /* current article number */ - - char *message_id; /* for reading groups */ - char *author; - char *subject; - - int32 original_content_length; /* the content length at the time of - * calling graph progress - */ - - /* random pointer for libmsg state */ -#ifdef XPCOM_XOVER - nsIMsgXOVERParser *xover_parser; -#else - void *xover_parse_state; -#endif - -#ifdef XPCOM_NEWSPARSE - nsIMsgNewsArticleList *article_list; -#else - void *newsgroup_parse_state; -#endif - - TCP_ConData * tcp_con_data; - - void * write_post_data_data; - - XP_Bool some_protocol_succeeded; /* We know we have done some protocol - with this newsserver recently, so don't - respond to an error by closing and - reopening it. */ - char *command_specific_data; - char *current_search; -#ifdef XPCOM_OFFLINE - nsIMsgOfflineNewsState *offline_state; -#else - void *offlineState; /* offline news state machine for article retrieval */ -#endif - XP_Bool articleIsOffline; - int previous_response_code; - -} NewsConData; - -static char * last_password = 0; -static char * last_password_hostname = 0; -static char * last_username=0; -static char * last_username_hostname=0; - -/* publicly available function to set the news host - * this will be a useful front end callable routine - */ -PUBLIC void NET_SetNewsHost (const char * value) -{ - /* ### This routine is obsolete and should go away. */ -} - - - -/* set the default number of articles retrieved by news at any one time - */ -PUBLIC void -NET_SetNumberOfNewsArticlesInListing(int32 number) -{ - net_NewsChunkSize = number; -} - -/* Whether we cache XOVER data. NYI. */ -PUBLIC void -NET_SetCacheXOVER(XP_Bool value) -{ -} - - - -PUBLIC void NET_CleanTempXOVERCache(void) -{ -} - - - -PUBLIC void net_graceful_shutdown(PRFileDesc* sock, XP_Bool bVal) -{ - static int32 int_pref = -1; - -#ifdef THIS_IS_DEPRICATED - if (sock == NULL) return; -#endif - - if (int_pref == -1) - PREF_GetIntPref("network.socket_shutdown", &int_pref); - if (int_pref > 0 && int_pref < 4) - { - if (bVal) - /* ??? */ - NET_BlockingWrite(sock, "", 0); - else - PR_Shutdown(sock, (PRShutdownHow)(int_pref-1)); - } -} - -static void net_nntp_close (NNTPConnection *con, int status) -{ - if (!con) - { - PR_ASSERT(FALSE); - return; - } - else if (status != MK_INTERRUPTED) - { - const char *command = "QUIT" CRLF; - status = NET_BlockingWrite (con->csock, command, PL_strlen(command)); - NNTP_LOG_WRITE (command); - if (status >= 0) { - HG51966 - } - PR_Close(con->csock); - } - - FREEIF(con->current_group); -} - -/* user has removed a news host from the UI. - * be sure it has also been removed from the - * connection cache so we renegotiate news host - * capabilities if we try to use it again - */ -PUBLIC void NET_OnNewsHostDeleted (const char *hostName) -{ - NNTPConnection *conn; - XP_List *list = nntp_connection_list; - - while ((conn = (NNTPConnection*) XP_ListNextObject(list)) != NULL) - { - if (!(PL_strcasecmp(conn->hostname, hostName))) - { - net_nntp_close (conn, /* conn->busy ? MK_INTERRUPTED : */ 0); - - list = list->prev ? list->prev : nntp_connection_list; - XP_ListRemoveObject (nntp_connection_list, conn); - FREEIF(conn->hostname); - FREE(conn); - } - } -} - - -/* display HTML error state in the context window - * returns negative error status - */ -PRIVATE int -net_display_html_error_state (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - XP_Bool inMsgPane = FALSE; - int major_opcode = MK_NNTP_RESPONSE_TYPE(cd->response_code); - /* #### maybe make this a dialog box - to do that, just return an error. - */ - - /* ERROR STATE - * Set up the HTML stream - */ - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - - /* If we're not in a message pane, don't try to spew HTML - * This allows error reporting from the folder pane, subscribe UI, etc. - */ - if (ce->URL_s->msg_pane) - inMsgPane = (MSG_MESSAGEPANE == MSG_GetPaneType(ce->URL_s->msg_pane)); - - if (ce->format_out == FO_PRESENT && inMsgPane) - { - cd->stream = NET_StreamBuilder(ce->format_out, ce->URL_s, - ce->window_id); - if(!cd->stream) - { - ce->URL_s->error_msg = - NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return MK_UNABLE_TO_CONVERT; - } - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - XP_GetString(XP_HTML_NEWS_ERROR), - cd->response_txt); - if(ce->status > -1) - ce->status = PUTSTRING(cd->output_buffer); - - if(cd->type_wanted == ARTICLE_WANTED || - cd->type_wanted == CANCEL_WANTED) - { - PL_strcpy(cd->output_buffer, - XP_GetString(XP_HTML_ARTICLE_EXPIRED)); - if(ce->status > -1) - PUTSTRING(cd->output_buffer); - - if (cd->path && *cd->path && ce->status > -1) - { - char *urlScheme; - HG72589 - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "<P>&lt;%.512s&gt;", cd->path); - if (cd->article_num > 0) - { - PR_snprintf(cd->output_buffer+PL_strlen(cd->output_buffer), - OUTPUT_BUFFER_SIZE-PL_strlen(cd->output_buffer), - " (%lu)", (unsigned long) cd->article_num); - if (ce->URL_s->msg_pane) - MSG_MarkMessageKeyRead(ce->URL_s->msg_pane, cd->article_num, ""); - } - PUTSTRING(cd->output_buffer); - - char *group_name; - cd->newsgroup->GetName(&group_name); - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, - "<P> <A HREF=\"%s//%s/%s?list-ids\">%s</A> </P>\n", - urlScheme, - cd->control_con->hostname, - group_name, - XP_GetString(MK_MSG_EXPIRE_NEWS_ARTICLES)); - PR_Free(group_name); - PUTSTRING(cd->output_buffer); - } - - if(ce->status > -1) - { - COMPLETE_STREAM; - cd->stream = 0; - } - } - else - if (cd->type_wanted == SEARCH_WANTED) - ce->status = net_xpat_send(ce); - - ce->URL_s->expires = 1; - /* ce->URL_s->error_msg = - NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - */ - } - else - { - /* FORMAT_OUT is not FO_PRESENT - so instead of emitting an HTML - error message, present it in a dialog box. */ - - PR_snprintf(cd->output_buffer, /* #### i18n */ - OUTPUT_BUFFER_SIZE, - XP_GetString(MK_NEWS_ERROR_FMT), - cd->response_txt); - ce->URL_s->error_msg = PL_strdup (cd->output_buffer); - } - - /* if the server returned a 400 error then it is an expected - * error. the NEWS_ERROR state will not sever the connection - */ - if(major_opcode == MK_NNTP_RESPONSE_TYPE_CANNOT) - cd->next_state = NEWS_ERROR; - else - cd->next_state = NNTP_ERROR; - - /* If we ever get an error, let's re-issue the GROUP command - before the next ARTICLE command; the overhead isn't very high, - and weird stuff seems to be happening... */ - FREEIF(cd->control_con->current_group); - - /* cd->control_con->prev_cache = FALSE; to keep if from reconnecting */ - return MK_NNTP_SERVER_ERROR; -} - - -/* gets the response code from the nntp server and the - * response line - * - * returns the TCP return code from the read - */ -PRIVATE int -net_news_response (ActiveEntry * ce) -{ - char * line; - NewsConData * cd = (NewsConData *)ce->con_data; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - NNTP_LOG_READ(cd->data_buf); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - /* if TCP error of if there is not a full line yet return - */ - if(ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, - PR_GetOSError()); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; - } - - cd->pause_for_read = FALSE; /* don't pause if we got a line */ - - HG43574 - /* almost correct - */ - if(ce->status > 1) - { - ce->bytes_received += ce->status; - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, ce->status, ce->URL_s->content_length); - } - - StrAllocCopy(cd->response_txt, line+4); - - cd->previous_response_code = cd->response_code; - - sscanf(line, "%d", &cd->response_code); - - /* authentication required can come at any time - */ -#ifdef CACHE_NEWSGRP_PASSWORD - /* - * This is an effort of trying to cache the username/password - * per newsgroup. It is extremely hard to make it work along with - * nntp voluntary password checking mechanism. We are backing this - * feature out. Instead of touching various of backend msg files - * at this late Dogbert 4.0 beta4 game, the infrastructure will - * remain in the msg library. We only modify codes within this file. - * Maybe one day we will try to do it again. Zzzzz -- jht - */ - if(MK_NNTP_RESPONSE_AUTHINFO_REQUIRE == cd->response_code || - MK_NTTP_RESPONSE_AUTHINFO_SIMPLE_REQUIRE == cd->response_code || - MK_NNTP_RESPONSE_PERMISSION_DENIED == cd->response_code) - { - cd->next_state = NNTP_BEGIN_AUTHORIZE; - if (MK_NNTP_RESPONSE_PERMISSION_DENIED == cd->response_code) { - if (MK_NNTP_RESPONSE_TYPE_OK == MK_NNTP_RESPONSE_TYPE(cd->previous_response_code) { - if (net_news_last_username_probably_valid) { - net_news_last_username_probably_valid = FALSE; - } - else { -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(NULL); - cd->newsgroup->SetPassword(NULL); -#else - MSG_SetNewsgroupUsername(cd->pane, NULL); - MSG_SetNewsgroupPassword(cd->pane, NULL); -#endif - } - } - else { - net_news_last_username_probably_valid = FALSE; - if (NNTP_PASSWORD_RESPONSE == cd->next_state_after_response) { -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(NULL); - cd->newsgroup->SetPassword(NULL); -#else - MSG_SetNewsgroupUsername(cd->pane, NULL); - MSG_SetNewsgroupPassword(cd->pane, NULL); -#endif - } - } - - } - } -#else - if (MK_NNTP_RESPONSE_AUTHINFO_REQUIRE == cd->response_code || - MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_REQUIRE == cd->response_code) - { - cd->next_state = NNTP_BEGIN_AUTHORIZE; - } - else if (MK_NNTP_RESPONSE_PERMISSION_DENIED == cd->response_code) - { - net_news_last_username_probably_valid = FALSE; - return net_display_html_error_state(ce); - } -#endif - else - { - cd->next_state = cd->next_state_after_response; - } - - return(0); /* everything ok */ -} - -HG43072 - -/* interpret the server response after the connect - * - * returns negative if the server responds unexpectedly - */ -PRIVATE int -net_nntp_login_response (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - XP_Bool postingAllowed = cd->response_code == MK_NNTP_RESPONSE_POSTING_ALLOWED; - - if(MK_NNTP_RESPONSE_TYPE(cd->response_code)!=MK_NNTP_RESPONSE_TYPE_OK) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_ERROR_MESSAGE, cd->response_txt); - - cd->next_state = NNTP_ERROR; - cd->control_con->prev_cache = FALSE; /* to keep if from reconnecting */ - return MK_BAD_NNTP_CONNECTION; - } - - cd->control_con->posting_allowed = postingAllowed; /* ###phil dead code */ -#ifdef XPCOM_NEWSHOST - cd->news_host->SetPostingAllowed(postingAllowed); -#else - MSG_SetNewsHostPostingAllowed (cd->host, postingAllowed); -#endif - - cd->next_state = NNTP_SEND_MODE_READER; - return(0); /* good */ -} - -PRIVATE int -net_nntp_send_mode_reader (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - PL_strcpy(cd->output_buffer, "MODE READER" CRLF); - - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_SEND_MODE_READER_RESPONSE; - cd->pause_for_read = TRUE; - - return(ce->status); - -} - -PRIVATE int -net_nntp_send_mode_reader_response (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - cd->mode_reader_performed = TRUE; - - /* ignore the response code and continue - */ -#ifdef XPCOM_NEWSHOST - PRBool pushAuth; - nsresult rv = cd->news_host->IsPushAuth(&pushAuth); - if (NS_SUCCEEDED(rv) && pushAuth) -#else - if (MSG_GetNewsHostPushAuth(cd->host)) -#endif - /* if the news host is set up to require volunteered (pushed) authentication, - * do that before we do anything else - */ - cd->next_state = NNTP_BEGIN_AUTHORIZE; - else - cd->next_state = SEND_LIST_EXTENSIONS; - - return(0); -} - -PRIVATE int net_nntp_send_list_extensions (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - PL_strcpy(cd->output_buffer, "LIST EXTENSIONS" CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = SEND_LIST_EXTENSIONS_RESPONSE; - cd->pause_for_read = TRUE; - return ce->status; -} - -PRIVATE int net_nntp_send_list_extensions_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - if (MK_NNTP_RESPONSE_TYPE(cd->response_code) == MK_NNTP_RESPONSE_TYPE_OK) - { - char *line = NULL; -#ifdef XPCOM_NEWSHOST - nsIMsgNewsHost *news_host = cd->news_host; -#else - MSG_NewsHost *host = cd->host; -#endif - - ce->status = NET_BufferedReadLine (ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - if (!line) - return ce->status; /* no line yet */ - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if ('.' != line[0]) -#ifdef XPCOM_NEWSHOST - news_host->AddExtension(line); -#else - MSG_AddNewsExtension (host, line); -#endif - else - { - /* tell libmsg that it's ok to ask this news host for extensions */ -#ifdef XPCOM_NEWSHOST - cd->news_host->SetSupportsExtensions(TRUE); -#else - MSG_SupportsNewsExtensions (cd->host, TRUE); -#endif - /* all extensions received */ - cd->next_state = SEND_LIST_SEARCHES; - cd->pause_for_read = FALSE; - } - } - else - { - /* LIST EXTENSIONS not recognized - * tell libmsg not to ask for any more extensions and move on to - * the real NNTP command we were trying to do. - */ -#ifdef XPCOM_NEWSHOST - cd->news_host->SetSupportsExtensions(FALSE); -#else - MSG_SupportsNewsExtensions (cd->host, FALSE); -#endif - cd->next_state = SEND_FIRST_NNTP_COMMAND; - } - - return ce->status; -} - -PRIVATE int net_nntp_send_list_searches (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool searchable=FALSE; - - rv = cd->news_host->QueryExtension("SEARCH",&searchable); - if (NS_SUCCEEDED(rv) && searchable) -#else - if (MSG_QueryNewsExtension (cd->host, "SEARCH")) -#endif - { - PL_strcpy(cd->output_buffer, "LIST SEARCHES" CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = SEND_LIST_SEARCHES_RESPONSE; - cd->pause_for_read = TRUE; - } - else - { - /* since SEARCH isn't supported, move on to GET */ - cd->next_state = NNTP_GET_PROPERTIES; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -PRIVATE int net_nntp_send_list_searches_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - char *line = NULL; - ce->status = NET_BufferedReadLine (ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - if (!line) - return ce->status; /* no line yet */ - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if ('.' != line[0]) - { -#ifdef XPCOM_NEWSHOST - cd->news_host->AddSearchableGroup(line); -#else - MSG_AddSearchableGroup (cd->host, line); -#endif - } - else - { - /* all searchable groups received */ - /* LIST SRCHFIELDS is legal if the server supports the SEARCH extension, which */ - /* we already know it does */ - cd->next_state = NNTP_LIST_SEARCH_HEADERS; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -PRIVATE int net_send_list_search_headers (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - PL_strcpy(cd->output_buffer, "LIST SRCHFIELDS" CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_LIST_SEARCH_HEADERS_RESPONSE; - cd->pause_for_read = TRUE; - - return ce->status; -} - -PRIVATE int net_send_list_search_headers_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; -#ifdef XPCOM_NEWSHOST - nsIMsgNewsHost* news_host = cd->news_host; -#else - MSG_NewsHost *host = cd->host; -#endif - - char *line = NULL; - ce->status = NET_BufferedReadLine (ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - if (!line) - return ce->status; /* no line yet */ - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if ('.' != line[0]) -#ifdef XPCOM_NEWSHOST - news_host->AddSearchableHeader(line); -#else - MSG_AddSearchableHeader (host, line); -#endif - else - { - cd->next_state = NNTP_GET_PROPERTIES; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -PRIVATE int nntp_get_properties (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool setget=FALSE; - - rv = cd->news_host->QueryExtension("SETGET",&setget); - if (NS_SUCCEEDED(rv) && setget) -#else - if (MSG_QueryNewsExtension (cd->host, "SETGET")) -#endif - { - PL_strcpy(cd->output_buffer, "GET" CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_GET_PROPERTIES_RESPONSE; - cd->pause_for_read = TRUE; - } - else - { - /* since GET isn't supported, move on LIST SUBSCRIPTIONS */ - cd->next_state = SEND_LIST_SUBSCRIPTIONS; - cd->pause_for_read = FALSE; - } - return ce->status; -} - -PRIVATE int nntp_get_properties_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - char *line = NULL; - ce->status = NET_BufferedReadLine (ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - if (!line) - return ce->status; /* no line yet */ - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if ('.' != line[0]) - { - char *propertyName = PL_strdup(line); - if (propertyName) - { - char *space = PL_strchr(propertyName, ' '); - if (space) - { - char *propertyValue = space + 1; - *space = '\0'; -#ifdef XPCOM_NEWSHOST - cd->news_host->AddPropertyForGet(propertyName, propertyValue); -#else - MSG_AddPropertyForGet (cd->host, - propertyName, propertyValue); -#endif - } - PR_Free(propertyName); - } - } - else - { - /* all GET properties received, move on to LIST SUBSCRIPTIONS */ - cd->next_state = SEND_LIST_SUBSCRIPTIONS; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -PRIVATE int net_send_list_subscriptions (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - -#if 0 -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool searchable=FALSE; - rv = cd->news_host->QueryExtension("LISTSUBSCR",&listsubscr); - if (NS_SUCCEEDED(rv) && listsubscr) -#else - if (MSG_QueryNewsExtension (cd->host, "LISTSUBSCR")) -#endif -#else - if (0) -#endif - { - PL_strcpy(cd->output_buffer, "LIST SUBSCRIPTIONS" CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = SEND_LIST_SUBSCRIPTIONS_RESPONSE; - cd->pause_for_read = TRUE; - } - else - { - /* since LIST SUBSCRIPTIONS isn't supported, move on to real work */ - cd->next_state = SEND_FIRST_NNTP_COMMAND; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -PRIVATE int net_send_list_subscriptions_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - char *line = NULL; - ce->status = NET_BufferedReadLine (ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - if (!line) - return ce->status; /* no line yet */ - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if ('.' != line[0]) - { -#if 0 - char *urlScheme; - HG56946 - char *url = PR_smprintf ("%s//%s/%s", urlScheme, cd->control_con->hostname, line); - if (url) - MSG_AddSubscribedNewsgroup (cd->pane, url); -#endif - } - else - { - /* all default subscriptions received */ - cd->next_state = SEND_FIRST_NNTP_COMMAND; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -/* figure out what the first command is and send it - * - * returns the status from the NETWrite - */ -PRIVATE int -net_send_first_nntp_command (ActiveEntry *ce) -{ - char *command=0; - NewsConData * cd = (NewsConData *)ce->con_data; - - if (cd->type_wanted == ARTICLE_WANTED) - { -#ifdef XPCOM_NEWSGROUP - const char *group = 0; -#endif - uint32 number = 0; - -#ifdef XPCOM_NEWSGROUP - nsresult rv; - nsIMsgNewsgroup *newsgroup; - rv = cd->news_host->GetNewsGroupAndNumberOfID(cd->path, - &newsgroup, &number); -#else - MSG_NewsGroupAndNumberOfID (cd->pane, cd->path, - &group, &number); -#endif - if (NS_SUCCEEDED(rv) && newsgroup && number) - { - cd->article_num = number; -#ifdef XPCOM_NEWSGROUP - cd->newsgroup = newsgroup; -#else - StrAllocCopy (cd->group_name, group); -#endif - - if (cd->control_con->current_group && !PL_strcmp (cd->control_con->current_group, group)) - cd->next_state = NNTP_SEND_ARTICLE_NUMBER; - else - cd->next_state = NNTP_SEND_GROUP_FOR_ARTICLE; - - cd->pause_for_read = FALSE; - return 0; - } - } - - if(cd->type_wanted == NEWS_POST && !ce->URL_s->post_data) - { - PR_ASSERT(0); - return(-1); - } - else if(cd->type_wanted == NEWS_POST) - { /* posting to the news group */ - StrAllocCopy(command, "POST"); - } - else if(cd->type_wanted == READ_NEWS_RC) - { - if(ce->URL_s->method == URL_POST_METHOD || - PL_strchr(ce->URL_s->address, '?')) - cd->next_state = NEWS_NEWS_RC_POST; - else - cd->next_state = NEWS_DISPLAY_NEWS_RC; - return(0); - } - else if(cd->type_wanted == NEW_GROUPS) - { -#ifdef XPCOM_NEWSHOST - PRTime last_update; - nsresult rv; - - rv = cd->news_host->GetLastUpdatedTime(&last_update); -#else - time_t last_update = - MSG_NewsgroupsLastUpdatedTime(cd->host); -#endif - char small_buf[64]; - PRExplodedTime expandedTime; - - if(!last_update) - { - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_NEWSGROUP_SCAN_ERROR); - cd->next_state = NEWS_ERROR; - return(MK_INTERRUPTED); - } - - /* subtract some hours just to be sure */ - last_update -= NEWGROUPS_TIME_OFFSET; - - { - int64 secToUSec, timeInSec, timeInUSec; - LL_I2L(timeInSec, last_update); - LL_I2L(secToUSec, PR_USEC_PER_SEC); - LL_MUL(timeInUSec, timeInSec, secToUSec); - PR_ExplodeTime(timeInUSec, PR_LocalTimeParameters, &expandedTime); - } - PR_FormatTimeUSEnglish(small_buf, sizeof(small_buf), - "NEWGROUPS %y%m%d %H%M%S", &expandedTime); - - StrAllocCopy(command, small_buf); - - } - else if(cd->type_wanted == LIST_WANTED) - { - - cd->use_fancy_newsgroup_listing = FALSE; -#ifdef XPCOM_NEWSHOST - PRTime last_update; - nsresult rv = cd->news_host->GetLastUpdatedTime(&last_update); - - if (NS_SUCCEEDED(rv) && last_update!=0) -#else - if (MSG_NewsgroupsLastUpdatedTime(cd->host)) -#endif - { - cd->next_state = DISPLAY_NEWSGROUPS; - return(0); - } - else - { -#ifdef BUG_21013 - if(!FE_Confirm(ce->window_id, XP_GetString(XP_CONFIRM_SAVE_NEWSGROUPS))) - { - cd->next_state = NEWS_ERROR; - return(MK_INTERRUPTED); - } -#endif /* BUG_21013 */ - -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool xactive=FALSE; - rv = cd->news_host->QueryExtension("XACTIVE",&xactive); - if (NS_SUCCEEDED(rv) && xactive) -#else - if (MSG_QueryNewsExtension(cd->host, "XACTIVE")) -#endif - { - StrAllocCopy(command, "LIST XACTIVE"); - cd->use_fancy_newsgroup_listing = TRUE; - } - else - { - StrAllocCopy(command, "LIST"); - } - } - } - else if(cd->type_wanted == GROUP_WANTED) - { - /* Don't use MKParse because the news: access URL doesn't follow traditional - * rules. For instance, if the article reference contains a '#', - * the rest of it is lost. - */ - char * slash; -#ifdef XPCOM_NEWSGROUP - char * group_name; - nsresult rv; -#endif - - StrAllocCopy(command, "GROUP "); -#ifdef XPCOM_NEWSGROUP - rv = cd->newsgroup->GetName(&group_name); - slash = PL_strchr(group_name, '/'); -#else - slash = PL_strchr(cd->group_name, '/'); /* look for a slash */ -#endif - cd->first_art = 0; - cd->last_art = 0; - if (slash) - { - *slash = '\0'; - (void) sscanf(slash+1, "%d-%d", &cd->first_art, &cd->last_art); - } - -#ifdef XPCOM_NEWSGROUP - StrAllocCopy (cd->control_con->current_group, group_name); -#else - StrAllocCopy (cd->control_con->current_group, cd->group_name); -#endif - StrAllocCat(command, cd->control_con->current_group); - } - else if (cd->type_wanted == SEARCH_WANTED) - { -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool searchable=FALSE; - rv = cd->news_host->QueryExtension("SEARCH", &searchable); - if (NS_SUCCEEDED(rv) && searchable) -#else - if (MSG_QueryNewsExtension(cd->host, "SEARCH")) -#endif - { - /* use the SEARCH extension */ - char *slash = PL_strchr (cd->command_specific_data, '/'); - if (slash) - { - char *allocatedCommand = MSG_UnEscapeSearchUrl (slash + 1); - if (allocatedCommand) - { - StrAllocCopy (command, allocatedCommand); - PR_Free(allocatedCommand); - } - } - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_SEARCH_RESPONSE; - } - else - { - nsresult rv; - char *group_name; - - /* for XPAT, we have to GROUP into the group before searching */ - StrAllocCopy (command, "GROUP "); -#ifdef XPCOM_NEWSGROUP - rv = cd->newsgroup->GetName(&group_name); - StrAllocCat (command, group_name); -#else - StrAllocCat (command, cd->group_name); -#endif - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_XPAT_SEND; - } - } - else if (cd->type_wanted == PRETTY_NAMES_WANTED) - { -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool listpretty=FALSE; - rv = cd->news_host->QueryExtension("LISTPRETTY",&listpretty); - if (NS_SUCCEEDED(rv) && listpretty) -#else - if (MSG_QueryNewsExtension(cd->host, "LISTPRETTY")) -#endif - { - cd->next_state = NNTP_LIST_PRETTY_NAMES; - return 0; - } - else - { - PR_ASSERT(FALSE); - cd->next_state = NNTP_ERROR; - } - } - else if (cd->type_wanted == PROFILE_WANTED) - { - char *slash = PL_strchr (cd->command_specific_data, '/'); - if (slash) - { - char *allocatedCommand = MSG_UnEscapeSearchUrl (slash + 1); - if (allocatedCommand) - { - StrAllocCopy (command, allocatedCommand); - PR_Free(allocatedCommand); - } - } - cd->next_state = NNTP_RESPONSE; - if (PL_strstr(ce->URL_s->address, "PROFILE NEW")) - cd->next_state_after_response = NNTP_PROFILE_ADD_RESPONSE; - else - cd->next_state_after_response = NNTP_PROFILE_DELETE_RESPONSE; - } - else if (cd->type_wanted == IDS_WANTED) - { -#ifndef XPCOM_NEWSGROUP - char *slash = PL_strchr(cd->group_name, '/'); /* look for a slash */ - if (slash) - *slash = '\0'; -#endif - cd->next_state = NNTP_LIST_GROUP; - return 0; - } - else /* article or cancel */ - { - if (cd->type_wanted == CANCEL_WANTED) - StrAllocCopy(command, "HEAD "); - else - StrAllocCopy(command, "ARTICLE "); - if (*cd->path != '<') - StrAllocCat(command,"<"); - StrAllocCat(command, cd->path); - if (PL_strchr(command+8, '>')==0) - StrAllocCat(command,">"); - } - - StrAllocCat(command, CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket, command, PL_strlen(command)); - NNTP_LOG_WRITE(command); - PR_Free(command); - - cd->next_state = NNTP_RESPONSE; - if (cd->type_wanted != SEARCH_WANTED && cd->type_wanted != PROFILE_WANTED) - cd->next_state_after_response = SEND_FIRST_NNTP_COMMAND_RESPONSE; - cd->pause_for_read = TRUE; - return(ce->status); - -} /* sent first command */ - - -/* interprets the server response from the first command sent - * - * returns negative if the server responds unexpectedly - */ -PRIVATE int -net_send_first_nntp_command_response (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - int major_opcode = MK_NNTP_RESPONSE_TYPE(cd->response_code); - - if((major_opcode == MK_NNTP_RESPONSE_TYPE_CONT && - cd->type_wanted == NEWS_POST) - || (major_opcode == MK_NNTP_RESPONSE_TYPE_OK && - cd->type_wanted != NEWS_POST) ) - { - - cd->next_state = SETUP_NEWS_STREAM; - cd->some_protocol_succeeded = TRUE; - - return(0); /* good */ - } - else - { - if (cd->response_code == MK_NNTP_RESPONSE_GROUP_NO_GROUP && - cd->type_wanted == GROUP_WANTED) -#ifdef XPCOM_NEWSHOST - cd->news_host->GroupNotFound(cd->control_con->current_group, - TRUE /* opening */); -#else - MSG_GroupNotFound(cd->pane, cd->host, - cd->control_con->current_group, TRUE /* opening group */); -#endif - return net_display_html_error_state(ce); - } - - /* start the graph progress indicator - */ - FE_GraphProgressInit(ce->window_id, ce->URL_s, ce->URL_s->content_length); - cd->destroy_graph_progress = TRUE; /* we will need to destroy it */ - cd->original_content_length = ce->URL_s->content_length; - - return(ce->status); -} - - -PRIVATE int -net_send_group_for_article (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - -#ifdef XPCOM_NEWSGROUP - nsresult rv; - PR_FREEIF(cd->control_con->current_group); - rv = cd->newsgroup->GetName(&cd->control_con->current_group); - PR_ASSERT(NS_SUCCEEEDED(rv)); -#else - StrAllocCopy (cd->control_con->current_group, cd->group_name); -#endif - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "GROUP %.512s" CRLF, - cd->control_con->current_group); - - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer, - PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE; - cd->pause_for_read = TRUE; - - return(ce->status); -} - -PRIVATE int -net_send_group_for_article_response (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - /* ignore the response code and continue - */ - cd->next_state = NNTP_SEND_ARTICLE_NUMBER; - - return(0); -} - - -PRIVATE int -net_send_article_number (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "ARTICLE %lu" CRLF, - cd->article_num); - - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer, - PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = SEND_FIRST_NNTP_COMMAND_RESPONSE; - cd->pause_for_read = TRUE; - - return(ce->status); -} - - - - -static char * -news_generate_news_url_fn (const char *dest, void *closure, - MimeHeaders *headers) -{ - ActiveEntry *ce = (ActiveEntry *) closure; - /* NOTE: you can't use NewsConData here, because ce might refer - to a file in the disk cache rather than an NNTP connection. */ - char *prefix = NET_ParseURL(ce->URL_s->address, - (GET_PROTOCOL_PART | GET_HOST_PART)); - char *new_dest = NET_Escape (dest, URL_XALPHAS); - char *result = (char *) PR_Malloc (PL_strlen (prefix) + - (new_dest ? PL_strlen (new_dest) : 0) - + 40); - if (result && prefix) - { - PL_strcpy (result, prefix); - if (prefix[PL_strlen(prefix) - 1] != ':') - /* If there is a host, it must be terminated with a slash. */ - PL_strcat (result, "/"); - PL_strcat (result, new_dest); - } - FREEIF (prefix); - FREEIF (new_dest); - return result; -} - -static char * -news_generate_reference_url_fn (const char *dest, void *closure, - MimeHeaders *headers) -{ - return news_generate_news_url_fn (dest, closure, headers); -} - - - -/* Initiates the stream and sets state for the transfer - * - * returns negative if unable to setup stream - */ -PRIVATE int -net_setup_news_stream (ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - if (cd->type_wanted == NEWS_POST) - { - NET_ClearReadSelect(ce->window_id, ce->socket); - NET_SetConnectSelect(ce->window_id, ce->socket); -#ifdef XP_WIN - cd->calling_netlib_all_the_time = TRUE; -#if 0 - /* This should be handled by NET_SetCallNetlibAllTheTime */ - net_call_all_the_time_count++; -#endif - NET_SetCallNetlibAllTheTime(ce->window_id,"mknews"); -#endif /* XP_WIN */ - - ce->con_sock = ce->socket; - cd->next_state = NNTP_SEND_POST_DATA; - - NET_Progress(ce->window_id, XP_GetString(MK_MSG_DELIV_NEWS)); - } - else if(cd->type_wanted == LIST_WANTED) - { - if (cd->use_fancy_newsgroup_listing) - cd->next_state = NNTP_LIST_XACTIVE_RESPONSE; - else - cd->next_state = NNTP_READ_LIST_BEGIN; - } - else if(cd->type_wanted == GROUP_WANTED) - cd->next_state = NNTP_XOVER_BEGIN; - else if(cd->type_wanted == NEW_GROUPS) - cd->next_state = NNTP_NEWGROUPS_BEGIN; - else if(cd->type_wanted == ARTICLE_WANTED || - cd->type_wanted == CANCEL_WANTED) - cd->next_state = NNTP_BEGIN_ARTICLE; - else if (cd->type_wanted == SEARCH_WANTED) - cd->next_state = NNTP_XPAT_SEND; - else if (cd->type_wanted == PRETTY_NAMES_WANTED) - cd->next_state = NNTP_LIST_PRETTY_NAMES; - else if (cd->type_wanted == PROFILE_WANTED) - { - if (PL_strstr(ce->URL_s->address, "PROFILE NEW")) - cd->next_state = NNTP_PROFILE_ADD; - else - cd->next_state = NNTP_PROFILE_DELETE; - } - else - { - PR_ASSERT(0); - return -1; - } - - return(0); /* good */ -} - -/* This doesn't actually generate HTML - but it is our hook into the - message display code, so that we can get some values out of it - after the headers-to-be-displayed have been parsed. - */ -static char * -news_generate_html_header_fn (const char *dest, void *closure, - MimeHeaders *headers) -{ - ActiveEntry *ce = (ActiveEntry *) closure; - /* NOTE: you can't always use NewsConData here if, because ce might - refer to a file in the disk cache rather than an NNTP connection. */ - NewsConData *cd = 0; - - PR_ASSERT(ce->protocol == NEWS_TYPE_URL || - ce->protocol == FILE_CACHE_TYPE_URL || - ce->protocol == MEMORY_CACHE_TYPE_URL); - if (ce->protocol == NEWS_TYPE_URL) - cd = (NewsConData *)ce->con_data; - - if (cd && cd->type_wanted == CANCEL_WANTED) - { - /* Save these for later (used in NEWS_DO_CANCEL state.) */ - cd->cancel_from = - MimeHeaders_get(headers, HEADER_FROM, FALSE, FALSE); - cd->cancel_newsgroups = - MimeHeaders_get(headers, HEADER_NEWSGROUPS, FALSE, TRUE); - cd->cancel_distribution = - MimeHeaders_get(headers, HEADER_DISTRIBUTION, FALSE, FALSE); - cd->cancel_id = - MimeHeaders_get(headers, HEADER_MESSAGE_ID, FALSE, FALSE); - } - else - { - MSG_Pane *messagepane = ce->URL_s->msg_pane; - if (!messagepane) - { - NNTP_LOG_NOTE(("news_generate_html_header_fn: url->msg_pane NULL for URL: %s", ce->URL_s->address)); - messagepane = MSG_FindPane(ce->window_id, MSG_MESSAGEPANE); - } - PR_ASSERT (!cd || cd->type_wanted == ARTICLE_WANTED); - - if (messagepane) - MSG_ActivateReplyOptions (messagepane, headers); - } - return 0; -} - - - -XP_Bool NET_IsNewsMessageURL (const char *url); - -int -net_InitializeNewsFeData (ActiveEntry * ce) -{ - MimeDisplayOptions *opt; - - if (!NET_IsNewsMessageURL (ce->URL_s->address)) - { - PR_ASSERT(0); - return -1; - } - - if (ce->URL_s->fe_data) - { - PR_ASSERT(0); - return -1; - } - - opt = PR_NEW (MimeDisplayOptions); - if (!opt) return MK_OUT_OF_MEMORY; - memset (opt, 0, sizeof(*opt)); - - opt->generate_reference_url_fn = news_generate_reference_url_fn; - opt->generate_news_url_fn = news_generate_news_url_fn; - opt->generate_header_html_fn = 0; - opt->generate_post_header_html_fn = news_generate_html_header_fn; - opt->html_closure = ce; - - ce->URL_s->fe_data = opt; - return 0; -} - - -PRIVATE int -net_begin_article(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - if (cd->type_wanted != ARTICLE_WANTED && - cd->type_wanted != CANCEL_WANTED) - return 0; - - /* Set up the HTML stream - */ - FREEIF (ce->URL_s->content_type); - ce->URL_s->content_type = PL_strdup (MESSAGE_RFC822); - -#ifdef NO_ARTICLE_CACHEING - ce->format_out = CLEAR_CACHE_BIT (ce->format_out); -#endif - - if (cd->type_wanted == CANCEL_WANTED) - { - PR_ASSERT(ce->format_out == FO_PRESENT); - ce->format_out = FO_PRESENT; - } - - /* Only put stuff in the fe_data if this URL is going to get - passed to MIME_MessageConverter(), since that's the only - thing that knows what to do with this structure. */ - if (CLEAR_CACHE_BIT(ce->format_out) == FO_PRESENT) - { - ce->status = net_InitializeNewsFeData (ce); - if (ce->status < 0) - { - /* #### what error message? */ - return ce->status; - } - } - - cd->stream = NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - PR_ASSERT (cd->stream); - if (!cd->stream) return -1; - - cd->next_state = NNTP_READ_ARTICLE; - - return 0; -} - - -PRIVATE int -net_news_begin_authorize(ActiveEntry * ce) -{ - char * command = 0; - NewsConData * cd = (NewsConData *)ce->con_data; - char * username = 0; - char * cp; - -#ifdef CACHE_NEWSGRP_PASSWORD - /* reuse cached username from newsgroup folder info*/ - if (cd->pane && - (!net_news_last_username_probably_valid || - (last_username_hostname && - PL_strcasecmp(last_username_hostname, cd->control_con->hostname)))) { -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->GetUsername(&username); -#else - username = HG63218 (MSG_GetNewsgroupUsername(cd->pane)); -#endif - if (username && last_username && - !PL_strcmp (username, last_username) && - (cd->previous_response_code == MK_NNTP_RESPONSE_AUTHINFO_OK || - cd->previous_response_code == MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_OK || - cd->previous_response_code == MK_NNTP_RESPONSE_GROUP_SELECTED)) { - FREEIF (username); -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(NULL); - cd->newsgroup->SetPassword(NULL); -#else - MSG_SetNewsgroupUsername(cd->pane, NULL); - MSG_SetNewsgroupPassword(cd->pane, NULL); -#endif - } - } -#endif - - if (cd->pane) - { - /* Following a snews://username:password@newhost.domain.com/newsgroup.topic - * backend calls MSG_Master::FindNewsHost() to locate the folderInfo and setting - * the username/password to the newsgroup folderInfo - */ -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->GetUsername(&username); -#else - username = HG63218 (MSG_GetNewsgroupUsername(cd->pane)); -#endif - if (username && *username) - { - StrAllocCopy(last_username, username); - StrAllocCopy(last_username_hostname, cd->control_con->hostname); - /* use it for only once */ -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(NULL); -#else - MSG_SetNewsgroupUsername(cd->pane, NULL); -#endif - } - else { - /* empty username; free and clear it so it will work with - * our logic - */ - FREEIF(username); - } - } - - /* If the URL/cd->control_con->hostname contains @ this must be triggered - * from the bookmark. Use the embed username if we could. - */ - if ((cp = PL_strchr(cd->control_con->hostname, '@')) != NULL) - { - /* in this case the username and possibly - * the password are in the URL - */ - char * colon; - *cp = '\0'; - - colon = PL_strchr(cd->control_con->hostname, ':'); - if(colon) - *colon = '\0'; - - StrAllocCopy(username, cd->control_con->hostname); - StrAllocCopy(last_username, cd->control_con->hostname); - StrAllocCopy(last_username_hostname, cp+1); - - *cp = '@'; - - if(colon) - *colon = ':'; - } - /* reuse global saved username if we think it is - * valid - */ - if (!username && net_news_last_username_probably_valid) - { - if( last_username_hostname && - !PL_strcasecmp(last_username_hostname, cd->control_con->hostname) ) - StrAllocCopy(username, last_username); - else - net_news_last_username_probably_valid = FALSE; - } - - - if (!username) { -#if defined(CookiesAndSignons) - username = SI_Prompt(ce->window_id, - XP_GetString(XP_PROMPT_ENTER_USERNAME), - "", - cd->control_con->hostname); - -#else - username = FE_Prompt(ce->window_id, - XP_GetString(XP_PROMPT_ENTER_USERNAME), - username ? username : ""); -#endif - - /* reset net_news_last_username_probably_valid to false */ - net_news_last_username_probably_valid = FALSE; - if(!username) { - ce->URL_s->error_msg = - NET_ExplainErrorDetails( MK_NNTP_AUTH_FAILED, "Aborted by user"); - return(MK_NNTP_AUTH_FAILED); - } - else { - StrAllocCopy(last_username, username); - StrAllocCopy(last_username_hostname, cd->control_con->hostname); - } - } - -#ifdef CACHE_NEWSGRP_PASSWORD -#ifdef XPCOM_NEWSGROUP - if (NS_SUCCEEDED(cd->newsgroup->GetUsername(&username)) { -#else - if (cd->pane && !MSG_GetNewsgroupUsername(cd->pane)) { -#endif - munged_username = HG64643 (username); -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(munged_username); -#else - MSG_SetNewsgroupUsername(cd->pane, munged_username); -#endif - PR_FreeIF(munged_username); - } -#endif - - StrAllocCopy(command, "AUTHINFO user "); - StrAllocCat(command, username); - StrAllocCat(command, CRLF); - - ce->status = (int) NET_BlockingWrite(ce->socket, command, PL_strlen(command)); - NNTP_LOG_WRITE(command); - - FREE(command); - FREE(username); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_AUTHORIZE_RESPONSE;; - - cd->pause_for_read = TRUE; - - return ce->status; -} - -PRIVATE int -net_news_authorize_response(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - if (MK_NNTP_RESPONSE_AUTHINFO_OK == cd->response_code || - MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_OK == cd->response_code) - { - /* successful login */ - nsresult rv; - PRBool pushAuth; - /* If we're here because the host demanded authentication before we - * even sent a single command, then jump back to the beginning of everything - */ - rv = cd->news_host->IsPushAuth(&pushAuth); - - if (!cd->mode_reader_performed) - cd->next_state = NNTP_SEND_MODE_READER; - /* If we're here because the host needs pushed authentication, then we - * should jump back to SEND_LIST_EXTENSIONS - */ -#ifdef XPCOM_NEWSHOST - else if (NS_SUCCEEDED(rv) && pushAuth) -#else - else if (MSG_GetNewsHostPushAuth(cd->host)) -#endif - cd->next_state = SEND_LIST_EXTENSIONS; - else - /* Normal authentication */ - cd->next_state = SEND_FIRST_NNTP_COMMAND; - - net_news_last_username_probably_valid = TRUE; - return(0); - } - else if (MK_NNTP_RESPONSE_AUTHINFO_CONT == cd->response_code) - { - /* password required - */ - char * command = 0; - char * password = 0; - char * cp; - - if (cd->pane) - { -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->GetPassword(&password); - password = HG63218 (password); - cd->newsgroup->SetPassword(NULL); -#else - password = HG63218 (MSG_GetNewsgroupPassword(cd->pane)); - /* use it only once */ - MSG_SetNewsgroupPassword(cd->pane, NULL); -#endif - } - - if (net_news_last_username_probably_valid - && last_password - && last_password_hostname - && !PL_strcasecmp(last_password_hostname, cd->control_con->hostname)) - { -#ifdef CACHE_NEWSGRP_PASSWORD - if (cd->pane) -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->GetPassword(&password); - password = HG63218 (password); -#else - password = HG63218(MSG_GetNewsgroupPassword(cd->pane)); -#endif -#else - StrAllocCopy(password, last_password); -#endif - } - else if ((cp = PL_strchr(cd->control_con->hostname, '@')) != NULL) - { - /* in this case the username and possibly - * the password are in the URL - */ - char * colon; - *cp = '\0'; - - colon = PL_strchr(cd->control_con->hostname, ':'); - if(colon) - { - *colon = '\0'; - - StrAllocCopy(password, colon+1); - StrAllocCopy(last_password, colon+1); - StrAllocCopy(last_password_hostname, cp+1); - - *colon = ':'; - } - - *cp = '@'; - - } - if (!password) { - password = -#if defined(CookiesAndSignons) - password = SI_PromptPassword - (ce->window_id, - XP_GetString - (XP_PLEASE_ENTER_A_PASSWORD_FOR_NEWS_SERVER_ACCESS), - cd->control_con->hostname, - TRUE, TRUE); -#else - FE_PromptPassword(ce->window_id, XP_GetString( - XP_PLEASE_ENTER_A_PASSWORD_FOR_NEWS_SERVER_ACCESS ) ); -#endif - net_news_last_username_probably_valid = FALSE; - } - - if(!password) { - ce->URL_s->error_msg = - NET_ExplainErrorDetails(MK_NNTP_AUTH_FAILED, "Aborted by user"); - return(MK_NNTP_AUTH_FAILED); - } - else { - StrAllocCopy(last_password, password); - StrAllocCopy(last_password_hostname, cd->control_con->hostname); - } - -#ifdef CACHE_NEWSGRP_PASSWORD -#ifdef XPCOM_NEWSGROUP - char *garbage_password; - nsresult rv; - rv = cd->newsgroup->GetPassword(&garbage_password); - if (!NS_SUCCEEDED(rv)) { - PR_Free(garbage_password); - munged_password = HG64643(password); - cd->newsgroup->SetPassword(munged_password); -#else - if (cd->pane && !MSG_GetNewsgroupPassword(cd->pane)) { - munged_password = HG64643(password); - MSG_SetNewsgroupPassword(cd->pane, munged_password); -#endif - PR_FreeIF(munged_password); - } -#endif - - StrAllocCopy(command, "AUTHINFO pass "); - StrAllocCat(command, password); - StrAllocCat(command, CRLF); - - ce->status = (int) NET_BlockingWrite(ce->socket, command, PL_strlen(command)); - NNTP_LOG_WRITE(command); - - FREE(command); - FREE(password); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_PASSWORD_RESPONSE; - cd->pause_for_read = TRUE; - - return ce->status; - } - else - { - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_NNTP_AUTH_FAILED, - cd->response_txt ? cd->response_txt : ""); -#ifdef CACHE_NEWSGRP_PASSWORD - if (cd->pane) -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(NULL); -#else - MSG_SetNewsgroupUsername(cd->pane, NULL); -#endif -#endif - net_news_last_username_probably_valid = FALSE; - - return(MK_NNTP_AUTH_FAILED); - } - - PR_ASSERT(0); /* should never get here */ - return(-1); - -} - -PRIVATE int -net_news_password_response(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - if (MK_NNTP_RESPONSE_AUTHINFO_OK == cd->response_code || - MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_OK == cd->response_code) - { - /* successful login */ - nsresult rv = NS_OK; - PRBool pushAuth; - /* If we're here because the host demanded authentication before we - * even sent a single command, then jump back to the beginning of everything - */ - rv = cd->news_host->IsPushAuth(&pushAuth); - - if (!cd->mode_reader_performed) - cd->next_state = NNTP_SEND_MODE_READER; - /* If we're here because the host needs pushed authentication, then we - * should jump back to SEND_LIST_EXTENSIONS - */ -#ifdef XPCOM_NEWSHOST - else if (NS_SUCCEEDED(rv) && pushAuth) -#else - else if (MSG_GetNewsHostPushAuth(cd->host)) -#endif - cd->next_state = SEND_LIST_EXTENSIONS; - else - /* Normal authentication */ - cd->next_state = SEND_FIRST_NNTP_COMMAND; - - net_news_last_username_probably_valid = TRUE; -#ifdef XPCOM_XOVER - rv = cd->xover_parser->Reset(); -#else - MSG_ResetXOVER( ce->URL_s->msg_pane, &cd->xover_parse_state ); -#endif - return(0); - } - else - { - ce->URL_s->error_msg = NET_ExplainErrorDetails( - MK_NNTP_AUTH_FAILED, - cd->response_txt ? cd->response_txt : ""); -#ifdef CACHE_NEWSGRP_PASSWORD - if (cd->pane) -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetPassword(NULL); -#else - MSG_SetNewsgroupPassword(cd->pane, NULL); -#endif -#endif - return(MK_NNTP_AUTH_FAILED); - } - - PR_ASSERT(0); /* should never get here */ - return(-1); -} - -PRIVATE int -net_display_newsgroups (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - cd->next_state = NEWS_DONE; - cd->pause_for_read = FALSE; - - NNTP_LOG_NOTE(("about to display newsgroups. path: %s",cd->path)); - -#if 0 - /* #### Now ignoring "news:alt.fan.*" - Need to open the root tree of the default news host and keep - opening one child at each level until we've exhausted the - wildcard... - */ - if(rv < 0) - return(rv); - else -#endif - return(MK_DATA_LOADED); /* all finished */ -} - -PRIVATE int -net_newgroups_begin (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - cd->next_state = NNTP_NEWGROUPS; - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_RECEIVE_NEWSGROUP)); - - ce->bytes_received = 0; - - return(ce->status); - -} - -PRIVATE int -net_process_newgroups (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - char *line, *s, *s1=NULL, *s2=NULL, *flag=NULL; - int32 oldest, youngest; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if(!line) - return(ce->status); /* no line yet */ - - if(ce->status<0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - /* End of list? - */ - if (line[0]=='.' && line[1]=='\0') - { - cd->pause_for_read = FALSE; -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool xactive=FALSE; - rv = cd->news_host->QueryExtension("XACTIVE",&xactive); - if (NS_SUCCEEDED(rv) && xactive) -#else - if (MSG_QueryNewsExtension(cd->host, "XACTIVE")) -#endif - { -#ifdef XPCOM_NEWSHOST - nsresult rv; - rv = cd->news_host->GetFirstGroupNeedingExtraInfo(&cd->newsgroup); -#else - cd->group_name = MSG_GetFirstGroupNeedingExtraInfo(cd->host); -#endif - if (NS_SUCCEEDED(rv) && cd->newsgroup) - { - cd->next_state = NNTP_LIST_XACTIVE; -#ifdef DEBUG_bienvenu1 - PR_LogPrint("listing xactive for %s\n", cd->group_name); -#endif - return 0; - } - } - cd->next_state = NEWS_DONE; - - if(ce->bytes_received == 0) - { - /* #### no new groups */ - } - - if(ce->status > 0) - return MK_DATA_LOADED; - else - return ce->status; - } - else if (line [0] == '.' && line [1] == '.') - /* The NNTP server quotes all lines beginning with "." by doubling it. */ - line++; - - /* almost correct - */ - if(ce->status > 1) - { - ce->bytes_received += ce->status; - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, ce->status, ce->URL_s->content_length); - } - - /* format is "rec.arts.movies.past-films 7302 7119 y" - */ - s = PL_strchr (line, ' '); - if (s) - { - *s = 0; - s1 = s+1; - s = PL_strchr (s1, ' '); - if (s) - { - *s = 0; - s2 = s+1; - s = PL_strchr (s2, ' '); - if (s) - { - *s = 0; - flag = s+1; - } - } - } - youngest = s2 ? atol(s1) : 0; - oldest = s1 ? atol(s2) : 0; - - ce->bytes_received++; /* small numbers of groups never seem - * to trigger this - */ - -#ifdef XPCOM_NEWSHOST - cd->news_host->AddNewNewsgroup(line, oldest, youngest, flag, PR_FALSE); -#else - MSG_AddNewNewsGroup(ce->URL_s->msg_pane, cd->host, - line, oldest, youngest, flag, FALSE); -#endif -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool xactive=FALSE; - rv = cd->news_host->QueryExtension("XACTIVE",&xactive); - if (NS_SUCCEEDED(rv) && xactive) -#else - if (MSG_QueryNewsExtension(cd->host, "XACTIVE")) -#endif - { -#ifdef XPCOM_NEWSHOST - cd->news_host->SetGroupNeedsExtraInfo(line, TRUE); -#else - MSG_SetGroupNeedsExtraInfo(cd->host, line, TRUE); -#endif - } - return(ce->status); -} - - -/* Ahhh, this like print's out the headers and stuff - * - * always returns 0 - */ -PRIVATE int -net_read_news_list_begin (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - cd->next_state = NNTP_READ_LIST; - - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_RECEIVE_NEWSGROUP)); - - return(ce->status); - - -} - -/* display a list of all or part of the newsgroups list - * from the news server - */ -PRIVATE int -net_read_news_list (ActiveEntry *ce) -{ - char * line; - char * description; - int i=0; - NewsConData * cd = (NewsConData *)ce->con_data; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*) &cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if(!line) - return(ce->status); /* no line yet */ - - if(ce->status<0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - /* End of list? */ - if (line[0]=='.' && line[1]=='\0') - { -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool listpnames=FALSE; - rv = cd->news_host->QueryExtension("LISTPNAMES",&listpnames); - if (NS_SUCCEEDED(rv) && listpnames) -#else - if (MSG_QueryNewsExtension(cd->host, "LISTPNAMES")) -#endif - { - cd->next_state = NNTP_LIST_PRETTY_NAMES; - } - else - { - cd->next_state = DISPLAY_NEWSGROUPS; - } - cd->pause_for_read = FALSE; - - return 0; - } - else if (line [0] == '.' && line [1] == '.') - /* The NNTP server quotes all lines beginning with "." by doubling it. */ - line++; - - /* almost correct - */ - if(ce->status > 1) - { - ce->bytes_received += ce->status; - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, ce->status, ce->URL_s->content_length); - } - - /* find whitespace seperator if it exits */ - for(i=0; line[i] != '\0' && !NET_IS_SPACE(line[i]); i++) - ; /* null body */ - - if(line[i] == '\0') - description = &line[i]; - else - description = &line[i+1]; - - line[i] = 0; /* terminate group name */ - - /* store all the group names - */ -#ifdef XPCOM_NEWSHOST - cd->news_host->AddNewNewsgroup(line, 0, 0, "", FALSE); -#else - MSG_AddNewNewsGroup(ce->URL_s->msg_pane, cd->host, - line, 0, 0, "", FALSE); -#endif - - - return(ce->status); -} - - - - -/* start the xover command - */ -PRIVATE int -net_read_xover_begin (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - int32 count; /* Response fields */ - - /* Make sure we never close and automatically reopen the connection at this - point; we'll confuse libmsg too much... */ - - cd->some_protocol_succeeded = TRUE; - - /* We have just issued a GROUP command and read the response. - Now parse that response to help decide which articles to request - xover data for. - */ - sscanf(cd->response_txt, - "%d %d %d", - &count, - &cd->first_possible_art, - &cd->last_possible_art); - - /* We now know there is a summary line there; make sure it has the - right numbers in it. */ -#ifdef XPCOM_NEWSHOST - nsresult rv; - char *group_name; - cd->newsgroup->GetName(&group_name); - - cd->news_host->DisplaySubscribedGroup(group_name, - cd->first_possible_art, - cd->last_possible_art, - count, TRUE); - PR_Free(group_name); -#else - ce->status = MSG_DisplaySubscribedGroup(cd->pane, - cd->host, - cd->group_name, - cd->first_possible_art, - cd->last_possible_art, - count, TRUE); -#endif - if (ce->status < 0) return ce->status; - - cd->num_loaded = 0; - cd->num_wanted = net_NewsChunkSize > 0 ? net_NewsChunkSize : 1L << 30; - - cd->next_state = NNTP_FIGURE_NEXT_CHUNK; - cd->pause_for_read = FALSE; - return 0; -} - - - -PRIVATE int -net_figure_next_chunk(ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - nsresult rv; - char *host_and_port = NET_ParseURL (ce->URL_s->address, GET_HOST_PART); - - if (!host_and_port) return MK_OUT_OF_MEMORY; - - if (cd->first_art > 0) { -#ifdef XPCOM_NEWSPARSE - nsresult rv; - /* XXX - parse state stored in MSG_Pane cd->pane */ - rv = cd->article_list->AddToKnownArticles(cd->first_art, - cd->last_art); - -#else - ce->status = MSG_AddToKnownArticles(cd->pane, cd->news_host, - cd->group_name, - cd->first_art, cd->last_art); -#endif - if (ce->status < 0) { - FREEIF (host_and_port); - return ce->status; - } - } - - - if (cd->num_loaded >= cd->num_wanted) { - FREEIF (host_and_port); - cd->next_state = NEWS_PROCESS_XOVER; - cd->pause_for_read = FALSE; - return 0; - } - - -#ifdef XPCOM_NEWSPARSE - /* XXX - parse state stored in MSG_Pane cd->pane */ - rv = - cd->article_list->GetRangeOfArtsToDownload(&ce->status, - cd->first_possible_art, - cd->last_possible_art, - cd->num_wanted - - cd->num_loaded, - &(cd->first_art), - &(cd->last_art)); -#else - ce->status = MSG_GetRangeOfArtsToDownload(cd->pane, - (void **)&cd->xover_parser, - cd->news_host, - cd->group_name, - cd->first_possible_art, - cd->last_possible_art, - cd->num_wanted - cd->num_loaded, - &(cd->first_art), - &(cd->last_art)); -#endif - if (ce->status < 0) { - FREEIF (host_and_port); - return ce->status; - } - - - if (cd->first_art <= 0 || cd->first_art > cd->last_art) { - /* Nothing more to get. */ - FREEIF (host_and_port); - cd->next_state = NEWS_PROCESS_XOVER; - cd->pause_for_read = FALSE; - return 0; - } - - NNTP_LOG_NOTE((" Chunk will be (%ld-%ld)", cd->first_art, cd->last_art)); - - cd->article_num = cd->first_art; -#ifdef XPCOM_XOVER - rv = NS_NewMsgXOVERParser(&cd->xover_parser, - cd->news_host, cd->newsgroup, - cd->first_art, cd->last_art, - cd->first_possible_art, - cd->last_possible_art); - /* convert nsresult->status */ - ce->status = !NS_SUCCEEDED(rv); -#else - ce->status = MSG_InitXOVER (cd->pane, - cd->news_host, cd->group_name, - cd->first_art, cd->last_art, - cd->first_possible_art, cd->last_possible_art, - &cd->xover_parse_state); -#endif - FREEIF (host_and_port); - - if (ce->status < 0) { - return ce->status; - } - - cd->pause_for_read = FALSE; - if (cd->control_con->no_xover) cd->next_state = NNTP_READ_GROUP; - else cd->next_state = NNTP_XOVER_SEND; - - return 0; -} - -PRIVATE int -net_xover_send (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "XOVER %ld-%ld" CRLF, - cd->first_art, - cd->last_art); - - /* printf("XOVER %ld-%ld\n", cd->first_art, cd->last_art); */ - - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_XOVER_RESPONSE; - cd->pause_for_read = TRUE; - - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_RECEIVE_LISTARTICLES)); - - return((int) NET_BlockingWrite(ce->socket, - cd->output_buffer, - PL_strlen(cd->output_buffer))); - NNTP_LOG_WRITE(cd->output_buffer); - -} - -/* see if the xover response is going to return us data - * if the proper code isn't returned then assume xover - * isn't supported and use - * normal read_group - */ -PRIVATE int -net_read_xover_response (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - -#ifdef TEST_NO_XOVER_SUPPORT - cd->response_code = MK_NNTP_RESPONSE_CHECK_ERROR; /* pretend XOVER generated an error */ -#endif - - if(cd->response_code != MK_NNTP_RESPONSE_XOVER_OK) - { - /* If we didn't get back "224 data follows" from the XOVER request, - then that must mean that this server doesn't support XOVER. Or - maybe the server's XOVER support is busted or something. So, - in that case, fall back to the very slow HEAD method. - - But, while debugging here at HQ, getting into this state means - something went very wrong, since our servers do XOVER. Thus - the assert. - */ - /*PR_ASSERT (0);*/ - cd->next_state = NNTP_READ_GROUP; - cd->control_con->no_xover = TRUE; - } - else - { - cd->next_state = NNTP_XOVER; - } - - return(0); /* continue */ -} - -/* process the xover list as it comes from the server - * and load it into the sort list. - */ -PRIVATE int -net_read_xover (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - char *line; - nsresult rv; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, - (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - NNTP_LOG_NOTE(("received unexpected TCP EOF!!!! aborting!")); - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if(!line) - { - return(ce->status); /* no line yet or TCP error */ - } - - if(ce->status<0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, - SOCKET_ERRNO); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - if(line[0] == '.' && line[1] == '\0') - { - cd->next_state = NNTP_FIGURE_NEXT_CHUNK; - cd->pause_for_read = FALSE; - return(0); - } - else if (line [0] == '.' && line [1] == '.') - /* The NNTP server quotes all lines beginning with "." by doubling it. */ - line++; - - /* almost correct - */ - if(ce->status > 1) - { - ce->bytes_received += ce->status; - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, ce->status, - ce->URL_s->content_length); - } - -#ifdef XPCOM_XOVER - rv = cd->xover_parser->Process(line, &ce->status); - PR_ASSERT(NS_SUCCEEDED(rv)); -#else - ce->status = MSG_ProcessXOVER (cd->pane, line, &cd->xover_parse_state); -#endif - - cd->num_loaded++; - - return ce->status; /* keep going */ -} - - -/* Finished processing all the XOVER data. - */ -PRIVATE int -net_process_xover (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - nsresult rv; - -#ifdef XPCOM_XOVER - /* xover_parse_state stored in MSG_Pane cd->pane */ - rv = cd->xover_parser->Finish(0,&ce->status); -#else - /* if (cd->xover_parse_state) { ### dmb - we need a different check */ - ce->status = MSG_FinishXOVER (cd->pane, &cd->xover_parse_state, 0); - PR_ASSERT (!cd->xover_parse_state); -#endif - if (NS_SUCCEEDED(rv) && ce->status < 0) return ce->status; - - cd->next_state = NEWS_DONE; - - return(MK_DATA_LOADED); -} - - -PRIVATE int net_profile_add (ActiveEntry *ce) -{ -#if 0 - NewsConData *cd = (NewsConData*) ce->con_data; - char *slash = PL_strrchr(ce->URL_s->address, '/'); - if (slash) - { - PL_strcpy (cd->output_buffer, slash + 1); - PL_strcat (cd->output_buffer, CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_PROFILE_ADD_RESPONSE; - cd->pause_for_read = TRUE; - } - else - { - cd->next_state = NNTP_ERROR; - ce->status = -1; - } - - return ce->status; -#else - PR_ASSERT(FALSE); - return -1; -#endif -} - -PRIVATE int net_profile_add_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - if (MK_NNTP_RESPONSE_TYPE(cd->response_code) == MK_NNTP_RESPONSE_TYPE_OK) - { -#ifdef XPCOM_NEWSHOST - cd->news_host->AddProfileGroup(cd->response_txt); -#else - MSG_AddProfileGroup (cd->pane, cd->host, cd->response_txt); -#endif - cd->next_state = NEWS_DONE; - } - else - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - - return ce->status; -} - -PRIVATE int net_profile_delete (ActiveEntry *ce) -{ -#if 0 - NewsConData *cd = (NewsConData*) ce->con_data; - char *slash = PL_strrchr(ce->URL_s->address, '/'); - if (slash) - { - PL_strcpy (cd->output_buffer, slash + 1); - PL_strcat (cd->output_buffer, CRLF); - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_PROFILE_DELETE_RESPONSE; - cd->pause_for_read = TRUE; - } - else - { - cd->next_state = NNTP_ERROR; - ce->status = -1; - } - - return ce->status; -#else - PR_ASSERT(FALSE); - return -1; -#endif -} - -PRIVATE int net_profile_delete_response (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - if (MK_NNTP_RESPONSE_TYPE(cd->response_code) == MK_NNTP_RESPONSE_TYPE_OK) - cd->next_state = NEWS_DONE; - else - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - - return ce->status; -} - -PRIVATE -int -net_read_news_group (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - if(cd->article_num > cd->last_art) - { /* end of groups */ - - cd->next_state = NNTP_FIGURE_NEXT_CHUNK; - cd->pause_for_read = FALSE; - return(0); - } - else - { - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "HEAD %ld" CRLF, - cd->article_num++); - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_READ_GROUP_RESPONSE; - - cd->pause_for_read = TRUE; - - NNTP_LOG_WRITE(cd->output_buffer); - return((int) NET_BlockingWrite(ce->socket, cd->output_buffer, PL_strlen(cd->output_buffer))); - } -} - -/* See if the "HEAD" command was successful - */ -PRIVATE int -net_read_news_group_response (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - nsresult rv; - - if (cd->response_code == MK_NNTP_RESPONSE_ARTICLE_HEAD) - { /* Head follows - parse it:*/ - cd->next_state = NNTP_READ_GROUP_BODY; - - if(cd->message_id) - *cd->message_id = '\0'; - - /* Give the message number to the header parser. */ -#ifdef XPCOM_XOVER - rv = cd->xover_parser->ProcessNonXOVER(cd->response_txt); - /* convert nsresult->status */ - return !NS_SUCCEEDED(rv); -#else - return MSG_ProcessNonXOVER (cd->pane, cd->response_txt, - &cd->xover_parse_state); -#endif - } - else - { - NNTP_LOG_NOTE(("Bad group header found!")); - cd->next_state = NNTP_READ_GROUP; - return(0); - } -} - -/* read the body of the "HEAD" command - */ -PRIVATE int -net_read_news_group_body (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - char *line; - nsresult rv; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - /* if TCP error of if there is not a full line yet return - */ - if(!line) - return ce->status; - - if(ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - NNTP_LOG_NOTE(("read_group_body: got line: %s|",line)); - - /* End of body? */ - if (line[0]=='.' && line[1]=='\0') - { - cd->next_state = NNTP_READ_GROUP; - cd->pause_for_read = FALSE; - } - else if (line [0] == '.' && line [1] == '.') - /* The NNTP server quotes all lines beginning with "." by doubling it. */ - line++; - -#ifdef XPCOM_XOVER - rv = cd->xover_parser->ProcessNonXOVER(line); - /* convert nsresult->status */ - return !NS_SUCCEEDED(rv); -#else - return MSG_ProcessNonXOVER (cd->pane, line, &cd->xover_parse_state); -#endif -} - - -PRIVATE int -net_send_news_post_data(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *) ce->con_data; - - /* returns 0 on done and negative on error - * positive if it needs to continue. - */ - ce->status = NET_WritePostData(ce->window_id, ce->URL_s, - ce->socket, - &cd->write_post_data_data, - TRUE); - - cd->pause_for_read = TRUE; - - if(ce->status == 0) - { - /* normal done - */ - PL_strcpy(cd->output_buffer, CRLF "." CRLF); - NNTP_LOG_WRITE(cd->output_buffer); - ce->status = (int) NET_BlockingWrite(ce->socket, - cd->output_buffer, - PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - NET_Progress(ce->window_id, - XP_GetString(XP_MESSAGE_SENT_WAITING_NEWS_REPLY)); - - NET_ClearConnectSelect(ce->window_id, ce->socket); -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - { - cd->calling_netlib_all_the_time = FALSE; -#if 0 - /* this should be handled by NET_ClearCallNetlibAllTheTime */ - net_call_all_the_time_count--; - if(net_call_all_the_time_count == 0) -#endif - NET_ClearCallNetlibAllTheTime(ce->window_id,"mknews"); - } -#endif - NET_SetReadSelect(ce->window_id, ce->socket); - ce->con_sock = 0; - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_SEND_POST_DATA_RESPONSE; - return(0); - } - - return(ce->status); - -} - - -/* interpret the response code from the server - * after the post is done - */ -PRIVATE int -net_send_news_post_data_response(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *) ce->con_data; - - - if (cd->response_code != MK_NNTP_RESPONSE_POST_OK) { - ce->URL_s->error_msg = - NET_ExplainErrorDetails(MK_NNTP_ERROR_MESSAGE, - cd->response_txt ? cd->response_txt : ""); - if (cd->response_code == MK_NNTP_RESPONSE_POST_FAILED - && MSG_GetPaneType(cd->pane) == MSG_COMPOSITIONPANE - && MSG_IsDuplicatePost(cd->pane) && - MSG_GetCompositionMessageID(cd->pane)) { - /* The news server won't let us post. We suspect that we're submitting - a duplicate post, and that's why it's failing. So, let's go see - if there really is a message out there with the same message-id. - If so, we'll just silently pretend everything went well. */ - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "STAT %s" CRLF, - MSG_GetCompositionMessageID(cd->pane)); - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_CHECK_FOR_MESSAGE; - NNTP_LOG_WRITE(cd->output_buffer); - return (int) NET_BlockingWrite(ce->socket, cd->output_buffer, - PL_strlen(cd->output_buffer)); - } - - MSG_ClearCompositionMessageID(cd->pane); /* So that if the user tries - to just post again, we - won't immediately decide - that this was a duplicate - message and ignore the - error. */ - cd->next_state = NEWS_ERROR; - return(MK_NNTP_ERROR_MESSAGE); - } - cd->next_state = NEWS_ERROR; /* even though it worked */ - cd->pause_for_read = FALSE; - return(MK_DATA_LOADED); -} - - -PRIVATE int -net_check_for_message(ActiveEntry* ce) -{ - NewsConData * cd = (NewsConData *) ce->con_data; - - cd->next_state = NEWS_ERROR; - if (cd->response_code >= 220 && cd->response_code <= 223) { - /* Yes, this article is already there, we're all done. */ - return MK_DATA_LOADED; - } else { - /* The article isn't there, so the failure we had earlier wasn't due to - a duplicate message-id. Return the error from that previous - posting attempt (which is already in ce->URL_s->error_msg). */ - MSG_ClearCompositionMessageID(cd->pane); - return MK_NNTP_ERROR_MESSAGE; - } -} - -#define NEWS_GROUP_DISPLAY_FREQ 20 - -PRIVATE int -net_DisplayNewsRC(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *) ce->con_data; - nsresult rv; - if(!cd->newsrc_performed) - { - cd->newsrc_performed = TRUE; -#ifdef XPCOM_NEWSHOST - rv = cd->news_host->GetNumGroupsNeedingCounts(&cd->newsrc_list_count); -#else - cd->newsrc_list_count = MSG_GetNewsRCCount(cd->pane, cd->news_host); -#endif - } - - - - FREEIF(cd->control_con->current_group); -#ifdef XPCOM_NEWSHOST - rv = - cd->news_host->GetFirstGroupNeedingCounts(&cd->control_con->current_group); -#else - cd->control_con->current_group = MSG_GetNewsRCGroup(cd->pane, cd->host); -#endif - - - if(NS_SUCCEEDED(rv) && cd->control_con->current_group) - { - /* send group command to server - */ - int32 percent; - - PR_snprintf(NET_Socket_Buffer, OUTPUT_BUFFER_SIZE, "GROUP %.512s" CRLF, - cd->control_con->current_group); - ce->status = (int) NET_BlockingWrite(ce->socket, NET_Socket_Buffer, - PL_strlen(NET_Socket_Buffer)); - NNTP_LOG_WRITE(NET_Socket_Buffer); - - percent = (cd->newsrc_list_count) ? - (int32) (100.0 * ( (double)cd->newsrc_list_index / (double)cd->newsrc_list_count )) : - 0; - FE_SetProgressBarPercent (ce->window_id, percent); - - /* only update every 20 groups for speed */ - if ((cd->newsrc_list_count <= NEWS_GROUP_DISPLAY_FREQ) || (cd->newsrc_list_index % NEWS_GROUP_DISPLAY_FREQ) == 0 || - (cd->newsrc_list_index == cd->newsrc_list_count)) - { - char thisGroup[20]; - char totalGroups[20]; - char *statusText; - - PR_snprintf (thisGroup, sizeof(thisGroup), "%ld", (long) cd->newsrc_list_index); - PR_snprintf (totalGroups, sizeof(totalGroups), "%ld", (long) cd->newsrc_list_count); - statusText = PR_smprintf (XP_GetString(XP_THERMO_PERCENT_FORM), thisGroup, totalGroups); - if (statusText) - { - FE_Progress (ce->window_id, statusText); - PR_Free(statusText); - } - } - - cd->newsrc_list_index++; - - cd->pause_for_read = TRUE; - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NEWS_DISPLAY_NEWS_RC_RESPONSE; - } - else - { - if (cd->newsrc_list_count) - { - FE_SetProgressBarPercent (ce->window_id, -1); - cd->newsrc_list_count = 0; - } - else if (cd->response_code == MK_NNTP_RESPONSE_LIST_OK) - { - /* - * 5-9-96 jefft - * If for some reason the news server returns an empty - * newsgroups list with a nntp response code MK_NNTP_RESPONSE_LIST_OK -- list of - * newsgroups follows. We set ce->status to MK_EMPTY_NEWS_LIST - * to end the infinite dialog loop. - */ - ce->status = MK_EMPTY_NEWS_LIST; - } - cd->next_state = NEWS_DONE; - - if(ce->status > -1) - return MK_DATA_LOADED; - else - return(ce->status); - } - - return(ce->status); /* keep going */ - -} - -/* Parses output of GROUP command */ -PRIVATE int -net_DisplayNewsRCResponse(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *) ce->con_data; - - if(cd->response_code == MK_NNTP_RESPONSE_GROUP_SELECTED) - { - char *num_arts = 0, *low = 0, *high = 0, *group = 0; - int32 first_art, last_art; - - /* line looks like: - * 211 91 3693 3789 comp.infosystems - */ - - num_arts = cd->response_txt; - low = PL_strchr(num_arts, ' '); - - if(low) - { - first_art = atol(low); - *low++ = '\0'; - high= PL_strchr(low, ' '); - } - if(high) - { - *high++ = '\0'; - group = PL_strchr(high, ' '); - } - if(group) - { - *group++ = '\0'; - /* the group name may be contaminated by "group selected" at - the end. This will be space separated from the group name. - If a space is found in the group name terminate at that - point. */ - strtok(group, " "); - last_art = atol(high); - } - -#ifdef XPCOM_NEWSHOST - cd->news_host->DisplaySubscribedGroup(group, - low ? atol(low) : 0, - high ? atol(high) : 0, - atol(num_arts), FALSE); -#else - ce->status = MSG_DisplaySubscribedGroup(cd->pane, - cd->host, - group, - low ? atol(low) : 0, - high ? atol(high) : 0, - atol(num_arts), FALSE); -#endif - if (ce->status < 0) - return ce->status; - } - else if (cd->response_code == MK_NNTP_RESPONSE_GROUP_NO_GROUP) - { -#ifdef XPCOM_NEWSHOST - cd->news_host->GroupNotFound(cd->control_con->current_group, FALSE); -#else - MSG_GroupNotFound(cd->pane, cd->host, cd->control_con->current_group, FALSE); -#endif - } - /* it turns out subscribe ui depends on getting this displaysubscribedgroup call, - even if there was an error. - */ - if(cd->response_code != MK_NNTP_RESPONSE_GROUP_SELECTED) - { - /* only on news server error or when zero articles - */ -#ifdef XPCOM_NEWSHOST - cd->news_host->DisplaySubscribedGroup(cd->control_con->current_group, - 0, 0, 0, FALSE); -#else - ce->status = MSG_DisplaySubscribedGroup(cd->pane, - cd->host, - cd->control_con->current_group, - 0, 0, 0, FALSE); -#endif - - } - - cd->next_state = NEWS_DISPLAY_NEWS_RC; - - return 0; -} - - -PRIVATE int -net_NewsRCProcessPost(ActiveEntry *ce) -{ - return(0); -} - - -#ifdef USE_LIBMSG -static void -net_cancel_done_cb (MWContext *context, void *data, int status, - const char *file_name) -{ - ActiveEntry *ce = (ActiveEntry *) data; - NewsConData *cd = (NewsConData *) ce->con_data; - cd->cancel_status = status; - PR_ASSERT(status < 0 || file_name); - cd->cancel_msg_file = (status < 0 ? 0 : PL_strdup(file_name)); -} -#endif - - -static int -net_start_cancel (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData *) ce->con_data; - char *command = "POST" CRLF; - - ce->status = (int) NET_BlockingWrite(ce->socket, command, PL_strlen(command)); - NNTP_LOG_WRITE(command); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NEWS_DO_CANCEL; - cd->pause_for_read = TRUE; - return (ce->status); -} - - -static int -net_do_cancel (ActiveEntry *ce) -{ - int status = 0; - NewsConData *cd = (NewsConData *) ce->con_data; - char *id, *subject, *newsgroups, *distribution, *other_random_headers, *body; - char *from, *old_from, *news_url; - int L; -#ifdef USE_LIBMSG - MSG_CompositionFields *fields = NULL; -#endif - - - /* #### Should we do a more real check than this? If the POST command - didn't respond with "MK_NNTP_RESPONSE_POST_SEND_NOW Ok", then it's not ready for us to throw a - message at it... But the normal posting code doesn't do this check. - Why? - */ - PR_ASSERT (cd->response_code == MK_NNTP_RESPONSE_POST_SEND_NOW); - - /* These shouldn't be set yet, since the headers haven't been "flushed" */ - PR_ASSERT (!cd->cancel_id && - !cd->cancel_from && - !cd->cancel_newsgroups && - !cd->cancel_distribution); - - /* Write out a blank line. This will tell mimehtml.c that the headers - are done, and it will call news_generate_html_header_fn which will - notice the fields we're interested in. - */ - PL_strcpy (cd->output_buffer, CRLF); /* CRLF used to be LINEBREAK. - LINEBREAK is platform dependent - and is only <CR> on a mac. This - CRLF is the protocol delimiter - and not platform dependent -km */ - ce->status = PUTSTRING(cd->output_buffer); - if (ce->status < 0) return ce->status; - - /* Now news_generate_html_header_fn should have been called, and these - should have values. */ - id = cd->cancel_id; - old_from = cd->cancel_from; - newsgroups = cd->cancel_newsgroups; - distribution = cd->cancel_distribution; - - PR_ASSERT (id && newsgroups); - if (!id || !newsgroups) return -1; /* "unknown error"... */ - - cd->cancel_newsgroups = 0; - cd->cancel_distribution = 0; - cd->cancel_from = 0; - cd->cancel_id = 0; - - L = PL_strlen (id); - - from = MIME_MakeFromField (); - subject = (char *) PR_Malloc (L + 20); - other_random_headers = (char *) PR_Malloc (L + 20); - body = (char *) PR_Malloc (PL_strlen (XP_AppCodeName) + 100); - - /* Make sure that this loser isn't cancelling someone else's posting. - Yes, there are occasionally good reasons to do so. Those people - capable of making that decision (news admins) have other tools with - which to cancel postings (like telnet.) - Don't do this if server tells us it will validate user. DMB 3/19/97 - */ -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool cancelchk=FALSE; - rv = cd->news_host->QueryExtension("CANCELCHK",&cancelchk); - if (NS_SUCCEEDED(rv) && cancelchk) -#else - if (!MSG_QueryNewsExtension(cd->host, "CANCELCHK")) -#endif - { - nsIMsgRFC822Parser *parser; - nsresult rv; - PRBool ok = FALSE; - - rv = NS_NewRFC822Parser(&parser); - if (NS_SUCCEEDED(rv)) { - char *us, *them; - nsresult rv1 = parser->ExtractRFC822AddressMailboxes(from, &us); - nsresult rv2 = parser->ExtractRFC822AddressMailboxes(old_from, &them); - ok = (NS_SUCCEEDED(rv1) && - NS_SUCCEEDED(rv2) && - !PL_strcasecmp(us, them)); - if (NS_SUCCEEDED(rv1)) PR_Free(us); - if (NS_SUCCEEDED(rv2)) PR_Free(them); - NS_RELEASE(parser); - } - if (!ok) - { - status = MK_NNTP_CANCEL_DISALLOWED; - ce->URL_s->error_msg = PL_strdup (XP_GetString(status)); - cd->next_state = NEWS_ERROR; /* even though it worked */ - cd->pause_for_read = FALSE; - goto FAIL; - } - } - - /* Last chance to cancel the cancel. - */ - if (!FE_Confirm (ce->window_id, XP_GetString(MK_NNTP_CANCEL_CONFIRM))) - { - status = MK_NNTP_NOT_CANCELLED; - goto FAIL; - } - - news_url = ce->URL_s->address; /* we can just post here. */ - - if (!from || !subject || !other_random_headers || !body) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - - PL_strcpy (subject, "cancel "); - PL_strcat (subject, id); - - PL_strcpy (other_random_headers, "Control: cancel "); - PL_strcat (other_random_headers, id); - PL_strcat (other_random_headers, CRLF); - if (distribution) - { - PL_strcat (other_random_headers, "Distribution: "); - PL_strcat (other_random_headers, distribution); - PL_strcat (other_random_headers, CRLF); - } - - PL_strcpy (body, "This message was cancelled from within "); - PL_strcat (body, XP_AppCodeName); - PL_strcat (body, "." CRLF); - -#ifdef USE_LIBMSG - fields = MSG_CreateCompositionFields(from, 0, 0, 0, 0, 0, newsgroups, - 0, 0, subject, id, other_random_headers, - 0, 0, news_url); -#endif - -/* so that this would compile - will probably change later */ -#if 0 - FALSE, - FALSE - ); -#endif - -#ifdef USE_LIBMSG - if (!fields) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - HG38712 -#endif - - cd->cancel_status = 0; - -#ifdef USE_LIBMSG - MSG_StartMessageDelivery (cd->pane, (void *) ce, - fields, - FALSE, /* digest_p */ - TRUE, /* dont_deliver_p */ - TEXT_PLAIN, body, PL_strlen (body), - 0, /* other attachments */ - NULL, /* multipart/related chunk */ - net_cancel_done_cb); - - /* Since there are no attachments, MSG_StartMessageDelivery will run - net_cancel_done_cb right away (it will be called before the return.) */ - - if (!cd->cancel_msg_file) - { - status = cd->cancel_status; - PR_ASSERT (status < 0); - if (status >= 0) status = -1; - goto FAIL; - } - - /* Now send the data - do it blocking, who cares; the message is known - to be very small. First suck the whole file into memory. Then delete - the file. Then do a blocking write of the data. - - (We could use file-posting, maybe, but I couldn't figure out how.) - */ - { - char *data; - uint32 data_size, data_fp; - XP_StatStruct st; - int nread = 0; - XP_File file = XP_FileOpen (cd->cancel_msg_file, - xpFileToPost, XP_FILE_READ); - if (! file) return -1; /* "unknown error"... */ - XP_Stat (cd->cancel_msg_file, &st, xpFileToPost); - - data_fp = 0; - data_size = st.st_size + 20; - data = (char *) PR_Malloc (data_size); - if (! data) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - - while ((nread = XP_FileRead (data + data_fp, data_size - data_fp, file)) - > 0) - data_fp += nread; - data [data_fp] = 0; - XP_FileClose (file); - XP_FileRemove (cd->cancel_msg_file, xpFileToPost); - - PL_strcat (data, CRLF "." CRLF CRLF); - status = NET_BlockingWrite(ce->socket, data, PL_strlen(data)); - NNTP_LOG_WRITE(data); - PR_Free (data); - if (status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, - status); - goto FAIL; - } - - cd->pause_for_read = TRUE; - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_SEND_POST_DATA_RESPONSE; - } -#else - - { - /* NET_BlockingWrite() should go away soon? I think. */ - /* The following are what we really need to cancel a posted message */ - char *data; - data = PR_smprintf("From: %s" CRLF - "Newsgroups: %s" CRLF - "Subject: %s" CRLF - "References: %s" CRLF - "%s" CRLF /* other_random_headers */ - "%s" /* body */ - CRLF "." CRLF CRLF, /* trailing SMTP "." */ - from, newsgroups, subject, id, - other_random_headers, body); - - status = NET_BlockingWrite(ce->socket, data, PL_strlen(data)); - NNTP_LOG_WRITE(data); - PR_Free (data); - if (status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, - status); - goto FAIL; - } - - cd->pause_for_read = TRUE; - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_SEND_POST_DATA_RESPONSE; - } - -#endif - - FAIL: - FREEIF (id); - FREEIF (from); - FREEIF (old_from); - FREEIF (subject); - FREEIF (newsgroups); - FREEIF (distribution); - FREEIF (other_random_headers); - FREEIF (body); - FREEIF (cd->cancel_msg_file); - -#ifdef USE_LIBMSG - if (fields) - MSG_DestroyCompositionFields(fields); -#endif - - return status; -} - - -static int net_xpat_send (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData *) ce->con_data; - int status = 0; - char *thisTerm = NULL; - - if (cd->current_search && - (thisTerm = PL_strchr(cd->current_search, '/')) != NULL) - { - /* extract the XPAT encoding for one query term */ -/* char *next_search = NULL; */ - char *command = NULL; - char *unescapedCommand = NULL; - char *endOfTerm = NULL; - StrAllocCopy (command, ++thisTerm); - endOfTerm = PL_strchr(command, '/'); - if (endOfTerm) - *endOfTerm = '\0'; - StrAllocCat (command, CRLF); - - unescapedCommand = MSG_UnEscapeSearchUrl(command); - - /* send one term off to the server */ - NNTP_LOG_WRITE(command); - status = NET_BlockingWrite(ce->socket, unescapedCommand, PL_strlen(unescapedCommand)); - NNTP_LOG_WRITE(unescapedCommand); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_XPAT_RESPONSE; - cd->pause_for_read = TRUE; - - PR_Free(command); - PR_Free(unescapedCommand); - } - else - { - cd->next_state = NEWS_DONE; - status = MK_DATA_LOADED; - } - return status; -} - -static int net_list_pretty_names(ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - -#ifdef XPCOM_NEWSGROUP - char *group_name; - nsresult rv = cd->newsgroup->GetName(&group_name); -#endif - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "LIST PRETTYNAMES %.512s" CRLF, -#ifdef XPCOM_NEWSGROUP - NS_SUCCEEDED(rv) ? group_name : ""); -#else - cd->group_name ? cd->group_name : ""); -#endif - - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); -#ifdef DEBUG_bienvenu1 - PR_LogPrint(cd->output_buffer); -#endif - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_LIST_PRETTY_NAMES_RESPONSE; - - return ce->status; -} - -static int net_list_pretty_names_response(ActiveEntry *ce) -{ - char *line; - char *prettyName; - - NewsConData * cd = (NewsConData *)ce->con_data; - - if (cd->response_code != MK_NNTP_RESPONSE_LIST_OK) - { - cd->next_state = DISPLAY_NEWSGROUPS; -/* cd->next_state = NEWS_DONE; */ - cd->pause_for_read = FALSE; - return 0; - } - - ce->status = NET_BufferedReadLine(ce->socket, &line, - &cd->data_buf, - &cd->data_buf_size, - (Bool*)&cd->pause_for_read); - NNTP_LOG_READ(line); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if (line) - { - if (line[0] != '.') - { - int i; - /* find whitespace seperator if it exits */ - for (i=0; line[i] != '\0' && !NET_IS_SPACE(line[i]); i++) - ; /* null body */ - - if(line[i] == '\0') - prettyName = &line[i]; - else - prettyName = &line[i+1]; - - line[i] = 0; /* terminate group name */ - if (i > 0) -#ifdef XPCOM_NEWSHOST - cd->news_host->AddPrettyName(line,prettyName); -#else - MSG_AddPrettyName(cd->host, line, prettyName); -#endif -#ifdef DEBUG_bienvenu1 - PR_LogPrint("adding pretty name %s\n", prettyName); -#endif - } - else - { - cd->next_state = DISPLAY_NEWSGROUPS; /* this assumes we were doing a list */ -/* cd->next_state = NEWS_DONE; */ /* ### dmb - don't really know */ - cd->pause_for_read = FALSE; - return 0; - } - } - return 0; -} - -static int net_list_xactive(ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - -#ifdef XPCOM_NEWSGROUP - char *group_name; - nsresult rv = cd->newsgroup->GetName(&group_name); -#endif - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "LIST XACTIVE %.512s" CRLF, -#ifdef XPCOM_NEWSGROUP - group_name); -#else - cd->group_name); -#endif - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_LIST_XACTIVE_RESPONSE; - - return ce->status; -} - -static int net_list_xactive_response(ActiveEntry *ce) -{ - char *line; - - NewsConData * cd = (NewsConData *)ce->con_data; - - PR_ASSERT(cd->response_code == MK_NNTP_RESPONSE_LIST_OK); - if (cd->response_code != MK_NNTP_RESPONSE_LIST_OK) - { - cd->next_state = DISPLAY_NEWSGROUPS; -/* cd->next_state = NEWS_DONE; */ - cd->pause_for_read = FALSE; - return MK_DATA_LOADED; - } - - ce->status = NET_BufferedReadLine(ce->socket, &line, - &cd->data_buf, - &cd->data_buf_size, - (Bool*)&cd->pause_for_read); - NNTP_LOG_READ(line); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - /* almost correct - */ - if(ce->status > 1) - { - ce->bytes_received += ce->status; - FE_GraphProgress(ce->window_id, ce->URL_s, ce->bytes_received, ce->status, ce->URL_s->content_length); - } - - if (line) - { - if (line[0] != '.') - { - char *s = line; - /* format is "rec.arts.movies.past-films 7302 7119 csp" - */ - while (*s && !NET_IS_SPACE(*s)) - s++; - if (s) - { - char flags[32]; /* ought to be big enough */ - *s = 0; - sscanf(s + 1, - "%d %d %31s", - &cd->first_possible_art, - &cd->last_possible_art, - flags); -#ifdef XPCOM_NEWSHOST - cd->news_host->AddNewNewsgroup(line, - cd->first_possible_art, - cd->last_possible_art, flags, TRUE); -#else - MSG_AddNewNewsGroup(cd->pane, cd->host, line, - cd->first_possible_art, - cd->last_possible_art, flags, TRUE /* xactive flags */); -#endif - /* we're either going to list prettynames first, or list - all prettynames every time, so we won't care so much - if it gets interrupted. */ -#ifdef DEBUG_bienvenu1 - PR_LogPrint("got xactive for %s of %s\n", line, flags); -#endif - /* This isn't required, because the extra info is - initialized to false for new groups. And it's - an expensive call. - */ - /* MSG_SetGroupNeedsExtraInfo(cd->host, line, FALSE); */ - } - } - else - { -#ifdef XPCOM_NEWSHOST - nsresult rv; - PRBool xactive=FALSE; - rv = cd->news_host->QueryExtension("XACTIVE",&xactive); - if (cd->type_wanted == NEW_GROUPS && - NS_SUCCEEDED(rv) && xactive) -#else - if (cd->type_wanted == NEW_GROUPS && MSG_QueryNewsExtension(cd->host, "XACTIVE")) -#endif - { -#ifdef XPCOM_NEWSGROUP - nsIMsgNewsgroup* old_newsgroup = cd->newsgroup; - cd->news_host->GetFirstGroupNeedingExtraInfo(&cd->newsgroup); - if (old_newsgroup && cd->newsgroup && - old_newsgroup != cd->newsgroup) - /* make sure we're not stuck on the same group */ - { - NS_RELEASE(old_newsgroup); -#else - char *old_group_name = cd->group_name; - cd->group_name = MSG_GetFirstGroupNeedingExtraInfo(cd->host); - if (old_group_name && cd->group_name && PL_strcmp(old_group_name, cd->group_name)) - /* make sure we're not stuck on the same group... */ - { - PR_Free(old_group_name); -#endif -#ifdef DEBUG_bienvenu1 - PR_LogPrint("listing xactive for %s\n", cd->group_name); -#endif - cd->next_state = NNTP_LIST_XACTIVE; - cd->pause_for_read = FALSE; - return 0; - } - else - { -#ifdef XPCOM_NEWSGROUP - NS_RELEASE(old_newsgroup); - cd->newsgroup = NULL; -#else - FREEIF(old_group_name); - cd->group_name = NULL; -#endif - } - } -#ifdef XPCOM_NEWSHOST - PRBool listpname; - rv = cd->news_host->QueryExtension("LISTPNAME",&listpname); - if (NS_SUCCEEDED(rv) && listpname) -#else - if (MSG_QueryNewsExtension(cd->host, "LISTPNAMES")) -#endif - cd->next_state = NNTP_LIST_PRETTY_NAMES; - else - cd->next_state = DISPLAY_NEWSGROUPS; /* this assumes we were doing a list - who knows? */ -/* cd->next_state = NEWS_DONE; */ /* ### dmb - don't really know */ - cd->pause_for_read = FALSE; - return 0; - } - } - return 0; -} - -static int net_list_group(ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - nsresult rv; -#ifdef XPCOM_NEWSGROUP - char *group_name; - rv = cd->newsgroup->GetName(&group_name); -#endif - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "listgroup %.512s" CRLF, -#ifdef XPCOM_NEWSGROUP - group_name); -#else - cd->group_name); -#endif - -#ifdef XPCOM_NEWSPARSE - rv = NS_NewMsgNewsArticleList(&cd->article_list, - cd->news_host, cd->newsgroup); -#else - MSG_InitAddArticleKeyToGroup(cd->pane, cd->host, cd->group_name, - &cd->newsgroup_parse_state); -#endif - ce->status = (int) NET_BlockingWrite(ce->socket,cd->output_buffer,PL_strlen(cd->output_buffer)); - NNTP_LOG_WRITE(cd->output_buffer); - - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_LIST_GROUP_RESPONSE; - - return ce->status; -} - -static int net_list_group_response(ActiveEntry *ce) -{ - char *line; - - NewsConData * cd = (NewsConData *)ce->con_data; - - PR_ASSERT(cd->response_code == MK_NNTP_RESPONSE_GROUP_SELECTED); - if (cd->response_code != MK_NNTP_RESPONSE_GROUP_SELECTED) - { - cd->next_state = NEWS_DONE; - cd->pause_for_read = FALSE; - return MK_DATA_LOADED; - } - - ce->status = NET_BufferedReadLine(ce->socket, &line, - &cd->data_buf, - &cd->data_buf_size, - (Bool*)&cd->pause_for_read); - NNTP_LOG_READ(line); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if (line) - { - if (line[0] != '.') - { - long found_id = MSG_MESSAGEKEYNONE; - nsresult rv; - sscanf(line, "%ld", &found_id); - -#ifdef XPCOM_NEWSPARSE - rv = cd->article_list->AddArticleKeyToGroup(found_id); -#else - MSG_AddArticleKeyToGroup(cd->newsgroup_parse_state, (int32) found_id); -#endif - } - else - { - cd->next_state = NEWS_DONE; /* ### dmb - don't really know */ - cd->pause_for_read = FALSE; - return 0; - } - } - return 0; -} - - -static int net_xpat_response (ActiveEntry *ce) -{ - char *line; - NewsConData * cd = (NewsConData *)ce->con_data; - - if (cd->response_code != MK_NNTP_RESPONSE_XPAT_OK) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_ERROR_MESSAGE, cd->response_txt); - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - return MK_NNTP_SERVER_ERROR; - } - - ce->status = NET_BufferedReadLine(ce->socket, &line, - &cd->data_buf, - &cd->data_buf_size, - (Bool*)&cd->pause_for_read); - NNTP_LOG_READ(line); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if (line) - { - if (line[0] != '.') - { - long articleNumber; - sscanf(line, "%ld", &articleNumber); - MSG_AddNewsXpatHit (ce->window_id, (uint32) articleNumber); - } - else - { - /* set up the next term for next time around */ - char *nextTerm = PL_strchr(cd->current_search, '/'); - if (nextTerm) - cd->current_search = ++nextTerm; - else - cd->current_search = NULL; - - cd->next_state = NNTP_XPAT_SEND; - cd->pause_for_read = FALSE; - return 0; - } - } - return 0; -} - - -PRIVATE int net_nntp_search(ActiveEntry *ce) -{ - PR_ASSERT(FALSE); - return 0; -} - -PRIVATE int net_nntp_search_response(ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - - if (MK_NNTP_RESPONSE_TYPE(cd->response_code) == MK_NNTP_RESPONSE_TYPE_OK) - cd->next_state = NNTP_SEARCH_RESULTS; - else - cd->next_state = NEWS_DONE; - cd->pause_for_read = FALSE; - return 0; -} - -PRIVATE int net_nntp_search_results (ActiveEntry *ce) -{ - NewsConData *cd = (NewsConData*) ce->con_data; - - char *line = NULL; - ce->status = NET_BufferedReadLine (ce->socket, &line, &cd->data_buf, - &cd->data_buf_size, (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return MK_NNTP_SERVER_ERROR; - } - if (!line) - return ce->status; /* no line yet */ - if (ce->status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - /* return TCP error */ - return MK_TCP_READ_ERROR; - } - - if ('.' != line[0]) - MSG_AddNewsSearchHit (ce->window_id, line); - else - { - /* all overview lines received */ - cd->next_state = NEWS_DONE; - cd->pause_for_read = FALSE; - } - - return ce->status; -} - -/* The main news load init routine, and URL parser. - The syntax of news URLs is: - - To list all hosts: - news: - - To list all groups on a host, or to post a new message: - news://HOST - - To list some articles in a group: - news:GROUP - news:/GROUP - news://HOST/GROUP - - To list a particular range of articles in a group: - news:GROUP/N1-N2 - news:/GROUP/N1-N2 - news://HOST/GROUP/N1-N2 - - To retrieve an article: - news:MESSAGE-ID (message-id must contain "@") - - To cancel an article: - news:MESSAGE-ID?cancel - - (Note that message IDs may contain / before the @:) - - news:SOME/ID@HOST?headers=all - news:/SOME/ID@HOST?headers=all - news:/SOME?ID@HOST?headers=all - are the same as - news://HOST/SOME/ID@HOST?headers=all - news://HOST//SOME/ID@HOST?headers=all - news://HOST//SOME?ID@HOST?headers=all - bug: if the ID is <//xxx@host> we will parse this correctly: - news://non-default-host///xxx@host - but will mis-parse it if it's on the default host: - news://xxx@host - whoever had the idea to leave the <> off the IDs should be flogged. - So, we'll make sure we quote / in message IDs as %2F. - - */ -int -NET_parse_news_url (const char *url, - char **host_and_portP, - XP_Bool *bValP, - char **groupP, - char **message_idP, - char **command_specific_dataP) -{ - int status = 0; - HG43575 - char *host_and_port = 0; - int32 port = 0; - char *group = 0; - char *message_id = 0; - char *command_specific_data = 0; - const char *path_part; - char *s; - - HG66376 - - host_and_port = NET_ParseURL (url, GET_HOST_PART); - if (!host_and_port || !*host_and_port) - { - char* defhost = NULL; - int32 defport = 0; - FREEIF(host_and_port); - PREF_CopyCharPref("network.hosts.nntp_server", &defhost); - if (defhost && *defhost == '\0') { - PR_Free(defhost); - defhost = NULL; - } - if (defhost) { - PREF_GetIntPref("news.server_port", &defport); - HG05417 - - if (defport) { - host_and_port = PR_smprintf("%s:%ld", defhost, (long) defport); - PR_Free(defhost); - } else { - host_and_port = defhost; - } - if (!host_and_port) { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - } - } - - if (!host_and_port) - { - status = MK_NO_NEWS_SERVER; - goto FAIL; - } - - /* If a port was specified, but it was the default port, pretend - it wasn't specified. - */ - s = PL_strchr (host_and_port, ':'); - if (s && sscanf (s+1, " %u ", &port) == 1 && - HG05998) - *s = 0; - - path_part = PL_strchr (url, ':'); - PR_ASSERT (path_part); - if (!path_part) - { - status = -1; - goto FAIL; - } - path_part++; - if (path_part[0] == '/' && path_part[1] == '/') - { - /* Skip over host name. */ - path_part = PL_strchr (path_part + 2, '/'); - if (path_part) - path_part++; - } - if (!path_part) - path_part = ""; - - group = PL_strdup (path_part); - if (!group) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - - NET_UnEscape (group); - - /* "group" now holds the part after the host name: - "message@id?search" or "/group/xxx?search" or "/message?id@xx?search" - - If there is an @, this is a message ID; else it is a group. - Either way, there may be search data at the end. - */ - - s = PL_strchr (group, '@'); - if (s) - { - message_id = group; - group = 0; - } - else if (!*group) - { - PR_Free (group); - group = 0; - } - - /* At this point, the search data is attached to `message_id' (if there - is one) or `group' (if there is one) or `host_and_port' (otherwise.) - Seperate the search data from what it is clinging to, being careful - to interpret the "?" only if it comes after the "@" in an ID, since - the syntax of message IDs is tricky. (There may be a ? in the - random-characters part of the ID (before @), but not in the host part - (after @).) - */ - if (message_id || group || host_and_port) - { - char *start; - if (message_id) - { - /* Move past the @. */ - PR_ASSERT (s && *s == '@'); - start = s; - } - else - { - start = group ? group : host_and_port; - } - - /* Take off the "?" or "#" search data */ - for (s = start; *s; s++) - if (*s == '?' || *s == '#') - break; - if (*s) - { - command_specific_data = PL_strdup (s); - *s = 0; - if (!command_specific_data) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - } - - /* Discard any now-empty strings. */ - if (message_id && !*message_id) - { - PR_Free (message_id); - message_id = 0; - } - else if (group && !*group) - { - PR_Free (group); - group = 0; - } - } - - FAIL: - PR_ASSERT (!message_id || message_id != group); - if (status >= 0) - { - *host_and_portP = host_and_port; - HG45873 - *groupP = group; - *message_idP = message_id; - *command_specific_dataP = command_specific_data; - } - else - { - FREEIF (host_and_port); - FREEIF (group); - FREEIF (message_id); - FREEIF (command_specific_data); - } - return status; -} - - -/* Returns true if this URL is a reference to a news message, - that is, the kind of news URL entity that can be displayed - in a regular browser window, and doesn't involve all kinds - of other magic state and callbacks like listing a group. - */ -XP_Bool -NET_IsNewsMessageURL (const char *url) -{ - char *host_and_port = 0; - XP_Bool bVal = FALSE; - char *group = 0; - char *message_id = 0; - char *command_specific_data = 0; - int status = NET_parse_news_url (url, &host_and_port, &bVal, - &group, &message_id, &command_specific_data); - XP_Bool result = FALSE; - if (status >= 0 && message_id && *message_id) - result = TRUE; - FREEIF (host_and_port); - FREEIF (group); - FREEIF (message_id); - FREEIF (command_specific_data); - return result; -} - -XP_Bool -NET_IsNewsServerURL( const char *url) -{ - char *host_and_port = 0; - XP_Bool bVal = FALSE; - char *group = 0; - char *message_id = 0; - char *command_specific_data = 0; - int status = NET_parse_news_url (url, &host_and_port, &bVal, - &group, &message_id, &command_specific_data); - XP_Bool result = FALSE; - if (status >= 0 && host_and_port && !group && !message_id) - result = TRUE; - FREEIF (host_and_port); - FREEIF (group); - FREEIF (message_id); - FREEIF (command_specific_data); - return result; -} - -static XP_Bool nntp_are_connections_available (NNTPConnection *conn) -{ - int connCount = 0; - - NNTPConnection *tmpConn; - XP_List *tmpList = nntp_connection_list; - - while ((tmpConn = (NNTPConnection*) XP_ListNextObject(tmpList)) != NULL) - { - NNTP_LOG_NOTE(("nntp_are_connections_available: comparing %08lX %s", tmpConn, tmpConn->busy ? "busy" : "available")); - - if (conn != tmpConn && tmpConn->busy && !PL_strcasecmp(tmpConn->hostname, conn->hostname)) - connCount++; - } - - return connCount < kMaxConnectionsPerHost; -} - -static XP_Bool isOnline = TRUE; -static XP_Bool prefInitialized = FALSE; - -#ifndef MAXHOSTNAMELEN -#define MAXHOSTNAMELEN 64 -#endif - -MODULE_PRIVATE int PR_CALLBACK NET_OnlinePrefChangedFunc(const char *pref, void *data) -{ - int status=0; - int32 port=0; - char * socksHost = NULL; - char text[MAXHOSTNAMELEN + 8]; - extern void NET_MaybeDownloadAutoAdminCfgFile(void); - - if (!PL_strcasecmp(pref,"network.online")) - status = PREF_GetBoolPref("network.online", &isOnline); - - if ( isOnline ) { - CACHE_CloseAllOpenSARCache(); - - NET_MaybeDownloadAutoAdminCfgFile(); - - /* If the user wants to use a socks server set it up. */ - if ( (NET_GetProxyStyle() == PROXY_STYLE_MANUAL) ) { - PREF_CopyCharPref("network.hosts.socks_server",&socksHost); - PREF_GetIntPref("network.hosts.socks_serverport",&port); - if (socksHost && *socksHost && port) { - PR_snprintf(text, sizeof(text), "%s:%d", socksHost, port); - NET_SetSocksHost(text); - } - else { - NET_SetSocksHost(socksHost); /* NULL is ok */ - } - } - } - else { - CACHE_OpenAllSARCache(); - } - - return status; -} - -MODULE_PRIVATE int PR_CALLBACK NET_NewsMaxArticlesChangedFunc(const char *pref, void *data) -{ - int status=0; - if (!PL_strcasecmp(pref,"news.max_articles")) - { - int32 maxArticles; - - status = PREF_GetIntPref("news.max_articles", &maxArticles); - NET_SetNumberOfNewsArticlesInListing(maxArticles); - } - return status; -} - -MODULE_PRIVATE int PR_CALLBACK net_news_timeout_changed (const char *pref, void *data) -{ - return PREF_GetIntPref ("news.timeout", &net_news_timeout); -} - -MODULE_PRIVATE XP_Bool -NET_IsOffline() -{ - /* Cache this value, and register a pref callback to - find out when it changes. - */ - if (!prefInitialized) - { - /*int status =*/ PREF_GetBoolPref("network.online", &isOnline); - PREF_RegisterCallback("network.online",NET_OnlinePrefChangedFunc, NULL); - - /* because this routine gets called so often, we can register this callback here too. */ - PREF_RegisterCallback("news.max_articles", NET_NewsMaxArticlesChangedFunc, NULL); - - PREF_GetIntPref ("news.timeout", &net_news_timeout); - PREF_RegisterCallback ("news.timeout", net_news_timeout_changed, NULL); - - prefInitialized = TRUE; - } - return !isOnline; -} - -MODULE_PRIVATE int -NET_NewsLoad (ActiveEntry *ce, char *proxy_server) -{ - int status = 0; - NewsConData *cd = PR_NEW(NewsConData); - XP_Bool bVal = FALSE; - XP_Bool default_host = FALSE; - char *url = ce->URL_s->address; - char *host_and_port = 0; - int32 port = 0; - char *group = 0; - char *message_id = 0; - char *command_specific_data = 0; - XP_Bool cancel_p = FALSE; - char* colon; - MSG_NewsHost* defhost = NULL; - nsresult rv; - - if(!cd) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - - memset(cd, 0, sizeof(NewsConData)); - ce->URL_s->content_length = 0; - StrAllocCopy(cd->proxy_server, proxy_server); - -#ifdef USE_PANES - cd->pane = ce->URL_s->msg_pane; - if (!cd->pane) - { - NNTP_LOG_NOTE(("NET_NewsLoad: url->msg_pane NULL for URL: %s\n", ce->URL_s->address)); - if (NET_IsNewsMessageURL(ce->URL_s->address)) - cd->pane = MSG_FindPane(ce->window_id, MSG_MESSAGEPANE); - else - cd->pane = MSG_FindPane(ce->window_id, MSG_ANYPANE); - } - PR_ASSERT(cd->pane && MSG_GetContext(cd->pane) == ce->window_id); - if (!cd->pane) - { - PR_ASSERT(FALSE); - status = -1; /* ### */ - goto FAIL; - } -#endif - -#ifdef DEBUG - { - char urlDate[64]; - PRTime now = PR_Now(); - XP_StrfTime(ce->window_id, urlDate, sizeof(urlDate), XP_DATE_TIME_FORMAT, localtime(&now)); - NNTP_LOG_NOTE (("******** Begin loading news URL [ %s ] at %s", ce->URL_s->address, urlDate)); - } -#endif - - cd->output_buffer = (char *) PR_Malloc(OUTPUT_BUFFER_SIZE); - if(!cd->output_buffer) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - - ce->con_data = cd; - ce->socket = NULL; - cd->article_num = -1; - - PR_ASSERT (url); - if (!url) - { - status = -1; - goto FAIL; - } - - - status = NET_parse_news_url (url, &host_and_port, &bVal, - &group, &message_id, &command_specific_data); - if (status < 0) - goto FAIL; - - colon = PL_strchr (host_and_port, ':'); - if (colon) { - *colon = '\0'; - sscanf (colon+1, " %u ", &port); - } - -#ifdef XPCOM_NEWSHOST - rv = NS_NewMsgNewsHost(&cd->news_host, host_and_port, bVal, port); -#else - cd->host = MSG_CreateNewsHost(MSG_GetMaster(cd->pane), host_and_port, - bVal, port); -#endif - if (colon) *colon = ':'; - -#ifdef XPCOM_NEWSHOST - PR_ASSERT(NS_SUCCEEDED(rv)); - if (!NS_SUCCEEDED(rv)) { -#else - PR_ASSERT(cd->host); - if (!cd->host) { -#endif - status = -1; - goto FAIL; - } - - if (message_id && command_specific_data && !PL_strcmp (command_specific_data, "?cancel")) - cancel_p = TRUE; - - StrAllocCopy(cd->path, message_id); -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetName(group); -#else - StrAllocCopy(cd->group_name, group); -#endif - - /* make sure the user has a news host configured */ - -#ifndef XPCOM_NEWSHOST - defhost = MSG_GetDefaultNewsHost(MSG_GetMaster(cd->pane)); - - if (defhost == NULL) - { - char* alert = NET_ExplainErrorDetails(MK_NNTP_SERVER_NOT_CONFIGURED); - FE_Alert(ce->window_id, alert); -#ifdef XP_MAC - /* AFTER the alert, not before! */ - FE_EditPreference(PREF_NewsHost); -#endif - status = -1; - goto FAIL; - } - - default_host = (cd->host == defhost); -#endif - - if (cancel_p && !ce->URL_s->internal_url) - { - /* Don't allow manual "news:ID?cancel" URLs, only internal ones. */ - status = -1; - goto FAIL; - } - else if (ce->URL_s->method == URL_POST_METHOD) - { - /* news://HOST done with a POST instead of a GET; - this means a new message is being posted. - Don't allow this unless it's an internal URL. - */ - if (!ce->URL_s->internal_url) - { - status = -1; - goto FAIL; - } - PR_ASSERT (!group && !message_id && !command_specific_data); - cd->type_wanted = NEWS_POST; - StrAllocCopy(cd->path, ""); - } - else if (message_id) - { - /* news:MESSAGE_ID - news:/GROUP/MESSAGE_ID (useless) - news://HOST/MESSAGE_ID - news://HOST/GROUP/MESSAGE_ID (useless) - */ - if (cancel_p) - cd->type_wanted = CANCEL_WANTED; - else - cd->type_wanted = ARTICLE_WANTED; - } - else if (command_specific_data) - { - if (PL_strstr (command_specific_data, "?newgroups")) - /* news://HOST/?newsgroups - news:/GROUP/?newsgroups (useless) - news:?newsgroups (default host) - */ - cd->type_wanted = NEW_GROUPS; - else - { - if (PL_strstr(command_specific_data, "?list-pretty")) - { - cd->type_wanted = PRETTY_NAMES_WANTED; - cd->command_specific_data = PL_strdup(command_specific_data); - } - else if (PL_strstr(command_specific_data, "?profile")) - { - cd->type_wanted = PROFILE_WANTED; - cd->command_specific_data = PL_strdup(command_specific_data); - } - else if (PL_strstr(command_specific_data, "?list-ids")) - { - cd->type_wanted = IDS_WANTED; - cd->command_specific_data = PL_strdup(command_specific_data); - } - else - { - cd->type_wanted = SEARCH_WANTED; - cd->command_specific_data = PL_strdup(command_specific_data); - cd->current_search = cd->command_specific_data; - } - } - } - else if (group) - { - /* news:GROUP - news:/GROUP - news://HOST/GROUP - */ - if (ce->window_id->type != MWContextNews && ce->window_id->type != MWContextNewsMsg - && ce->window_id->type != MWContextMailMsg - && ce->window_id->type != MWContextMail && ce->window_id->type != MWContextMailNewsProgress) - { - status = -1; - goto FAIL; - } - if (PL_strchr (group, '*')) - cd->type_wanted = LIST_WANTED; - else - cd->type_wanted = GROUP_WANTED; - } - else - { - /* news: - news://HOST - */ - cd->type_wanted = READ_NEWS_RC; - } - - - /* let's look for the user name and password in the url */ - { - char * unamePwd = NET_ParseURL(url, GET_USERNAME_PART | GET_PASSWORD_PART); - char *userName,*colon,*password=NULL; - - /* get the username & password out of the combo string */ - if( (colon = PL_strchr(unamePwd, ':')) != NULL ) - { - *colon = '\0'; - userName = PL_strdup(unamePwd); - password = PL_strdup(colon+1); - *colon = ':'; - PR_Free(unamePwd); - } - else - { - userName = unamePwd; - } - if (userName) - { - char *mungedUsername = HG64643(userName); -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetUsername(mungedUsername); -#else - MSG_SetNewsgroupUsername(cd->pane, mungedUsername); -#endif - PR_FREEIF(mungedUsername); - PR_Free(userName); - } - if (password) - { - char *mungedPassword = HG64643(password); -#ifdef XPCOM_NEWSGROUP - cd->newsgroup->SetPassword(mungedPassword); -#else - MSG_SetNewsgroupPassword(cd->pane, mungedPassword); -#endif - PR_FREEIF(mungedPassword); - PR_Free(password); - } - - } - /* At this point, we're all done parsing the URL, and know exactly - what we want to do with it. - */ - -#ifndef NO_ARTICLE_CACHEING - /* Turn off caching on all news entities, except articles. */ - /* It's very important that this be turned off for CANCEL_WANTED; - for the others, I don't know what cacheing would cause, but - it could only do harm, not good. */ - if(cd->type_wanted != ARTICLE_WANTED) -#endif - ce->format_out = CLEAR_CACHE_BIT (ce->format_out); - - if (cd->type_wanted == ARTICLE_WANTED) - { - uint32 number = 0; -#ifdef XPCOM_NEWSGROUP - nsresult rv; - PRBool articleIsOffline; - rv =cd->newsgroup->IsOfflineArticle(number,&articleIsOffline); -#else - const char *group = 0; - XP_Bool articleIsOffline = MSG_IsOfflineArticle (cd->pane, cd->path, &group, &number); -#endif - if (NET_IsOffline() || (NS_SUCCEEDED(rv) && articleIsOffline)) - { - ce->local_file = TRUE; - cd->articleIsOffline = articleIsOffline; - ce->socket = NULL; - -#if 0 - /* this should be handled by NET_SetCallNetlibAllTheTime */ - net_call_all_the_time_count++; -#endif - if (!articleIsOffline) - ce->format_out = CLEAR_CACHE_BIT(ce->format_out); - NET_SetCallNetlibAllTheTime(ce->window_id,"mknews"); -#ifdef XPCOM_OFFLINE - rv = NS_NewOfflineNewState(&cd->offline_state, - cd->newsgroup, number); -#else - MSG_StartOfflineRetrieval(cd->pane, group, number, &cd->offlineState); -#endif - } - } -#ifdef XPCOM_OFFLINE - if (cd->offline_state) -#else - if (cd->offlineState) -#endif - goto FAIL; /* we don't need to do any of this connection stuff */ - - /* check for established connection and use it if available - */ - if(nntp_connection_list) - { - NNTPConnection * tmp_con; - XP_List * list_entry = nntp_connection_list; - - while((tmp_con = (NNTPConnection *)XP_ListNextObject(list_entry)) - != NULL) - { - /* if the hostnames match up exactly and the connection - * is not busy at the moment then reuse this connection. - */ - if(!PL_strcmp(tmp_con->hostname, host_and_port) - && HG78293 - &&!tmp_con->busy) - { - /* check to see if this connection can be reused, or if it should be aged away */ - int32 con_age = XP_TIME() - tmp_con->last_used_time; - if (con_age <= net_news_timeout) - { - cd->control_con = tmp_con; - - NNTP_LOG_NOTE(("Reusing control_con %08lX (age %ld secs) for %s", tmp_con, con_age, url)); - - /* set select on the control socket */ - ce->socket = cd->control_con->csock; - NET_SetReadSelect(ce->window_id, cd->control_con->csock); - cd->control_con->prev_cache = TRUE; /* this was from the cache */ - break; - } - else - { - NNTP_LOG_NOTE(("Aging away control_con %08lX (age %ld secs)", tmp_con, con_age)); - - /* kill idle conn which has lived too long */ - list_entry = list_entry->prev ? list_entry->prev : nntp_connection_list; - XP_ListRemoveObject(nntp_connection_list, tmp_con); - net_nntp_close(tmp_con, ce->status); - FREEIF(tmp_con->hostname); - PR_Free(tmp_con); - } - } - } - } - else - { - /* initialize the connection list - */ - nntp_connection_list = XP_ListNew(); - } - - - if(cd->control_con) - { - cd->next_state = SEND_FIRST_NNTP_COMMAND; - /* set the connection busy - */ - cd->control_con->busy = TRUE; - NET_TotalNumberOfOpenConnections++; - } - else - { - /* build a control connection structure so we - * can store the data as we go along - */ - cd->control_con = PR_NEW(NNTPConnection); - if(!cd->control_con) - { - status = MK_OUT_OF_MEMORY; - goto FAIL; - } - NNTP_LOG_NOTE(("Created control_con %08lX for %s", cd->control_con, ce->URL_s->address)); - memset(cd->control_con, 0, sizeof(NNTPConnection)); - -#ifndef XPCOM_NEWSHOST - cd->control_con->default_host = default_host; -#endif - StrAllocCopy(cd->control_con->hostname, host_and_port); - NNTP_LOG_NOTE(("Set host string: %s", cd->control_con->hostname)); - - HG01869 - - cd->control_con->prev_cache = FALSE; /* this wasn't from the cache */ - - cd->control_con->csock = NULL; - - cd->control_con->last_used_time = XP_TIME(); - - /* define this to test support for older NNTP servers - * that don't support the XOVER command - */ -#ifdef TEST_NO_XOVER_SUPPORT - cd->control_con->no_xover = TRUE; -#endif /* TEST_NO_XOVER_SUPPORT */ - - /* add this structure to the connection list even - * though it's not really valid yet. - * we will fill it in as we go and if - * an error occurs will will remove it from the - * list. No one else will be able to use it since - * we will mark it busy. - */ - XP_ListAddObject(nntp_connection_list, cd->control_con); - - /* set the connection busy - */ - cd->control_con->busy = TRUE; - - /* gate the maximum number of cached connections - * but don't delete busy ones. - */ - if(XP_ListCount(nntp_connection_list) > kMaxCachedConnections) - { - XP_List * list_ptr = nntp_connection_list->next; - NNTPConnection * con; - - while(list_ptr) - { - con = (NNTPConnection *) list_ptr->object; - list_ptr = list_ptr->next; - if(!con->busy) - { - XP_ListRemoveObject(nntp_connection_list, con); - net_nntp_close (con, status); - FREEIF(con->hostname); - PR_Free(con); - break; - } - } - } - - cd->next_state = NNTP_CONNECT; - } - - FAIL: - - FREEIF (host_and_port); - FREEIF (group); - FREEIF (message_id); - FREEIF (command_specific_data); - - if (status < 0) - { - FREEIF (cd->output_buffer); - FREEIF (cd); - ce->URL_s->error_msg = NET_ExplainErrorDetails(status); - return status; - } - else - { - return (net_ProcessNews (ce)); - } -} -/* process the offline news state machine, such as it is. */ - -PRIVATE int -NET_ProcessOfflineNews(ActiveEntry *ce, NewsConData *cd) -{ - int32 read_size = 0; - int status; - nsresult rv; - - cd->pause_for_read = TRUE; - - if (cd->stream) - read_size = (*cd->stream->is_write_ready) - (cd->stream); - else - { - StrAllocCopy(ce->URL_s->content_type, cd->articleIsOffline ? MESSAGE_RFC822 : TEXT_HTML); - if (CLEAR_CACHE_BIT(ce->format_out) == FO_PRESENT) - { - ce->status = net_InitializeNewsFeData (ce); - if (ce->status < 0) - { - /* #### what error message? */ - return ce->status; - } - } - cd->stream = NET_StreamBuilder(ce->format_out, ce->URL_s, ce->window_id); - if (!cd->stream) - ce->status = -1; - } - if(!read_size) - return(0); /* wait until we are ready to write */ - else - read_size = MIN(read_size, NET_Socket_Buffer_Size); -#ifdef XPCOM_OFFLINE - rv = cd->offline_state->Process(&NET_Socket_Buffer, read_size, &status); - if (NS_SUCCEEDED(rv) && status > 0) -#else - status = MSG_ProcessOfflineNews(cd->offlineState, NET_Socket_Buffer, read_size); - if(status > 0) -#endif - { - ce->bytes_received += status; - FE_GraphProgress(ce->window_id, ce->URL_s, - ce->bytes_received, status, - ce->URL_s->content_length); - PUT_STREAM(NET_Socket_Buffer, status); /* blow off error? ### dmb */ - } - - if (status == 0) - { - if (cd->stream) - COMPLETE_STREAM; -#if 0 - /* this should be handled by NET_ClearCallNetlibAllTheTime()*/ - net_call_all_the_time_count--; - if(net_call_all_the_time_count < 1) -#endif - NET_ClearCallNetlibAllTheTime(ce->window_id,"mknews"); - - if(cd->destroy_graph_progress) - FE_GraphProgressDestroy(ce->window_id, - ce->URL_s, - cd->original_content_length, - ce->bytes_received); - status = -1; - - } - return status; -} - -/* process the state machine - * - * returns negative when completely done - */ -MODULE_PRIVATE int -net_ProcessNews (ActiveEntry *ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - -#ifdef XPCOM_OFFLINE - if (cd->offline_state != NULL) -#else - if (cd->offlineState != NULL) -#endif - { - return NET_ProcessOfflineNews(ce, cd); - } - cd->pause_for_read = FALSE; - - while(!cd->pause_for_read) - { - -#if DEBUG - NNTP_LOG_NOTE(("Next state: %s",stateLabels[cd->next_state])); -#endif - - switch(cd->next_state) - { - case NNTP_RESPONSE: - ce->status = net_news_response(ce); - break; - -#ifdef BLOCK_UNTIL_AVAILABLE_CONNECTION - case NNTP_BLOCK_UNTIL_CONNECTIONS_ARE_AVAILABLE: - if (nntp_are_connections_available(cd->control_con)) - { - /* haven't reached connection ceiling on this host; go to connect */ - cd->next_state = NNTP_CONNECTIONS_ARE_AVAILABLE; - cd->pause_for_read = FALSE; - } - else - { - NET_SetReadSelect(ce->window_id, ce->socket); - cd->pause_for_read = TRUE; - } - break; - case NNTP_CONNECTIONS_ARE_AVAILABLE: - /* release our hacky little lock and move on to connection */ -#if 0 - /* this should be handled by NET_ClearCallNetlibAllTheTime()*/ - net_call_all_the_time_count--; - if (net_call_all_the_time_count == 0) -#endif - NET_ClearCallNetlibAllTheTime(ce->window_id,"mknews"); - - cd->next_state = NNTP_CONNECT; - cd->pause_for_read = FALSE; - break; -#endif - - case NNTP_CONNECT: - if (nntp_are_connections_available(cd->control_con)) - { - ce->status = NET_BeginConnect( - HG51154, - NULL, - "NNTP", - HG28465, - &ce->socket, - HG42817, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - - if(ce->socket != NULL) - NET_TotalNumberOfOpenConnections++; - - cd->pause_for_read = TRUE; - if(ce->status == MK_CONNECTED) - { - HG51514 - { - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_LOGIN_RESPONSE; - } - NET_SetReadSelect(ce->window_id, ce->socket); - cd->control_con->csock = ce->socket; - } - else if(ce->status > -1) - { - ce->con_sock = ce->socket; /* set con_sock so we can select on it */ - cd->control_con->csock = ce->socket; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - cd->next_state = NNTP_CONNECT_WAIT; - } - } - else - { -#ifdef BLOCK_UNTIL_AVAILABLE_CONNECTION - /* ###phil this doesn't work yet, but the idea is that we've - * maxed out connections on this host; stay in this state - */ - ce->con_sock = ce->socket; /* set con_sock so we can select on it */ - cd->control_con->csock = ce->socket; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - cd->next_state = NNTP_BLOCK_UNTIL_CONNECTIONS_ARE_AVAILABLE; -#else - ce->status = -1; - cd->next_state = NNTP_ERROR; - ce->socket = cd->control_con->csock = NULL; -#endif - } - break; - - case NNTP_CONNECT_WAIT: - ce->status = NET_FinishConnect( - HG65321, - "NNTP", - HG28465, - &ce->socket, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - - cd->pause_for_read = TRUE; - if(ce->status == MK_CONNECTED) - { - cd->control_con->csock = ce->socket; - HG28477 - { - cd->next_state = NNTP_RESPONSE; - cd->next_state_after_response = NNTP_LOGIN_RESPONSE; - } - - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = NULL; /* reset con_sock so we don't select on it */ - NET_SetReadSelect(ce->window_id, ce->socket); - } - else if(ce->status < 0) - { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - } - else - { - /* the not yet connected state */ - - /* unregister the old ce->socket from the select list - * and register the new value in the case that it changes - */ - if(ce->con_sock != ce->socket) - { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = ce->socket; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - } - break; - - HG42871 - - case NNTP_LOGIN_RESPONSE: - ce->status = net_nntp_login_response(ce); - break; - - case NNTP_SEND_MODE_READER: - ce->status = net_nntp_send_mode_reader(ce); - break; - - case NNTP_SEND_MODE_READER_RESPONSE: - ce->status = net_nntp_send_mode_reader_response(ce); - break; - - case SEND_LIST_EXTENSIONS: - ce->status = net_nntp_send_list_extensions(ce); - break; - case SEND_LIST_EXTENSIONS_RESPONSE: - ce->status = net_nntp_send_list_extensions_response(ce); - break; - case SEND_LIST_SEARCHES: - ce->status = net_nntp_send_list_searches(ce); - break; - case SEND_LIST_SEARCHES_RESPONSE: - ce->status = net_nntp_send_list_searches_response(ce); - break; - case NNTP_LIST_SEARCH_HEADERS: - ce->status = net_send_list_search_headers(ce); - break; - case NNTP_LIST_SEARCH_HEADERS_RESPONSE: - ce->status = net_send_list_search_headers_response(ce); - break; - case NNTP_GET_PROPERTIES: - ce->status = nntp_get_properties(ce); - break; - case NNTP_GET_PROPERTIES_RESPONSE: - ce->status = nntp_get_properties_response(ce); - break; - - case SEND_LIST_SUBSCRIPTIONS: - ce->status = net_send_list_subscriptions(ce); - break; - case SEND_LIST_SUBSCRIPTIONS_RESPONSE: - ce->status = net_send_list_subscriptions_response(ce); - break; - - case SEND_FIRST_NNTP_COMMAND: - ce->status = net_send_first_nntp_command(ce); - break; - - case SEND_FIRST_NNTP_COMMAND_RESPONSE: - ce->status = net_send_first_nntp_command_response(ce); - break; - - case NNTP_SEND_GROUP_FOR_ARTICLE: - ce->status = net_send_group_for_article(ce); - break; - case NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE: - ce->status = net_send_group_for_article_response(ce); - break; - case NNTP_SEND_ARTICLE_NUMBER: - ce->status = net_send_article_number(ce); - break; - - case SETUP_NEWS_STREAM: - ce->status = net_setup_news_stream(ce); - break; - - case NNTP_BEGIN_AUTHORIZE: - ce->status = net_news_begin_authorize(ce); - break; - - case NNTP_AUTHORIZE_RESPONSE: - ce->status = net_news_authorize_response(ce); - break; - - case NNTP_PASSWORD_RESPONSE: - ce->status = net_news_password_response(ce); - break; - - case NNTP_READ_LIST_BEGIN: - ce->status = net_read_news_list_begin(ce); - break; - - case NNTP_READ_LIST: - ce->status = net_read_news_list(ce); - break; - - case DISPLAY_NEWSGROUPS: - ce->status = net_display_newsgroups(ce); - break; - - case NNTP_NEWGROUPS_BEGIN: - ce->status = net_newgroups_begin(ce); - break; - - case NNTP_NEWGROUPS: - ce->status = net_process_newgroups(ce); - break; - - case NNTP_BEGIN_ARTICLE: - ce->status = net_begin_article(ce); - break; - - case NNTP_READ_ARTICLE: - { - char *line; - NewsConData * cd = - (NewsConData *)ce->con_data; - - ce->status = NET_BufferedReadLine(ce->socket, &line, - &cd->data_buf, - &cd->data_buf_size, - (Bool*)&cd->pause_for_read); - - if(ce->status == 0) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - ce->URL_s->error_msg = - NET_ExplainErrorDetails(MK_NNTP_SERVER_ERROR); - return(MK_NNTP_SERVER_ERROR); - } - - if(ce->status > 1) - { - ce->bytes_received += ce->status; - FE_GraphProgress(ce->window_id, ce->URL_s, - ce->bytes_received, ce->status, - ce->URL_s->content_length); - } - - if(!line) - return(ce->status); /* no line yet or error */ - - if (cd->type_wanted == CANCEL_WANTED && - cd->response_code != MK_NNTP_RESPONSE_ARTICLE_HEAD) - { - /* HEAD command failed. */ - return MK_NNTP_CANCEL_ERROR; - } - - if (line[0] == '.' && line[1] == 0) - { - if (cd->type_wanted == CANCEL_WANTED) - cd->next_state = NEWS_START_CANCEL; - else - cd->next_state = NEWS_DONE; - - cd->pause_for_read = FALSE; - } - else - { - if (line[0] == '.') - PL_strcpy (cd->output_buffer, line + 1); - else - PL_strcpy (cd->output_buffer, line); - - /* When we're sending this line to a converter (ie, - it's a message/rfc822) use the local line termination - convention, not CRLF. This makes text articles get - saved with the local line terminators. Since SMTP - and NNTP mandate the use of CRLF, it is expected that - the local system will convert that to the local line - terminator as it is read. - */ - PL_strcat (cd->output_buffer, LINEBREAK); - /* Don't send content-type to mime parser if we're doing a cancel - because it confuses mime parser into not parsing. - */ - if (cd->type_wanted != CANCEL_WANTED || XP_STRNCMP(cd->output_buffer, "Content-Type:", 13)) - ce->status = PUTSTRING(cd->output_buffer); - } - break; - } - - case NNTP_XOVER_BEGIN: - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_READ_NEWSGROUPINFO)); - ce->status = net_read_xover_begin(ce); - break; - - case NNTP_FIGURE_NEXT_CHUNK: - ce->status = net_figure_next_chunk(ce); - break; - - case NNTP_XOVER_SEND: - ce->status = net_xover_send(ce); - break; - - case NNTP_XOVER: - ce->status = net_read_xover(ce); - break; - - case NNTP_XOVER_RESPONSE: - ce->status = net_read_xover_response(ce); - break; - - case NEWS_PROCESS_XOVER: - case NEWS_PROCESS_BODIES: - NET_Progress(ce->window_id, XP_GetString(XP_PROGRESS_SORT_ARTICLES)); - ce->status = net_process_xover(ce); - break; - - case NNTP_PROFILE_ADD: - ce->status = net_profile_add (ce); - break; - case NNTP_PROFILE_ADD_RESPONSE: - ce->status = net_profile_add_response(ce); - break; - case NNTP_PROFILE_DELETE: - ce->status = net_profile_delete (ce); - break; - case NNTP_PROFILE_DELETE_RESPONSE: - ce->status = net_profile_delete_response(ce); - break; - - case NNTP_READ_GROUP: - ce->status = net_read_news_group(ce); - break; - - case NNTP_READ_GROUP_RESPONSE: - ce->status = net_read_news_group_response(ce); - break; - - case NNTP_READ_GROUP_BODY: - ce->status = net_read_news_group_body(ce); - break; - - case NNTP_SEND_POST_DATA: - ce->status = net_send_news_post_data(ce); - break; - - case NNTP_SEND_POST_DATA_RESPONSE: - ce->status = net_send_news_post_data_response(ce); - break; - - case NNTP_CHECK_FOR_MESSAGE: - ce->status = net_check_for_message(ce); - break; - - case NEWS_NEWS_RC_POST: - ce->status = net_NewsRCProcessPost(ce); - break; - - case NEWS_DISPLAY_NEWS_RC: - ce->status = net_DisplayNewsRC(ce); - break; - - case NEWS_DISPLAY_NEWS_RC_RESPONSE: - ce->status = net_DisplayNewsRCResponse(ce); - break; - - case NEWS_START_CANCEL: - ce->status = net_start_cancel(ce); - break; - - case NEWS_DO_CANCEL: - ce->status = net_do_cancel(ce); - break; - - case NNTP_XPAT_SEND: - ce->status = net_xpat_send(ce); - break; - case NNTP_XPAT_RESPONSE: - ce->status = net_xpat_response(ce); - break; - case NNTP_SEARCH: - ce->status = net_nntp_search(ce); - break; - case NNTP_SEARCH_RESPONSE: - ce->status = net_nntp_search_response(ce); - break; - case NNTP_SEARCH_RESULTS: - ce->status = net_nntp_search_results(ce); - break; - case NNTP_LIST_PRETTY_NAMES: - ce->status = net_list_pretty_names(ce); - break; - case NNTP_LIST_PRETTY_NAMES_RESPONSE: - ce->status = net_list_pretty_names_response(ce); - break; - case NNTP_LIST_XACTIVE: - ce->status = net_list_xactive(ce); - break; - case NNTP_LIST_XACTIVE_RESPONSE: - ce->status = net_list_xactive_response(ce); - break; - case NNTP_LIST_GROUP: - ce->status = net_list_group(ce); - break; - case NNTP_LIST_GROUP_RESPONSE: - ce->status = net_list_group_response(ce); - break; - case NEWS_DONE: - /* call into libmsg and see if the article counts - * are up to date. If they are not then we - * want to do a "news://host/group" URL so that we - * can finish up the article counts. - */ - if (cd->stream) - COMPLETE_STREAM; - - cd->next_state = NEWS_FREE; - /* set the connection unbusy - */ - cd->control_con->busy = FALSE; - NET_TotalNumberOfOpenConnections--; - - NET_ClearReadSelect(ce->window_id, cd->control_con->csock); - NET_RefreshCacheFileExpiration(ce->URL_s); - break; - - case NEWS_ERROR: - if(cd->stream) - ABORT_STREAM(ce->status); - cd->next_state = NEWS_FREE; - /* set the connection unbusy - */ - cd->control_con->busy = FALSE; - NET_TotalNumberOfOpenConnections--; - - if(cd->control_con->csock != NULL) - { - NET_ClearReadSelect(ce->window_id, cd->control_con->csock); - } - break; - - case NNTP_ERROR: - if(cd->stream) - { - ABORT_STREAM(ce->status); - cd->stream=0; - } - - if(cd->control_con && cd->control_con->csock != NULL) - { - NNTP_LOG_NOTE(("Clearing read and connect select on socket %d", - cd->control_con->csock)); - NET_ClearConnectSelect(ce->window_id, cd->control_con->csock); - NET_ClearReadSelect(ce->window_id, cd->control_con->csock); -#if 0 - /* this is probably depricated/merged into - NET_ClearReadSelect */ - NET_ClearFileReadSelect(ce->window_id, - cd->control_con->csock); -#endif -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - { - cd->calling_netlib_all_the_time = FALSE; -#if 0 - /* this should be handled by NET_ClearCallNetlibAllTheTime()*/ - net_call_all_the_time_count--; - if(net_call_all_the_time_count == 0) -#endif - NET_ClearCallNetlibAllTheTime(ce->window_id,"mknews"); - } -#endif /* XP_WIN */ -#if defined(XP_WIN) || (defined(XP_UNIX)&&defined(UNIX_ASYNC_DNS)) - NET_ClearDNSSelect(ce->window_id, cd->control_con->csock); -#endif /* XP_WIN || XP_UNIX */ - net_nntp_close (cd->control_con, ce->status); /* close the - socket */ - NET_TotalNumberOfOpenConnections--; - ce->socket = NULL; - } - - /* check if this connection came from the cache or if it was - * a new connection. If it was not new lets start it over - * again. But only if we didn't have any successful protocol - * dialog at all. - */ - if(cd->control_con && cd->control_con->prev_cache && - !cd->some_protocol_succeeded) - { - cd->control_con->prev_cache = FALSE; - cd->next_state = NNTP_CONNECT; - ce->status = 0; /* keep going */ - } - else - { - cd->next_state = NEWS_FREE; - - /* remove the connection from the cache list - * and free the data - */ - XP_ListRemoveObject(nntp_connection_list, cd->control_con); - if(cd->control_con) - { - FREEIF(cd->control_con->hostname); - FREE(cd->control_con); - cd->control_con = NULL; - } - } - break; - - case NEWS_FREE: - - /* do we need to know if we're parsing xover to call finish xover? */ - /* yes, I think we do! Why did I think we should??? */ - /* If we've gotten to NEWS_FREE and there is still XOVER - data, there was an error or we were interrupted or - something. So, tell libmsg there was an abnormal - exit so that it can free its data. */ -#ifdef XPCOM_XOVER - if (cd->xover_parser != NULL) -#else - if (cd->xover_parse_state != NULL) -#endif - { - int status; - nsresult rv; -/* PR_ASSERT (ce->status < 0);*/ -#ifdef XPCOM_XOVER - /* XXX - how/when to Release() this? */ - rv = cd->xover_parser->Finish(ce->status,&status); - PR_ASSERT(NS_SUCCEEDED(rv)); - - if (NS_SUCCEEDED(rv)) - NS_RELEASE(cd->xover_parser); - -#else - status = MSG_FinishXOVER (cd->pane, - &cd->xover_parse_state, - ce->status); - PR_ASSERT (!cd->xover_parse_state); -#endif - if (NS_SUCCEEDED(rv) && - ce->status >= 0 && status < 0) - ce->status = status; - } - else - { -#ifdef XPCOM_NEWSPARSE - /* XXX - state is stored in the MSG_Pane cd->pane */ - NS_RELEASE(cd->article_list); -#else - MSG_ClearListNewsgroupState(cd->pane, cd->host, cd->group_name, ce->status); -#endif - } - - if (cd->control_con) - cd->control_con->last_used_time = XP_TIME(); - - FREEIF(cd->path); - FREEIF(cd->response_txt); - FREEIF(cd->data_buf); - - FREEIF(cd->output_buffer); - FREEIF(cd->proxy_server); - FREEIF(cd->stream); /* don't forget the stream */ - if(cd->tcp_con_data) - NET_FreeTCPConData(cd->tcp_con_data); - -#ifdef XPCOM_NEWSGROUP - NS_RELEASE(cd->newsgroup); -#else - FREEIF(cd->group_name); -#endif - - FREEIF (cd->cancel_id); - FREEIF (cd->cancel_from); - FREEIF (cd->cancel_newsgroups); - FREEIF (cd->cancel_distribution); - - if(cd->destroy_graph_progress) - FE_GraphProgressDestroy(ce->window_id, - ce->URL_s, - cd->original_content_length, - ce->bytes_received); - PR_Free(cd); - - /* gate the maximum number of cached connections - * but don't delete busy ones. - */ - if(XP_ListCount(nntp_connection_list) > kMaxCachedConnections) - { - XP_List * list_ptr = nntp_connection_list->next; - NNTPConnection * con; - - NNTP_LOG_NOTE(("killing cached news connection")); - - while(list_ptr) - { - con = (NNTPConnection *) list_ptr->object; - list_ptr = list_ptr->next; - if(!con->busy) - { - XP_ListRemoveObject(nntp_connection_list, con); - net_nntp_close(con, ce->status); - FREEIF(con->hostname); - PR_Free(con); - break; - } - } - } - return(-1); /* all done */ - - default: - /* big error */ - return(-1); - } - - if(ce->status < 0 && cd->next_state != NEWS_ERROR && - cd->next_state != NNTP_ERROR && cd->next_state != NEWS_FREE) - { - cd->next_state = NNTP_ERROR; - cd->pause_for_read = FALSE; - } - } /* end big while */ - - return(0); /* keep going */ -} - -/* abort the connection in progress - */ -MODULE_PRIVATE int -NET_InterruptNews(ActiveEntry * ce) -{ - NewsConData * cd = (NewsConData *)ce->con_data; - nsresult rv; -#ifdef XPCOM_OFFLINE - if (cd->offline_state != NULL) { - int status; - rv = cd->offline_state->Interrupt(&status); - if (NS_SUCCEEDED(rv)) - return status; - else - return -1; /* ??? */ - } -#else - if (cd->offlineState != NULL) - return MSG_InterruptOfflineNews(cd->offlineState); -#endif - - cd->next_state = NNTP_ERROR; - ce->status = MK_INTERRUPTED; - - if (cd->control_con) - cd->control_con->prev_cache = FALSE; /* to keep if from reconnecting */ - - return(net_ProcessNews(ce)); -} - -/* Free any memory used up - * close cached connections and - * free newsgroup listings - */ -MODULE_PRIVATE void -NET_CleanupNews(void) -{ - NNTP_LOG_NOTE(("NET_CleanupNews called")); - - /* this is a small leak but since I don't have another function to - * clear my connections I need to call this one alot and I don't - * want to free the newshost - * - * FREE_AND_CLEAR(NET_NewsHost); - */ - - if(nntp_connection_list) - { - NNTPConnection * tmp_con; - - while((tmp_con = (NNTPConnection *)XP_ListRemoveTopObject(nntp_connection_list)) != NULL) - { - if(!tmp_con->busy) - { - FREE(tmp_con->hostname); - FREEIF(tmp_con->current_group); - if(tmp_con->csock != NULL) - { - net_nntp_close(tmp_con, 0 /* status? */); - } - FREE(tmp_con); - } - } - - if(XP_ListIsEmpty(nntp_connection_list)) - { - XP_ListDestroy(nntp_connection_list); - nntp_connection_list = 0; - } - } - - return; -} - - - -#ifdef PROFILE -#pragma profile off -#endif - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/protocol/nntp/mknews.h b/mozilla/network/protocol/nntp/mknews.h deleted file mode 100644 index 8d02638a98a..00000000000 --- a/mozilla/network/protocol/nntp/mknews.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * Global NNTP-related functions and error conditions - */ - -#ifndef MKNEWS_H -#define MKNEWS_H - -#ifndef MKGETURL_H -#include "mkgeturl.h" -#endif /* MKGETURL_H */ - -#define MK_NNTP_RESPONSE_HELP 100 - -#define MK_NNTP_RESPONSE_POSTING_ALLOWED 200 -#define MK_NNTP_RESPONSE_POSTING_DENIED 201 - -#define MK_NNTP_RESPONSE_DISCONTINUED 400 - -#define MK_NNTP_RESPONSE_COMMAND_UNKNOWN 500 -#define MK_NNTP_RESPONSE_SYNTAX_ERROR 501 -#define MK_NNTP_RESPONSE_PERMISSION_DENIED 502 -#define MK_NNTP_RESPONSE_SERVER_ERROR 503 - -#define MK_NNTP_RESPONSE_ARTICLE_BOTH 220 -#define MK_NNTP_RESPONSE_ARTICLE_HEAD 221 -#define MK_NNTP_RESPONSE_ARTICLE_BODY 222 -#define MK_NNTP_RESPONSE_ARTICLE_NONE 223 -#define MK_NNTP_RESPONSE_ARTICLE_NO_GROUP 412 -#define MK_NNTP_RESPONSE_ARTICLE_NO_CURRENT 420 -#define MK_NNTP_RESPONSE_ARTICLE_NONEXIST 423 -#define MK_NNTP_RESPONSE_ARTICLE_NOTFOUND 430 - -#define MK_NNTP_RESPONSE_GROUP_SELECTED 211 -#define MK_NNTP_RESPONSE_GROUP_NO_GROUP 411 - -#define MK_NNTP_RESPONSE_IHAVE_OK 235 -#define MK_NNTP_RESPONSE_IHAVE_ARTICLE 335 -#define MK_NNTP_RESPONSE_IHAVE_NOT_WANTED 435 -#define MK_NNTP_RESPONSE_IHAVE_FAILED 436 -#define MK_NNTP_RESPONSE_IHAVE_REJECTED 437 - -#define MK_NNTP_RESPONSE_LAST_OK 223 -#define MK_NNTP_RESPONSE_LAST_NO_GROUP 412 -#define MK_NNTP_RESPONSE_LAST_NO_CURRENT 420 -#define MK_NNTP_RESPONSE_LAST_NO_ARTICLE 422 - -#define MK_NNTP_RESPONSE_LIST_OK 215 - -#define MK_NNTP_RESPONSE_NEWGROUPS_OK 231 - -#define MK_NNTP_RESPONSE_NEWNEWS_OK 230 - -#define MK_NNTP_RESPONSE_NEXT_OK 223 -#define MK_NNTP_RESPONSE_NEXT_NO_GROUP 412 -#define MK_NNTP_RESPONSE_NEXT_NO_CURRENT 420 -#define MK_NNTP_RESPONSE_NEXT_NO_ARTICLE 421 - -#define MK_NNTP_RESPONSE_POST_OK 240 -#define MK_NNTP_RESPONSE_POST_SEND_NOW 340 -#define MK_NNTP_RESPONSE_POST_DENIED 440 -#define MK_NNTP_RESPONSE_POST_FAILED 441 - -#define MK_NNTP_RESPONSE_QUIT_OK 205 - -#define MK_NNTP_RESPONSE_SLAVE_OK 202 - -#define MK_NNTP_RESPONSE_CHECK_NO_ARTICLE 238 -#define MK_NNTP_RESPONSE_CHECK_NO_ACCEPT 400 -#define MK_NNTP_RESPONSE_CHECK_LATER 431 -#define MK_NNTP_RESPONSE_CHECK_DONT_SEND 438 -#define MK_NNTP_RESPONSE_CHECK_DENIED 480 -#define MK_NNTP_RESPONSE_CHECK_ERROR 500 - -#define MK_NNTP_RESPONSE_XHDR_OK 221 -#define MK_NNTP_RESPONSE_XHDR_NO_GROUP 412 -#define MK_NNTP_RESPONSE_XHDR_NO_CURRENT 420 -#define MK_NNTP_RESPONSE_XHDR_NO_ARTICLE 430 -#define MK_NNTP_RESPONSE_XHDR_DENIED 502 - -#define MK_NNTP_RESPONSE_XOVER_OK 224 -#define MK_NNTP_RESPONSE_XOVER_NO_GROUP 412 -#define MK_NNTP_RESPONSE_XOVER_NO_CURRENT 420 -#define MK_NNTP_RESPONSE_XOVER_DENIED 502 - -#define MK_NNTP_RESPONSE_XPAT_OK 221 -#define MK_NNTP_RESPONSE_XPAT_NO_ARTICLE 430 -#define MK_NNTP_RESPONSE_XPAT_DENIED 502 - -#define MK_NNTP_RESPONSE_AUTHINFO_OK 281 -#define MK_NNTP_RESPONSE_AUTHINFO_CONT 381 -#define MK_NNTP_RESPONSE_AUTHINFO_REQUIRE 480 -#define MK_NNTP_RESPONSE_AUTHINFO_REJECT 482 -#define MK_NNTP_RESPONSE_AUTHINFO_DENIED 502 - -#define MK_NNTP_RESPONSE_ - -#define MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_OK 250 -#define MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_CONT 350 -#define MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_REQUIRE 450 -#define MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_REJECT 452 - - - -#define MK_NNTP_RESPONSE_TYPE_INFO 1 -#define MK_NNTP_RESPONSE_TYPE_OK 2 -#define MK_NNTP_RESPONSE_TYPE_CONT 3 -#define MK_NNTP_RESPONSE_TYPE_CANNOT 4 -#define MK_NNTP_RESPONSE_TYPE_ERROR 5 - -#define MK_NNTP_RESPONSE_TYPE(x) (x/100) -extern CONST char * NET_MKGetNewsHost (); -extern int net_InitializeNewsFeData (ActiveEntry * cur_entry); -extern void NET_InitNewsProtocol(void); - -#endif /* MKNEWS_H */ diff --git a/mozilla/network/protocol/nntp/mknewsgr.cpp b/mozilla/network/protocol/nntp/mknewsgr.cpp deleted file mode 100644 index 4a7ebe88b4d..00000000000 --- a/mozilla/network/protocol/nntp/mknewsgr.cpp +++ /dev/null @@ -1,437 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * newsrc file stuff. - */ - -#include "mkutils.h" -#include "msgcom.h" -#include "xp_qsort.h" - -/* UNIX doesn't need this stuff since it uses the file system - * to store the mappings as filenames - */ - -XP_List *HostMapList=0; -Bool NewsrcMapDirty=FALSE; - -typedef struct _NewsrcHostMap { - char * filename; - char * psuedo_name; - Bool is_newsgroups_file; /* This was Bool * */ -} NewsrcHostMap; - -/* register a newsrc file mapping - */ -PUBLIC Bool -NET_RegisterNewsrcFile(char * filename, - char *hostname, - Bool bs, - Bool is_newsgroups_file) -{ - NewsrcHostMap *host_map_struct = PR_NEW(NewsrcHostMap); - XP_List * list_prt; - NewsrcHostMap *tmp_host_map_struct; - - if(!host_map_struct) - return(FALSE); - - memset(host_map_struct, 0, sizeof(NewsrcHostMap)); - - /* you losers, there's no such thing as XP_Assert in xfe!! */ - assert(filename); - assert(hostname); - - if(bs) - StrAllocCopy(host_map_struct->psuedo_name, "snewsrc-"); - else - StrAllocCopy(host_map_struct->psuedo_name, "newsrc-"); - - StrAllocCat(host_map_struct->psuedo_name, hostname); - - StrAllocCopy(host_map_struct->filename, filename); - - host_map_struct->is_newsgroups_file = is_newsgroups_file; - - if(!HostMapList) - HostMapList = XP_ListNew(); - - if(!HostMapList) - return(FALSE); - - NewsrcMapDirty = TRUE; - - /* search for duplicate mappings */ - list_prt = HostMapList; - while((tmp_host_map_struct = (NewsrcHostMap *)XP_ListNextObject(list_prt)) != NULL) - { - if(tmp_host_map_struct->is_newsgroups_file == is_newsgroups_file - && !PL_strcasecmp(tmp_host_map_struct->psuedo_name, - host_map_struct->psuedo_name)) - { - XP_ListRemoveObject(HostMapList, tmp_host_map_struct); - FREEIF(tmp_host_map_struct->psuedo_name); - FREEIF(tmp_host_map_struct->filename); - FREE(tmp_host_map_struct); - - break; /* end search */ - } - } - - XP_ListAddObjectToEnd(HostMapList, host_map_struct); - - NET_SaveNewsrcFileMappings(); - - return(TRUE); -} - -/* removes a newshost to file mapping. Removes both - * the newsrc and the newsgroups mapping - * this function does not remove the actual files, - * that is left up to the caller - */ -PUBLIC void -NET_UnregisterNewsHost(const char *host, - Bool bs) -{ - XP_List * list_prt = HostMapList; - NewsrcHostMap *host_map_struct; - char *hostname; - - PR_ASSERT(host); - - if(!host) - return; - - /* Run through the entire list and remove all entries that - * match that hostname - */ - while((host_map_struct = (NewsrcHostMap *)XP_ListNextObject(list_prt)) != NULL) - { - - if(bs && *host_map_struct->psuedo_name != 's') - continue; - - if(!bs && *host_map_struct->psuedo_name == 's') - continue; - - hostname = PL_strchr(host_map_struct->psuedo_name, '-'); - - if(!hostname) - continue; - - hostname++; - - if(PL_strcasecmp(hostname, host)) - continue; - - XP_ListRemoveObject(HostMapList, host_map_struct); - - NewsrcMapDirty = TRUE; - - /* free the data */ - FREEIF(host_map_struct->psuedo_name); - FREEIF(host_map_struct->filename); - FREE(host_map_struct); - - /* we must start over in the list because the - * act of removeing an item will cause purity - * errors if we don't start over - */ - list_prt = HostMapList; - } - NET_SaveNewsrcFileMappings(); -} - -/* map a filename and security status into a filename - * - * returns NULL on error or no mapping. - */ -PUBLIC char * -NET_MapNewsrcHostToFilename(char * host, - Bool bs, - Bool is_newsgroups_file) -{ - XP_List * list_prt = HostMapList; - NewsrcHostMap *host_map_struct; - char *hostname; - - while((host_map_struct = (NewsrcHostMap *)XP_ListNextObject(list_prt)) != NULL) - { - if(is_newsgroups_file != host_map_struct->is_newsgroups_file) - continue; - - if(bs && *host_map_struct->psuedo_name != 's') - continue; - - if(!bs && *host_map_struct->psuedo_name == 's') - continue; - - hostname = PL_strchr(host_map_struct->psuedo_name, '-'); - - if(!hostname) - continue; - - hostname++; - - if(PL_strcasecmp(hostname, host)) - continue; - - return(host_map_struct->filename); - - } - - return(NULL); -} - -#define NEWSRC_MAP_FILE_COOKIE "netscape-newsrc-map-file" - -/* save newsrc file mappings from memory onto disk - */ -PUBLIC Bool -NET_SaveNewsrcFileMappings() -{ - XP_List * list_prt = HostMapList; - NewsrcHostMap *host_map_struct; - XP_File fp; - - if(!NewsrcMapDirty) - return(TRUE); - - if(!(fp = XP_FileOpen("", xpNewsrcFileMap, XP_FILE_WRITE_BIN))) - { - return(FALSE); - } - - XP_FileWrite(NEWSRC_MAP_FILE_COOKIE, PL_strlen(NEWSRC_MAP_FILE_COOKIE), fp); - XP_FileWrite(LINEBREAK, PL_strlen(LINEBREAK), fp); - - while((host_map_struct = (NewsrcHostMap *)XP_ListNextObject(list_prt)) != NULL) - { - - XP_FileWrite(host_map_struct->psuedo_name, - PL_strlen(host_map_struct->psuedo_name), - fp); - - XP_FileWrite("\t", 1, fp); - - XP_FileWrite(host_map_struct->filename, - PL_strlen(host_map_struct->filename), - fp); - - XP_FileWrite("\t", 1, fp); - - if(host_map_struct->is_newsgroups_file) - XP_FileWrite("TRUE", 4, fp); - else - XP_FileWrite("FALSE", 5, fp); - - XP_FileWrite(LINEBREAK, PL_strlen(LINEBREAK), fp); - } - - XP_FileClose(fp); - - NewsrcMapDirty = FALSE; - - return(TRUE); -} - -/* read newsrc file mappings from disk into memory - */ -PUBLIC Bool -NET_ReadNewsrcFileMappings() -{ - XP_File fp; - char buffer[512]; - char psuedo_name[512]; - char filename[512]; - char is_newsgroup[512]; - NewsrcHostMap * hs_struct; - - if(!(fp = XP_FileOpen("", xpNewsrcFileMap, XP_FILE_READ_BIN))) - { - return(FALSE); - } - - if(!HostMapList) - HostMapList = XP_ListNew(); - - /* get the cookie and ignore */ - XP_FileReadLine(buffer, sizeof(buffer), fp); - - while(XP_FileReadLine(buffer, sizeof(buffer), fp)) - { - char * p; - int i; - - hs_struct = PR_NEW(NewsrcHostMap); - - if(!hs_struct) - return(FALSE); - - memset(hs_struct, 0, sizeof(NewsrcHostMap)); - - /* - This used to be scanf() call which would incorrectly - parse long filenames with spaces in them. - JRE - */ - - filename[0] = '\0'; - is_newsgroup[0]='\0'; - - for (i = 0, p = buffer; *p && *p != '\t' && i < 500; p++, i++) - psuedo_name[i] = *p; - psuedo_name[i] = '\0'; - if (*p) - { - for (i = 0, p++; *p && *p != '\t' && i < 500; p++, i++) - filename[i] = *p; - filename[i]='\0'; - if (*p) - { - for (i = 0, p++; *p && *p != '\r' && i < 500; p++, i++) - is_newsgroup[i] = *p; - is_newsgroup[i]='\0'; - } - } - - StrAllocCopy(hs_struct->psuedo_name, psuedo_name); - StrAllocCopy(hs_struct->filename, filename); - - if(!XP_STRNCMP(is_newsgroup, "TRUE", 4)) - hs_struct->is_newsgroups_file = TRUE; - - XP_ListAddObjectToEnd(HostMapList, hs_struct); - } - - - XP_FileClose(fp); - - return(TRUE); -} - -PUBLIC void -NET_FreeNewsrcFileMappings(void) -{ - NewsrcHostMap *host_map_struct; - - while((host_map_struct = (NewsrcHostMap *)XP_ListRemoveTopObject(HostMapList)) != NULL) - { - FREEIF(host_map_struct->psuedo_name); - FREEIF(host_map_struct->filename); - FREE(host_map_struct); - } -} - - -#if defined(DEBUG) && defined(XP_UNIX) - -PUBLIC void -TestNewsrcFileMappings(void) -{ - - HG04206; - printf("insec flop maps to: %s\n", NET_MapNewsrcHostToFilename("flop", FALSE, FALSE)); - printf("insec news maps to: %s\n", NET_MapNewsrcHostToFilename("news", FALSE, FALSE)); - - NET_RegisterNewsrcFile("newsrc-flop", "flop", FALSE, FALSE); - NET_RegisterNewsrcFile("snewsrc-flop", "flop", TRUE, FALSE); - NET_RegisterNewsrcFile("newsrc-news", "news", FALSE, FALSE); - - HG04206; - printf("insec flop maps to: %s\n", NET_MapNewsrcHostToFilename("flop", FALSE, FALSE)); - printf("insec news maps to: %s\n", NET_MapNewsrcHostToFilename("news", FALSE, FALSE)); - - printf("saving mappings\n"); - NET_SaveNewsrcFileMappings(); - printf("freeing mappings\n"); - NET_FreeNewsrcFileMappings(); - printf("reading mappings\n"); - NET_ReadNewsrcFileMappings(); - - printf("adding duplicates\n"); - NET_RegisterNewsrcFile("newsrc-flop", "flop", FALSE, FALSE); - NET_RegisterNewsrcFile("snewsrc-flop", "flop", TRUE, FALSE); - NET_RegisterNewsrcFile("newsrc-news", "news", FALSE, FALSE); - - HG04206; - printf("insec flop maps to: %s\n", NET_MapNewsrcHostToFilename("flop", FALSE, FALSE)); - printf("insec news maps to: %s\n", NET_MapNewsrcHostToFilename("news", FALSE, FALSE)); -} -#endif - -/* XP_GetNewsRCFiles returns a null terminated array - * of pointers to malloc'd filename's. Each filename - * represents a different newsrc file. - * - * return only the filename since the path is not needed - * or wanted. - * - * Netlib is expecting a string of the form: - * [s]newsrc-host.name.domain[:port] - * - * examples: - * newsrc-news.mcom.com - * snewsrc-flop.mcom.com - * newsrc-news.mcom.com:118 - * snewsrc-flop.mcom.com:1191 - * - * the port number is optional and should only be - * there when different from the default. - * the "s" in front of newsrc signifies that - * security is to be used. - * - * return NULL on critical error or no files - */ -#if !defined(XP_UNIX) -PUBLIC char ** XP_GetNewsRCFiles(void) -{ - /* @@@ max number of newsrc's is 512 - */ - char ** rv = (char **)PL_Malloc(sizeof(char*)*512); - XP_List * list_prt = HostMapList; - NewsrcHostMap *host_map_struct; - int count=0; - - if(!rv) - return(NULL); - - memset(rv, 0, sizeof(char*)*512); - - while((host_map_struct = (NewsrcHostMap *)XP_ListNextObject(list_prt)) != NULL) - { - - if(host_map_struct->is_newsgroups_file) - continue; - - StrAllocCopy(rv[count++], host_map_struct->psuedo_name); - - if(count >= 510) - break; - } - - return(rv); -} -#endif /* UNIX */ - - diff --git a/mozilla/network/protocol/nntp/mknewsgr.h b/mozilla/network/protocol/nntp/mknewsgr.h deleted file mode 100644 index 38cf92f741b..00000000000 --- a/mozilla/network/protocol/nntp/mknewsgr.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -/* - * functions to manage large numbers of USENET newsgroups - * store them on disk, free them, search them, etc. - * - */ - -#ifndef MKNEWSGR_H -#define MKNEWSGR_H - -/* save a newsgroup name - * - * will munge the newsgroup name passed in for efficiency - * - */ -extern void NET_StoreNewsGroup(char *hostname, XP_Bool is_secure, char * newsgroup); - -/* free up the list of newsgroups - */ -extern void NET_FreeNewsgroups(char *hostname, XP_Bool is_secure); - -/* sort the newsgroups - */ -extern void NET_SortNewsgroups(char *hostname, XP_Bool is_secure); - -/* Search and display newsgroups - */ -extern int NET_DisplayNewsgroups(MWContext *context, - char *hostname, - Bool is_secure, - char *search_string); - -/* Save them out to disk - */ -extern void NET_SaveNewsgroupsToDisk(char *hostname, XP_Bool is_secure); - -/* read them from disk - */ -extern time_t NET_ReadNewsgroupsFromDisk(char *hostname, XP_Bool is_secure); - -/* Get the last access date, load the newsgroups from - * disk if they are not loaded - */ -extern time_t NET_NewsgroupsLastUpdatedTime(char *hostname, XP_Bool is_secure); - -#endif - diff --git a/mozilla/network/protocol/nntp/public/Makefile.in b/mozilla/network/protocol/nntp/public/Makefile.in deleted file mode 100644 index a3168e544c9..00000000000 --- a/mozilla/network/protocol/nntp/public/Makefile.in +++ /dev/null @@ -1,30 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/protocol/pop3/MANIFEST b/mozilla/network/protocol/pop3/MANIFEST deleted file mode 100644 index 9510174c7dc..00000000000 --- a/mozilla/network/protocol/pop3/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mkpop3.h diff --git a/mozilla/network/protocol/pop3/Makefile.in b/mozilla/network/protocol/pop3/Makefile.in deleted file mode 100644 index 05717ae88b1..00000000000 --- a/mozilla/network/protocol/pop3/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = pop3url -LIBRARY_NAME = pop3url - -REQUIRES = netcache network dbm util pref js java fileurl security layer img httpurl mimetype htmldlgs - -CSRCS = mkpop3.c - -EXPORTS = $(srcdir)/mkpop3.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/pop3/makefile.win b/mozilla/network/protocol/pop3/makefile.win deleted file mode 100644 index fdc146591d9..00000000000 --- a/mozilla/network/protocol/pop3/makefile.win +++ /dev/null @@ -1,87 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkpop3.obj \ - $(NULL) - -CSRCS = \ - mkpop3.c \ - $(NULL) - - -LIBRARY_NAME=pop3url -MODULE=pop3url -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network ldap -EXPORTS= mkpop3.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\mimetype \ -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/pop3/mkpop3.c b/mozilla/network/protocol/pop3/mkpop3.c deleted file mode 100644 index f8647d42cdd..00000000000 --- a/mozilla/network/protocol/pop3/mkpop3.c +++ /dev/null @@ -1,3879 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * state machine to speak pop3 - * - * Originally designed and implemented by Lou Montulli '95 - * Extremely heavily modified by Terry Weissman and Jamie Zawinski '95 '96 - */ - -/* Please leave outside of ifdef for windows precompiled headers */ -#include "rosetta.h" -#include "mkutils.h" -#include "mktcp.h" -#include "netutils.h" - -/* A more guaranteed way of making sure that we never get duplicate messages -is to always get each message's UIDL (if the server supports it) -and use these for storing up deletes which were not committed on the -server. Based on our experience, it looks like we do NOT need to -do this (it has performance tradeoffs, etc.). To turn it on, three -things need to happen: #define POP_ALWAYS_USE_UIDL_FOR_DUPLICATES, verify that -the uidl's are correctly getting added when the delete response is received, -and change the POP3_QUIT_RESPONSE state to flush the newly committed deletes. */ - -/* - * Cannot have the following line uncommented. It is defined. - * #ifdef POP_ALWAYS_USE_UIDL_FOR_DUPLICATES will always be evaluated - * as TRUE. - * -#define POP_ALWAYS_USE_UIDL_FOR_DUPLICATES 0 - * - */ - -#ifdef MOZILLA_CLIENT - -#include "mkgeturl.h" -#include "mkpop3.h" -#include "xp_hash.h" -#include "merrors.h" -#include "secnav.h" -#include "ssl.h" -#include "prio.h" -#include "xp_error.h" -#include "xpgetstr.h" -#include "prerror.h" -#include "prefapi.h" - -extern int MK_OUT_OF_MEMORY; -extern int MK_POP3_DELE_FAILURE; -extern int MK_POP3_LIST_FAILURE; -extern int MK_POP3_MESSAGE_WRITE_ERROR; -extern int MK_POP3_NO_MESSAGES; -extern int MK_POP3_OUT_OF_DISK_SPACE; -extern int MK_POP3_PASSWORD_FAILURE; -extern int MK_POP3_PASSWORD_UNDEFINED; -extern int MK_POP3_RETR_FAILURE; -extern int MK_POP3_SERVER_ERROR; -extern int MK_POP3_USERNAME_FAILURE; -extern int MK_POP3_USERNAME_UNDEFINED; -extern int MK_TCP_READ_ERROR; -extern int MK_TCP_WRITE_ERROR; -extern int XP_ERRNO_EWOULDBLOCK; -extern int XP_NO_ANSWER; -extern int XP_THE_POP3_SERVER_DOES_NOT_SUPPORT_UIDL_ETC; -extern int XP_RECEIVING_MESSAGE_OF; -extern int XP_THE_POP3_SERVER_DOES_NOT_SUPPORT_THE_TOP_COMMAND; -extern int XP_THE_PREVIOUSLY_ENTERED_PASSWORD_IS_INVALID_ETC; -extern int XP_CONNECT_HOST_CONTACTED_SENDING_LOGIN_INFORMATION; -extern int XP_PASSWORD_FOR_POP3_USER; -extern int MK_MSG_DOWNLOAD_COUNT; -extern int MK_UNABLE_TO_CONNECT; -extern int MK_CONNECTION_REFUSED; -extern int MK_CONNECTION_TIMED_OUT; - -extern void net_graceful_shutdown(PRFileDesc * sock, XP_Bool isSecure); - -#define POP3_PORT 110 /* the iana port for pop3 */ -#define OUTPUT_BUFFER_SIZE 512 /* max size of command string */ - -/* Globals */ - PRIVATE char *net_pop3_password=0; /* obfuscated pop3 password */ -PRIVATE XP_Bool net_pop3_password_pending=FALSE; -PRIVATE XP_Bool net_pop3_block = FALSE; - -/* We set this if we find that the UIDL command doesn't work. - It is reset to FALSE if the user name is re-set (a cheap way - of seeing if the server has changed...) - */ -PRIVATE XP_Bool net_uidl_command_unimplemented = FALSE; -PRIVATE XP_Bool net_xtnd_xlst_command_unimplemented = FALSE; -PRIVATE XP_Bool net_top_command_unimplemented = FALSE; - -/* definitions of extended POP3 capabilities - */ -typedef enum { - POP3_CAPABILITY_UNDEFINED = 0x00000000, - POP3_AUTH_LOGIN_UNDEFINED = 0x00000001, - POP3_HAS_AUTH_LOGIN = 0x00000002, - POP3_XSENDER_UNDEFINED = 0x00000004, - POP3_HAS_XSENDER = 0x00000008, - POP3_GURL_UNDEFINED = 0x00000010, - POP3_HAS_GURL = 0x00000020 -} Pop3CapabilityEnum; - -PRIVATE uint32 pop3CapabilityFlags = POP3_AUTH_LOGIN_UNDEFINED | - POP3_XSENDER_UNDEFINED | - POP3_GURL_UNDEFINED; - - -/* definitions of state for the state machine design - */ -typedef enum { - POP3_READ_PASSWORD, - POP3_START_CONNECT, - POP3_FINISH_CONNECT, - POP3_WAIT_FOR_RESPONSE, - POP3_WAIT_FOR_START_OF_CONNECTION_RESPONSE, - POP3_SEND_USERNAME, - POP3_SEND_PASSWORD, - POP3_SEND_STAT, - POP3_GET_STAT, - POP3_SEND_LIST, - POP3_GET_LIST, - POP3_SEND_UIDL_LIST, - POP3_GET_UIDL_LIST, - POP3_SEND_XTND_XLST_MSGID, - POP3_GET_XTND_XLST_MSGID, - POP3_GET_MSG, - POP3_SEND_TOP, - POP3_TOP_RESPONSE, - POP3_SEND_RETR, - POP3_RETR_RESPONSE, - POP3_SEND_DELE, - POP3_DELE_RESPONSE, - POP3_SEND_QUIT, - POP3_DONE, - POP3_ERROR_DONE, - POP3_FREE, - /* The following 3 states support the use of the 'TOP' command instead of UIDL - for leaving mail on the pop server -km */ - POP3_START_USE_TOP_FOR_FAKE_UIDL, - POP3_SEND_FAKE_UIDL_TOP, - POP3_GET_FAKE_UIDL_TOP, - POP3_SEND_AUTH, - POP3_AUTH_RESPONSE, - POP3_AUTH_LOGIN, - POP3_AUTH_LOGIN_RESPONSE, - POP3_SEND_XSENDER, - POP3_XSENDER_RESPONSE, - POP3_SEND_GURL, - POP3_GURL_RESPONSE, -#ifdef POP_ALWAYS_USE_UIDL_FOR_DUPLICATES - POP3_QUIT_RESPONSE, -#endif - POP3_INTERRUPTED -} Pop3StatesEnum; - -/* structure to hold data pertaining to the active state of - * a transfer in progress. - * - */ - - - -#define KEEP 'k' /* If we want to keep this item on server. */ -#define DELETE_CHAR 'd' /* If we want to delete this item. */ -#define TOO_BIG 'b' /* item left on server because it was too big */ - -typedef struct Pop3AllocedString { /* Need this silliness as a place to - keep the strings that are allocated - for the keys in the hash table. ### */ - char* str; - struct Pop3AllocedString* next; -} Pop3AllocedString; - -typedef struct Pop3UidlHost { - char* host; - char* user; - XP_HashTable hash; - Pop3AllocedString* strings; - struct Pop3UidlHost* next; -} Pop3UidlHost; - - -typedef struct Pop3MsgInfo { - int32 size; - char* uidl; -} Pop3MsgInfo; - -typedef struct _Pop3ConData { - MSG_Pane* pane; /* msglib pane object. */ - char* host; - char* username; - char* password; - char* accountdir; - - XP_Bool leave_on_server; /* Whether we're supposed to leave messages - on server. */ - int32 size_limit; /* Leave messages bigger than this on the - server and only download a partial - message. */ - - Pop3StatesEnum next_state; /* the next state or action to be taken */ - Pop3StatesEnum next_state_after_response; - Bool pause_for_read; /* Pause now for next read? */ - - XP_Bool command_succeeded; /* did the last command succeed? */ - char *command_response; /* text of last response */ - int32 first_msg; - TCP_ConData *tcp_con_data; /* Data pointer for tcp connect state machine */ - char *data_buffer; - int32 data_buffer_size; - - char *obuffer; /* line buffer for output to msglib */ - uint32 obuffer_size; - uint32 obuffer_fp; - - int32 number_of_messages; - Pop3MsgInfo *msg_info; /* Message sizes and uidls (used only if we - are playing games that involve leaving - messages on the server). */ - int32 last_accessed_msg; - int32 cur_msg_size; - char *output_buffer; - XP_Bool truncating_cur_msg; /* are we using top and uidl? */ - XP_Bool msg_del_started; /* True if MSG_BeginMailDel... - * called - */ - XP_Bool only_check_for_new_mail; - /* MSG_BIFF_STATE biffstate; If just checking for, what the answer is. */ - - XP_Bool password_failed; /* flag for password querying */ - void *msg_closure; - int32 bytes_received_in_message; - int32 total_folder_size; - - int32 total_download_size; /* Number of bytes we're going to - download. Might be much less - than the total_folder_size. */ - - XP_Bool graph_progress_bytes_p; /* whether we should display info about - the bytes transferred (usually we - display info about the number of - messages instead.) */ - - Pop3UidlHost *uidlinfo; - XP_HashTable newuidl; - char *only_uidl; /* If non-NULL, then load only this UIDL. */ - - /* the following three fields support the - use of the 'TOP' command instead of UIDL - for leaving mail on the pop server -km */ - - /* the current message that we are retrieving - with the TOP command */ - int32 current_msg_to_top; - - /* we will download this many in - POP3_GET_MSG */ - int32 number_of_messages_not_seen_before; - /* reached when we have TOPped - all of the new messages */ - XP_Bool found_new_message_boundary; - - /* if this is true then we don't stop - at new message boundary, we have to - TOP em all to delete some */ - XP_Bool delete_server_message_during_top_traversal; - XP_Bool get_url; - XP_Bool seenFromHeader; - char *sender_info; - NET_StreamClass *teststream; - URL_Struct *testurls; - void *rdf; - char* current_from; - char* current_to; - char* current_date; - char* current_subject; -} Pop3ConData; - -void *MSG_IncorporateBegin (ActiveEntry *ce) ; -int MSG_IncorporateAbort (Pop3ConData *cd) ; -int MSG_IncorporateWrite (Pop3ConData *cd, const char *block, int32 length) ; -int MSG_IncorporateComplete(Pop3ConData *cd) ; - -char * POP_Base64Encode (char *src, int32 srclen); - -PUBLIC void -NET_LeavePopMailOnServer(Bool do_it) -{ - /* XP_ASSERT(0);*/ /* This routine is obsolete. */ -} - -/* Well, someone finally found a legitimate reason to put an @ in the - * mail server user name. They're trying to use the user name as a UID - * in the LDAP directory, and the UIDs happen to have the format - * foo@bar.com. We don't change our default behavior, but we let admins - * turn it off if they want - */ -PRIVATE XP_Bool net_allow_at_sign_in_mail_user_name = FALSE; - -MODULE_PRIVATE XP_Bool NET_GetAllowAtSignInMailUserName() -{ - return net_allow_at_sign_in_mail_user_name; -} - -MODULE_PRIVATE void NET_SetAllowAtSignInMailUserName(XP_Bool allow) -{ - net_allow_at_sign_in_mail_user_name = allow; -} - -PUBLIC void -NET_SetPopUsername(const char *username) -{ -} - -PUBLIC const char* -NET_GetPopUsername(void) -{ - return NULL; -} - -PRIVATE void -net_set_pop3_password(const char *password) -{ - -} - -PRIVATE char * -net_get_pop3_password(void) -{ - return NULL; -} - -PUBLIC void -NET_SetPopPassword(const char *password) -{ -} - -PUBLIC const char * -NET_GetPopPassword(void) -{return NULL ; -} - -/* fix Mac warning of missing prototype */ -PUBLIC void -NET_SetPopPassword2(const char *password); - -PUBLIC void -NET_SetPopPassword2(const char *password) -{ - net_set_pop3_password(password); -} - -/* sets the size limit for pop3 messages - * - * set the size negative to make it infinite length - */ -PUBLIC void -NET_SetPopMsgSizeLimit(int32 size) -{ - XP_ASSERT(0); /* This routine is obsolete */ -} - -PUBLIC int32 -NET_GetPopMsgSizeLimit(void) -{ - XP_ASSERT(0); /* This routine is obsolete */ - return -1; -} - - -static int -uidl_cmp (const void *obj1, const void *obj2) -{ - XP_ASSERT (obj1 && obj2); - return XP_STRCMP ((char *) obj1, (char *) obj2); -} - - -static void -put_hash(Pop3UidlHost* host, XP_HashTable table, const char* key, char value) -{ - Pop3AllocedString* tmp; - int v = value; - - tmp = XP_NEW_ZAP(Pop3AllocedString); - if (tmp) { - tmp->str = XP_STRDUP(key); - if (tmp->str) { - tmp->next = host->strings; - host->strings = tmp; - XP_Puthash(table, tmp->str, (void*) v); - } else { - XP_FREE(tmp); - } - } -} - -PRIVATE Pop3UidlHost* net_pop3_load_state(Pop3ConData *cd) -{ - - XP_File file; - char* buf; - char* host; - char* user; - char* uidl; - char* flags; - Pop3UidlHost* result = NULL; - Pop3UidlHost* current = NULL; - Pop3UidlHost* tmp; - char* searchhost = cd->host; - char* searchuser = cd->username; - - result = XP_NEW_ZAP(Pop3UidlHost); - if (!result) return NULL; - result->host = XP_STRDUP(searchhost); - result->user = XP_STRDUP(searchuser); - result->hash = XP_HashTableNew(20, XP_StringHash, uidl_cmp); - if (!result->host || !result->user || !result->hash) { - FREEIF(result->host); - FREEIF(result->user); - if (result->hash) XP_HashTableDestroy(result->hash); - XP_FREE(result); - return NULL; - } - - file = XP_FileOpen(cd->accountdir, xpMailPopState, XP_FILE_READ); - - if (!file) return result; - buf = (char*)XP_ALLOC(512); - if (buf) { - while (XP_FileReadLine(buf, 512, file)) { - if (*buf == '#' || *buf == CR || *buf == LF || *buf == 0) - continue; - if (buf[0] == '*') { - /* It's a host&user line. */ - current = NULL; - host = XP_STRTOK(buf + 1, " \t" LINEBREAK); - user = XP_STRTOK(NULL, " \t" LINEBREAK); - if (host == NULL || user == NULL) continue; - for (tmp = result ; tmp ; tmp = tmp->next) { - if (XP_STRCMP(host, tmp->host) == 0 && - XP_STRCMP(user, tmp->user) == 0) { - current = tmp; - break; - } - } - if (!current) { - current = XP_NEW_ZAP(Pop3UidlHost); - if (current) { - current->host = XP_STRDUP(host); - current->user = XP_STRDUP(user); - current->hash = XP_HashTableNew(20, XP_StringHash, uidl_cmp); - if (!current->host || !current->user || !current->hash) { - FREEIF(current->host); - FREEIF(current->user); - if (current->hash) XP_HashTableDestroy(current->hash); - XP_FREE(current); - } else { - current->next = result->next; - result->next = current; - } - } - } - } else { - /* It's a line with a UIDL on it. */ - if (current) { - flags = XP_STRTOK(buf, " \t" LINEBREAK); - uidl = XP_STRTOK(NULL, " \t" LINEBREAK); - if (flags && uidl) { - XP_ASSERT((flags[0] == KEEP) || (flags[0] == DELETE_CHAR) || (flags[0] == TOO_BIG)); - if ((flags[0] == KEEP) || (flags[0] == DELETE_CHAR) || (flags[0] == TOO_BIG)) { - put_hash(current, current->hash, uidl, flags[0]); - } - } - } - } - } - XP_FREE(buf); - } - XP_FileClose(file); - return result; -} - - - -static XP_Bool -hash_empty_mapper(XP_HashTable hash, const void* key, void* value, - void* closure) -{ - *((XP_Bool*) closure) = FALSE; - return FALSE; -} - -static XP_Bool -hash_empty(XP_HashTable hash) -{ - XP_Bool result = TRUE; - XP_Maphash(hash, hash_empty_mapper, &result); - return result; -} - - -PRIVATE XP_Bool -net_pop3_write_mapper(XP_HashTable hash, const void* key, void* value, - void* closure) -{ - XP_File file = (XP_File) closure; - XP_ASSERT((value == ((void *) (int) KEEP)) || - (value == ((void *) (int) DELETE_CHAR)) || - (value == ((void *) (int) TOO_BIG))); - XP_FilePrintf(file, "%c %s" LINEBREAK, (char)(long)value, (char*) key); - return TRUE; -} - - -PRIVATE void -net_pop3_write_state(Pop3ConData *cd) -{ - XP_File file; - int32 len = 0; - Pop3UidlHost* host = cd->uidlinfo; - - file = XP_FileOpen(cd->accountdir, xpMailPopState, XP_FILE_WRITE_BIN); - - if (!file) return; - len = XP_FileWrite("# Netscape POP3 State File" LINEBREAK - "# This is a generated file! Do not edit." LINEBREAK LINEBREAK, - -1, file); - for (; host && (len >= 0); host = host->next) - { - if (!hash_empty(host->hash)) - { - XP_FileWrite("*", 1, file); - XP_FileWrite(host->host, -1, file); - XP_FileWrite(" ", 1, file); - XP_FileWrite(host->user, -1, file); - len = XP_FileWrite(LINEBREAK, LINEBREAK_LEN, file); - XP_Maphash(host->hash, net_pop3_write_mapper, file); - } - } - XP_FileClose(file); -} - - -/* -Wrapper routines for POP data. The following routines are used from MSG_FolderInfoMail to -allow deleting of messages that have been kept on a POP3 server due to their size or -a preference to keep the messages on the server. When "deleting" messages we load -our state file, mark any messages we have for deletion and then re-save the state file. -*/ -extern char* ReadPopData(char *name); -extern void SavePopData(char *data); -extern void net_pop3_delete_if_in_server(char *data, char *uidl, XP_Bool *changed); -extern void KillPopData(char* data); - -/* -char* ReadPopData(char *name) -{ - Pop3UidlHost *uidlHost = NULL; - - if(!net_pop3_username || !*net_pop3_username) - return (char*) uidlHost; - - uidlHost = net_pop3_load_state(name, net_pop3_username); - return (char*) uidlHost; - return NULL; -} - -void SavePopData(ActiveEntry *ce) -{ - Pop3UidlHost *host = (Pop3UidlHost*) data; - - if (!host) - return; - net_pop3_write_state(host); -} - - -/* -Look for a specific UIDL string in our hash tables, if we have it then we need -to mark the message for deletion so that it can be deleted later. If the uidl of the -message is not found, then the message was downloaded completly and already deleted -from the server. So this only applies to messages kept on the server or too big -for download. */ - -void net_pop3_delete_if_in_server(char *data, char *uidl, XP_Bool *changed) -{ - Pop3UidlHost *host = (Pop3UidlHost*) data; - - if (!host) - return; - if (XP_Gethash (host->hash, (const void*) uidl, 0)) - { - XP_Puthash(host->hash, uidl, (void*) DELETE_CHAR); - *changed = TRUE; - } -} - - - - -PRIVATE void -net_pop3_free_state(Pop3UidlHost* host) -{ - Pop3UidlHost* h; - Pop3AllocedString* tmp; - Pop3AllocedString* next; - while (host) { - h = host->next; - XP_FREE(host->host); - XP_FREE(host->user); - XP_HashTableDestroy(host->hash); - tmp = host->strings; - while (tmp) { - next = tmp->next; - XP_FREE(tmp->str); - XP_FREE(tmp); - tmp = next; - } - XP_FREE(host); - host = h; - } -} - - -void KillPopData(char* data) -{ - if (!data) - return; - net_pop3_free_state((Pop3UidlHost*) data); -} - -PRIVATE void -net_pop3_free_msg_info(ActiveEntry* ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - int i; - if (cd->msg_info) { - for (i=0 ; i<cd->number_of_messages ; i++) { - if (cd->msg_info[i].uidl) - XP_FREE(cd->msg_info[i].uidl); - cd->msg_info[i].uidl = NULL; - } - XP_FREE(cd->msg_info); - cd->msg_info = NULL; - } -} - -/* km - This function will read one line and only go on to the next state - if the first character of that line is a '+' character. This will - accomodate pop mail servers that print a banner when the client - initiates a connection. Bug #7165 -*/ -PRIVATE int -net_pop3_wait_for_start_of_connection_response(ActiveEntry * ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - return(0); - } - else if(ce->status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - TRACEMSG(("TCP Error: %d", rv)); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - if(*line == '+') - { - cd->command_succeeded = TRUE; - if(XP_STRLEN(line) > 4) - StrAllocCopy(cd->command_response, line+4); - else - StrAllocCopy(cd->command_response, line); - - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - } - - - return(1); /* everything ok */ -} - -PRIVATE int -net_pop3_wait_for_response(ActiveEntry * ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - return(0); - } - else if(ce->status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - TRACEMSG(("TCP Error: %d", rv)); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - if(*line == '+') - { - cd->command_succeeded = TRUE; - if(XP_STRLEN(line) > 4) - StrAllocCopy(cd->command_response, line+4); - else - StrAllocCopy(cd->command_response, line); - } - else - { - cd->command_succeeded = FALSE; - if(XP_STRLEN(line) > 5) - StrAllocCopy(cd->command_response, line+5); - else - StrAllocCopy(cd->command_response, line); - } - - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - - return(1); /* everything ok */ -} - -PRIVATE int -net_pop3_error(ActiveEntry *ce, int err_code) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - ce->URL_s->error_msg = NET_ExplainErrorDetails(err_code, - cd->command_response ? cd->command_response : - XP_GetString( XP_NO_ANSWER ) ); - - cd->next_state = POP3_ERROR_DONE; - cd->pause_for_read = FALSE; - - return(err_code); -} - -PRIVATE int -net_pop3_send_command(ActiveEntry *ce, const char * command) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - int status; - - status = (int) NET_BlockingWrite(ce->socket, - command, - XP_STRLEN(command)); - - TRACEMSG(("Pop3 Tx: %s", cd->output_buffer)); - - if(status < 0) - { - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_WRITE_ERROR, SOCKET_ERRNO); - cd->next_state = POP3_ERROR_DONE; - return(MK_TCP_WRITE_ERROR); - } - - cd->pause_for_read = TRUE; - cd->next_state = POP3_WAIT_FOR_RESPONSE; - - return(status); -} - -/* - * POP3 AUTH LOGIN extention - */ - -PRIVATE int -net_pop3_send_auth(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - /* check login response */ - if(!cd->command_succeeded) - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "AUTH" CRLF); - - cd->next_state_after_response = POP3_AUTH_RESPONSE; - - return net_pop3_send_command(ce, cd->output_buffer); -} - -PRIVATE int -net_pop3_auth_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - - if (POP3_AUTH_LOGIN_UNDEFINED & pop3CapabilityFlags) - pop3CapabilityFlags &= ~POP3_AUTH_LOGIN_UNDEFINED; - - if (!cd->command_succeeded) - { - /* AUTH command not implemented - * no base64 encoded username/password - */ - cd->command_succeeded = TRUE; - pop3CapabilityFlags &= ~POP3_HAS_AUTH_LOGIN; - cd->next_state = POP3_SEND_USERNAME; - return 0; - } - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - cd->next_state = cd->next_state_after_response; - cd->pause_for_read = FALSE; /* don't pause */ - return(0); - } - else if (ce->status < 0) - { - int rv = SOCKET_ERRNO; - - TRACEMSG(("TCP Error: %d", rv)); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if (!line) - return ce->status; /* wait for line */ - - TRACEMSG((" Rx: %s", line)); - - if (!XP_STRCMP(line, ".")) - { - /* now that we've read all the AUTH responses, decide which - * state to go to next - */ - if (pop3CapabilityFlags & POP3_HAS_AUTH_LOGIN) - cd->next_state = POP3_AUTH_LOGIN; - else - cd->next_state = POP3_SEND_USERNAME; - cd->pause_for_read = FALSE; /* don't pause */ - } - else if (!XP_STRCASECMP (line, "LOGIN")) - pop3CapabilityFlags |= POP3_HAS_AUTH_LOGIN; - - return 0; -} - -PRIVATE int -net_pop3_auth_login(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - /* check login response */ - if(!cd->command_succeeded) { - pop3CapabilityFlags &= ~POP3_HAS_AUTH_LOGIN; - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - } - - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "AUTH LOGIN" CRLF); - - cd->next_state_after_response = POP3_AUTH_LOGIN_RESPONSE; - - return net_pop3_send_command(ce, cd->output_buffer); - -} - -PRIVATE int -net_pop3_auth_login_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - if (!cd->command_succeeded) - { - /* sounds like server does not support auth-skey extension - resume regular logon process */ - /* reset command_succeeded to true */ - cd->command_succeeded = TRUE; - /* reset auth login state */ - pop3CapabilityFlags &= ~POP3_HAS_AUTH_LOGIN; - } - else - { - pop3CapabilityFlags |= POP3_HAS_AUTH_LOGIN; - } - cd->next_state = POP3_SEND_USERNAME; - return 0; -} - - -PRIVATE int -net_pop3_send_username(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - /* check login response */ - if(!cd->command_succeeded) - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - - if(!cd->username) - return(net_pop3_error(ce, MK_POP3_USERNAME_UNDEFINED)); - - if (POP3_HAS_AUTH_LOGIN & pop3CapabilityFlags) { - char * str = - POP_Base64Encode(cd->username, - XP_STRLEN(cd->username)); - if (str) - { - PR_snprintf(cd->output_buffer, OUTPUT_BUFFER_SIZE, "%.256s" CRLF, - str); - - } - else - { - return (net_pop3_error(ce, MK_POP3_USERNAME_UNDEFINED)); - } - } - else { - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "USER %.256s" CRLF, cd->username); - } - - cd->next_state_after_response = POP3_SEND_PASSWORD; - - return(net_pop3_send_command(ce, cd->output_buffer)); -} - -PRIVATE int -net_pop3_send_password(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char *password; - - /* check username response */ - if (!cd->command_succeeded) - return(net_pop3_error(ce, MK_POP3_USERNAME_FAILURE)); - - password = cd->password; - - if (password == NULL) - return(net_pop3_error(ce, MK_POP3_PASSWORD_UNDEFINED)); - - if (POP3_HAS_AUTH_LOGIN & pop3CapabilityFlags) { - char * str = - POP_Base64Encode(password, XP_STRLEN(password)); - if (str) - { - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, "%.256s" CRLF, str); - - } - else - { - return (net_pop3_error(ce, MK_POP3_PASSWORD_UNDEFINED)); - } - } - else { - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, "PASS %.256s" CRLF, password); - } - - - if (cd->get_url) - cd->next_state_after_response = POP3_SEND_GURL; - else - cd->next_state_after_response = POP3_SEND_STAT; - - return(net_pop3_send_command(ce, cd->output_buffer)); -} - -PRIVATE int -net_pop3_send_stat_or_gurl(ActiveEntry *ce, XP_Bool sendStat) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - /* check password response */ - if(!cd->command_succeeded) - { - /* The password failed. - - Sever the connection and go back to the `read password' state, - which, upon success, will re-open the connection. Set a flag - which causes the prompt to be different that time (to indicate - that the old password was bogus.) - - But if we're just checking for new mail (biff) then don't bother - prompting the user for a password: just fail silently. */ - if (cd->only_check_for_new_mail) - return MK_POP3_PASSWORD_UNDEFINED; - - cd->password_failed = TRUE; - cd->next_state = POP3_ERROR_DONE; /* close */ - cd->pause_for_read = FALSE; /* try again right away */ - pop3CapabilityFlags = POP3_AUTH_LOGIN_UNDEFINED | POP3_XSENDER_UNDEFINED | - POP3_GURL_UNDEFINED; - /*if (cd->pane) { - MSG_SetUserAuthenticated(MSG_GetMaster(cd->pane), FALSE); - MSG_SetMailAccountURL(MSG_GetMaster(cd->pane), NULL); - } */ - /* clear the bogus password in case - * we need to sync with auth smtp password - */ - - return 0; - } - else if (net_pop3_password_pending) - { - /* - * First time with this password. Record it as a keeper. - * (The user's preference might say to save it.) - - FE_RememberPopPassword(ce->window_id, net_pop3_password); */ - net_pop3_password_pending = FALSE; - /* if (cd->pane) - MSG_SetUserAuthenticated(MSG_GetMaster(cd->pane), TRUE); */ - } - - if (sendStat) { - XP_STRCPY(cd->output_buffer, "STAT" CRLF); - cd->next_state_after_response = POP3_GET_STAT; - } - else { - XP_STRCPY(cd->output_buffer, "GURL" CRLF); - cd->next_state_after_response = POP3_GURL_RESPONSE; - } - - return(net_pop3_send_command(ce, cd->output_buffer)); -} - - -PRIVATE int -net_pop3_send_stat(ActiveEntry *ce) -{ - return net_pop3_send_stat_or_gurl(ce, TRUE); -} - - -PRIVATE int -net_pop3_get_stat(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - char *num; - - /* check stat response */ - if(!cd->command_succeeded) - return(net_pop3_error(ce, MK_POP3_PASSWORD_FAILURE)); - - /* stat response looks like: %d %d - * The first number is the number of articles - * The second number is the number of bytes - * - * grab the first and second arg of stat response - */ - num = XP_STRTOK(cd->command_response, " "); - - cd->number_of_messages = atol(num); - - num = XP_STRTOK(NULL, " "); - - cd->total_folder_size = (int32) atol(num); - - cd->total_download_size = -1; /* Means we need to calculate it, later. */ - - if(cd->number_of_messages <= 0) { - /* We're all done. We know we have no mail. */ - cd->next_state = POP3_SEND_QUIT; - XP_Clrhash(cd->uidlinfo->hash); - return(0); - } - - if (cd->only_check_for_new_mail && !cd->leave_on_server && - cd->size_limit < 0) { - /* We're just checking for new mail, and we're not playing any games that - involve keeping messages on the server. Therefore, we now know enough - to finish up. If we had no messages, that would have been handled - above; therefore, we know we have some new messages. */ - /* cd->biffstate = MSG_BIFF_NewMail; */ - cd->next_state = POP3_SEND_QUIT; - return(0); - } - - - if (!cd->only_check_for_new_mail) { - /* cd->msg_del_started = MSG_BeginMailDelivery(cd->pane); */ - cd->msg_del_started = 1; - if(!cd->msg_del_started) - { - return(net_pop3_error(ce, MK_POP3_MESSAGE_WRITE_ERROR)); - } - } - - /* -#ifdef POP_ALWAYS_USE_UIDL_FOR_DUPLICATES - if (net_uidl_command_unimplemented && net_xtnd_xlst_command_unimplemented && net_top_command_unimplemented) -#else - if ((net_uidl_command_unimplemented && net_xtnd_xlst_command_unimplemented && net_top_command_unimplemented) || - (!cd->only_uidl && !cd->leave_on_server && - (cd->size_limit < 0 || net_top_command_unimplemented))) -#endif */ - /* We don't need message size or uidl info; go directly to getting - messages. */ - /* cd->next_state = POP3_GET_MSG; - else */ /* Fix bug 51262 where pop messages kept on server are re-downloaded after unchecking keep on server */ - - cd->next_state = POP3_SEND_LIST; - return 0; -} - - - -PRIVATE int -net_pop3_send_gurl(ActiveEntry *ce) -{ - if (pop3CapabilityFlags == POP3_CAPABILITY_UNDEFINED || - pop3CapabilityFlags & POP3_GURL_UNDEFINED || - pop3CapabilityFlags & POP3_HAS_GURL) - return net_pop3_send_stat_or_gurl(ce, FALSE); - else - return -1; -} - - -PRIVATE int -net_pop3_gurl_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - if (POP3_GURL_UNDEFINED & pop3CapabilityFlags) - pop3CapabilityFlags &= ~POP3_GURL_UNDEFINED; - - if (cd->command_succeeded) { - pop3CapabilityFlags |= POP3_HAS_GURL; - /* if (cd->pane) - MSG_SetMailAccountURL(MSG_GetMaster(cd->pane), cd->command_response); */ - } - else { - pop3CapabilityFlags &= ~POP3_HAS_GURL; - } - cd->next_state = POP3_SEND_QUIT; - return 0; -} - -PRIVATE int -net_pop3_send_list(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - cd->msg_info = (Pop3MsgInfo *) XP_ALLOC(sizeof(Pop3MsgInfo) * - cd->number_of_messages); - if (!cd->msg_info) - return(MK_OUT_OF_MEMORY); - XP_MEMSET(cd->msg_info, 0, sizeof(Pop3MsgInfo) * cd->number_of_messages); - XP_STRCPY(cd->output_buffer, "LIST" CRLF); - cd->next_state_after_response = POP3_GET_LIST; - return(net_pop3_send_command(ce, cd->output_buffer)); -} - - - -PRIVATE int -net_pop3_get_list(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - int32 msg_num; - - /* check list response - * This will get called multiple times - * but it's alright since command_succeeded - * will remain constant - */ - if(!cd->command_succeeded) - return(net_pop3_error(ce, MK_POP3_LIST_FAILURE)); - - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - } - else if(ce->status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - /* remove CRLF */ - XP_StripLine(line); - - /* parse the line returned from the list command - * it looks like - * #msg_number #bytes - * - * list data is terminated by a ".CRLF" line - */ - if(!XP_STRCMP(line, ".")) - { - cd->next_state = POP3_SEND_UIDL_LIST; - cd->pause_for_read = FALSE; - return(0); - } - - msg_num = atol(XP_STRTOK(line, " ")); - - if(msg_num <= cd->number_of_messages && msg_num > 0) - cd->msg_info[msg_num-1].size = atol(XP_STRTOK(NULL, " ")); - - return(0); -} -/* km - * - * - * Process state: POP3_START_USE_TOP_FOR_FAKE_UIDL - * - * If we get here then UIDL and XTND are not supported by the mail server. - * - * Now we will walk backwards, from higher message numbers to lower, - * using the TOP command. Along the way, keep track of messages to down load - * by POP3_GET_MSG. - * - * Stop when we reach a msg that we knew about before or we run out of - * messages. - * - * There is also conditional code to handle: - * BIFF - * Pop3ConData->only_uidl == true (fetching one message only) - * emptying message hash table if all messages are new - * Deleting messages that are marked deleted. - * - * -*/ - -/* this function gets called for each hash table entry. If it finds a message - marked delete, then we will have to traverse all of the server messages - with TOP in order to delete those that are marked delete. - - - If UIDL or XTND XLST are supported then this function will never get called. - - A pointer to this function is passed to XP_Maphash -km */ - -PRIVATE XP_Bool -net_pop3_check_for_hash_messages_marked_delete(XP_HashTable table, - const void *key, - void *value, - void *closure) -{ - char valueChar = (char) (int) value; - if (valueChar == DELETE_CHAR) - { - ((Pop3ConData *) closure)->delete_server_message_during_top_traversal = TRUE; - return FALSE; /* XP_Maphash will stop traversing hash table now */ - } - - return TRUE; /* XP_Maphash will continue traversing the hash */ -} - -PRIVATE int -send_fake_uidl_top(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "TOP %ld 1" CRLF, - cd->current_msg_to_top); - - cd->next_state_after_response = POP3_GET_FAKE_UIDL_TOP; - cd->pause_for_read = TRUE; - return(net_pop3_send_command(ce, cd->output_buffer)); -} - -PRIVATE int -start_use_top_for_fake_uidl(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - cd->current_msg_to_top = cd->number_of_messages; - cd->number_of_messages_not_seen_before = 0; - cd->found_new_message_boundary = FALSE; - cd->delete_server_message_during_top_traversal = FALSE; - - /* may set delete_server_message_during_top_traversal to true */ - XP_Maphash(cd->uidlinfo->hash, - net_pop3_check_for_hash_messages_marked_delete, cd); - - return (send_fake_uidl_top(ce)); -} - - -PRIVATE int -get_fake_uidl_top(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - - /* check list response - * This will get called multiple times - * but it's alright since command_succeeded - * will remain constant - */ - if(!cd->command_succeeded) { - - /* UIDL, XTND and TOP are all unsupported for this mail server. - Tell the user to join the 20th century. - - Tell the user this, and refuse to download any messages until they've - gone into preferences and turned off the `Keep Mail on Server' and - `Maximum Message Size' prefs. Some people really get their panties - in a bunch if we download their mail anyway. (bug 11561) - */ - char *fmt = XP_GetString(XP_THE_POP3_SERVER_DOES_NOT_SUPPORT_UIDL_ETC); - char *host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - ce->URL_s->error_msg = PR_smprintf (fmt, (host ? host : "(null)")); - FREEIF(host); - cd->next_state = POP3_ERROR_DONE; - cd->pause_for_read = FALSE; - return -1; - - } - - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - } - else if(ce->status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - /* remove CRLF */ - XP_StripLine(line); - - if(!XP_STRCMP(line, ".")) - { - cd->current_msg_to_top--; - if (!cd->current_msg_to_top || - (cd->found_new_message_boundary && - !cd->delete_server_message_during_top_traversal)) - { - /* we either ran out of messages or reached the edge of new - messages and no messages are marked dele */ - cd->next_state = POP3_GET_MSG; - cd->pause_for_read = FALSE; - - /* if all of the messages are new, toss all hash table entries */ - if (!cd->current_msg_to_top && !cd->found_new_message_boundary) - XP_Clrhash(cd->uidlinfo->hash); - } - else - { - /* this message is done, go to the next */ - cd->next_state = POP3_SEND_FAKE_UIDL_TOP; - cd->pause_for_read = FALSE; - } - } - else - { - /* we are looking for a string of the form - Message-Id: <199602071806.KAA14787@neon.netscape.com> */ - char *firstToken = XP_STRTOK(line, " "); - int state = 0; - - if (firstToken && !XP_STRCASECMP(firstToken, "MESSAGE-ID:") ) - { - char *message_id_token = XP_STRTOK(NULL, " "); - state = (int) XP_Gethash(cd->uidlinfo->hash, message_id_token, 0); - - if (!cd->only_uidl && message_id_token && (state == 0)) - { /* we have not seen this message before */ - - /* if we are only doing a biff, stop here */ - if (cd->only_check_for_new_mail) - { - /* cd->biffstate = MSG_BIFF_NewMail; */ - cd->next_state = POP3_SEND_QUIT; - cd->pause_for_read = FALSE; - } - else /* we will retrieve it and cache it in GET_MSG */ - { - cd->number_of_messages_not_seen_before++; - cd->msg_info[cd->current_msg_to_top-1].uidl = XP_STRDUP(message_id_token); - if (!cd->msg_info[cd->current_msg_to_top-1].uidl) - return MK_OUT_OF_MEMORY; - } - } - else if (cd->only_uidl && message_id_token && - !XP_STRCMP(cd->only_uidl, message_id_token)) - { - cd->last_accessed_msg = cd->current_msg_to_top - 1; - cd->found_new_message_boundary = TRUE; - cd->msg_info[cd->current_msg_to_top-1].uidl = XP_STRDUP(message_id_token); - if (!cd->msg_info[cd->current_msg_to_top-1].uidl) - return MK_OUT_OF_MEMORY; - } - else if (!cd->only_uidl) - { /* we have seen this message and we care about the edge, - stop looking for new ones */ - if (cd->number_of_messages_not_seen_before != 0) - { - cd->last_accessed_msg = cd->current_msg_to_top; /* -1 ? */ - cd->found_new_message_boundary = TRUE; - /* we stay in this state so we can process the rest of the - lines in the top message */ - } - else - { - cd->next_state = POP3_SEND_QUIT; - cd->pause_for_read = FALSE; - } - } - } - } - return 0; -} - - -/* km - * - * net_pop3_send_xtnd_xlst_msgid - * - * Process state: POP3_SEND_XTND_XLST_MSGID - * - * If we get here then UIDL is not supported by the mail server. - * Some mail servers support a similar command: - * - * XTND XLST Message-Id - * - * Here is a sample transaction from a QUALCOMM server - - >>XTND XLST Message-Id - <<+OK xlst command accepted; headers coming. - <<1 Message-ID: <3117E4DC.2699@netscape.com> - <<2 Message-Id: <199602062335.PAA19215@lemon.mcom.com> - - * This function will send the xtnd command and put us into the - * POP3_GET_XTND_XLST_MSGID state - * -*/ -PRIVATE int -net_pop3_send_xtnd_xlst_msgid(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - if (net_xtnd_xlst_command_unimplemented) - return(start_use_top_for_fake_uidl(ce)); - - - XP_STRCPY(cd->output_buffer, "XTND XLST Message-Id" CRLF); - cd->next_state_after_response = POP3_GET_XTND_XLST_MSGID; - cd->pause_for_read = TRUE; - return(net_pop3_send_command(ce, cd->output_buffer)); -} - - -/* km - * - * net_pop3_get_xtnd_xlst_msgid - * - * This code was created from the net_pop3_get_uidl_list boiler plate. - * The difference is that the XTND reply strings have one more token per - * string than the UIDL reply strings do. - * - */ - -PRIVATE int -net_pop3_get_xtnd_xlst_msgid(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - int32 msg_num; - - /* check list response - * This will get called multiple times - * but it's alright since command_succeeded - * will remain constant - */ - if(!cd->command_succeeded) { - net_xtnd_xlst_command_unimplemented = TRUE; - cd->next_state = POP3_START_USE_TOP_FOR_FAKE_UIDL; - cd->pause_for_read = FALSE; - return(0); - } - - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - } - else if(ce->status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - /* remove CRLF */ - XP_StripLine(line); - - - /* parse the line returned from the list command - * it looks like - * 1 Message-ID: <3117E4DC.2699@netscape.com> - * - * list data is terminated by a ".CRLF" line - */ - if(!XP_STRCMP(line, ".")) - { - cd->next_state = POP3_GET_MSG; - cd->pause_for_read = FALSE; - return(0); - } - - msg_num = atol(XP_STRTOK(line, " ")); - - if(msg_num <= cd->number_of_messages && msg_num > 0) { -/* char *eatMessageIdToken = XP_STRTOK(NULL, " "); */ - char *uidl = XP_STRTOK(NULL, " "); /* not really a uidl but a unique token -km */ - - if (!uidl) - /* This is bad. The server didn't give us a UIDL for this message. - I've seen this happen when somehow the mail spool has a message - that contains a header that reads "X-UIDL: \n". But how that got - there, I have no idea; must be a server bug. Or something. */ - uidl = ""; - - cd->msg_info[msg_num-1].uidl = XP_STRDUP(uidl); - if (!cd->msg_info[msg_num-1].uidl) - return MK_OUT_OF_MEMORY; - } - - return(0); -} - - -PRIVATE int -net_pop3_send_uidl_list(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - if (net_uidl_command_unimplemented) - return(net_pop3_send_xtnd_xlst_msgid(ce)); - - - XP_STRCPY(cd->output_buffer, "UIDL" CRLF); - cd->next_state_after_response = POP3_GET_UIDL_LIST; - cd->pause_for_read = TRUE; - return(net_pop3_send_command(ce, cd->output_buffer)); -} - - -PRIVATE int -net_pop3_get_uidl_list(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char * line; - int32 msg_num; - - /* check list response - * This will get called multiple times - * but it's alright since command_succeeded - * will remain constant - */ - if(!cd->command_succeeded) { - cd->next_state = POP3_SEND_XTND_XLST_MSGID; - cd->pause_for_read = FALSE; - net_uidl_command_unimplemented = TRUE; - return(0); - -#if 0 /* this if block shows what UIDL used to do in this case */ - /* UIDL doesn't work so we can't retrieve the message later, and we - * can't play games notating how to keep it on the server. Therefore - * just go download the whole thing, and warn the user. - */ - char *host, *fmt, *buf; - - net_uidl_command_unimplemented = TRUE; - - fmt = XP_GetString( XP_THE_POP3_SERVER_DOES_NOT_SUPPORT_UIDL_ETC ); - - host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - XP_ASSERT(host); - if (!host) - host = "(null)"; - buf = PR_smprintf (fmt, host); - if (!buf) - return MK_OUT_OF_MEMORY; - FE_Alert (ce->window_id, buf); - XP_FREE (buf); - - /* Free up the msg_info structure, as we use its presence later to - decide if we can do UIDL-based games. */ - net_pop3_free_msg_info(ce); - - cd->next_state = POP3_GET_MSG; - return(0); - -#endif /* 0 */ - } - - - ce->status = NET_BufferedReadLine(ce->socket, &line, &cd->data_buffer, - &cd->data_buffer_size, &cd->pause_for_read); - - if(ce->status == 0) - { - /* this shouldn't really happen, but... - */ - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - } - else if(ce->status < 0) - { - int rv = PR_GetError(); - - if (rv == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return(0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, rv); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return ce->status; /* wait for line */ - } - - TRACEMSG((" Rx: %s", line)); - - /* remove CRLF */ - XP_StripLine(line); - - /* parse the line returned from the list command - * it looks like - * #msg_number uidl - * - * list data is terminated by a ".CRLF" line - */ - if(!XP_STRCMP(line, ".")) - { - cd->next_state = POP3_GET_MSG; - cd->pause_for_read = FALSE; - return(0); - } - - msg_num = atol(XP_STRTOK(line, " ")); - - if(msg_num <= cd->number_of_messages && msg_num > 0) { - char *uidl = XP_STRTOK(NULL, " "); - - if (!uidl) - /* This is bad. The server didn't give us a UIDL for this message. - I've seen this happen when somehow the mail spool has a message - that contains a header that reads "X-UIDL: \n". But how that got - there, I have no idea; must be a server bug. Or something. */ - uidl = ""; - - cd->msg_info[msg_num-1].uidl = XP_STRDUP(uidl); - if (!cd->msg_info[msg_num-1].uidl) - return MK_OUT_OF_MEMORY; - } - - return(0); -} - - - - -/* this function decides if we are going to do a - * normal RETR or a TOP. The first time, it also decides the total number - * of bytes we're probably going to get. - */ -PRIVATE int -net_pop3_get_msg(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char c; - int i; - XP_Bool prefBool = FALSE; - - if(cd->last_accessed_msg >= cd->number_of_messages) { - /* Oh, gee, we're all done. */ - cd->next_state = POP3_SEND_QUIT; - return 0; - } - - if (cd->total_download_size < 0) { - /* First time. Figure out how many bytes we're about to get. - If we didn't get any message info, then we are going to get - everything, and it's easy. Otherwise, if we only want one - uidl, than that's the only one we'll get. Otherwise, go - through each message info, decide if we're going to get that - message, and add the number of bytes for it. When a message is too - large (per user's preferences) only add the size we are supposed - to get. */ - if (cd->msg_info) { - cd->total_download_size = 0; - for (i=0 ; i < cd->number_of_messages ; i++) { - c = 0; - if (cd->only_uidl) { - if (cd->msg_info[i].uidl && XP_STRCMP(cd->msg_info[i].uidl, - cd->only_uidl) == 0) { - /*if (cd->msg_info[i].size > cd->size_limit) - cd->total_download_size = cd->size_limit; */ /* if more than max, only count max */ - /*else*/ - cd->total_download_size = cd->msg_info[i].size; - break; - } - continue; - } - if (cd->msg_info[i].uidl) - c = (char) (int) XP_Gethash(cd->uidlinfo->hash, cd->msg_info[i].uidl, 0); - if ((c == KEEP) && !cd->leave_on_server) - { /* This message has been downloaded but kept on server, we no longer want to keep it there */ - if (cd->newuidl == NULL) - { - cd->newuidl = XP_HashTableNew(20, XP_StringHash, uidl_cmp); - if (!cd->newuidl) - return MK_OUT_OF_MEMORY; - } - c = DELETE_CHAR; - put_hash(cd->uidlinfo, cd->newuidl, cd->msg_info[i].uidl, DELETE_CHAR); /* Mark message to be deleted in new table */ - put_hash(cd->uidlinfo, cd->uidlinfo->hash, cd->msg_info[i].uidl, DELETE_CHAR); /* and old one too */ - } - if ((c != KEEP) && (c != DELETE_CHAR) && (c != TOO_BIG)) { /* mesage left on server */ - /*if (cd->msg_info[i].size > cd->size_limit) - cd->total_download_size += cd->size_limit; */ /* if more than max, only count max */ - /*else*/ - cd->total_download_size += cd->msg_info[i].size; - } - } - } else { - cd->total_download_size = cd->total_folder_size; - } - /* cd->only_check_for_new_mail = 0; */ - if (cd->only_check_for_new_mail) { - /* if (cd->total_download_size > 0) cd->biffstate = MSG_BIFF_NewMail;*/ - cd->next_state = POP3_SEND_QUIT; - return(0); - } - /* get the amount of available space on the drive - * and make sure there is enough - */ - - { - /* const char* dir = MSG_GetFolderDirectory(MSG_GetPrefs(cd->pane)); - - When checking for disk space available, take in consideration possible database - changes, therefore ask for a little more than what the message size is. - Also, due to disk sector sizes, allocation blocks, etc. The space "available" may be greater - than the actual space usable. - if((cd->total_download_size > 0) - && ((uint32)cd->total_download_size + (uint32) 3096) > FE_DiskSpaceAvailable(ce->window_id, dir)) - { - return(net_pop3_error(ce, MK_POP3_OUT_OF_DISK_SPACE)); - } -*/ - } - } - - - /* Look at this message, and decide whether to ignore it, get it, just get - the TOP of it, or delete it. */ - - PREF_GetBoolPref("mail.auth_login", &prefBool); - if (prefBool && (pop3CapabilityFlags & POP3_HAS_XSENDER || - pop3CapabilityFlags & POP3_XSENDER_UNDEFINED)) - cd->next_state = POP3_SEND_XSENDER; - else - cd->next_state = POP3_SEND_RETR; - cd->truncating_cur_msg = FALSE; - cd->pause_for_read = FALSE; - if (cd->msg_info) { - Pop3MsgInfo* info = cd->msg_info + cd->last_accessed_msg; - if (cd->only_uidl) { - if (info->uidl == NULL || XP_STRCMP(info->uidl, cd->only_uidl)) - cd->next_state = POP3_GET_MSG; - else - cd->next_state = POP3_SEND_RETR; - } else { - c = 0; - if (cd->newuidl == NULL) { - cd->newuidl = XP_HashTableNew(20, XP_StringHash, uidl_cmp); - if (!cd->newuidl) - return MK_OUT_OF_MEMORY; - } - if (info->uidl) { - c = (char) (int) XP_Gethash(cd->uidlinfo->hash, info->uidl, 0); - } - cd->truncating_cur_msg = FALSE; - if (c == DELETE_CHAR) { - cd->next_state = POP3_SEND_DELE; - } else if (c == KEEP) { - cd->next_state = POP3_GET_MSG; - } else if ((c != TOO_BIG) && (cd->size_limit > 0) && (info->size > cd->size_limit) && - !net_top_command_unimplemented && (cd->only_uidl == NULL)) { - /* message is too big */ - cd->truncating_cur_msg = TRUE; - cd->next_state = POP3_SEND_TOP; - put_hash(cd->uidlinfo, cd->newuidl, info->uidl, TOO_BIG); - } else if (c == TOO_BIG) { /* message previously left on server, see if the - max download size has changed, because we may - want to download the message this time around. - Otherwise ignore the message, we have the header. */ - if ((cd->size_limit > 0) && (info->size <= cd->size_limit)) - XP_Remhash (cd->uidlinfo->hash, (void*) info->uidl); /* remove from our table, and download */ - else - { - cd->truncating_cur_msg = TRUE; - cd->next_state = POP3_GET_MSG; /* ignore this message and get next one */ - put_hash(cd->uidlinfo, cd->newuidl, info->uidl, TOO_BIG); - } - } - } - if ((cd->leave_on_server && cd->next_state != POP3_SEND_DELE) || - cd->next_state == POP3_GET_MSG || cd->next_state == POP3_SEND_TOP) { - - /* This is a message we have decided to keep on the server. Notate - that now for the future. (Don't change the popstate file at all - if only_uidl is set; in that case, there might be brand new messages - on the server that we *don't* want to mark KEEP; we just want to - leave them around until the user next does a GetNewMail.) */ - - if (info->uidl && cd->only_uidl == NULL) { - if (!cd->truncating_cur_msg) /* message already marked as too_big */ - put_hash(cd->uidlinfo, cd->newuidl, info->uidl, KEEP); - } - } - if (cd->next_state == POP3_GET_MSG) { - cd->last_accessed_msg++; /* Make sure we check the next message next - time! */ - } - } - return 0; -} - - -/* start retreiving just the first 20 lines - */ -PRIVATE int -net_pop3_send_top(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - XP_ASSERT(!(net_uidl_command_unimplemented && - net_xtnd_xlst_command_unimplemented && - net_top_command_unimplemented) ); - XP_ASSERT(!net_top_command_unimplemented); - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "TOP %ld 20" CRLF, - cd->last_accessed_msg+1); - - cd->next_state_after_response = POP3_TOP_RESPONSE; - - cd->cur_msg_size = -1; - - /* zero the bytes received in message in preparation for - * the next - */ - cd->bytes_received_in_message = 0; - - return(net_pop3_send_command(ce, cd->output_buffer)); -} - -/* send the xsender command - */ -PRIVATE int -net_pop3_send_xsender(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *) ce->con_data; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "XSENDER %ld" CRLF, - cd->last_accessed_msg+1); - - cd->next_state_after_response = POP3_XSENDER_RESPONSE; - return net_pop3_send_command(ce, cd->output_buffer); -} - -PRIVATE int -net_pop3_xsender_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *) ce->con_data; - - cd->seenFromHeader = FALSE; - FREEIF(cd->sender_info); - - if (POP3_XSENDER_UNDEFINED & pop3CapabilityFlags) - pop3CapabilityFlags &= ~POP3_XSENDER_UNDEFINED; - - if (cd->command_succeeded) { - if (XP_STRLEN (cd->command_response) > 4) - { - StrAllocCopy(cd->sender_info, cd->command_response); - } - if (! (POP3_HAS_XSENDER & pop3CapabilityFlags)) - pop3CapabilityFlags |= POP3_HAS_XSENDER; - } - else { - pop3CapabilityFlags &= ~POP3_HAS_XSENDER; - } - if (cd->truncating_cur_msg) - cd->next_state = POP3_SEND_TOP; - else - cd->next_state = POP3_SEND_RETR; - return 0; -} - -/* retreive the whole message - */ -PRIVATE int -net_pop3_send_retr(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char buf[OUTPUT_BUFFER_SIZE]; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "RETR %ld" CRLF, - cd->last_accessed_msg+1); - - cd->next_state_after_response = POP3_RETR_RESPONSE; - - cd->cur_msg_size = -1; - - /* zero the bytes received in message in preparation for - * the next - */ - cd->bytes_received_in_message = 0; - - if (cd->only_uidl) - { - /* Display bytes if we're only downloading one message. */ - XP_ASSERT(!cd->graph_progress_bytes_p); - if (!cd->graph_progress_bytes_p) - FE_GraphProgressInit(ce->window_id, ce->URL_s, - cd->total_download_size); - cd->graph_progress_bytes_p = TRUE; - } - else - { - PR_snprintf(buf, OUTPUT_BUFFER_SIZE, - XP_GetString( XP_RECEIVING_MESSAGE_OF ), - cd->last_accessed_msg+1, - cd->number_of_messages); - NET_Progress(ce->window_id, buf); - } - - return(net_pop3_send_command(ce, cd->output_buffer)); -} - -/* #### should include msgutils.h instead... */ -int msg_LineBuffer (const char *net_buffer, int32 net_buffer_size, - char **bufferP, uint32 *buffer_sizeP, - uint32 *buffer_fpP, - XP_Bool convert_newlines_p, - int32 (*per_line_fn) (char *line, uint32 - line_length, void *closure), - void *closure); - - -PRIVATE int32 net_pop3_retr_handle_line(char *line, uint32 line_length, - void *closure); - -static int32 gPOP3parsed_bytes, gPOP3size; -static XP_Bool gPOP3dotFix, gPOP3AssumedEnd; - - -/* - To fix a bug where we think the message is over, check the alleged size of the message - before we assume that CRLF.CRLF is the end. - return TRUE if end of message is unlikely. parsed bytes is not accurate since we add - bytes every now and then. -*/ - -XP_Bool NET_POP3TooEarlyForEnd(int32 len) -{ - if (!gPOP3dotFix) - return FALSE; /* fix turned off */ - gPOP3parsed_bytes += len; - if (gPOP3parsed_bytes >= (gPOP3size - 3)) - return FALSE; - return TRUE; -} - - - -/* digest the message - */ -PRIVATE int -net_pop3_retr_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - char *buffer; - int32 buffer_size; - int32 flags = 0; - char *uidl = NULL; - int32 old_bytes_received = ce->bytes_received; - XP_Bool fix = FALSE; - - if(cd->cur_msg_size == -1) - { - /* this is the beginning of a message - * get the response code and byte size - */ - if(!cd->command_succeeded) - return net_pop3_error(ce, MK_POP3_RETR_FAILURE); - - /* a successful RETR response looks like: #num_bytes Junk - from TOP we only get the +OK and data - */ - if (cd->truncating_cur_msg) - { /* TOP, truncated message */ - cd->cur_msg_size = cd->size_limit; - /* xxx flags |= MSG_FLAG_PARTIAL; */ - } - else - cd->cur_msg_size = atol(XP_STRTOK(cd->command_response, " ")); /* RETR complete message */ - - /* xxx if (cd->sender_info) - flags |= MSG_FLAG_SENDER_AUTHED; */ - - if(cd->cur_msg_size < 0) - cd->cur_msg_size = 0; - - if (cd->msg_info && cd->msg_info[cd->last_accessed_msg].uidl) - uidl = cd->msg_info[cd->last_accessed_msg].uidl; - - gPOP3parsed_bytes = 0; - gPOP3size = cd->cur_msg_size; - gPOP3AssumedEnd = FALSE; - PREF_GetBoolPref("mail.dot_fix", &fix); - gPOP3dotFix = fix; - - - TRACEMSG(("Opening message stream: MSG_IncorporateBegin")); - /* open the message stream so we have someplace - * to put the data - */ - cd->msg_closure = MSG_IncorporateBegin (ce); - - TRACEMSG(("Done opening message stream!")); - - /* if(!cd->msg_closure) - return(net_pop3_error(ce, MK_POP3_MESSAGE_WRITE_ERROR)); */ - } - - if (cd->data_buffer_size > 0) - { - XP_ASSERT(cd->obuffer_fp == 0); /* must be the first time */ - buffer = cd->data_buffer; - buffer_size = cd->data_buffer_size; - cd->data_buffer_size = 0; - } - else - { - ce->status = PR_Read(ce->socket, - NET_Socket_Buffer, - NET_Socket_Buffer_Size); - buffer = NET_Socket_Buffer; - buffer_size = ce->status; - - cd->pause_for_read = TRUE; - - if(ce->status == 0) - { - /* should never happen */ - return(net_pop3_error(ce, MK_POP3_SERVER_ERROR)); - } - else if(ce->status < 0) /* error */ - { - int err = PR_GetError(); - - if (err == PR_WOULD_BLOCK_ERROR) - { - /* - (rb) If we have the dot fix, and the server reported the wrong number of bytes there may - be nothing else to read, so now go ahead and close the message if we saw something - resembling the end of the message. - */ - if (gPOP3dotFix && gPOP3AssumedEnd) - { - ce->status = MSG_IncorporateComplete(cd); - cd->msg_closure = 0; - buffer_size = 0; - } - else - { - cd->pause_for_read = TRUE; - return (0); - } - } - else - { - TRACEMSG(("TCP Error: %d", err)); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, err); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - } - } - - if (cd->msg_closure) /* not done yet */ - ce->status = msg_LineBuffer(buffer, buffer_size, - &cd->obuffer, &cd->obuffer_size, - &cd->obuffer_fp, FALSE, - net_pop3_retr_handle_line, (void *) ce); - - if (ce->status < 0) - { - if (cd->msg_closure) - { - MSG_IncorporateAbort(cd); - cd->msg_closure = NULL; - } - /* MSG_AbortMailDelivery(cd->pane); */ - return(net_pop3_error(ce, MK_POP3_MESSAGE_WRITE_ERROR)); - } - - /* normal read. Yay! */ - if (cd->bytes_received_in_message + buffer_size > cd->cur_msg_size) - buffer_size = cd->cur_msg_size - cd->bytes_received_in_message; - - cd->bytes_received_in_message += buffer_size; - ce->bytes_received += buffer_size; - - if (!cd->msg_closure) /* meaning _handle_line read ".\r\n" at end-of-msg */ - { - cd->pause_for_read = FALSE; - if (cd->truncating_cur_msg || - (cd->leave_on_server && !(net_uidl_command_unimplemented && - net_xtnd_xlst_command_unimplemented && - net_top_command_unimplemented) )) - { - /* We've retrieved all or part of this message, but we want to - keep it on the server. Go on to the next message. */ - cd->last_accessed_msg++; - cd->next_state = POP3_GET_MSG; - } else - { - cd->next_state = POP3_SEND_DELE; - } - - /* if we didn't get the whole message add the bytes that we didn't get - to the bytes received part so that the progress percent stays sane. - */ - if(cd->bytes_received_in_message < cd->cur_msg_size) - ce->bytes_received += (cd->cur_msg_size - cd->bytes_received_in_message); - } - - if (cd->graph_progress_bytes_p) - FE_GraphProgress(ce->window_id, ce->URL_s, - ce->bytes_received, - ce->bytes_received - old_bytes_received, - cd->cur_msg_size); - - /* set percent done to portion of total bytes of all messages - that we're going to download. */ - if (cd->total_download_size) - FE_SetProgressBarPercent(ce->window_id, ((ce->bytes_received*100) / cd->total_download_size)); - - return(0); -} - - -PRIVATE int -net_pop3_top_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - if(cd->cur_msg_size == -1 && /* first line after TOP command sent */ - !cd->command_succeeded) /* and TOP command failed */ - { - /* TOP doesn't work so we can't retrieve the first part of this msg. - So just go download the whole thing, and warn the user. - - Note that the progress bar will not be accurate in this case. - Oops. #### */ - char *host, *fmt, *buf; - int size; - XP_Bool prefBool = FALSE; - - net_top_command_unimplemented = TRUE; - cd->truncating_cur_msg = FALSE; - - fmt = XP_GetString( XP_THE_POP3_SERVER_DOES_NOT_SUPPORT_THE_TOP_COMMAND ); - - host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - size = XP_STRLEN(fmt) + XP_STRLEN(host ? host : "(null)") + 100; - buf = (char *) XP_ALLOC (size); - if (!buf) { - FREEIF(host); - return MK_OUT_OF_MEMORY; - } - PR_snprintf (buf, size, fmt, host ? host : "(null)"); - FE_Alert (ce->window_id, buf); - XP_FREE (buf); - FREEIF(host); - - PREF_GetBoolPref ("mail.auth_login", &prefBool); - if (prefBool && (POP3_XSENDER_UNDEFINED & pop3CapabilityFlags || - POP3_HAS_XSENDER & pop3CapabilityFlags)) - cd->next_state = POP3_SEND_XSENDER; - else - cd->next_state = POP3_SEND_RETR; - return(0); - } - - /* If TOP works, we handle it in the same way as RETR. */ - return net_pop3_retr_response(ce); -} - - - -PRIVATE int32 -net_pop3_retr_handle_line(char *line, uint32 line_length, void *closure) -{ - ActiveEntry *ce = (ActiveEntry *) closure; - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - int status; - - XP_ASSERT(cd->msg_closure); - if (!cd->msg_closure) - return -1; - - if (cd->sender_info && !cd->seenFromHeader) - { - if (line_length > 6 && !XP_MEMCMP("From: ", line, 6)) - { - /* Zzzzz XP_STRSTR only works with NULL terminated string. Since, - * the last character of a line is either a carriage return - * or a linefeed. Temporary setting the last character of the - * line to NULL and later setting it back should be the right - * thing to do. - */ - char ch = line[line_length-1]; - line[line_length-1] = 0; - cd->seenFromHeader = TRUE; - /* if (XP_STRSTR(line, cd->sender_info) == NULL) - MSG_ClearSenderAuthedFlag(cd->pane, cd->msg_closure); */ - line[line_length-1] = ch; - } - } - - - status = MSG_IncorporateWrite(cd, line, line_length); - - if ((status >= 0) && - (line[0] == '.') && - ((line[1] == CR) || (line[1] == LF))) - { - gPOP3AssumedEnd = TRUE; /* in case byte count from server is wrong, mark we may have had the end */ - if (!gPOP3dotFix || (gPOP3parsed_bytes >= (gPOP3size -3))) - { - status = MSG_IncorporateComplete(cd); - cd->msg_closure = 0; - } - } - - return status; -} - - -PRIVATE int -net_pop3_send_dele(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - /* increment the last accessed message since we have now read it - */ - cd->last_accessed_msg++; - - PR_snprintf(cd->output_buffer, - OUTPUT_BUFFER_SIZE, - "DELE %ld" CRLF, - cd->last_accessed_msg); - - cd->next_state_after_response = POP3_DELE_RESPONSE; - - return(net_pop3_send_command(ce, cd->output_buffer)); -} - -PRIVATE int -net_pop3_dele_response(ActiveEntry *ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - Pop3UidlHost *host = NULL; - - if (cd) - host = cd->uidlinfo; - - /* the return from the delete will come here - */ - if(!cd->command_succeeded) - return(net_pop3_error(ce, MK_POP3_DELE_FAILURE)); - - - /* ###chrisf - the delete succeeded. Write out state so that we - keep track of all the deletes which have not yet been - committed on the server. Flush this state upon successful - QUIT. - - We will do this by adding each successfully deleted message id - to a list which we will write out to popstate.dat in - net_pop3_write_state(cd). - */ - if (host) - { - if (cd->msg_info && cd->msg_info[cd->last_accessed_msg-1].uidl) { - if (cd->newuidl) - XP_Remhash(cd->newuidl, (void*) cd->msg_info[cd->last_accessed_msg-1].uidl); /* kill message in new hash table */ - else - XP_Remhash(host->hash, (void*) cd->msg_info[cd->last_accessed_msg-1].uidl); - } - } - - cd->next_state = POP3_GET_MSG; - - cd->pause_for_read = FALSE; - - return(0); -} - - -PRIVATE int -net_pop3_commit_state(ActiveEntry *ce, XP_Bool remove_last_entry) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - if (remove_last_entry) - { - /* now, if we are leaving messages on the server, pull out the last - uidl from the hash, because it might have been put in there before - we got it into the database. */ - if (cd->msg_info) { - Pop3MsgInfo* info = cd->msg_info + cd->last_accessed_msg; - if (info && info->uidl && (cd->only_uidl == NULL) && cd->newuidl) { - XP_Bool val = XP_Remhash (cd->newuidl, info->uidl); - XP_ASSERT(val); - } - } - } - - if (cd->newuidl) { - XP_HashTableDestroy(cd->uidlinfo->hash); - cd->uidlinfo->hash = cd->newuidl; - cd->newuidl = NULL; - } - if (!cd->only_check_for_new_mail) { - net_pop3_write_state(cd); - } - return 0; -} - - -/* start a pop3 load - */ -PRIVATE int32 -net_Pop3Load (ActiveEntry * ce) -{ - Pop3ConData * cd = XP_NEW(Pop3ConData); - char* uidl; - int err = 0; - int dirlen; - - XP_MEMSET(cd, 0, sizeof(Pop3ConData)); - cd->host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - cd->username = NET_ParseURL(ce->URL_s->address, GET_USERNAME_PART | GET_PASSWORD_PART); - dirlen = strlen(cd->host) + strlen(cd->username) + 1; - cd->accountdir = XP_ALLOC(dirlen); - sprintf(cd->accountdir, "%s@%s", cd->username, cd->host); - cd->rdf = ce->URL_s->fe_data; - - - if (net_pop3_block) /* we already have a connection going */ - { - FREEIF(cd->host); - FREE(cd); - return -1; /* avoid looping back in */ - } - if(!cd || !cd->host /* guha || !ce->URL_s->internal_url */) { - FREEIF(cd->host); - FREEIF(cd); - return(MK_OUT_OF_MEMORY); - } - - - - - if (cd->username && strchr(cd->username, ':')) { - char* temp = cd->username; - size_t len = strlen(temp); - char* pw = strchr(temp, ':'); - size_t l1 = len - strlen(pw); - cd->password = XP_STRDUP(&temp[l1+1]); - temp[l1] = '\0'; - cd->username = XP_STRDUP(temp); - FREE(temp); - } else cd->password = NULL; - if(!cd->username) - { - FREEIF(cd->host); - FREE(cd); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_POP3_USERNAME_UNDEFINED); - ce->status = MK_POP3_USERNAME_UNDEFINED; -#ifdef XP_MAC - FE_Alert(ce->window_id, ce->URL_s->error_msg); /* BEFORE going to the prefs window */ - FE_EditPreference(PREF_Pop3ID); -#endif - return(MK_POP3_USERNAME_UNDEFINED); - } - - /* acquire the semaphore which prevents POP3 from making more connections */ - net_pop3_block = TRUE; - - if(strcasestr(ce->URL_s->address, "?check")) - cd->only_check_for_new_mail = TRUE; - - if(strcasestr(ce->URL_s->address, "?gurl")) - cd->get_url = TRUE; - - if (!cd->only_check_for_new_mail) { - XP_Bool tmp = FALSE; - /* guha cd->pane = ce->URL_s->msg_pane; - if (!cd->pane) - { -#ifdef DEBUG_phil - XP_Trace ("NET_Pop3Load: url->msg_pane NULL for URL: %s\n", ce->URL_s->address); -#endif - cd->pane = MSG_FindPane(ce->window_id, MSG_FOLDERPANE); - } - XP_ASSERT(cd->pane); - if (cd->pane == NULL) - { - net_pop3_block = FALSE; - return -1; - } -*/ - PREF_GetBoolPref("mail.leave_on_server", &(cd->leave_on_server)); - cd->leave_on_server = 1; - PREF_GetBoolPref("mail.limit_message_size", &tmp); - if (tmp) { - PREF_GetIntPref("mail.max_size", &(cd->size_limit)); - cd->size_limit *= 1024; - } else { - cd->size_limit = -1; - } - } - - cd->uidlinfo = net_pop3_load_state(cd); - - cd->output_buffer = (char*)XP_ALLOC(OUTPUT_BUFFER_SIZE); - if(!cd->uidlinfo || !cd->output_buffer) - goto FAIL; - - - ce->con_data = cd; - - /* cd->biffstate = MSG_BIFF_NoMail; Return "no mail" unless proven - otherwise. */ - - uidl = strcasestr(ce->URL_s->address, "?uidl="); - if (uidl) { - uidl += 6; - cd->only_uidl = XP_STRDUP(uidl); - if (!cd->only_uidl) - goto FAIL; - } - - ce->socket = NULL; - - cd->next_state = POP3_READ_PASSWORD; - - /* acquire the semaphore which prevents biff from interrupting connections */ - net_pop3_block = TRUE; - - err = net_ProcessPop3(ce); - if (err < 0) - net_pop3_block = FALSE; - return (err); - -FAIL: - /* release the semaphore which prevents POP3 from making more connections */ - net_pop3_block = FALSE; - if (cd->uidlinfo) - net_pop3_free_state(cd->uidlinfo); - if (cd->output_buffer) - XP_FREE(cd->output_buffer); - FREE(cd); - return(MK_OUT_OF_MEMORY); -} - -/* NET_process_Pop3 will control the state machine that - * loads messages from a pop3 server - * - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -PRIVATE int32 -net_ProcessPop3 (ActiveEntry *ce) -{ - - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - int oldStatus = 0; - - TRACEMSG(("Entering net_ProcessPop3")); - - cd->pause_for_read = FALSE; /* already paused; reset */ - - if(!cd->username) - return(net_pop3_error(ce, MK_POP3_USERNAME_UNDEFINED)); - - while(!cd->pause_for_read) - { - - TRACEMSG(("POP3: Entering state: %d", cd->next_state)); - - switch(cd->next_state) - { - case POP3_READ_PASSWORD: - /* This is a seperate state so that we're waiting for the - user to type in a password while we don't actually have - a connection to the pop server open; this saves us from - having to worry about the server timing out on us while - we wait for user input. */ - { - char *fmt1 = 0, *fmt2 = 0; - - /* If we're just checking for new mail (biff) then don't - prompt the user for a password; just tell him we don't - know whether he has new mail. */ - - if ((cd->only_check_for_new_mail) && - (!cd->username)) - { - ce->status = MK_POP3_PASSWORD_UNDEFINED; - /* cd->biffstate = MSG_BIFF_Unknown; - MSG_SetBiffStateAndUpdateFE(cd->biffstate); update old style biff */ - cd->next_state = POP3_FREE; - cd->pause_for_read = FALSE; - break; - } - - XP_ASSERT(cd->username); - - if (cd->password_failed) - fmt2 = - XP_GetString( XP_THE_PREVIOUSLY_ENTERED_PASSWORD_IS_INVALID_ETC ); - else if (!cd->password) - fmt1 = - XP_GetString( XP_PASSWORD_FOR_POP3_USER ); - - if (!cd->password && (fmt1 || fmt2)) /* We need to read a password. */ - { - char *password; - char *host = cd->host; - size_t len = (XP_STRLEN(fmt1 ? fmt1 : fmt2) + - (host ? XP_STRLEN(host) : 0) + 300) - * sizeof(char); - char *prompt = (char *) XP_ALLOC (len); - - if (!prompt) { - FREEIF(host); - net_pop3_block = FALSE; - return MK_OUT_OF_MEMORY; - } - if (fmt1) - PR_snprintf (prompt, len, fmt1, cd->username, cd->host); - else - PR_snprintf (prompt, len, fmt2, - (cd->command_response - ? cd->command_response - : XP_GetString(XP_NO_ANSWER)), - cd->username, cd->host); - - - cd->password_failed = FALSE; - password = FE_PromptPassword - (ce->window_id, prompt); - - XP_FREE(prompt); - - if (password == NULL) - { - net_pop3_block = FALSE; - return MK_POP3_PASSWORD_UNDEFINED; - } - - cd->password = XP_STRDUP(password); - - net_pop3_password_pending = TRUE; - } - - XP_ASSERT (cd->username && cd->password); - if (!cd->username) - { - net_pop3_block = FALSE; - return -1; - } - - cd->next_state = POP3_START_CONNECT; - cd->pause_for_read = FALSE; - break; - } - - case POP3_START_CONNECT: - - /* Start the thermometer (in cylon mode.) */ - FE_SetProgressBarPercent(ce->window_id, -1); - - ce->status = NET_BeginConnect(ce->URL_s->address, - ce->URL_s->IPAddressString, - "POP3", - POP3_PORT, - &ce->socket, - HG09439 - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - - if ((ce->status == MK_UNABLE_TO_CONNECT) || - (ce->status == MK_CONNECTION_TIMED_OUT) || - (ce->status == MK_CONNECTION_REFUSED)) - if(ce->socket != NULL) - NET_TotalNumberOfOpenConnections++; - - cd->pause_for_read = TRUE; - - if(ce->status == MK_CONNECTED) - { - XP_Bool prefBool = FALSE; - - cd->next_state = POP3_WAIT_FOR_START_OF_CONNECTION_RESPONSE; - - /* cd->next_state_after_response = POP3_SEND_USERNAME; */ - PREF_GetBoolPref ("mail.auth_login", &prefBool); - - if (prefBool) { - if (pop3CapabilityFlags & POP3_AUTH_LOGIN_UNDEFINED) - cd->next_state_after_response = POP3_SEND_AUTH; - else if (pop3CapabilityFlags & POP3_HAS_AUTH_LOGIN) - cd->next_state_after_response = POP3_AUTH_LOGIN; - else - cd->next_state_after_response = POP3_SEND_USERNAME; - } - else - cd->next_state_after_response = POP3_SEND_USERNAME; - - NET_SetReadSelect(ce->window_id, ce->socket); -/*DSR112096 - serious thrashing getting mail by modem if this guy isn't reset properly*/ -/*see defect 19736 for more info. I suspect it is a general defect in the backend. */ -#ifdef XP_OS2_FIX - ce->con_sock = NULL; /* set con sock so we can select on it */ -#endif - } - else if(ce->status > -1) - { - cd->next_state = POP3_FINISH_CONNECT; - ce->con_sock = ce->socket; /* set con sock so we can select on it */ - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - else if(ce->status < 0) - { - /* close and clear the socket here - * so that we don't try and send a RSET - */ - if(ce->socket != NULL) - { - if (NET_TotalNumberOfOpenConnections > 0) NET_TotalNumberOfOpenConnections--; - NET_ClearConnectSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing socket ce->socket: %d", ce->socket)); - PR_Close(ce->socket); - ce->socket = NULL; - cd->next_state = POP3_ERROR_DONE; - } - } - break; - - case POP3_FINISH_CONNECT: - ce->status = NET_FinishConnect(ce->URL_s->address, - "POP3", - POP3_PORT, - &ce->socket, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - - cd->pause_for_read = TRUE; - - if(ce->status == MK_CONNECTED) - { - XP_Bool prefBool = FALSE; - - cd->next_state = POP3_WAIT_FOR_START_OF_CONNECTION_RESPONSE; - PREF_GetBoolPref ("mail.auth_login", &prefBool); - if (prefBool) { - if (pop3CapabilityFlags & POP3_AUTH_LOGIN_UNDEFINED) - cd->next_state_after_response = POP3_SEND_AUTH; - else if (pop3CapabilityFlags & POP3_HAS_AUTH_LOGIN) - cd->next_state_after_response = POP3_AUTH_LOGIN; - else - cd->next_state_after_response = POP3_SEND_USERNAME; - } - else - cd->next_state_after_response = POP3_SEND_USERNAME; - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - NET_SetReadSelect(ce->window_id, ce->socket); - ce->con_sock = NULL; /* set con sock so we can select on it */ - } - else if(ce->status > -1) - { - - /* unregister the old CE_SOCK from the select list - * and register the new value in the case that it changes - */ - if(ce->con_sock != ce->socket) - { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = ce->socket; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - } - else if(ce->status < 0) - { - /* close and clear the socket here - * so that we don't try and send a RSET - */ - if (NET_TotalNumberOfOpenConnections > 0) NET_TotalNumberOfOpenConnections--; - NET_ClearConnectSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing socket ce->socket: %d", ce->socket)); - PR_Close(ce->socket); - ce->socket = NULL; - cd->next_state = POP3_ERROR_DONE; - } - break; - - case POP3_WAIT_FOR_RESPONSE: - ce->status = net_pop3_wait_for_response(ce); - break; - - case POP3_WAIT_FOR_START_OF_CONNECTION_RESPONSE: - net_pop3_wait_for_start_of_connection_response(ce); - break; - - case POP3_SEND_AUTH: - ce->status = net_pop3_send_auth(ce); - break; - - case POP3_AUTH_RESPONSE: - ce->status = net_pop3_auth_response(ce); - break; - - case POP3_AUTH_LOGIN: - ce->status = net_pop3_auth_login(ce); - break; - - case POP3_AUTH_LOGIN_RESPONSE: - ce->status = net_pop3_auth_login_response(ce); - break; - - case POP3_SEND_USERNAME: - NET_Progress(ce->window_id, - XP_GetString(XP_CONNECT_HOST_CONTACTED_SENDING_LOGIN_INFORMATION) ); - ce->status = net_pop3_send_username(ce); - break; - - case POP3_SEND_PASSWORD: - ce->status = net_pop3_send_password(ce); - break; - - case POP3_SEND_GURL: - ce->status = net_pop3_send_gurl(ce); - break; - - case POP3_GURL_RESPONSE: - ce->status = net_pop3_gurl_response(ce); - break; - - case POP3_SEND_STAT: - ce->status = net_pop3_send_stat(ce); - break; - - case POP3_GET_STAT: - ce->status = net_pop3_get_stat(ce); - break; - - case POP3_SEND_LIST: - ce->status = net_pop3_send_list(ce); - break; - - case POP3_GET_LIST: - ce->status = net_pop3_get_list(ce); - break; - - case POP3_SEND_UIDL_LIST: - ce->status = net_pop3_send_uidl_list(ce); - break; - - case POP3_GET_UIDL_LIST: - ce->status = net_pop3_get_uidl_list(ce); - break; - - case POP3_SEND_XTND_XLST_MSGID: - ce->status = net_pop3_send_xtnd_xlst_msgid(ce); - break; - - case POP3_GET_XTND_XLST_MSGID: - ce->status = net_pop3_get_xtnd_xlst_msgid(ce); - break; - - case POP3_START_USE_TOP_FOR_FAKE_UIDL: - ce->status = start_use_top_for_fake_uidl(ce); - break; - - case POP3_SEND_FAKE_UIDL_TOP: - ce->status = send_fake_uidl_top(ce); - break; - - case POP3_GET_FAKE_UIDL_TOP: - ce->status = get_fake_uidl_top(ce); - break; - - case POP3_GET_MSG: - ce->status = net_pop3_get_msg(ce); - break; - - case POP3_SEND_TOP: - ce->status = net_pop3_send_top(ce); - break; - - case POP3_TOP_RESPONSE: - ce->status = net_pop3_top_response(ce); - break; - - case POP3_SEND_XSENDER: - ce->status = net_pop3_send_xsender(ce); - break; - - case POP3_XSENDER_RESPONSE: - ce->status = net_pop3_xsender_response(ce); - break; - - case POP3_SEND_RETR: - ce->status = net_pop3_send_retr(ce); - break; - - case POP3_RETR_RESPONSE: - ce->status = net_pop3_retr_response(ce); - break; - - case POP3_SEND_DELE: - ce->status = net_pop3_send_dele(ce); - break; - - case POP3_DELE_RESPONSE: - ce->status = net_pop3_dele_response(ce); - break; - - case POP3_SEND_QUIT: - /* attempt to send a server quit command. Since this means - everything went well, this is a good time to update the - status file and the FE's biff state. - */ - if (!cd->only_uidl) { - if (cd->only_check_for_new_mail) { - /* MSG_SetBiffStateAndUpdateFE(cd->biffstate); update old style biff - } else { - /* We don't want to pop up a warning message any more (see bug 54116), - so instead we put the "no new messages" or "retrieved x new messages" - in the status line. Unfortunately, this tends to be running - in a progress pane, so we try to get the real pane and - show the message there. */ - MWContext* context = ce->window_id; - /* if (cd->pane) { - MSG_Pane* parentpane = MSG_GetParentPane(cd->pane); - if (parentpane) - context = MSG_GetContext(parentpane); - } */ - if (cd->total_download_size <= 0) { - /* There are no new messages. */ - if (context) - NET_Progress(context, XP_GetString(MK_POP3_NO_MESSAGES)); - } - else { - /* at least 1 message was queued to download */ - char *statusTemplate = XP_GetString (MK_MSG_DOWNLOAD_COUNT); - char *statusString = PR_smprintf (statusTemplate, cd->last_accessed_msg, cd->number_of_messages); - if (context) - NET_Progress(context, statusString); - FREEIF(statusString); - /* MSG_SetBiffStateAndUpdateFE(MSG_BIFF_NewMail); */ - } - } - } - XP_STRCPY(cd->output_buffer, "QUIT" CRLF); - oldStatus = ce->status; - ce->status = net_pop3_send_command(ce, cd->output_buffer); - if (oldStatus == MK_INTERRUPTED) - cd->pause_for_read = FALSE; /* aborting connection, finish clean */ - cd->next_state = POP3_WAIT_FOR_RESPONSE; -#ifdef POP_ALWAYS_USE_UIDL_FOR_DUPLICATES - cd->next_state_after_response = POP3_QUIT_RESPONSE; -#else - cd->next_state_after_response = POP3_DONE; -#endif - break; - -#ifdef POP_ALWAYS_USE_UIDL_FOR_DUPLICATES - case POP3_QUIT_RESPONSE: - if(cd->command_succeeded) - { - /* the QUIT succeeded. We can now flush the state in popstate.dat which - keeps track of any uncommitted DELE's */ - - /* here we need to clear the hash of all our - uncommitted deletes */ - /* - if (cd->uidlinfo && cd->uidlinfo->uncommitted_deletes) - XP_Clrhash (cd->uidlinfo->uncommitted_deletes);*/ - - cd->next_state = POP3_DONE; - - } - else - { - cd->next_state = POP3_ERROR_DONE; - } - break; -#endif - - case POP3_DONE: - net_pop3_commit_state(ce, FALSE); - if(ce->socket != NULL) - { - NET_ClearReadSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing sock ce->socket: %d", - ce->socket)); - PR_Close(ce->socket); - if (NET_TotalNumberOfOpenConnections > 0) NET_TotalNumberOfOpenConnections--; - ce->socket = NULL; - } - - /* if(cd->msg_del_started) - MSG_EndMailDelivery(cd->pane); - else if (cd->pane) - MSG_GetNextURL(cd->pane); */ - - cd->next_state = POP3_FREE; - break; - - case POP3_INTERRUPTED: - { - XP_STRCPY(cd->output_buffer, "QUIT" CRLF); - NET_BlockingWrite(ce->socket, cd->output_buffer, - XP_STRLEN(cd->output_buffer)); - PR_Shutdown(ce->socket, PR_SHUTDOWN_SEND); /* make sure QUIT get send - * before closing down the socket - */ - cd->pause_for_read = FALSE; - cd->next_state = POP3_ERROR_DONE; - net_pop3_block = FALSE; - } - break; - - case POP3_ERROR_DONE: - - /* write out the state */ - net_pop3_commit_state(ce, TRUE); - - if(ce->socket != NULL) - { -#if 0 - /* attempt to send a server reset command - * so that messages will not be marked as read - - #### turns out we never need to do this -- this causes - our DELE commands to not be honored, but that turns out - to never be the right thing, since we never issue a - DELE command until the messages are known to be safely - on disk. - */ - XP_STRCPY(cd->output_buffer, "RSET" CRLF); - net_pop3_send_command(ce, cd->output_buffer); -#endif /* 0 */ - - NET_ClearReadSelect(ce->window_id, ce->socket); - NET_ClearConnectSelect(ce->window_id, ce->socket); - TRACEMSG(("Closing and clearing socket ce->socket: %d", - ce->socket)); - PR_Close(ce->socket); - if (NET_TotalNumberOfOpenConnections > 0) NET_TotalNumberOfOpenConnections--; - ce->socket = NULL; - } - - if(cd->msg_closure) - { - MSG_IncorporateAbort(cd); - cd->msg_closure = NULL; - /* MSG_AbortMailDelivery(cd->pane); */ - } - - if(cd->msg_del_started) - { - char *statusTemplate = XP_GetString (MK_MSG_DOWNLOAD_COUNT); - char *statusString = PR_smprintf (statusTemplate, cd->last_accessed_msg, cd->number_of_messages); - MWContext* context = ce->window_id; - /* if (cd->pane) { - MSG_Pane* parentpane = MSG_GetParentPane(cd->pane); - if (parentpane) { - context = MSG_GetContext(parentpane); - } - } */ - XP_ASSERT (!cd->password_failed); - /* MSG_AbortMailDelivery(cd->pane); - if (context) - NET_Progress(context, statusString); */ - FREEIF(statusString); - } - - if (cd->password_failed) - /* We got here because the password was wrong, so go - read a new one and re-open the connection. */ - cd->next_state = POP3_READ_PASSWORD; - else - /* Else we got a "real" error, so finish up. */ - cd->next_state = POP3_FREE; - - cd->pause_for_read = FALSE; - break; - - case POP3_FREE: - if (cd->newuidl) XP_HashTableDestroy(cd->newuidl); - net_pop3_free_state(cd->uidlinfo); - if (cd->graph_progress_bytes_p) { - /* Only destroy it if we have initialized it. */ - FE_GraphProgressDestroy(ce->window_id, ce->URL_s, - cd->cur_msg_size, - ce->bytes_received); - } - net_pop3_free_msg_info(ce); - FREEIF(cd->only_uidl); - FREEIF(cd->output_buffer); - FREEIF(cd->obuffer); - FREEIF(cd->data_buffer); - FREEIF(cd->command_response); - FREEIF(cd->sender_info); - FREE(ce->con_data); - - /* release the semaphore which prevents POP3 from creating more connections */ - net_pop3_block = FALSE; - - if (oldStatus == MK_INTERRUPTED) - return MK_INTERRUPTED; /* Make sure everyone knows we got canceled */ - return(-1); - break; - - default: - XP_ASSERT(0); - - } /* end switch */ - - if((ce->status < 0) && (cd->next_state != POP3_FREE)) - { - cd->pause_for_read = FALSE; - cd->next_state = POP3_ERROR_DONE; - } - - } /* end while */ - if (oldStatus == MK_INTERRUPTED) - ce->status = MK_INTERRUPTED; /* Make sure everyone knows we got canceled */ - - return(ce->status); - -} - -/* abort the connection in progress - */ -PRIVATE int32 -net_InterruptPop3(ActiveEntry * ce) -{ - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - - TRACEMSG(("net_InterruptPop3 called")); - - cd->next_state = POP3_SEND_QUIT; /* interrupt does not give enough time for the quit - command to be executed on the server, leaving us - with a bunch of messages to be re-downloaded. - Make a graceful quit instead. - POP3_INTERRUPTED; */ - - ce->status = MK_INTERRUPTED; - - return(net_ProcessPop3(ce)); -} - -PRIVATE void -net_CleanupPop3(void) -{ -} - -MODULE_PRIVATE void -NET_InitPop3Protocol(void) -{ - static NET_ProtoImpl pop3_proto_impl; - pop3_proto_impl.init = net_Pop3Load; - pop3_proto_impl.process = net_ProcessPop3; - pop3_proto_impl.interrupt = net_InterruptPop3; - pop3_proto_impl.resume = NULL; - pop3_proto_impl.cleanup = net_CleanupPop3; - NET_RegisterProtocolImplementation(&pop3_proto_impl, POP3_TYPE_URL); - NET_InitMailboxProtocol(); -} - -extern void RDF_StartMessageDelivery (void* rdf) ; -extern void RDF_AddMessageLine(void* rdf, const char* line, int32 length); -extern void RDF_FinishMessageDelivery (void* rdf) ; - -void *MSG_IncorporateBegin (ActiveEntry *ce) { - Pop3ConData * cd = (Pop3ConData *)ce->con_data; - void* rdf = cd->rdf; - RDF_StartMessageDelivery(rdf); - return (void*)1; - -} - -int MSG_IncorporateWrite (Pop3ConData *cd, const char *block, int32 length) { - void* rdf = cd->rdf; - RDF_AddMessageLine(rdf, block, length); - return 1; -} - - - -int MSG_IncorporateComplete(Pop3ConData *cd) { - void* rdf = cd->rdf; - RDF_FinishMessageDelivery(rdf); - return 1; -} - -int MSG_IncorporateAbort (Pop3ConData *cd) { - return 0; -} - -int -msg_GrowBuffer (uint32 desired_size, uint32 element_size, uint32 quantum, - char **buffer, uint32 *size) -{ - if (*size <= desired_size) - { - char *new_buf; - uint32 increment = desired_size - *size; - if (increment < quantum) /* always grow by a minimum of N bytes */ - increment = quantum; - -#ifdef TESTFORWIN16 - if (((*size + increment) * (element_size / sizeof(char))) >= 64000) - { - /* Make sure we don't choke on WIN16 */ - XP_ASSERT(0); - return MK_OUT_OF_MEMORY; - } -#endif /* DEBUG */ - - new_buf = (*buffer - ? (char *) XP_REALLOC (*buffer, (*size + increment) - * (element_size / sizeof(char))) - : (char *) XP_ALLOC ((*size + increment) - * (element_size / sizeof(char)))); - if (! new_buf) - return MK_OUT_OF_MEMORY; - *buffer = new_buf; - *size += increment; - } - return 0; -} - -/* Take the given buffer, tweak the newlines at the end if necessary, and - send it off to the given routine. We are guaranteed that the given - buffer has allocated space for at least one more character at the end. */ -static int -msg_convert_and_send_buffer(char* buf, uint32 length, XP_Bool convert_newlines_p, - int32 (*per_line_fn) (char *line, - uint32 line_length, - void *closure), - void *closure) -{ - /* Convert the line terminator to the native form. - */ - char* newline; - - XP_ASSERT(buf && length > 0); - if (!buf || length <= 0) return -1; - newline = buf + length; - XP_ASSERT(newline[-1] == CR || newline[-1] == LF); - if (newline[-1] != CR && newline[-1] != LF) return -1; - - if (!convert_newlines_p) - { - } -#if (LINEBREAK_LEN == 1) - else if ((newline - buf) >= 2 && - newline[-2] == CR && - newline[-1] == LF) - { - /* CRLF -> CR or LF */ - buf [length - 2] = LINEBREAK[0]; - length--; - } - else if (newline > buf + 1 && - newline[-1] != LINEBREAK[0]) - { - /* CR -> LF or LF -> CR */ - buf [length - 1] = LINEBREAK[0]; - } -#else - else if (((newline - buf) >= 2 && newline[-2] != CR) || - ((newline - buf) >= 1 && newline[-1] != LF)) - { - /* LF -> CRLF or CR -> CRLF */ - length++; - buf[length - 2] = LINEBREAK[0]; - buf[length - 1] = LINEBREAK[1]; - } -#endif - - return (*per_line_fn)(buf, length, closure); -} - -int -msg_LineBuffer (const char *net_buffer, int32 net_buffer_size, - char **bufferP, uint32 *buffer_sizeP, uint32 *buffer_fpP, - XP_Bool convert_newlines_p, - int32 (*per_line_fn) (char *line, uint32 line_length, - void *closure), - void *closure) -{ - int status = 0; - if (*buffer_fpP > 0 && *bufferP && (*bufferP)[*buffer_fpP - 1] == CR && - net_buffer_size > 0 && net_buffer[0] != LF) { - /* The last buffer ended with a CR. The new buffer does not start - with a LF. This old buffer should be shipped out and discarded. */ - XP_ASSERT(*buffer_sizeP > *buffer_fpP); - if (*buffer_sizeP <= *buffer_fpP) return -1; - status = msg_convert_and_send_buffer(*bufferP, *buffer_fpP, - convert_newlines_p, - per_line_fn, closure); - if (status < 0) return status; - *buffer_fpP = 0; - } - while (net_buffer_size > 0) - { - const char *net_buffer_end = net_buffer + net_buffer_size; - const char *newline = 0; - const char *s; - - - for (s = net_buffer; s < net_buffer_end; s++) - { - /* Move forward in the buffer until the first newline. - Stop when we see CRLF, CR, or LF, or the end of the buffer. - *But*, if we see a lone CR at the *very end* of the buffer, - treat this as if we had reached the end of the buffer without - seeing a line terminator. This is to catch the case of the - buffers splitting a CRLF pair, as in "FOO\r\nBAR\r" "\nBAZ\r\n". - */ - if (*s == CR || *s == LF) - { - newline = s; - if (newline[0] == CR) - { - if (s == net_buffer_end - 1) - { - /* CR at end - wait for the next character. */ - newline = 0; - break; - } - else if (newline[1] == LF) - /* CRLF seen; swallow both. */ - newline++; - } - newline++; - break; - } - } - - /* Ensure room in the net_buffer and append some or all of the current - chunk of data to it. */ - { - const char *end = (newline ? newline : net_buffer_end); - uint32 desired_size = (end - net_buffer) + (*buffer_fpP) + 1; - - if (desired_size >= (*buffer_sizeP)) - { - status = msg_GrowBuffer (desired_size, sizeof(char), 1024, - bufferP, buffer_sizeP); - if (status < 0) return status; - } - XP_MEMCPY ((*bufferP) + (*buffer_fpP), net_buffer, (end - net_buffer)); - (*buffer_fpP) += (end - net_buffer); - } - - /* Now *bufferP contains either a complete line, or as complete - a line as we have read so far. - - If we have a line, process it, and then remove it from `*bufferP'. - Then go around the loop again, until we drain the incoming data. - */ - if (!newline) - return 0; - - status = msg_convert_and_send_buffer(*bufferP, *buffer_fpP, - convert_newlines_p, - per_line_fn, closure); - if (status < 0) return status; - - net_buffer_size -= (newline - net_buffer); - net_buffer = newline; - (*buffer_fpP) = 0; - } - return 0; -} - - -struct MimeEncoderData { - - /* Buffer for the base64 encoder. */ - unsigned char in_buffer[3]; - int32 in_buffer_count; - - int32 current_column, line_byte_count; - - /* Where to write the encoded data */ - int (*write_buffer) (const char *buf, int32 size, void *closure); - void *closure; -}; - -int pop_mime_encode_base64_buffer (MimeEncoderData *data, const char *buffer, int32 size); -MimeEncoderData* pop_mime_encoder_init (int (*output_fn) (const char *, int32, void *), void *closure); -int PopMimeEncoderDestroy (MimeEncoderData *data, XP_Bool abort_p); -int net_buffer_output_fn ( const char *buf, int32 size, void *closure); - - -int -PopMimeEncoderDestroy (MimeEncoderData *data, XP_Bool abort_p) -{ - int status = 0; - - /* If we're uuencoding, we have our own finishing routine. */ - - /* Since Base64 (and uuencode) output needs to do some buffering to get - a multiple of three bytes on each block, there may be a few bytes - left in the buffer after the last block has been written. We need to - flush those out now. - */ - - - if (!abort_p && - data->in_buffer_count > 0) - { - char buf2 [6]; - char *buf = buf2 + 2; - char *out = buf; - int j; - /* fixed bug 55998, 61302, 61866 - * type casting to uint32 before shifting - */ - uint32 n = ((uint32) data->in_buffer[0]) << 16; - if (data->in_buffer_count > 1) - n = n | (((uint32) data->in_buffer[1]) << 8); - - buf2[0] = CR; - buf2[1] = LF; - - for (j = 18; j >= 0; j -= 6) - { - unsigned int k = (n >> j) & 0x3F; - if (k < 26) *out++ = k + 'A'; - else if (k < 52) *out++ = k - 26 + 'a'; - else if (k < 62) *out++ = k - 52 + '0'; - else if (k == 62) *out++ = '+'; - else if (k == 63) *out++ = '/'; - else abort (); - } - - /* Pad with equal-signs. */ - if (data->in_buffer_count == 1) - buf[2] = '='; - buf[3] = '='; - - if (data->current_column >= 72) - status = data->write_buffer (buf2, 6, data->closure); - else - status = data->write_buffer (buf, 4, data->closure); - } - - - XP_FREE (data); - return status; -} - -MimeEncoderData * -pop_mime_encoder_init (int (*output_fn) (const char *, int32, void *), - void *closure) -{ - MimeEncoderData *data = XP_NEW(MimeEncoderData); - if (!data) return 0; - XP_MEMSET(data, 0, sizeof(*data)); - data->write_buffer = output_fn; - data->closure = closure; - return data; -} - -typedef struct { - char *buffer; - int32 size; - int32 pos; -} BufferStruct; - - -char * POP_Base64Encode (char *src, int32 srclen) -{ - BufferStruct bs; - MimeEncoderData *encoder_data = NULL; - - XP_ASSERT (src); - if (!src) - return NULL; - else if (srclen == 0) - return XP_STRDUP(""); - - XP_MEMSET (&bs, 0, sizeof (BufferStruct)); - encoder_data = pop_mime_encoder_init(net_buffer_output_fn, (void *) &bs); - if (!encoder_data) - return NULL; - - if (pop_mime_encode_base64_buffer(encoder_data, src, srclen) < 0) - { - PopMimeEncoderDestroy(encoder_data, FALSE); - XP_FREEIF(bs.buffer); - return NULL; - } - - PopMimeEncoderDestroy(encoder_data, FALSE); - /* caller must free the returned pointer to prevent - * memory leak problem. - */ - return bs.buffer; -} - -int -pop_mime_encode_base64_buffer (MimeEncoderData *data, const char *buffer, int32 size) -{ - int status = 0; - const unsigned char *in = (unsigned char *) buffer; - const unsigned char *end = in + size; - char out_buffer[80]; - char *out = out_buffer; - uint32 i = 0, n = 0; - uint32 off; - - if (size == 0) - return 0; - else if (size < 0) - { - XP_ASSERT(0); - return -1; - } - - - /* If this input buffer is too small, wait until next time. */ - if (size < (3 - data->in_buffer_count)) - { - XP_ASSERT(size < 3 && size > 0); - data->in_buffer[data->in_buffer_count++] = buffer[0]; - if (size > 1) - data->in_buffer[data->in_buffer_count++] = buffer[1]; - XP_ASSERT(data->in_buffer_count < 3); - return 0; - } - - - /* If there are bytes that were put back last time, take them now. - */ - i = 0; - if (data->in_buffer_count > 0) n = data->in_buffer[0]; - if (data->in_buffer_count > 1) n = (n << 8) + data->in_buffer[1]; - i = data->in_buffer_count; - data->in_buffer_count = 0; - - /* If this buffer is not a multiple of three, put one or two bytes back. - */ - off = ((size + i) % 3); - if (off) - { - data->in_buffer[0] = buffer [size - off]; - if (off > 1) - data->in_buffer [1] = buffer [size - off + 1]; - data->in_buffer_count = off; - size -= off; - XP_ASSERT (! ((size + i) % 3)); - end = (unsigned char *) (buffer + size); - } - - /* Populate the out_buffer with base64 data, one line at a time. - */ - while (in < end) - { - int32 j; - - while (i < 3) - { - n = (n << 8) | *in++; - i++; - } - i = 0; - - for (j = 18; j >= 0; j -= 6) - { - unsigned int k = (n >> j) & 0x3F; - if (k < 26) *out++ = k + 'A'; - else if (k < 52) *out++ = k - 26 + 'a'; - else if (k < 62) *out++ = k - 52 + '0'; - else if (k == 62) *out++ = '+'; - else if (k == 63) *out++ = '/'; - else abort (); - } - - data->current_column += 4; - if (data->current_column >= 72) - { - /* Do a linebreak before column 76. Flush out the line buffer. */ - data->current_column = 0; - *out++ = '\015'; - *out++ = '\012'; - status = data->write_buffer (out_buffer, (out - out_buffer), - data->closure); - out = out_buffer; - if (status < 0) return status; - } - } - - /* Write out the unwritten portion of the last line buffer. */ - if (out > out_buffer) - { - status = data->write_buffer (out_buffer, (out - out_buffer), - data->closure); - if (status < 0) return status; - } - - return 0; -} - -int -net_buffer_output_fn ( const char *buf, int32 size, void *closure) -{ - BufferStruct *bs = (BufferStruct *) closure; - /* if the size greater or equal to the available buffer size - * reallocate the buffer - */ - PR_ASSERT (buf && bs && size > 0); - if ( !buf || !bs || size <= 0 ) - return -1; - - if (size >= bs->size - bs->pos) - { - int32 len; - char *newBuffer; - - len = (bs->size << 1) - bs->pos + size + 1; /* null terminated */ - if (bs->buffer) - newBuffer = PR_Realloc (bs->buffer, len); - else - newBuffer = PR_Malloc(len); - if (!newBuffer) - return MK_OUT_OF_MEMORY; - memset(newBuffer+bs->pos, 0, len-bs->pos); - bs->size = len; - bs->buffer = newBuffer; - } - memcpy (bs->buffer+bs->pos, buf, size); - bs->pos += size; - return 0; -} - - - -/* Stick the mailbox stuff here. The mailbox stuff in mkmailbox.c is too ... */ - - -typedef struct _MBoxConData { - FILE *mbox; - int32 offset; - int32 status; - NET_StreamClass *stream; - int32 pos; - char* buff; -} MBoxConData; - - -extern void* getTranslator (char* url); -extern FILE *getPopMBox(void* db); - -int32 -net_ProcessMBox (ActiveEntry * ce) { - MBoxConData *cd = (MBoxConData *)ce->con_data; - if ((cd->status == 1) && (cd->stream)) { - memset(cd->buff, '\0', 100000); - fseek(cd->mbox, cd->offset, SEEK_SET); - while (fgets(cd->buff, 100000, cd->mbox)) { - cd->offset = ftell(cd->mbox); - if (!startsWith("From ", cd->buff)) { - (*(cd->stream->put_block))(cd->stream, cd->buff, strlen(cd->buff)); - } else break; - memset(cd->buff, '\0', 100000); - fseek(cd->mbox, cd->offset, SEEK_SET); - } - (*cd->stream->complete)(cd->stream); - XP_FREE(cd->buff); - cd->status = 0; - XP_FREE(cd); - XP_FREE(ce->URL_s->content_type); - ce->URL_s->content_type = NULL; - ce->con_data = NULL; - } - return -1; -} - -char* normalizeMTs (char* mt) { - if (strcmp(mt, "text/html") ==0) { - return TEXT_HTML; - } if (strcmp(mt, "text/plain") ==0) { - return TEXT_PLAIN; - } if (strcmp(mt, "text") ==0) { - return TEXT_PLAIN; - } else return mt; -} - -void -ShowMailFolder (NET_StreamClass *stream, char* url) { - char* buff = XP_ALLOC(2000); - /* this really sucks. The right way is to have some javascript on the page that - spits this out. Then it will be really customizable */ - sprintf(buff, "<html>\n<body marginwidth=0 marginheight=0>\n<object title=\"Summary\" target=\"messages\" width=100%% height=100%% type=builtin/tree data=\"mailbox://%s\">\n<param name=\"title\" value=\"Summary\">\n<param name=\"Column\" value=\"mail:From\">\n<param name=\"Column\" value=\"mail:Subject\">\n<param name=\"Column\" value=\"mail:Date\">\n</object>", &url[17]); - (*stream->put_block)(stream, buff, strlen(buff)); - sprintf(buff, "</body>\n</html>\n\n"); - (*stream->put_block)(stream, buff, strlen(buff)); - XP_FREE(buff); - (*stream->complete)(stream); -} - -PRIVATE int32 -net_MBoxLoad (ActiveEntry * ce) -{ - /* displaying mailbox items */ - void* db; - char* offset = strchr(ce->URL_s->address, '?') ; - if (!offset) { - NET_StreamClass *stream; - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - stream = NET_StreamBuilder(1, ce->URL_s, (MWContext*) ce->window_id); - ShowMailFolder(stream, ce->URL_s->address); - return -1; - } else { - MBoxConData *cd = (MBoxConData *)XP_NEW(MBoxConData); - char* mbox = XP_ALLOC(100); - PRBool mimeTypeSet = 0; - memset(mbox, '\0', 100); - offset = offset+1; - memcpy(mbox, ce->URL_s->address, offset-(ce->URL_s->address+1)); - sscanf(offset, "%d",&cd->offset); - db = getTranslator(mbox); - cd->mbox = getPopMBox(db); - cd->status = 1; - cd->buff = XP_ALLOC(100000); - memset(cd->buff, '\0', 100000); - fseek(cd->mbox, cd->offset, SEEK_SET); - StrAllocCopy(ce->URL_s->content_type, MESSAGE_RFC822); - cd->stream = NET_StreamBuilder(1, ce->URL_s, (MWContext*) ce->window_id); - ce->con_data = cd; - XP_FREE(mbox); - return net_ProcessMBox(ce); - } -} - - -int32 -net_InterruptMBox (ActiveEntry *ce) { - MBoxConData* cd = (MBoxConData*)ce->con_data; - cd->status = 0; - return 0; -} - -int32 -net_CleanupMBox (void) { - return 0; -} - -/* NET_process_Pop3 will control the state machine that - * loads messages from a pop3 server - * - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ - -MODULE_PRIVATE void -NET_InitMailboxProtocol(void) -{ - static NET_ProtoImpl mbox_proto_impl; - mbox_proto_impl.init = net_MBoxLoad; - mbox_proto_impl.process = net_ProcessMBox; - mbox_proto_impl.interrupt = net_InterruptMBox; - mbox_proto_impl.resume = NULL; - mbox_proto_impl.cleanup = net_CleanupMBox; - NET_RegisterProtocolImplementation(&mbox_proto_impl, MAILBOX_TYPE_URL); -} - - - - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/protocol/pop3/mkpop3.h b/mozilla/network/protocol/pop3/mkpop3.h deleted file mode 100644 index 7214fe2c1b4..00000000000 --- a/mozilla/network/protocol/pop3/mkpop3.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKPOP3_H -#define MKPOP3_H - -extern void NET_InitPop3Protocol(void); -extern void NET_InitMailboxProtocol(void); - -MODULE_PRIVATE XP_Bool NET_GetAllowAtSignInMailUserName(); -MODULE_PRIVATE int32 net_ProcessPop3 (ActiveEntry *ce); -MODULE_PRIVATE int32 net_ProcessMBox (ActiveEntry *ce); -MODULE_PRIVATE void NET_SetAllowAtSignInMailUserName(XP_Bool allow); - -#endif /* not MKPOP3_H */ diff --git a/mozilla/network/protocol/remote/MANIFEST b/mozilla/network/protocol/remote/MANIFEST deleted file mode 100644 index 9879b458ec5..00000000000 --- a/mozilla/network/protocol/remote/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -remoturl.h diff --git a/mozilla/network/protocol/remote/Makefile.in b/mozilla/network/protocol/remote/Makefile.in deleted file mode 100644 index 04b4cf5796f..00000000000 --- a/mozilla/network/protocol/remote/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = remoturl -LIBRARY_NAME = remoturl - -REQUIRES = network dbm util pref js java fileurl security layer img httpurl - -CSRCS = mkremote.c - -EXPORTS = $(srcdir)/remoturl.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/remote/makefile.win b/mozilla/network/protocol/remote/makefile.win deleted file mode 100644 index 0e74b9c96e4..00000000000 --- a/mozilla/network/protocol/remote/makefile.win +++ /dev/null @@ -1,84 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -OBJS= \ - .\$(OBJDIR)\mkremote.obj \ - $(NULL) - - -CSRCS = \ - mkremote.c \ - $(NULL) - - -LIBRARY_NAME=remoturl -MODULE=remoturl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= remoturl.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(XPDIST)\public\nspr2 \ - -I$(XPDIST)\public\util \ - -I$(XPDIST)\public\java \ - -I$(XPDIST)\public\pref \ - -I$(XPDIST)\public\js \ - -I$(XPDIST)\public\security \ - -I$(XPDIST)\public\network -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/remote/mkremote.c b/mozilla/network/protocol/remote/mkremote.c deleted file mode 100644 index f4cfe43d34a..00000000000 --- a/mozilla/network/protocol/remote/mkremote.c +++ /dev/null @@ -1,187 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* forks a telnet process - * - * Designed and implemented by Lou Montulli - */ - -/* Please leave outside of ifdef for windows precompiled headers */ - -#include "xp.h" -#include "plstr.h" -#include "prmem.h" -#include "netutils.h" -#include "mkselect.h" -#include "mktcp.h" -#include "mkgeturl.h" - -#ifdef MOZILLA_CLIENT - -#include "mkparse.h" -#include "remoturl.h" -#include "glhist.h" -#include "mkgeturl.h" /* for URL types */ -#include "merrors.h" - -/* - * begin a session with a remote host. - * - * URL types permitted: Telnet, TN3270, and Rlogin - */ -MODULE_PRIVATE int32 -NET_RemoteHostLoad (ActiveEntry * cur_entry) -{ - char * host_string; - int url_type; - char * cp; - char * username; - char * hostname; - char * port_string; - - TRACEMSG(("In NET_RemoteHostLoad")); - - GH_UpdateGlobalHistory(cur_entry->URL_s); - - if(cur_entry->format_out == FO_CACHE_AND_PRESENT || cur_entry->format_out == FO_PRESENT) - { - url_type = NET_URL_Type(cur_entry->URL_s->address); - host_string = NET_ParseURL(cur_entry->URL_s->address, GET_USERNAME_PART | GET_PASSWORD_PART | GET_HOST_PART); - - hostname = PL_strchr(host_string, '@'); - port_string = PL_strchr(host_string, ':'); - - if (hostname) - { - *hostname++ = '\0'; - username = NET_UnEscape(host_string); - } - else - { - hostname = host_string; - username = NULL; /* no username given */ - } - - if (port_string) - { - *port_string++ = '\0'; - - /* Sanity check the port part - * prevent telnet://hostname:30;rm -rf * URL's (VERY BAD) - * only allow digits - */ - for(cp=port_string; *cp != '\0'; cp++) - if(!isdigit(*cp)) - { - *cp = '\0'; - break; - } - } - - - if(username) - { - /* Sanity check the username part - * prevent telnet://hostname:30;rm -rf * URL's (VERY BAD) - * only allow alphanums - */ - for(cp=username; *cp != '\0'; cp++) - if(!isalnum(*cp)) - { - *cp = '\0'; - break; - } - } - - /* now sanity check the hostname part - * prevent telnet://hostname;rm -rf * URL's (VERY BAD) - * only allow alphanumeric characters and a few symbols - */ - for(cp=hostname; *cp != '\0'; cp++) - if(!isalnum(*cp) && *cp != '_' && *cp != '-' && - *cp != '+' && *cp != ':' && *cp != '.' && *cp != '@') - { - *cp = '\0'; - break; - } - - TRACEMSG(("username: %s, hostname: %s, port: %s", - username ? username : "(null)", - hostname ? hostname : "(null)", - port_string ? port_string : "(null)")); - - if(url_type == TELNET_TYPE_URL) - { - FE_ConnectToRemoteHost(cur_entry->window_id, FE_TELNET_URL_TYPE, hostname, port_string, username); - } - else if(url_type == TN3270_TYPE_URL) - { - FE_ConnectToRemoteHost(cur_entry->window_id, FE_TN3270_URL_TYPE, hostname, port_string, username); - } - else if(url_type == RLOGIN_TYPE_URL) - { - FE_ConnectToRemoteHost(cur_entry->window_id, FE_RLOGIN_URL_TYPE, hostname, port_string, username); - } - /* fall through if it wasn't any of the above url types */ - - PR_Free(host_string); - } - - cur_entry->status = MK_NO_DATA; - return -1; -} - -PRIVATE int32 -net_ProcessRemote(ActiveEntry *ce) -{ - PR_ASSERT(0); - return -1; -} - -PRIVATE int32 -net_InterruptRemote(ActiveEntry *ce) -{ - PR_ASSERT(0); - return -1; -} - -PRIVATE void -net_CleanupRemote(void) -{ -} - -MODULE_PRIVATE void -NET_InitRemoteProtocol(void) -{ - static NET_ProtoImpl remote_proto_impl; - - remote_proto_impl.init = NET_RemoteHostLoad; - remote_proto_impl.process = net_ProcessRemote; - remote_proto_impl.interrupt = net_InterruptRemote; - remote_proto_impl.resume = NULL; - remote_proto_impl.cleanup = net_CleanupRemote; - - NET_RegisterProtocolImplementation(&remote_proto_impl, RLOGIN_TYPE_URL); - NET_RegisterProtocolImplementation(&remote_proto_impl, TELNET_TYPE_URL); - NET_RegisterProtocolImplementation(&remote_proto_impl, TN3270_TYPE_URL); -} - -#endif /* MOZILLA_CLIENT */ diff --git a/mozilla/network/protocol/remote/remoturl.h b/mozilla/network/protocol/remote/remoturl.h deleted file mode 100644 index b5ec645adcf..00000000000 --- a/mozilla/network/protocol/remote/remoturl.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * Remote host access routines for Telnet, tn3270, rlogin - */ - -#ifndef REMOTE_H -#define REMOTE_H - -#ifndef MKGETURL_H -#include "mkgeturl.h" -#endif /* MKGETURL_H */ - -extern int32 NET_RemoteHostLoad (ActiveEntry * cur_entry); -extern void NET_InitRemoteProtocol (void); - -#endif /* REMOTE_H */ diff --git a/mozilla/network/protocol/smtp/MANIFEST b/mozilla/network/protocol/smtp/MANIFEST deleted file mode 100644 index 6d2e73b9327..00000000000 --- a/mozilla/network/protocol/smtp/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -mksmtp.h diff --git a/mozilla/network/protocol/smtp/Makefile.in b/mozilla/network/protocol/smtp/Makefile.in deleted file mode 100644 index 0dd2a07dd15..00000000000 --- a/mozilla/network/protocol/smtp/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = smtpurl -LIBRARY_NAME = smtpurl - -REQUIRES = netcache network dbm util pref js java fileurl security layer img httpurl mimetype htmldlgs - -CSRCS = mksmtp.c - -EXPORTS = $(srcdir)/mksmtp.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/smtp/makefile.win b/mozilla/network/protocol/smtp/makefile.win deleted file mode 100644 index 9c7257e263c..00000000000 --- a/mozilla/network/protocol/smtp/makefile.win +++ /dev/null @@ -1,89 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -LLIBS= \ - $(NULL) -OBJS= \ - .\$(OBJDIR)\mksmtp.obj \ - $(NULL) - -CSRCS = \ - mksmtp.c \ - $(NULL) - - -LIBRARY_NAME=smtpurl -MODULE=smtpurl -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network ldap -EXPORTS= mksmtp.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\ldap \ - -I$(PUBLIC)\mimetype \ -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/smtp/mksmtp.c b/mozilla/network/protocol/smtp/mksmtp.c deleted file mode 100644 index bfdcb120fc8..00000000000 --- a/mozilla/network/protocol/smtp/mksmtp.c +++ /dev/null @@ -1,1705 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * state machine to speak SMTP - */ - -/* Please leave outside of ifdef for windows precompiled headers */ -#include "rosetta.h" -#include "mkutils.h" -#include "netutils.h" - -#if defined(MOZILLA_CLIENT) || defined(LIBNET_SMTP) -#if defined(MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) -#include "mkgeturl.h" -#include "mksmtp.h" -#include "mime.h" -#include "glhist.h" -#include "mktcp.h" -#include "mkparse.h" -#include "msgcom.h" -#include "msgnet.h" -#include "xp_time.h" -#include "xp_thrmo.h" -#include "merrors.h" -#include "ssl.h" -#include "imap.h" - -#include "xp_error.h" -#include "prefapi.h" -#include "libi18n.h" - -#ifdef AUTH_SKEY_DEFINED -extern int btoa8(char *out, char*in); -#endif - -extern void NET_SetPopPassword2(const char *password); -extern void net_free_write_post_data_object(struct WritePostDataData *obj); -MODULE_PRIVATE char* NET_MailRelayHost(MWContext *context); - -/* for XP_GetString() */ -#include "xpgetstr.h" -extern int XP_PROGRESS_MAILSENT; -extern int MK_COULD_NOT_GET_USERS_MAIL_ADDRESS; -extern int MK_COULD_NOT_LOGIN_TO_SMTP_SERVER; -extern int MK_ERROR_SENDING_DATA_COMMAND; -extern int MK_ERROR_SENDING_FROM_COMMAND; -extern int MK_ERROR_SENDING_MESSAGE; -extern int MK_ERROR_SENDING_RCPT_COMMAND; -extern int MK_OUT_OF_MEMORY; -extern int MK_SMTP_SERVER_ERROR; -extern int MK_TCP_READ_ERROR; -extern int XP_MESSAGE_SENT_WAITING_MAIL_REPLY; -extern int MK_MSG_DELIV_MAIL; -extern int MK_MSG_NO_SMTP_HOST; -extern int MK_MIME_NO_RECIPIENTS; - -extern int MK_POP3_USERNAME_UNDEFINED; -extern int MK_POP3_PASSWORD_UNDEFINED; -extern int XP_PASSWORD_FOR_POP3_USER; -extern int XP_RETURN_RECEIPT_NOT_SUPPORT; -extern int MK_SENDMAIL_BAD_TLS; - -#define SMTP_PORT 25 - -/* definitions of state for the state machine design - */ -#define SMTP_RESPONSE 0 -#define SMTP_START_CONNECT 1 -#define SMTP_FINISH_CONNECT 2 -#define SMTP_LOGIN_RESPONSE 3 -#define SMTP_SEND_HELO_RESPONSE 4 -#define SMTP_SEND_VRFY_RESPONSE 5 -#define SMTP_SEND_MAIL_RESPONSE 6 -#define SMTP_SEND_RCPT_RESPONSE 7 -#define SMTP_SEND_DATA_RESPONSE 8 -#define SMTP_SEND_POST_DATA 9 -#define SMTP_SEND_MESSAGE_RESPONSE 10 -#define SMTP_DONE 11 -#define SMTP_ERROR_DONE 12 -#define SMTP_FREE 13 -#define SMTP_EXTN_LOGIN_RESPONSE 14 -#define SMTP_SEND_EHLO_RESPONSE 15 - -#define SMTP_SEND_AUTH_LOGIN_USERNAME 16 -#define SMTP_SEND_AUTH_LOGIN_PASSWORD 17 -#define SMTP_AUTH_LOGIN_RESPONSE 18 -#define SMTP_AUTH_RESPONSE 19 - -HG08747 - -/* structure to hold data pertaining to the active state of - * a transfer in progress. - * - */ -typedef struct _SMTPConData { - int next_state; /* the next state or action to be taken */ - int next_state_after_response; /* the state after the response one */ - Bool pause_for_read; /* Pause now for next read? */ -#ifdef XP_WIN - Bool calling_netlib_all_the_time; -#endif - char *response_text; - int response_code; - char *data_buffer; - int32 data_buffer_size; - char *address_copy; - char *mail_to_address_ptr; - int mail_to_addresses_left; - TCP_ConData * tcp_con_data; - int continuation_response; - char *hostname; - char *verify_address; - void *write_post_data_data; /* a data object for the - * WritePostData function - */ - int32 total_amt_written; - uint32 total_message_size; - unsigned long last_time; - XP_Bool ehlo_dsn_enabled; - XP_Bool auth_login_enabled; -HG60917 -} SMTPConData; - -/* macro's to simplify variable names */ -#define CD_NEXT_STATE cd->next_state -#define CD_NEXT_STATE_AFTER_RESPONSE cd->next_state_after_response -#define CD_PAUSE_FOR_READ cd->pause_for_read -#define CD_RESPONSE_TXT cd->response_text -#define CD_RESPONSE_CODE cd->response_code -#define CD_DATA_BUFFER cd->data_buffer -#define CD_DATA_BUFFER_SIZE cd->data_buffer_size -#define CD_ADDRESS_COPY cd->address_copy -#define CD_MAIL_TO_ADDRESS_PTR cd->mail_to_address_ptr -#define CD_MAIL_TO_ADDRESSES_LEFT cd->mail_to_addresses_left -#define CD_TCP_CON_DATA cd->tcp_con_data -#define CD_CONTINUATION_RESPONSE cd->continuation_response -#define CD_HOSTNAME cd->hostname -#define CD_VERIFY_ADDRESS cd->verify_address -#define CD_TOTAL_AMT_WRITTEN cd->total_amt_written -#define CD_TOTAL_MESSAGE_SIZE cd->total_message_size -#define CD_EHLO_DSN_ENABLED cd->ehlo_dsn_enabled - -#define CD_AUTH_LOGIN_ENABLED cd->auth_login_enabled -HG82493 - -#define CE_URL_S cur_entry->URL_s -#define CE_SOCK cur_entry->socket -#define CE_CON_SOCK cur_entry->con_sock -#define CE_STATUS cur_entry->status -#define CE_WINDOW_ID cur_entry->window_id -#define CE_BYTES_RECEIVED cur_entry->bytes_received -#define CE_FORMAT_OUT cur_entry->format_out - -PRIVATE char *net_smtp_relay_host=0; -PRIVATE char *net_smtp_password=0; - -/* forward decl */ -PRIVATE int32 net_ProcessMailto (ActiveEntry *cur_entry); - -/* fix Mac warning of missing prototype */ -MODULE_PRIVATE char * -NET_MailRelayHost(MWContext *context); - -MODULE_PRIVATE char * -NET_MailRelayHost(MWContext *context) -{ - if (net_smtp_relay_host) - return net_smtp_relay_host; - else - return ""; /* caller now checks for empty string and returns MK_MSG_NO_SMTP_HOST */ -} - -PUBLIC void -NET_SetMailRelayHost(char * host) -{ - char * at = NULL; - - /* - ** If we are called with data like "fred@bedrock.com", then we will - ** help the user by ignoring the stuff before the "@". People with - ** @ signs in their host names will be hosed. They also can't possibly - ** be current happy internet users. - */ - if (host) at = XP_STRCHR(host, '@'); - if (at != NULL) host = at + 1; - StrAllocCopy(net_smtp_relay_host, host); -} - -/* - * gets user domian name out from FE_UsersMailAddress() - */ -PRIVATE const char * -net_smtp_get_user_domain_name() -{ - const char *mail_addr, *at_sign = NULL; - mail_addr = FE_UsersMailAddress(); - at_sign = XP_STRCHR(mail_addr, '@'); - return (at_sign ? at_sign+1 : mail_addr); -} - -/* RFC 1891 -- extended smtp value encoding scheme - - 5. Additional parameters for RCPT and MAIL commands - - The extended RCPT and MAIL commands are issued by a client when it wishes to request a DSN from the - server, under certain conditions, for a particular recipient. The extended RCPT and MAIL commands are - identical to the RCPT and MAIL commands defined in [1], except that one or more of the following parameters - appear after the sender or recipient address, respectively. The general syntax for extended SMTP commands is - defined in [4]. - - NOTE: Although RFC 822 ABNF is used to describe the syntax of these parameters, they are not, in the - language of that document, "structured field bodies". Therefore, while parentheses MAY appear within an - emstp-value, they are not recognized as comment delimiters. - - The syntax for "esmtp-value" in [4] does not allow SP, "=", control characters, or characters outside the - traditional ASCII range of 1- 127 decimal to be transmitted in an esmtp-value. Because the ENVID and - ORCPT parameters may need to convey values outside this range, the esmtp-values for these parameters are - encoded as "xtext". "xtext" is formally defined as follows: - - xtext = *( xchar / hexchar ) - - xchar = any ASCII CHAR between "!" (33) and "~" (126) inclusive, except for "+" and "=". - - ; "hexchar"s are intended to encode octets that cannot appear - ; as ASCII characters within an esmtp-value. - - hexchar = ASCII "+" immediately followed by two upper case hexadecimal digits - - When encoding an octet sequence as xtext: - - + Any ASCII CHAR between "!" and "~" inclusive, except for "+" and "=", - MAY be encoded as itself. (A CHAR in this range MAY instead be encoded as a "hexchar", at the - implementor's discretion.) - - + ASCII CHARs that fall outside the range above must be encoded as - "hexchar". - - */ -/* caller must free the return buffer */ -PRIVATE char * -esmtp_value_encode(char *addr) -{ - char *buffer = XP_ALLOC(512); /* esmpt ORCPT allow up to 500 chars encoded addresses */ - char *bp = buffer, *bpEnd = buffer+500; - int len, i; - - if (!buffer) return NULL; - - *bp=0; - if (! addr || *addr == 0) /* this will never happen */ - return buffer; - - for (i=0, len=XP_STRLEN(addr); i < len && bp < bpEnd; i++) - { - if (*addr >= 0x21 && - *addr <= 0x7E && - *addr != '+' && - *addr != '=') - { - *bp++ = *addr++; - } - else - { - PR_snprintf(bp, bpEnd-bp, "+%.2X", ((int)*addr++)); - bp += XP_STRLEN(bp); - } - } - *bp=0; - return buffer; -} - -/* - * gets the response code from the nntp server and the - * response line - * - * returns the TCP return code from the read - */ -PRIVATE int -net_smtp_response (ActiveEntry * cur_entry) -{ - char * line; - char cont_char; - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - int err = 0; - - CE_STATUS = NET_BufferedReadLine(CE_SOCK, &line, &CD_DATA_BUFFER, - &CD_DATA_BUFFER_SIZE, &CD_PAUSE_FOR_READ); - - if(CE_STATUS == 0) - { - CD_NEXT_STATE = SMTP_ERROR_DONE; - CD_PAUSE_FOR_READ = FALSE; - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_SMTP_SERVER_ERROR, - CD_RESPONSE_TXT); - CE_STATUS = MK_SMTP_SERVER_ERROR; - return(MK_SMTP_SERVER_ERROR); - } - - /* if TCP error of if there is not a full line yet return - */ - if(CE_STATUS < 0) - { - HG22864 - CE_URL_S->error_msg = - NET_ExplainErrorDetails(MK_TCP_READ_ERROR, SOCKET_ERRNO); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - else if(!line) - { - return CE_STATUS; - } - - TRACEMSG(("SMTP Rx: %s\n", line)); - - cont_char = ' '; /* default */ - sscanf(line, "%d%c", &CD_RESPONSE_CODE, &cont_char); - - if(CD_CONTINUATION_RESPONSE == -1) - { - if (cont_char == '-') /* begin continuation */ - CD_CONTINUATION_RESPONSE = CD_RESPONSE_CODE; - - if(XP_STRLEN(line) > 3) - StrAllocCopy(CD_RESPONSE_TXT, line+4); - } - else - { /* have to continue */ - if (CD_CONTINUATION_RESPONSE == CD_RESPONSE_CODE && cont_char == ' ') - CD_CONTINUATION_RESPONSE = -1; /* ended */ - - StrAllocCat(CD_RESPONSE_TXT, "\n"); - if(XP_STRLEN(line) > 3) - StrAllocCat(CD_RESPONSE_TXT, line+4); - } - - if(CD_CONTINUATION_RESPONSE == -1) /* all done with this response? */ - { - CD_NEXT_STATE = CD_NEXT_STATE_AFTER_RESPONSE; - CD_PAUSE_FOR_READ = FALSE; /* don't pause */ - } - - return(0); /* everything ok */ -} - -PRIVATE int -net_smtp_login_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[356]; - - if(CD_RESPONSE_CODE != 220) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_COULD_NOT_LOGIN_TO_SMTP_SERVER); - return(MK_COULD_NOT_LOGIN_TO_SMTP_SERVER); - } - - - PR_snprintf(buffer, sizeof(buffer), "HELO %.256s" CRLF, - net_smtp_get_user_domain_name()); - - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_HELO_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - - return(CE_STATUS); -} - - -PRIVATE int -net_smtp_extension_login_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[356]; - - if(CD_RESPONSE_CODE != 220) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_COULD_NOT_LOGIN_TO_SMTP_SERVER); - return(MK_COULD_NOT_LOGIN_TO_SMTP_SERVER); - } - - PR_snprintf(buffer, sizeof(buffer), "EHLO %.256s" CRLF, - net_smtp_get_user_domain_name()); - - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_EHLO_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - - return(CE_STATUS); -} - - -PRIVATE int -net_smtp_send_helo_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[620]; - const char *mail_add = FE_UsersMailAddress(); - - /* don't check for a HELO response because it can be bogus and - * we don't care - */ - - if(!mail_add) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_COULD_NOT_GET_USERS_MAIL_ADDRESS); - return(MK_COULD_NOT_GET_USERS_MAIL_ADDRESS); - } - - if(CD_VERIFY_ADDRESS) - { - PR_snprintf(buffer, sizeof(buffer), "VRFY %.256s" CRLF, CD_VERIFY_ADDRESS); - } - else - { - /* else send the MAIL FROM: command */ - char *s = MSG_MakeFullAddress (NULL, mail_add); - if (!s) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - if (CE_URL_S->msg_pane) { - if (MSG_RequestForReturnReceipt(CE_URL_S->msg_pane)) { - if (CD_EHLO_DSN_ENABLED) { - PR_snprintf(buffer, sizeof(buffer), - "MAIL FROM:<%.256s> RET=FULL ENVID=NS40112696JT" CRLF, - s); - } - else { - FE_Alert (CE_WINDOW_ID, XP_GetString(XP_RETURN_RECEIPT_NOT_SUPPORT)); - PR_snprintf(buffer, sizeof(buffer), "MAIL FROM:<%.256s>" CRLF, s); - } - } - else if (MSG_SendingMDNInProgress(CE_URL_S->msg_pane)) { - PR_snprintf(buffer, sizeof(buffer), "MAIL FROM:<%.256s>" CRLF, ""); - } - else { - PR_snprintf(buffer, sizeof(buffer), "MAIL FROM:<%.256s>" CRLF, s); - } - } - else { - PR_snprintf(buffer, sizeof(buffer), "MAIL FROM:<%.256s>" CRLF, s); - } - XP_FREE (s); - } - - TRACEMSG(("Tx: %s", buffer)); - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - - CD_NEXT_STATE = SMTP_RESPONSE; - - if(CD_VERIFY_ADDRESS) - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_VRFY_RESPONSE; - else - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_MAIL_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - - return(CE_STATUS); -} - - -PRIVATE int -net_smtp_send_ehlo_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - - if (CD_RESPONSE_CODE != 250) { - /* EHLO not implemented */ - char buffer[384]; - -HG85890 - - PR_snprintf(buffer, sizeof(buffer), "HELO %.256s" CRLF, - net_smtp_get_user_domain_name()); - - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_HELO_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - return (CE_STATUS); - } - else { - char *ptr = NULL; -HG09714 - - ptr = strcasestr(CD_RESPONSE_TXT, "DSN"); - CD_EHLO_DSN_ENABLED = (ptr && XP_TO_UPPER(*(ptr-1)) != 'X'); - /* should we use auth login */ - PREF_GetBoolPref("mail.auth_login", &(CD_AUTH_LOGIN_ENABLED)); - if (CD_AUTH_LOGIN_ENABLED) { - /* okay user has set to use skey - let's see does the server have the capability */ - CD_AUTH_LOGIN_ENABLED = (NULL != strcasestr(CD_RESPONSE_TXT, "AUTH LOGIN")); - if (!CD_AUTH_LOGIN_ENABLED) - CD_AUTH_LOGIN_ENABLED = (NULL != strcasestr(CD_RESPONSE_TXT, "AUTH=LOGIN")); /* check old style */ - } - - HG90967 - - CD_NEXT_STATE = CD_NEXT_STATE_AFTER_RESPONSE = SMTP_AUTH_RESPONSE; - - HG59852 - return (CE_STATUS); - } -} - - -PRIVATE int -net_smtp_auth_login_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - - switch (CD_RESPONSE_CODE/100) { - case 2: - { -#ifdef MOZ_MAIL_NEWS - char *pop_password = (char *)NET_GetPopPassword(); - CD_NEXT_STATE = SMTP_SEND_HELO_RESPONSE; - if (pop_password == NULL) - NET_SetPopPassword2(net_smtp_password); - if ( IMAP_GetPassword() == NULL ) - IMAP_SetPassword(net_smtp_password); - XP_FREEIF(pop_password); -#else /* MOZ_MAIL_NEWS */ - XP_ASSERT(0); -#endif /* MOZ_MAIL_NEWS */ - } - break; - case 3: - CD_NEXT_STATE = SMTP_SEND_AUTH_LOGIN_PASSWORD; - break; - case 5: - default: - { - char* pop_username = (char *) NET_GetPopUsername(); -#if defined(SingleSignon) - char *username = 0; - char host[256]; - int len = 256; -#endif - /* NET_GetPopUsername () returns pointer to the cached - * username. It did *NOT* alloc a new string - */ - XP_FREEIF(net_smtp_password); -#if defined(SingleSignon) - /* - * need to alloc a new string for username because call to - * SI_PromptUsernameAndPassword below will attempt to free - * it if it is not null - */ - StrAllocCopy(username, pop_username); /* alloc a new string */ - PREF_GetCharPref("network.hosts.smtp_server", host, &len); - SI_RemoveUser(host, pop_username, TRUE); - /* prefill prompt with previous username/passwords if any */ - if (SI_PromptUsernameAndPassword - (cur_entry->window_id, " ", - &username, &net_smtp_password, host)) { -#else - if (FE_PromptUsernameAndPassword(cur_entry->window_id, - NULL, &pop_username, &net_smtp_password)) { -#endif - CD_NEXT_STATE = SMTP_SEND_AUTH_LOGIN_USERNAME; -#if defined(SingleSignon) - XP_FREEIF(username); -#else - /* FE_PromptUsernameAndPassword() always alloc a new string - * for pop_username. The caller has to free it. - */ - XP_FREEIF(pop_username); -#endif - } - else { - /* User hit cancel, but since the client and server both say - * they want auth login we're just going to return an error - * and not let the msg be sent to the server - */ - CE_STATUS = MK_POP3_PASSWORD_UNDEFINED; - } - } - break; - } - - return (CE_STATUS); -} - -PRIVATE int -net_smtp_auth_login_username(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[512]; - char *pop_username = (char *) NET_GetPopUsername(); - char *base64Str = NULL; - - if (!pop_username || !*pop_username) - return (MK_POP3_USERNAME_UNDEFINED); - -#ifdef MOZ_MAIL_NEWS - base64Str = NET_Base64Encode(pop_username, - XP_STRLEN(pop_username)); - if (base64Str) { - PR_snprintf(buffer, sizeof(buffer), "AUTH LOGIN %.256s" CRLF, base64Str); - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_AUTH_LOGIN_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - XP_FREEIF(base64Str); - - return (CE_STATUS); - } -#endif /* MOZ_MAIL_NEWS */ - - return -1; -} - -PRIVATE int -net_smtp_auth_login_password(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[1024]; - - /* use cached smtp password first - * if not then use cached pop password - * if pop password undefined - * sync with smtp password - */ - - if (!net_smtp_password || !*net_smtp_password) { - XP_FREEIF(net_smtp_password); /* in case its an empty string */ -#ifdef MOZ_MAIL_NEWS - net_smtp_password = (char *) NET_GetPopPassword(); -#endif /* MOZ_MAIL_NEWS */ - } - - if (!net_smtp_password || !*net_smtp_password) { - char *fmt = XP_GetString (XP_PASSWORD_FOR_POP3_USER); - char host[256]; - int len = 256; -#if defined(SingleSignon) - char *usernameAndHost=0; -#endif - - XP_MEMSET(host, 0, 256); - PREF_GetCharPref("network.hosts.smtp_server", host, &len); - - PR_snprintf(buffer, sizeof (buffer), - fmt, NET_GetPopUsername(), host); - XP_FREEIF(net_smtp_password); -#if defined(SingleSignon) - StrAllocCopy(usernameAndHost, NET_GetPopUsername()); - StrAllocCat(usernameAndHost, "@"); - StrAllocCat(usernameAndHost, host); - - net_smtp_password = SI_PromptPassword(cur_entry->window_id, buffer, - usernameAndHost, FALSE); - XP_FREE(usernameAndHost); -#else - net_smtp_password = FE_PromptPassword(cur_entry->window_id, buffer); -#endif - if (!net_smtp_password) - return MK_POP3_PASSWORD_UNDEFINED; - } - - XP_ASSERT(net_smtp_password); - - if (net_smtp_password) { - char *base64Str = NULL; - -#ifdef MOZ_MAIL_NEWS - base64Str = NET_Base64Encode(net_smtp_password, XP_STRLEN(net_smtp_password)); -#endif /* MOZ_MAIL_NEWS */ - - if (base64Str) { - PR_snprintf(buffer, sizeof(buffer), "%.256s" CRLF, base64Str); - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_AUTH_LOGIN_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - XP_FREEIF(base64Str); - - return (CE_STATUS); - } - } - - return -1; -} - -PRIVATE int -net_smtp_send_vrfy_response(ActiveEntry *cur_entry) -{ -#if 0 - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[512]; - - if(CD_RESPONSE_CODE == 250 || CD_RESPONSE_CODE == 251) - return(MK_USER_VERIFIED_BY_SMTP); - else - return(MK_USER_NOT_VERIFIED_BY_SMTP); -#else - XP_ASSERT(0); - return(-1); -#endif -} - -PRIVATE int -net_smtp_send_mail_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[1024]; - - if(CD_RESPONSE_CODE != 250) - { - CE_URL_S->error_msg = - NET_ExplainErrorDetails(MK_ERROR_SENDING_FROM_COMMAND, - CD_RESPONSE_TXT); - return(MK_ERROR_SENDING_FROM_COMMAND); - } - - /* Send the RCPT TO: command */ - if (CD_EHLO_DSN_ENABLED && - (CE_URL_S->msg_pane && - MSG_RequestForReturnReceipt(CE_URL_S->msg_pane))) - { - char *encodedAddress = esmtp_value_encode(CD_MAIL_TO_ADDRESS_PTR); - - if (encodedAddress) { - PR_snprintf(buffer, sizeof(buffer), - "RCPT TO:<%.256s> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;%.500s" CRLF, - CD_MAIL_TO_ADDRESS_PTR, encodedAddress); - XP_FREEIF(encodedAddress); - } - else { - CE_STATUS = MK_OUT_OF_MEMORY; - return (CE_STATUS); - } - } - else - { - PR_snprintf(buffer, sizeof(buffer), "RCPT TO:<%.256s>" CRLF, CD_MAIL_TO_ADDRESS_PTR); - } - /* take the address we sent off the list (move the pointer to just - past the terminating null.) */ - CD_MAIL_TO_ADDRESS_PTR += XP_STRLEN (CD_MAIL_TO_ADDRESS_PTR) + 1; - CD_MAIL_TO_ADDRESSES_LEFT--; - - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_RCPT_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - - return(CE_STATUS); -} - -PRIVATE int -net_smtp_send_rcpt_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char buffer[16]; - - if(CD_RESPONSE_CODE != 250 && CD_RESPONSE_CODE != 251) - { - CE_URL_S->error_msg = - NET_ExplainErrorDetails(MK_ERROR_SENDING_RCPT_COMMAND, - CD_RESPONSE_TXT); - return(MK_ERROR_SENDING_RCPT_COMMAND); - } - - if(CD_MAIL_TO_ADDRESSES_LEFT > 0) - { - /* more senders to RCPT to - */ - CD_NEXT_STATE = SMTP_SEND_MAIL_RESPONSE; - return(0); - } - - /* else send the RCPT TO: command */ - XP_STRCPY(buffer, "DATA" CRLF); - - TRACEMSG(("Tx: %s", buffer)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, buffer, XP_STRLEN(buffer)); - - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_DATA_RESPONSE; - CD_PAUSE_FOR_READ = TRUE; - - return(CE_STATUS); -} - -PRIVATE int -net_smtp_send_data_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char * command=0; - - if(CD_RESPONSE_CODE != 354) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails( - MK_ERROR_SENDING_DATA_COMMAND, - CD_RESPONSE_TXT ? CD_RESPONSE_TXT : ""); - return(MK_ERROR_SENDING_DATA_COMMAND); - } - -#ifdef XP_UNIX - { - const char * FE_UsersRealMailAddress(void); /* definition */ - const char *real_name; - char *s = 0; - XP_Bool suppress_sender_header = FALSE; - - PREF_GetBoolPref ("mail.suppress_sender_header", &suppress_sender_header); - if (!suppress_sender_header) - { - real_name = FE_UsersRealMailAddress(); - s = (real_name ? MSG_MakeFullAddress (NULL, real_name) : 0); - if (real_name && !s) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - if(real_name) - { - char buffer[512]; - PR_snprintf(buffer, sizeof(buffer), "Sender: %.256s" CRLF, real_name); - StrAllocCat(command, buffer); - if(!command) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return(MK_OUT_OF_MEMORY); - } - } - - TRACEMSG(("sending extra unix header: %s", command)); - - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, command, XP_STRLEN(command)); - if(CE_STATUS < 0) - { - TRACEMSG(("Error sending message")); - } - } - } -#endif /* XP_UNIX */ - - /* set connect select since we need to select on - * writes - */ - NET_ClearReadSelect(CE_WINDOW_ID, CE_SOCK); - NET_SetConnectSelect(CE_WINDOW_ID, CE_SOCK); -#ifdef XP_WIN - cd->calling_netlib_all_the_time = TRUE; - NET_SetCallNetlibAllTheTime(CE_WINDOW_ID, "mksmtp"); -#endif - CE_CON_SOCK = CE_SOCK; - - FREE(command); - - CD_NEXT_STATE = SMTP_SEND_POST_DATA; - CD_PAUSE_FOR_READ = FALSE; /* send data directly */ - - NET_Progress(CE_WINDOW_ID, XP_GetString(MK_MSG_DELIV_MAIL)); - - /* get the size of the message */ - if(CE_URL_S->post_data_is_file) - { - XP_StatStruct stat_entry; - - if(-1 != XP_Stat(CE_URL_S->post_data, - &stat_entry, - xpFileToPost)) - CD_TOTAL_MESSAGE_SIZE = stat_entry.st_size; - } - else - { - CD_TOTAL_MESSAGE_SIZE = CE_URL_S->post_data_size; - } - - - return(CE_STATUS); -} - -PRIVATE int -net_smtp_send_post_data(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - unsigned long curtime; - - /* returns 0 on done and negative on error - * positive if it needs to continue. - */ - CE_STATUS = NET_WritePostData(CE_WINDOW_ID, CE_URL_S, - CE_SOCK, - &cd->write_post_data_data, - TRUE); - - cd->pause_for_read = TRUE; - - if(CE_STATUS == 0) - { - /* normal done - */ - XP_STRCPY(cd->data_buffer, CRLF "." CRLF); - TRACEMSG(("sending %s", cd->data_buffer)); - CE_STATUS = (int) NET_BlockingWrite(CE_SOCK, - cd->data_buffer, - XP_STRLEN(cd->data_buffer)); - - NET_Progress(CE_WINDOW_ID, - XP_GetString(XP_MESSAGE_SENT_WAITING_MAIL_REPLY)); - - NET_ClearConnectSelect(CE_WINDOW_ID, CE_SOCK); -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - { - cd->calling_netlib_all_the_time = FALSE; - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mksmtp"); - } -#endif - NET_SetReadSelect(CE_WINDOW_ID, CE_SOCK); - CE_CON_SOCK = 0; - - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_SEND_MESSAGE_RESPONSE; - return(0); - } - - CD_TOTAL_AMT_WRITTEN += CE_STATUS; - - /* Update the thermo and the status bar. This is done by hand, rather - than using the FE_GraphProgress* functions, because there seems to be - no way to make FE_GraphProgress shut up and not display anything more - when all the data has arrived. At the end, we want to show the - "message sent; waiting for reply" status; FE_GraphProgress gets in - the way of that. See bug #23414. */ - - curtime = XP_TIME(); - if (curtime != cd->last_time) { - FE_Progress(CE_WINDOW_ID, XP_ProgressText(CD_TOTAL_MESSAGE_SIZE, - CD_TOTAL_AMT_WRITTEN, - 0, 0)); - cd->last_time = curtime; - } - - if(CD_TOTAL_MESSAGE_SIZE) - FE_SetProgressBarPercent(CE_WINDOW_ID, - CD_TOTAL_AMT_WRITTEN*100/CD_TOTAL_MESSAGE_SIZE); - - return(CE_STATUS); -} - - - -PRIVATE int -net_smtp_send_message_response(ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - - if(CD_RESPONSE_CODE != 250) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_ERROR_SENDING_MESSAGE, - CD_RESPONSE_TXT); - return(MK_ERROR_SENDING_MESSAGE); - } - - NET_Progress(CE_WINDOW_ID, XP_GetString(XP_PROGRESS_MAILSENT)); - - /* else */ - CD_NEXT_STATE = SMTP_DONE; - return(MK_NO_DATA); -} - - -PRIVATE int32 -net_MailtoLoad (ActiveEntry * cur_entry) -{ - /* get memory for Connection Data */ - SMTPConData * cd = XP_NEW(SMTPConData); - int32 pref = 0; - - cur_entry->con_data = cd; - if(!cur_entry->con_data) - { - CE_URL_S->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - CE_STATUS = MK_OUT_OF_MEMORY; - return (CE_STATUS); - } - -/* GH_UpdateGlobalHistory(cur_entry->URL_s); */ - - /* init */ - XP_MEMSET(cd, 0, sizeof(SMTPConData)); - - CD_CONTINUATION_RESPONSE = -1; /* init */ - - CE_SOCK = NULL; -HG61365 - - - /* make a copy of the address - */ - if(CE_URL_S->method == URL_POST_METHOD) - { - int status=0; - char *addrs1 = 0; - char *addrs2 = 0; - CD_NEXT_STATE = SMTP_START_CONNECT; - - /* Remove duplicates from the list, to prevent people from getting - more than one copy (the SMTP host may do this too, or it may not.) - This causes the address list to be parsed twice; this probably - doesn't matter. - */ - addrs1 = MSG_RemoveDuplicateAddresses (CE_URL_S->address+7, 0, FALSE /*removeAliasesToMe*/); - - /* Extract just the mailboxes from the full RFC822 address list. - This means that people can post to mailto: URLs which contain - full RFC822 address specs, and we will still send the right - thing in the SMTP RCPT command. - */ - if (addrs1 && *addrs1) - { - status = MSG_ParseRFC822Addresses (addrs1, 0, &addrs2); - FREEIF (addrs1); - } - - if (status < 0) return status; - - if (status == 0 || addrs2 == 0) - { - CD_NEXT_STATE = SMTP_ERROR_DONE; - CD_PAUSE_FOR_READ = FALSE; - CE_STATUS = MK_MIME_NO_RECIPIENTS; - CE_URL_S->error_msg = NET_ExplainErrorDetails(CE_STATUS); - return CE_STATUS; - } - - CD_ADDRESS_COPY = addrs2; - CD_MAIL_TO_ADDRESS_PTR = CD_ADDRESS_COPY; - CD_MAIL_TO_ADDRESSES_LEFT = status; - return(net_ProcessMailto(cur_entry)); - } - else - { - /* parse special headers and stuff from the search data in the - URL address. This data is of the form - - mailto:TO_FIELD?FIELD1=VALUE1&FIELD2=VALUE2 - - where TO_FIELD may be empty, VALUEn may (for now) only be - one of "cc", "bcc", "subject", "newsgroups", "references", - and "attachment". - - "to" is allowed as a field/value pair as well, for consistency. - - One additional parameter is allowed, which does not correspond - to a visible field: "newshost". This is the NNTP host (and port) - to connect to if newsgroups are specified. - - Each parameter may appear only once, but the order doesn't - matter. All values must be URL-encoded. - */ - HG27655 - - char *parms = NET_ParseURL (CE_URL_S->address, GET_SEARCH_PART); - char *rest = parms; - char *from = 0; /* internal only */ - char *reply_to = 0; /* internal only */ - char *to = 0; - char *cc = 0; - char *bcc = 0; - char *fcc = 0; /* internal only */ - char *newsgroups = 0; - char *followup_to = 0; - char *html_part = 0; /* internal only */ - char *organization = 0; /* internal only */ - char *subject = 0; - char *references = 0; - char *attachment = 0; /* internal only */ - char *body = 0; - char *other_random_headers = 0; /* unused (for now) */ - char *priority = 0; - char *newshost = 0; /* internal only */ - XP_Bool encrypt_p = FALSE; - XP_Bool sign_p = FALSE; /* internal only */ - - char *newspost_url = 0; - XP_Bool force_plain_text = FALSE; - MSG_Pane *cpane = 0; - - to = NET_ParseURL (CE_URL_S->address, GET_PATH_PART); - - if (rest && *rest == '?') - { - /* start past the '?' */ - rest++; - rest = XP_STRTOK (rest, "&"); - while (rest && *rest) - { - char *token = rest; - char *value = 0; - char *eq = XP_STRCHR (token, '='); - if (eq) - { - value = eq+1; - *eq = 0; - } - switch (*token) - { - case 'A': case 'a': - if (!strcasecomp (token, "attachment") && - CE_URL_S->internal_url) - StrAllocCopy (attachment, value); - break; - case 'B': case 'b': - if (!strcasecomp (token, "bcc")) - { - if (bcc && *bcc) - { - StrAllocCat (bcc, ", "); - StrAllocCat (bcc, value); - } - else - { - StrAllocCopy (bcc, value); - } - } - else if (!strcasecomp (token, "body")) - { - if (body && *body) - { - StrAllocCat (body, "\n"); - StrAllocCat (body, value); - } - else - { - StrAllocCopy (body, value); - } - } - break; - case 'C': case 'c': - if (!strcasecomp (token, "cc")) - { - if (cc && *cc) - { - StrAllocCat (cc, ", "); - StrAllocCat (cc, value); - } - else - { - StrAllocCopy (cc, value); - } - } - break; - case 'E': case 'e': - if (!strcasecomp (token, "encrypt") || - !strcasecomp (token, "encrypted")) - encrypt_p = (!strcasecomp(value, "true") || - !strcasecomp(value, "yes")); - break; - case 'F': case 'f': - if (!strcasecomp (token, "followup-to")) - StrAllocCopy (followup_to, value); - else if (!strcasecomp (token, "from") && - CE_URL_S->internal_url) - StrAllocCopy (from, value); - else if (!strcasecomp (token, "force-plain-text") && - CE_URL_S->internal_url) - force_plain_text = TRUE; - break; - case 'H': case 'h': - if (!strcasecomp(token, "html-part") && - CE_URL_S->internal_url) { - StrAllocCopy(html_part, value); - } - case 'N': case 'n': - if (!strcasecomp (token, "newsgroups")) - StrAllocCopy (newsgroups, value); - else if (!strcasecomp (token, "newshost") && - CE_URL_S->internal_url) - StrAllocCopy (newshost, value); - break; - case 'O': case 'o': - if (!strcasecomp (token, "organization") && - CE_URL_S->internal_url) - StrAllocCopy (organization, value); - break; - case 'R': case 'r': - if (!strcasecomp (token, "references")) - StrAllocCopy (references, value); - else if (!strcasecomp (token, "reply-to") && - CE_URL_S->internal_url) - StrAllocCopy (reply_to, value); - break; - case 'S': case 's': - if(!strcasecomp (token, "subject")) - StrAllocCopy (subject, value); - else if ((!strcasecomp (token, "sign") || - !strcasecomp (token, "signed")) && - CE_URL_S->internal_url) - sign_p = (!strcasecomp(value, "true") || - !strcasecomp(value, "yes")); - break; - case 'P': case 'p': - if (!strcasecomp (token, "priority")) - StrAllocCopy (priority, value); - break; - case 'T': case 't': - if (!strcasecomp (token, "to")) - { - if (to && *to) - { - StrAllocCat (to, ", "); - StrAllocCat (to, value); - } - else - { - StrAllocCopy (to, value); - } - } - break; - } - if (eq) - *eq = '='; /* put it back */ - rest = XP_STRTOK (0, "&"); - } - } - - FREEIF (parms); - if (to) - NET_UnEscape (to); - if (cc) - NET_UnEscape (cc); - if (subject) - NET_UnEscape (subject); - if (newsgroups) - NET_UnEscape (newsgroups); - if (references) - NET_UnEscape (references); - if (attachment) - NET_UnEscape (attachment); - if (body) - NET_UnEscape (body); - if (newshost) - NET_UnEscape (newshost); - - if(newshost) - { - char *prefix = "news://"; - char *slash = XP_STRRCHR (newshost, '/'); - HG83763 - newspost_url = (char *) XP_ALLOC (XP_STRLEN (prefix) + - XP_STRLEN (newshost) + 10); - if (newspost_url) - { - XP_STRCPY (newspost_url, prefix); - XP_STRCAT (newspost_url, newshost); - XP_STRCAT (newspost_url, "/"); - } - } - else - { - HG35353 - newspost_url = XP_STRDUP ("news:"); - } - - /* Tell the message library and front end to pop up an edit window. - */ -#ifdef XP_UNIX - cpane = MSG_ComposeMessage (CE_WINDOW_ID, - from, reply_to, to, cc, bcc, fcc, - newsgroups, followup_to, organization, - subject, references, other_random_headers, - priority, attachment, newspost_url, body, - force_plain_text, - html_part); -#endif //XP_UNIX - -#ifdef MOZ_MAIL_NEWS - if (cpane && CE_URL_S->fe_data) { - /* Tell libmsg what to do after deliver the message */ - MSG_SetPostDeliveryActionInfo (cpane, CE_URL_S->fe_data); - } -#endif /* MOZ_MAIL_NEWS */ - - FREEIF(from); - FREEIF(reply_to); - FREEIF(to); - FREEIF(cc); - FREEIF(bcc); - FREEIF(fcc); - FREEIF(newsgroups); - FREEIF(followup_to); - FREEIF(html_part); - FREEIF(organization); - FREEIF(subject); - FREEIF(references); - FREEIF(attachment); - FREEIF(body); - FREEIF(other_random_headers); - FREEIF(newshost); - FREEIF(priority); - FREEIF(newspost_url); - - CE_STATUS = MK_NO_DATA; - XP_FREE(cd); /* no one else is gonna do it! */ - return(-1); - } -} - - - - -/* - We have connected to the mail relay and the type of authorization/login required - has been established. Before we actually send our name and password check - and see if we should or must turn the connection to safer mode. -*/ - -PRIVATE int -NET_CheckAuthResponse (ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - int err = 0; - HG54978 - - if (CD_AUTH_LOGIN_ENABLED) - { - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_AUTH_LOGIN_RESPONSE; - CD_NEXT_STATE = SMTP_SEND_AUTH_LOGIN_USERNAME; - return (CE_STATUS); - } - CD_NEXT_STATE = SMTP_SEND_HELO_RESPONSE; - return (CE_STATUS); -} - - - - -/* - * returns negative if the transfer is finished or error'd out - * - * returns zero or more if the transfer needs to be continued. - */ -PRIVATE int32 -net_ProcessMailto (ActiveEntry *cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - char *mail_relay_host; - - TRACEMSG(("Entering NET_ProcessSMTP")); - - CD_PAUSE_FOR_READ = FALSE; /* already paused; reset */ - - while(!CD_PAUSE_FOR_READ) - { - - TRACEMSG(("In NET_ProcessSMTP with state: %d", CD_NEXT_STATE)); - - switch(CD_NEXT_STATE) { - - case SMTP_RESPONSE: - net_smtp_response (cur_entry); - break; - - case SMTP_START_CONNECT: - mail_relay_host = NET_MailRelayHost(CE_WINDOW_ID); - if (XP_STRLEN(mail_relay_host) == 0) - { - CE_STATUS = MK_MSG_NO_SMTP_HOST; - break; - } - CE_STATUS = NET_BeginConnect(NET_MailRelayHost(CE_WINDOW_ID), - NULL, - "SMTP", - SMTP_PORT, - &CE_SOCK, - FALSE, - &CD_TCP_CON_DATA, - CE_WINDOW_ID, - &CE_URL_S->error_msg, - cur_entry->socks_host, - cur_entry->socks_port, - CE_URL_S->localIP); - CD_PAUSE_FOR_READ = TRUE; - if(CE_STATUS == MK_CONNECTED) - { - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_EXTN_LOGIN_RESPONSE; - NET_SetReadSelect(CE_WINDOW_ID, CE_SOCK); - } - else if(CE_STATUS > -1) - { - CE_CON_SOCK = CE_SOCK; /* set con_sock so we can select on it */ - NET_SetConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - CD_NEXT_STATE = SMTP_FINISH_CONNECT; - } - break; - - case SMTP_FINISH_CONNECT: - CE_STATUS = NET_FinishConnect(NET_MailRelayHost(CE_WINDOW_ID), - "SMTP", - SMTP_PORT, - &CE_SOCK, - &CD_TCP_CON_DATA, - CE_WINDOW_ID, - &CE_URL_S->error_msg, - CE_URL_S->localIP); - - CD_PAUSE_FOR_READ = TRUE; -HG18931 - if(CE_STATUS == MK_CONNECTED) - { - CD_NEXT_STATE = SMTP_RESPONSE; - CD_NEXT_STATE_AFTER_RESPONSE = SMTP_EXTN_LOGIN_RESPONSE; - NET_ClearConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - CE_CON_SOCK = NULL; /* reset con_sock so we don't select on it */ - NET_SetReadSelect(CE_WINDOW_ID, CE_SOCK); - } - else - { - /* unregister the old CE_SOCK from the select list - * and register the new value in the case that it changes - */ - if(CE_CON_SOCK != CE_SOCK) - { - NET_ClearConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - CE_CON_SOCK = CE_SOCK; - NET_SetConnectSelect(CE_WINDOW_ID, CE_CON_SOCK); - } - } - break; - - case SMTP_AUTH_RESPONSE: - CE_STATUS = NET_CheckAuthResponse(cur_entry); - break; - - case SMTP_LOGIN_RESPONSE: - CE_STATUS = net_smtp_login_response(cur_entry); - break; - - case SMTP_EXTN_LOGIN_RESPONSE: - CE_STATUS = net_smtp_extension_login_response(cur_entry); - break; - - case SMTP_SEND_HELO_RESPONSE: - CE_STATUS = net_smtp_send_helo_response(cur_entry); - break; - - case SMTP_SEND_EHLO_RESPONSE: - CE_STATUS = net_smtp_send_ehlo_response(cur_entry); - break; - - case SMTP_AUTH_LOGIN_RESPONSE: - CE_STATUS = net_smtp_auth_login_response(cur_entry); - break; - - case SMTP_SEND_AUTH_LOGIN_USERNAME: - CE_STATUS = net_smtp_auth_login_username(cur_entry); - break; - - case SMTP_SEND_AUTH_LOGIN_PASSWORD: - CE_STATUS = net_smtp_auth_login_password(cur_entry); - break; - - case SMTP_SEND_VRFY_RESPONSE: - CE_STATUS = net_smtp_send_vrfy_response(cur_entry); - break; - - case SMTP_SEND_MAIL_RESPONSE: - CE_STATUS = net_smtp_send_mail_response(cur_entry); - break; - - case SMTP_SEND_RCPT_RESPONSE: - CE_STATUS = net_smtp_send_rcpt_response(cur_entry); - break; - - case SMTP_SEND_DATA_RESPONSE: - CE_STATUS = net_smtp_send_data_response(cur_entry); - break; - - case SMTP_SEND_POST_DATA: - CE_STATUS = net_smtp_send_post_data(cur_entry); - break; - - case SMTP_SEND_MESSAGE_RESPONSE: - CE_STATUS = net_smtp_send_message_response(cur_entry); - break; - - case SMTP_DONE: - NET_BlockingWrite(CE_SOCK, "QUIT", 4); - NET_ClearReadSelect(CE_WINDOW_ID, CE_SOCK); - PR_Close(CE_SOCK); - CD_NEXT_STATE = SMTP_FREE; - break; - - case SMTP_ERROR_DONE: - if(CE_SOCK != NULL) - { - /* we only send out quit if user interrupt - * else must be server error which may not be - * able to blocking write command - */ - if (CE_STATUS == MK_INTERRUPTED) - NET_BlockingWrite(CE_SOCK, "QUIT", 4); - NET_ClearReadSelect(CE_WINDOW_ID, CE_SOCK); - NET_ClearConnectSelect(CE_WINDOW_ID, CE_SOCK); -#ifdef XP_WIN - if(cd->calling_netlib_all_the_time) - { - cd->calling_netlib_all_the_time = FALSE; - NET_ClearCallNetlibAllTheTime(CE_WINDOW_ID, "mksmtp"); - } -#endif /* XP_WIN */ - NET_ClearDNSSelect(CE_WINDOW_ID, CE_SOCK); - PR_Close(CE_SOCK); - } - CD_NEXT_STATE = SMTP_FREE; - break; - - case SMTP_FREE: - FREEIF(CD_DATA_BUFFER); - FREEIF(CD_ADDRESS_COPY); - FREEIF(CD_RESPONSE_TXT); - if(CD_TCP_CON_DATA) - NET_FreeTCPConData(CD_TCP_CON_DATA); - if (cd->write_post_data_data) - NET_free_write_post_data_object((struct WritePostDataData *) - cd->write_post_data_data); - FREE(cd); - - return(-1); /* final end */ - - default: /* should never happen !!! */ - TRACEMSG(("SMTP: BAD STATE!")); - CD_NEXT_STATE = SMTP_ERROR_DONE; - break; - } - - /* check for errors during load and call error - * state if found - */ - if(CE_STATUS < 0 && CD_NEXT_STATE != SMTP_FREE) - { - CD_NEXT_STATE = SMTP_ERROR_DONE; - /* don't exit! loop around again and do the free case */ - CD_PAUSE_FOR_READ = FALSE; - } - } /* while(!CD_PAUSE_FOR_READ) */ - - return(CE_STATUS); -} - -/* abort the connection in progress - */ -PRIVATE int32 -net_InterruptMailto(ActiveEntry * cur_entry) -{ - SMTPConData * cd = (SMTPConData *)cur_entry->con_data; - - CD_NEXT_STATE = SMTP_ERROR_DONE; - CE_STATUS = MK_INTERRUPTED; - - return(net_ProcessMailto(cur_entry)); -} - -/* Free any memory that might be used in caching etc. - */ -PRIVATE void -net_CleanupMailto(void) -{ - /* nothing so far needs freeing */ - return; -} - -MODULE_PRIVATE void -NET_InitMailtoProtocol(void) -{ - static NET_ProtoImpl mailto_proto_impl; - - mailto_proto_impl.init = net_MailtoLoad; - mailto_proto_impl.process = net_ProcessMailto; - mailto_proto_impl.interrupt = net_InterruptMailto; - mailto_proto_impl.resume = NULL; - mailto_proto_impl.cleanup = net_CleanupMailto; - - NET_RegisterProtocolImplementation(&mailto_proto_impl, MAILTO_TYPE_URL); -} - -#endif /* defined(MOZ_MAIL_NEWS) || defined(MOZ_MAIL_COMPOSE) */ - -static void -MessageSendingDone(URL_Struct* url, int status, MWContext* context) -{ - if (status < 0) { - char *error_msg = NET_ExplainErrorDetails(status, 0, 0, 0, 0); - if (error_msg) { - FE_Alert(context, error_msg); - } - XP_FREEIF(error_msg); - } - if (url->post_data) { - XP_FREE(url->post_data); - url->post_data = NULL; - } - if (url->post_headers) { - XP_FREE(url->post_headers); - url->post_headers = NULL; - } - NET_FreeURLStruct(url); -} - - - -int -NET_SendMessageUnattended(MWContext* context, char* to, char* subject, - char* otherheaders, char* body) -{ - char* urlstring; - URL_Struct* url; - int16 win_csid; - int16 csid; - char* convto; - char* convsub; - - win_csid = INTL_DefaultWinCharSetID(context); - csid = INTL_DefaultMailCharSetID(win_csid); - convto = IntlEncodeMimePartIIStr(to, csid, TRUE); - convsub = IntlEncodeMimePartIIStr(subject, csid, TRUE); - - urlstring = PR_smprintf("mailto:%s", convto ? convto : to); - - if (!urlstring) return MK_OUT_OF_MEMORY; - url = NET_CreateURLStruct(urlstring, NET_DONT_RELOAD); - XP_FREE(urlstring); - if (!url) return MK_OUT_OF_MEMORY; - - - - url->post_headers = PR_smprintf("To: %s\n\ -Subject: %s\n\ -%s\n", - convto ? convto : to, - convsub ? convsub : subject, - otherheaders); - if (convto) XP_FREE(convto); - if (convsub) XP_FREE(convsub); - if (!url->post_headers) return MK_OUT_OF_MEMORY; - url->post_data = XP_STRDUP(body); - if (!url->post_data) return MK_OUT_OF_MEMORY; - url->post_data_size = XP_STRLEN(url->post_data); - url->post_data_is_file = FALSE; - url->method = URL_POST_METHOD; - url->internal_url = TRUE; - return NET_GetURL(url, FO_PRESENT, context, MessageSendingDone); - -} - -#if !defined(MOZ_MAIL_NEWS) && !defined(SMART_MAIL) -PUBLIC const char* -NET_GetPopUsername () -{ - return 0; -} -#endif /* MOZ_MAIL_NEWS */ - - -#endif /* defined(MOZILLA_CLIENT) || defined(LIBNET_SMTP) */ diff --git a/mozilla/network/protocol/smtp/mksmtp.h b/mozilla/network/protocol/smtp/mksmtp.h deleted file mode 100644 index fa328f08b0a..00000000000 --- a/mozilla/network/protocol/smtp/mksmtp.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -#ifndef MKSMTP_H -#define MKSMTP_H - -extern void NET_InitMailtoProtocol(void); - -#endif /* MKSMTP_H */ diff --git a/mozilla/network/protocol/sockstub/MANIFEST b/mozilla/network/protocol/sockstub/MANIFEST deleted file mode 100644 index 0718d0d282a..00000000000 --- a/mozilla/network/protocol/sockstub/MANIFEST +++ /dev/null @@ -1,5 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - -sockstub.h diff --git a/mozilla/network/protocol/sockstub/Makefile.in b/mozilla/network/protocol/sockstub/Makefile.in deleted file mode 100644 index 6c708f858f9..00000000000 --- a/mozilla/network/protocol/sockstub/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = sockstuburl -LIBRARY_NAME = sockstuburl - -REQUIRES = raptor js dbm nspr security pref xpcom util img layer network netcache fileurl ftpurl abouturl httpurl gophurl remoturl netcnvts netlib progress - -CPPSRCS = sockstub.cpp - -EXPORTS = $(srcdir)/sockstub.h - -include $(topsrcdir)/config/rules.mk - -DEFINES += -D_IMPL_NS_NET - diff --git a/mozilla/network/protocol/sockstub/makefile.win b/mozilla/network/protocol/sockstub/makefile.win deleted file mode 100644 index 736f91ad401..00000000000 --- a/mozilla/network/protocol/sockstub/makefile.win +++ /dev/null @@ -1,92 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network file protocol LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -CPP_OBJS= \ - .\$(OBJDIR)\sockstub.obj \ - $(NULL) - -CPPSRCS = \ - sockstub.cpp \ - $(NULL) - - -LIBRARY_NAME=sockstub -MODULE=sockstub -DEPTH=..\..\.. - -LOCAL_INCLUDES=-I. -I$(DEPTH)/dist/public/zlib -I$(DEPTH)/dist/public/parse -INCLUDES = $(LOCAL_INCLUDES) - - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= sockstub.h - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\nspr2 \ - -I$(PUBLIC)\util \ - -I$(PUBLIC)\java \ - -I$(PUBLIC)\pref \ - -I$(PUBLIC)\raptor \ - -I$(PUBLIC)\htmldlgs \ - -I$(PUBLIC)\js \ - -I$(PUBLIC)\security \ - -I$(PUBLIC)\netcache \ - -I$(PUBLIC)\network \ - -I$(PUBLIC)\mimetype \ -!ifdef MOZ_SMOOTH_PROGRESS - -I$(PUBLIC)\progress \ -!endif - -I$(PUBLIC)\xpcom \ - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/protocol/sockstub/sockstub.cpp b/mozilla/network/protocol/sockstub/sockstub.cpp deleted file mode 100644 index 21e7030107d..00000000000 --- a/mozilla/network/protocol/sockstub/sockstub.cpp +++ /dev/null @@ -1,651 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ -/* - * Stub protocol for turning socket i/o into a stream interface. - */ - -#include "xp.h" -#include "netutils.h" -#include "mktcp.h" -#include "mkgeturl.h" -#include "mkselect.h" -#include "netstream.h" -#include "plstr.h" -#include "prerror.h" -#include "prmem.h" -#include "prmon.h" - -#include "nsHashtable.h" -#include "sockstub.h" - -#define DEF_SOCKSTUB_PORT 80 - -extern "C" { -extern int MK_UNABLE_TO_LOCATE_HOST; -extern int MK_ZERO_LENGTH_FILE; -extern int MK_TCP_READ_ERROR; -extern int MK_OUT_OF_MEMORY; - -} - -/* definitions of state for the state machine design - */ -typedef enum { - SOCKSTUB_START_CONNECT, - SOCKSTUB_FINISH_CONNECT, - SOCKSTUB_SETUP_STREAM, - SOCKSTUB_FLUSH_DATA, - SOCKSTUB_DONE, - SOCKSTUB_ERROR_DONE, - SOCKSTUB_FREE -} SockStubStatesEnum; - -typedef struct _SockStubConData { - SockStubStatesEnum next_state; /* the next state or action to be taken */ - char* line_buffer; /* temporary string storage */ - int32 line_buffer_size; /* current size of the line buffer */ - NET_StreamClass* stream; /* The output stream */ - Bool pause_for_read; /* Pause now for next read? */ - TCP_ConData* tcp_con_data; /* Data pointer for tcp connect state machine */ - Bool reuse_stream; - Bool connection_is_valid; - char* hostname; /* hostname string (may contain :port) */ - PRFileDesc* sock; /* socket */ - int32 original_content_length; -} SockStubConData; - -PRIVATE int32 -net_InterruptSockStub (ActiveEntry * ce); - -PRIVATE int32 -net_ProcessSockStub (ActiveEntry * ce); - -PRIVATE -int ReturnErrorStatus (int status) -{ - if (status < 0) - status |= status; /* set a breakpoint HERE to find errors */ - return status; -} - - -#define STATUS(Status) ReturnErrorStatus (Status) - -#define PUTBLOCK(b, l) (*cd->stream->put_block) \ - (cd->stream, b, l) -#define PUTSTRING(s) (*cd->stream->put_block) \ - (cd->stream, s, PL_strlen(s)) -#define COMPLETE_STREAM (*cd->stream->complete) \ - (cd->stream) -#define ABORT_STREAM(s) (*cd->stream->abort) \ - (cd->stream, s) - - -// forward declaration -PRIVATE int32 net_ProcessSockStub (ActiveEntry * ce); - -static nsHashtable *theUrlToSocketHashtable = new nsHashtable(); - - -class net_IntegerKey: public nsHashKey { -private: - PRUint32 itsHash; - -public: - net_IntegerKey(PRUint32 hash) { - itsHash = hash; - } - - PRUint32 HashValue(void) const { - return itsHash; - } - - PRBool Equals(const nsHashKey *aKey) const { - return (itsHash == (((const net_IntegerKey *) aKey)->itsHash)) ? PR_TRUE : PR_FALSE; - } - - nsHashKey *Clone(void) const { - return new net_IntegerKey(itsHash); - } -}; - - -static PRMonitor *sockStub_lock = NULL; - -static -PRBool -nsSockStub_lock(void) -{ - if(sockStub_lock == NULL) - { - sockStub_lock = PR_NewMonitor(); - if(sockStub_lock == NULL) - return PR_FALSE; - } - PR_EnterMonitor(sockStub_lock); - return PR_TRUE; -} - -static -void -nsSockStub_unlock(void) -{ - PR_ASSERT(sockStub_lock != NULL); - - if(sockStub_lock != NULL) - { - PR_ExitMonitor(sockStub_lock); - } -} - - - -PRIVATE void -net_AddSocketToHashTable(URL_Struct* URL_s, ActiveEntry * ce) -{ - nsSockStub_lock(); - net_IntegerKey ikey((PRUint32)URL_s); - theUrlToSocketHashtable->Put(&ikey, ce); - nsSockStub_unlock(); -} - -PRIVATE void -net_RemoveSocketToHashTable(URL_Struct* URL_s) -{ - nsSockStub_lock(); - net_IntegerKey ikey((PRUint32)URL_s); - theUrlToSocketHashtable->Remove(&ikey); - nsSockStub_unlock(); -} - -extern "C" { -PUBLIC PRFileDesc * -NET_GetSocketToHashTable(URL_Struct_* URL_s) -{ - nsSockStub_lock(); - net_IntegerKey ikey((PRUint32)URL_s); - ActiveEntry * ce = (ActiveEntry *)theUrlToSocketHashtable->Get(&ikey); - nsSockStub_unlock(); - - SockStubConData * cd = (SockStubConData *)ce->con_data; - return cd->sock; -} -} - -extern "C" { -PUBLIC int32 -NET_FreeSocket(URL_Struct_* URL_s) -{ - nsSockStub_lock(); - net_IntegerKey ikey((PRUint32)URL_s); - ActiveEntry * ce = (ActiveEntry *)theUrlToSocketHashtable->Get(&ikey); - nsSockStub_unlock(); - - /* XXX: The interrupt will set the error state and will do the - * cleanup of the socket - */ - SockStubConData * cd = (SockStubConData *)ce->con_data; - - ce->status = MK_DATA_LOADED; - cd->next_state = SOCKSTUB_DONE; - - return STATUS (net_ProcessSockStub(ce)); -} -} - -/* begins the connect process - * - * returns the TCP status code - */ -PRIVATE int -net_start_sockstub_connect(ActiveEntry * ce) { - SockStubConData * cd = (SockStubConData *)ce->con_data; - - int def_port = DEF_SOCKSTUB_PORT; - char * host_string = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - - // now try to extract the port number from the url - char * startOfPort = PL_strchr(host_string, ':'); - if (startOfPort && *startOfPort && *(startOfPort+1)) - def_port = atoi(startOfPort+1); - - ce->status = NET_BeginConnect (ce->URL_s->address, - ce->URL_s->IPAddressString, - "SOCKSTUB", - def_port, - &cd->sock, - HG02873 - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->socks_host, - ce->socks_port, - ce->URL_s->localIP); - - - /* set this so mkgeturl can select on it */ - ce->socket = cd->sock; - - if(cd->sock != NULL) - NET_TotalNumberOfOpenConnections++; - - if (ce->status < 0) { - if(ce->status == MK_UNABLE_TO_LOCATE_HOST) - { - /* no need to set the state since this - * is the state we want again - */ - if(cd->sock != NULL) { - PR_Close(cd->sock); - cd->sock = NULL; - ce->socket = NULL; - } - return(0); - } - - TRACEMSG(("SockStub: Unable to connect to host for `%s' (errno = %d).", - ce->URL_s->address, PR_GetOSError())); - /* - * Proxy failover - */ - - cd->next_state = SOCKSTUB_ERROR_DONE; - return STATUS(ce->status); - } /* end status < 0 */ - - if(ce->status == MK_CONNECTED) - { - cd->next_state = SOCKSTUB_SETUP_STREAM; - TRACEMSG(("Connected through SockStub gateway on sock #%d",cd->sock)); - NET_SetReadSelect(ce->window_id, cd->sock); - } else { - cd->next_state = SOCKSTUB_FINISH_CONNECT; - cd->pause_for_read = TRUE; - ce->con_sock = cd->sock; /* set the socket for select */ - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - - net_AddSocketToHashTable(ce->URL_s, ce); - return STATUS(ce->status); -} - - -/* begins the connect process - * - * returns the TCP status code - */ -PRIVATE int -net_finish_sockstub_connect(ActiveEntry * ce) -{ - SockStubConData * cd = (SockStubConData *)ce->con_data; - int def_port; - - def_port = DEF_SOCKSTUB_PORT; - - ce->status = NET_FinishConnect(ce->URL_s->address, - "SOCKSTUB", - def_port, - &cd->sock, - &cd->tcp_con_data, - ce->window_id, - &ce->URL_s->error_msg, - ce->URL_s->localIP); - - if (ce->status < 0) { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - TRACEMSG(("SockStub: Unable to connect to host for `%s' (errno = %d).", - ce->URL_s->address, PR_GetOSError())); - - cd->next_state = SOCKSTUB_ERROR_DONE; - return STATUS(ce->status); - } /* end status < 0 */ - - if(ce->status == MK_CONNECTED) { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = NULL; /* reset the socket so we don't select on it */ - /* set this so mkgeturl can select on it */ - ce->socket = cd->sock; - cd->next_state = SOCKSTUB_SETUP_STREAM; - NET_SetReadSelect(ce->window_id, cd->sock); - TRACEMSG(("Connected through SockStub on sock #%d",cd->sock)); - } else { - /* unregister the old ce->socket from the select list - * and register the new value in the case that it changes - */ - if(ce->con_sock != cd->sock) { - NET_ClearConnectSelect(ce->window_id, ce->con_sock); - ce->con_sock = cd->sock; - NET_SetConnectSelect(ce->window_id, ce->con_sock); - } - - cd->pause_for_read = TRUE; - } - - net_AddSocketToHashTable(ce->URL_s, ce); - - return STATUS(ce->status); -} - - -/* sets up the stream - * - * returns the tcp status code - */ -PRIVATE int -net_setup_sockstub_stream(ActiveEntry * ce) { - SockStubConData * cd = (SockStubConData *)ce->con_data; - XP_Bool need_to_do_again = FALSE; - MWContext * stream_context; - - TRACEMSG(("NET_ProcessSockStub: setting up stream")); - - /* set a default content type if one wasn't given - */ - if(!ce->URL_s->content_type || !*ce->URL_s->content_type) - StrAllocCopy(ce->URL_s->content_type, TEXT_HTML); - - /* If a stream previously exists from a partial cache - * situation, reuse it - */ - if(!cd->stream) { - /* clear to prevent tight loop */ - NET_ClearReadSelect(ce->window_id, cd->sock); - stream_context = ce->window_id; - - /* Set up the stream stack to handle the body of the message */ - cd->stream = NET_StreamBuilder(ce->format_out, - ce->URL_s, - stream_context); - - if (!cd->stream) { - ce->status = MK_UNABLE_TO_CONVERT; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_UNABLE_TO_CONVERT); - return STATUS(ce->status); - } - - NET_SetReadSelect(ce->window_id, cd->sock); - - } - - cd->next_state = SOCKSTUB_FLUSH_DATA; - - return STATUS(ce->status); -} - - -/* flushes data from/to socket to/from stream - * (For now, it only reads from the socket to the stream.) - * returns the tcp status code - */ -PRIVATE int -net_flush_sockstub_data(ActiveEntry * ce) -{ - SockStubConData * cd = (SockStubConData *)ce->con_data; - unsigned int write_ready, read_size; - - TRACEMSG(("NET_ProcessSockStub: flushing data")); - - ///////// SOCKET->STREAM (reading from the net) //////////////// - - - /* check to see if the stream is ready for writing - */ - write_ready = (*cd->stream->is_write_ready)(cd->stream); - - TRACEMSG(("NET_ProcessSockStub: Flush: write ready returned %d", write_ready)); - - if(!write_ready) - { - cd->pause_for_read = TRUE; - return(0); /* wait until we are ready to write */ - } - else if(write_ready < (unsigned int) NET_Socket_Buffer_Size) - { - read_size = write_ready; - } - else - { - read_size = NET_Socket_Buffer_Size; - } - - ce->status = PR_Read(cd->sock, NET_Socket_Buffer, read_size); - - TRACEMSG(("NET_ProcessSockStub: Flush: just read %d bytes.", ce->status)); - cd->pause_for_read = TRUE; /* pause for the next read */ - - if(ce->status > 0) - { - ce->bytes_received += ce->status; - ce->status = PUTBLOCK(NET_Socket_Buffer, ce->status); - - // For now, just so we exit when we have at least gotten something, - // to test that stream data is crossing the thread. - /* cd->next_state = SOCKSTUB_DONE; */ - - - if(cd->original_content_length - && ce->bytes_received >= cd->original_content_length) - { - // normal end of transfer - /* XXX: We should go back and wait for data - ce->status = MK_DATA_LOADED; - cd->next_state = SOCKSTUB_DONE; - */ - cd->pause_for_read = FALSE; - } - } - else if(ce->status == 0) - { - // transfer finished - TRACEMSG(("SOCKSTUB: Caught TCP EOF ending stream")); - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_ZERO_LENGTH_FILE); - cd->next_state = SOCKSTUB_ERROR_DONE; - cd->pause_for_read = FALSE; - return(MK_ZERO_LENGTH_FILE); - } - else /* error */ - { - // temporary hack by mscott - // otherwise data isn't ready yet: - cd->pause_for_read = TRUE; -#if 0 - ce->status = 1; - return STATUS(ce->status); -#endif - - int err = PR_GetError(); - - TRACEMSG(("TCP Error: %d", err)); - - if (err == PR_WOULD_BLOCK_ERROR) - { - cd->pause_for_read = TRUE; - return (0); - } - - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_TCP_READ_ERROR, err); - - /* return TCP error - */ - return MK_TCP_READ_ERROR; - } - - return STATUS(ce->status); -} - - -PRIVATE int32 -net_LoadSockStub (ActiveEntry * ce) -{ - SockStubConData * cd = PR_NEW(SockStubConData); - ce->con_data = cd; - if(!ce->con_data) - { - ce->status = MK_OUT_OF_MEMORY; - ce->URL_s->error_msg = NET_ExplainErrorDetails(MK_OUT_OF_MEMORY); - return STATUS(ce->status); - } - - char *use_host = NET_ParseURL(ce->URL_s->address, GET_HOST_PART); - - /* Init connection data */ - memset(cd, 0, sizeof(SockStubConData)); - cd->sock = NULL; - StrAllocCopy(cd->hostname, use_host); - - PR_Free(use_host); - - return STATUS (net_ProcessSockStub(ce)); -} - -PRIVATE int32 -net_ProcessSockStub (ActiveEntry * ce) -{ - SockStubConData * cd = (SockStubConData *)ce->con_data; - TRACEMSG(("Entering NET_ProcessSockStub")); - - cd->pause_for_read = FALSE; /* already paused; reset */ - - while(!cd->pause_for_read) - { - - switch(cd->next_state) - { - - case SOCKSTUB_START_CONNECT: - ce->status = net_start_sockstub_connect(ce); - break; - - case SOCKSTUB_FINISH_CONNECT: - ce->status = net_finish_sockstub_connect(ce); - break; - - case SOCKSTUB_SETUP_STREAM: - ce->status = net_setup_sockstub_stream(ce); - break; - - case SOCKSTUB_FLUSH_DATA: - ce->status = net_flush_sockstub_data(ce); - break; - - case SOCKSTUB_DONE: - net_RemoveSocketToHashTable(ce->URL_s); - NET_ClearReadSelect(ce->window_id, cd->sock); - NET_TotalNumberOfOpenConnections--; - PR_Close(cd->sock); - - if(cd->stream) { - COMPLETE_STREAM; - PR_Free(cd->stream); - cd->stream = 0; - } - - cd->next_state = SOCKSTUB_FREE; - break; - - case SOCKSTUB_ERROR_DONE: - if(cd->sock != NULL) { - net_RemoveSocketToHashTable(ce->URL_s); - NET_ClearDNSSelect(ce->window_id, cd->sock); - NET_ClearReadSelect(ce->window_id, cd->sock); - NET_ClearConnectSelect(ce->window_id, cd->sock); - PR_Close(cd->sock); - NET_TotalNumberOfOpenConnections--; - cd->sock = NULL; - } - - cd->next_state = SOCKSTUB_FREE; - - if(cd->stream) { - ABORT_STREAM(ce->status); - PR_Free(cd->stream); - cd->stream = 0; - } - - break; /* SOCKSTUB_ERROR_DONE */ - - case SOCKSTUB_FREE: - - PR_FREEIF(cd->line_buffer); - PR_Free(cd->stream); /* don't forget the stream */ - PR_Free(cd->hostname); - if(cd->tcp_con_data) - NET_FreeTCPConData(cd->tcp_con_data); - PR_FREEIF(cd); - return STATUS (-1); /* final end SOCKSTUB_FREE */ - - default: /* should never happen !!! */ - TRACEMSG(("SOCKSTUB: BAD STATE!")); - cd->next_state = SOCKSTUB_ERROR_DONE; - break; - } /* end switch */ - - /* check for errors during load and call error state if found */ - if(ce->status < 0 && cd->next_state != SOCKSTUB_FREE) - { - cd->next_state = SOCKSTUB_ERROR_DONE; - } - - } /* while(!cd->pause_for_read) */ - - return STATUS(ce->status); -} - -PRIVATE int32 -net_InterruptSockStub (ActiveEntry * ce) -{ - SockStubConData * cd = (SockStubConData *)ce->con_data; - - cd->next_state = SOCKSTUB_ERROR_DONE; - ce->status = MK_INTERRUPTED; - - return STATUS (net_ProcessSockStub(ce)); -} - -PRIVATE void -net_CleanupSockStub(void) -{ -} - - -#define SOCKSTUB_SCHEME "sockstub:" - -extern "C" { - -MODULE_PRIVATE void -NET_InitSockStubProtocol(void) -{ - static NET_ProtoImpl sockstub_proto_impl; - - sockstub_proto_impl.init = net_LoadSockStub; - sockstub_proto_impl.process = net_ProcessSockStub; - sockstub_proto_impl.interrupt = net_InterruptSockStub; - sockstub_proto_impl.resume = NULL; - sockstub_proto_impl.cleanup = net_CleanupSockStub; - StrAllocCopy(sockstub_proto_impl.scheme, SOCKSTUB_SCHEME); - - - NET_RegisterProtocolImplementation(&sockstub_proto_impl, SOCKSTUB_TYPE_URL); -} - -} diff --git a/mozilla/network/protocol/sockstub/sockstub.h b/mozilla/network/protocol/sockstub/sockstub.h deleted file mode 100644 index 7891b083de1..00000000000 --- a/mozilla/network/protocol/sockstub/sockstub.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef SOCKSTUB_H -#define SOCKSTUB_H - -#include "prio.h" - -/* forward declaration */ -struct URL_Struct_; - - -extern "C" void -NET_InitSockStubProtocol(void); - -/* XXX: Hack the following is a realy hack. Should go away */ -extern "C" PRFileDesc * -NET_GetSocketToHashTable(URL_Struct_* URL_s); - -extern "C" int32 -NET_FreeSocket(URL_Struct_* URL_s); - -#endif /* SOCKSTUB_H */ diff --git a/mozilla/network/public/MANIFEST b/mozilla/network/public/MANIFEST deleted file mode 100644 index 9b2f06ebf08..00000000000 --- a/mozilla/network/public/MANIFEST +++ /dev/null @@ -1,12 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist:network:module directory -# - -nsIHttpURL.h -nsILoadAttribs.h -nsIPostToServer.h -nsIStreamListener.h -nsIStreamObserver.h -nsIURL.h -nsITransport.h -nsIBlockingNotification.h diff --git a/mozilla/network/public/Makefile.in b/mozilla/network/public/Makefile.in deleted file mode 100644 index 15fd1db8861..00000000000 --- a/mozilla/network/public/Makefile.in +++ /dev/null @@ -1,45 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = netlib - -EXPORTS = \ - nsIStreamListener.h \ - nsIStreamObserver.h \ - nsIURL.h \ - nsIPostToServer.h \ - nsIHttpURL.h \ - nsILoadAttribs.h \ - nsITransport.h \ - nsIBlockingNotification.h \ - $(NULL) - -EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS)) - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/public/makefile.win b/mozilla/network/public/makefile.win deleted file mode 100644 index e556551272c..00000000000 --- a/mozilla/network/public/makefile.win +++ /dev/null @@ -1,59 +0,0 @@ -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - -IGNORE_MANIFEST = 1 - -#//------------------------------------------------------------------------ -#// -# New build system where zip dll is build indepenant of java stubs. -#// -#//------------------------------------------------------------------------ -MODULE = netlib -EXPORTS = nsIStreamObserver.h \ - nsIStreamListener.h \ - nsIURL.h \ - nsIPostToServer.h \ - nsIHttpURL.h \ - nsILoadAttribs.h \ - nsITransport.h \ - nsIBlockingNotification.h \ - $(NULL) - -#//------------------------------------------------------------------------ -#// -#// Specify the depth of the current directory relative to the -#// root of NS -#// -#//------------------------------------------------------------------------ -DEPTH= ..\..\ - -#//------------------------------------------------------------------------ -#// -#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...) -#// (these must be defined before the common makefiles are included) -#// -#//------------------------------------------------------------------------ - -#//------------------------------------------------------------------------ -#// -#// Include the common makefile rules -#// -#//------------------------------------------------------------------------ -include <$(DEPTH)/config/rules.mak> - diff --git a/mozilla/network/public/nsIBlockingNotification.h b/mozilla/network/public/nsIBlockingNotification.h deleted file mode 100644 index a8faf798f68..00000000000 --- a/mozilla/network/public/nsIBlockingNotification.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIBlockingCallback_h___ -#define nsIBlockingCallback_h___ - -#include "nscore.h" -#include "nsISupports.h" -#include "prthread.h" - -/* forward declarations... */ -class nsIURI; - -/* 7a3e0350-d724-11d2-99db-0080c7cb1080 */ -#define NS_IBLOCKINGNOTIFICATION_IID \ -{ 0x7a3e0350, 0xd724, 0x11d2, \ - {0x99, 0xdb, 0x00, 0x80, 0xc7, 0xcb, 0x10, 0x80} } - - -class nsIBlockingNotification : public nsISupports -{ -public: - NS_IMETHOD IsBlocked(nsIURI *aUrl, PRBool *aResult) = 0; - NS_IMETHOD Resume(nsIURI *aUrl, void *aExtraInfo) = 0; -}; - - - -/* bd697440-d724-11d2-99db-0080c7cb1080 */ -#define NS_IBLOCKINGNOTIFICATION_OBSERVER_IID \ -{ 0xbd697440, 0xd724, 0x11d2, \ - {0x99, 0xdb, 0x00, 0x80, 0xc7, 0xcb, 0x10, 0x80} } - - -class nsIBlockingNotificationObserver : public nsISupports -{ -public: - NS_IMETHOD Notify(nsIBlockingNotification *aCaller, - nsIURI *aUrl, - PRThread *aThread, - PRInt32 aCode, - void *aExtraInfo) = 0; - - NS_IMETHOD CancelNotify(nsIURI *aUrl) = 0; -}; - - -/* Generic status codes for nsIBlockingNotificationObserver::Notify(...) */ -#define NS_NOTIFY_SUCCEEDED NS_OK -#define NS_NOTIFY_BLOCKED NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_NETWORK, 10) - -#endif /* nsIBlockingCallback_h___ */ diff --git a/mozilla/network/public/nsIHttpURL.h b/mozilla/network/public/nsIHttpURL.h deleted file mode 100644 index 19d52ac6992..00000000000 --- a/mozilla/network/public/nsIHttpURL.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIHttpURL_h___ -#define nsIHttpURL_h___ - -#include "nscore.h" -#include "nsISupports.h" -#include "nspr.h" - -/* 1A0B6FA1-EA25-11d1-BEAE-00805F8A66DC */ - -#define NS_IHTTPURL_IID \ -{ 0x1a0b6fa1, 0xea25, 0x11d1, \ - { 0xbe, 0xae, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0xdc } } - -struct nsIHttpURL : public nsISupports -{ - static const nsIID& GetIID() { static nsIID iid = NS_IHTTPURL_IID; return iid; } - - /** - * Parse the mime header into the url struct. - * This method is intended to be used when an HTML META tag is encoutered - * with the type http-equiv. In this case, the http-equiv header should - * be added to the url in netlib, immediately after the http-equiv meta - * tag is encoutered. - * - * @param shell The shell loading this url. - * @param url The url to parse the mime header into. - * @param name The name of the mime header. - * @param value The value of the mime header. - */ - NS_IMETHOD AddMimeHeader(const char *name, const char *value) = 0; -}; - -/** Create a new HttpURL. */ -extern "C" NS_NET nsresult NS_NewHttpURL(nsISupports** aInstancePtrResult, - nsISupports* aOuter); - -#endif /* nsIHttpURL_h___ */ diff --git a/mozilla/network/public/nsILoadAttribs.h b/mozilla/network/public/nsILoadAttribs.h deleted file mode 100644 index 97e8bb5b340..00000000000 --- a/mozilla/network/public/nsILoadAttribs.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsILoadAttribs_h___ -#define nsILoadAttribs_h___ - -#include "nscore.h" -#include "prtypes.h" -#include "nsISupports.h" - -// Class ID for an implementation of nsILoadAttribs -// {8942D321-48D3-11d2-9E7A-006008BF092E} -#define NS_ILOAD_ATTRIBS_IID \ - { 0x8942d321, 0x48d3, 0x11d2,{0x9e, 0x7a, 0x00, 0x60, 0x08, 0xbf, 0x09, 0x2e}} - -/* - * The nsReloadType represents the following: - * nsURLReload - normal reload (uses cache) - * nsURLReloadBypassCache - bypass the cache - * nsURLReloadBypassCacheAndProxy - bypass the proxy (not yet implemented) - */ -typedef enum { - nsURLReload = 0, - nsURLReloadBypassCache, - nsURLReloadBypassProxy, - nsURLReloadBypassCacheAndProxy, - nsURLReloadMax, - nsURLReloadFromHistory -} nsURLReloadType; - -/* - * The nsLoadType represents the following: - * nsURLLoadNormal - Load the URL normally. - * nsURLLoadBackground - Supress all notifications when loading the URL. - */ -typedef enum { - nsURLLoadNormal = 0, - nsURLLoadBackground, - nsURLLoadMax -} nsURLLoadType; - -// Defining attributes of a url's load behavior. -class nsILoadAttribs : public nsISupports { -public: - static const nsIID& GetIID() { static nsIID iid = NS_ILOAD_ATTRIBS_IID; return iid; } - // Copy the state of another nsILoadAttribs instance. - NS_IMETHOD Clone(nsILoadAttribs* aLoadAttribs) = 0; - - // Bypass Proxy. - NS_IMETHOD SetBypassProxy(PRBool aBypass) = 0; - NS_IMETHOD GetBypassProxy(PRBool *aBypass) = 0; - - // Local IP address. - NS_IMETHOD SetLocalIP(const PRUint32 aLocalIP) = 0; - NS_IMETHOD GetLocalIP(PRUint32 *aLocalIP) = 0; - - // Reload method. - NS_IMETHOD SetReloadType(nsURLReloadType aType) = 0; - NS_IMETHOD GetReloadType(nsURLReloadType* aResult) = 0; - - // Load method - NS_IMETHOD SetLoadType(nsURLLoadType aType) = 0; - NS_IMETHOD GetLoadType(nsURLLoadType* aResult) = 0; - - // Byte Range Support - NS_IMETHOD SetByteRangeHeader(const char *aByteRangeHeader) = 0; - NS_IMETHOD GetByteRangeHeader(char** aByteRangeHeader) = 0; - -}; - -/* Creation routines. */ - -extern NS_NET nsresult NS_NewLoadAttribs(nsILoadAttribs** aInstancePtrResult); - -#endif // nsILoadAttribs_h___ diff --git a/mozilla/network/public/nsIPostToServer.h b/mozilla/network/public/nsIPostToServer.h deleted file mode 100644 index 8b39b58ef25..00000000000 --- a/mozilla/network/public/nsIPostToServer.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIPostToServer_h___ -#define nsIPostToServer_h___ - -#include "nscore.h" -#include "nsISupports.h" - -#include "nspr.h" - -/* EADF7B41-EBC0-11d1-BEAE-00805F8A66DC */ -#define NS_IPOSTTOSERVER_IID \ -{ 0xeadf7b41, 0xebc0, 0x11d1, \ - { 0xbe, 0xae, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0xdc } } - - - -struct nsIPostToServer : public nsISupports -{ - static const nsIID& GetIID() { static nsIID iid = NS_IPOSTTOSERVER_IID; return iid; } - - NS_IMETHOD SendFile(const char *aFile) = 0; - NS_IMETHOD SendData(const char *aBuffer, PRUint32 aLength) = 0; - NS_IMETHOD SendDataFromFile(const char *aFile) = 0; -}; - -#define NS_IPOSTTOSERVER_ALREADY_POSTING NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_NETWORK, 1) - - -#endif /* nsIPostToServer_h___ */ diff --git a/mozilla/network/public/nsIStreamListener.h b/mozilla/network/public/nsIStreamListener.h deleted file mode 100644 index 98aa1103a2e..00000000000 --- a/mozilla/network/public/nsIStreamListener.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIStreamListener_h___ -#define nsIStreamListener_h___ - -#include "nsIStreamObserver.h" - -/* forward declaration */ -class nsIInputStream; -class nsString; -class nsIURI; - -struct nsStreamBindingInfo { - PRBool seekable; - /* ...more... */ -}; - -/* 45d234d0-c6c9-11d1-bea2-00805f8a66dc */ -#define NS_ISTREAMLISTENER_IID \ -{ 0x45d234d0, 0xc6c9, 0x11d1, \ - {0xbe, 0xa2, 0x00, 0x80, 0x5f, 0x8a, 0x66, 0xdc} } - -/** - * The nsIStreamListener interface provides the necessary notifications - * during both synchronous and asynchronous URL loading. - * This is a preliminary interface which <B>will</B> change over time! - * <BR><BR> - * An instance of this interface is passed to nsINetService::Open(...) to - * allow the client to receive status and notifications during the loading - * of the URL. - * <BR><BR> - * Over time this interface will provide the same functionality as the - * IBindStatusCallback interface in the MS INET-SDK... - */ -class nsIStreamListener : public nsIStreamObserver { -public: - static const nsIID& GetIID() { static nsIID iid = NS_ISTREAMLISTENER_IID; return iid; } - /** - * Return information regarding the current URL load.<BR> - * The info structure that is passed in is filled out and returned - * to the caller. - * - * This method is currently not called. - */ - NS_IMETHOD GetBindInfo(nsIURI* aURL, nsStreamBindingInfo* aInfo) = 0; - - /** - * Notify the client that data is available in the input stream. This - * method is called whenver data is written into the input stream by the - * networking library...<BR><BR> - * - * @param pIStream The input stream containing the data. This stream can - * be either a blocking or non-blocking stream. - * @param length The amount of data that was just pushed into the stream. - * @return The return value is currently ignored. - */ - NS_IMETHOD OnDataAvailable(nsIURI* aURL, nsIInputStream *aIStream, - PRUint32 aLength) = 0; -}; - -#endif /* nsIStreamListener_h___ */ diff --git a/mozilla/network/public/nsIStreamObserver.h b/mozilla/network/public/nsIStreamObserver.h deleted file mode 100644 index 0b26ca1003d..00000000000 --- a/mozilla/network/public/nsIStreamObserver.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIStreamObserver_h___ -#define nsIStreamObserver_h___ - -#include "nsISupports.h" -#include "nscore.h" - -/* forward declaration */ -class nsIInputStream; -class nsString; -class nsIURI; - - -/* 97566110-ff60-11d1-beb9-00805f8a66dc */ -#define NS_ISTREAMOBSERVER_IID \ -{ 0x97566110, 0xff60, 0x11d1, \ - {0xbe, 0xb9, 0x00, 0x80, 0x5f, 0x8a, 0x66, 0xdc} } - - -class nsIStreamObserver : public nsISupports { -public: - static const nsIID& GetIID() { static nsIID iid = NS_ISTREAMOBSERVER_IID; return iid; } - - /** - * Notify the observer that the URL has started to load. This method is - * called only once, at the beginning of a URL load.<BR><BR> - * - * @return The return value is currently ignored. In the future it may be - * used to cancel the URL load.. - */ - NS_IMETHOD OnStartRequest(nsIURI* aURL, const char *aContentType) = 0; - - /** - * Notify the observer that progress as occurred for the URL load.<BR> - */ - NS_IMETHOD OnProgress(nsIURI* aURL, PRUint32 aProgress, PRUint32 aProgressMax) = 0; - - /** - * Notify the observer with a status message for the URL load.<BR> - */ - NS_IMETHOD OnStatus(nsIURI* aURL, const PRUnichar* aMsg) = 0; - - /** - * Notify the observer that the URL has finished loading. This method is - * called once when the networking library has finished processing the - * URL transaction initiatied via the nsINetService::Open(...) call.<BR><BR> - * - * This method is called regardless of whether the URL loaded successfully.<BR><BR> - * - * @param status Status code for the URL load. - * @param msg A text string describing the error. - * @return The return value is currently ignored. - */ - NS_IMETHOD OnStopRequest(nsIURI* aURL, nsresult aStatus, const PRUnichar* aMsg) = 0; -}; - -/* Generic status codes for OnStopRequest */ -#define NS_BINDING_SUCCEEDED NS_OK -#define NS_BINDING_FAILED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 1) -#define NS_BINDING_ABORTED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 2) - -#endif /* nsIStreamObserver_h___ */ diff --git a/mozilla/network/public/nsITransport.h b/mozilla/network/public/nsITransport.h deleted file mode 100644 index e4f560b3130..00000000000 --- a/mozilla/network/public/nsITransport.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsITransport_h___ -#define nsITransport_h___ - -#include "nscore.h" -#include "nsISupports.h" -#include "prio.h" -#include "nsIStreamListener.h" -#include "nsIOutputStream.h" -#include "nsIURL.h" - -#define NS_ITRANSPORT_IID \ -{ 0x54ae75a0, 0x99e8, 0x11d2, \ - {0xb9, 0x47, 0x00, 0x80, 0x5f, 0x52, 0x35, 0x1a} } - -class nsITransport : public nsIStreamListener { -public: - static const nsIID& GetIID() { static nsIID iid = NS_ITRANSPORT_IID; return iid; } - - /** Accessors */ - - /** - * Returns the URL that is associated with the Transport. - * - * If the transport doesn't have URL associated with it - * because it was constructed by passing host and port, - * it will return NULL. - * - * @param result the URL that was used to build the transport - * @return The return value is currently ignored. - */ - NS_IMETHOD GetURL(nsIURI* *result) = 0; - - /** - * Sets up the InputStreamListener. Transport layer will notify this - * consumer when it writes data from the socket into its input stream. - * - * @param aListener: The InputStreamConsumer provided by the protocol - * instance which the transport layer should use for input stream - * notifications. The transport layer assumes responsibility for - * building a stream listener proxy for the protocol's listener. - * - * @return The return value is currently ignored. - */ - NS_IMETHOD SetInputStreamConsumer(nsIStreamListener* listener) = 0; - - /** - * Returns a proxied stream listener which the transport layer expects - * notifications through for the output stream. The protocol will bind the - * listener returned to its output stream where it writes data it wants - * sent through the transport layer. - * As with the input stream consumer case, the transport layer returns a - * proxied consumer. - * - * @return aConsumer: The proxied transport layer's consumer for the - * protocol's output stream. - */ - - NS_IMETHOD GetOutputStreamConsumer(nsIStreamListener ** aConsumer) = 0; - - /** - * Returns an output stream which the protocol instance should write data - * it wants transmitted through the transport layer into. After writing data - * to this stream, the protocol should notify the output stream consumer. - * This informs the transport layer that data is available. - * - * @param aOutputStream: The output stream the protocol will write data for - * transmission into. - * - * @return NS_FAILURE if the stream could not be returned. - */ - - NS_IMETHOD GetOutputStream(nsIOutputStream ** aOutputStream) = 0; - - /** - * Returns true if the transport has been opened already and FALSE otherwise. - * If a transport has not been opened yet, then you should open it using - * Open(nsIURI *). - **/ - - NS_IMETHOD IsTransportOpen(PRBool * aSocketOpen) = 0; - - /** - * This replaces LoadUrl. Before using a transport, you should open the transport. - * This functionality may go away after we remove the reliance on sock stub. You - * should always call open the first time you want to use the transport in order to - * open its underlying object (file, socket, etc.). You can later issue a ::StopBinding - * call on the transport which should cause the underlying object (file, socket, etc.) to - * be closed. You could then open the transport again with another URL. Note, for sockets, - * if you wish to re-use a connection, you shouldn't call StopBinding on it as this would - * cause the connection to be closed... - **/ - - NS_IMETHOD Open(nsIURI * aUrl) = 0; -}; - - -#endif /* nsITransport_h___ */ diff --git a/mozilla/network/public/nsIURL.h b/mozilla/network/public/nsIURL.h deleted file mode 100644 index 8e479cc28ff..00000000000 --- a/mozilla/network/public/nsIURL.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - -#ifndef nsIURL_h___ -#define nsIURL_h___ - -#include "nscore.h" -#include "nsISupports.h" -#include "nsILoadAttribs.h" - -class nsIInputStream; -class nsIStreamListener; -class nsString; -class nsILoadGroup; - -#define NS_IURL_IID \ -{ 0x6ecb2900, 0x93b5, 0x11d1, \ - {0x89, 0x5b, 0x00, 0x60, 0x08, 0x91, 0x1b, 0x81} } - -class nsIURI : public nsISupports { -public: - static const nsIID& GetIID() { static nsIID iid = NS_IURL_IID; return iid; } - - /** Equality operator */ - NS_IMETHOD_(PRBool) Equals(const nsIURI *aURL) const = 0; - - /** Accessors */ - //@{ - /** @return string originally used to construct the URL */ - NS_IMETHOD GetSpec(const char* *result) const = 0; - - NS_IMETHOD SetSpec(const char* spec) = 0; - - /** @return protocol part of the URL */ - NS_IMETHOD GetProtocol(const char* *result) const = 0; - - NS_IMETHOD SetProtocol(const char* protocol) = 0; - - /** @return host part of the URL */ - NS_IMETHOD GetHost(const char* *result) const = 0; - - NS_IMETHOD SetHost(const char* host) = 0; - - /** @return ref part of the URL */ - NS_IMETHOD GetHostPort(PRUint32 *result) const = 0; - - NS_IMETHOD SetHostPort(PRUint32 port) = 0; - - /** @return file part of the URL */ - NS_IMETHOD GetFile(const char* *result) const = 0; - - NS_IMETHOD SetFile(const char* file) = 0; - - /** @return ref part of the URL */ - NS_IMETHOD GetRef(const char* *result) const = 0; - - NS_IMETHOD SetRef(const char* ref) = 0; - - /** @return search part of the URL */ - NS_IMETHOD GetSearch(const char* *result) const = 0; - - NS_IMETHOD SetSearch(const char* search) = 0; - - NS_IMETHOD GetContainer(nsISupports* *result) const = 0; - NS_IMETHOD SetContainer(nsISupports* container) = 0; - - NS_IMETHOD GetLoadAttribs(nsILoadAttribs* *result) const = 0; - NS_IMETHOD SetLoadAttribs(nsILoadAttribs* loadAttribs) = 0; - - NS_IMETHOD GetLoadGroup(nsILoadGroup* *result) const = 0; - NS_IMETHOD SetLoadGroup(nsILoadGroup* group) = 0; - //@} - - NS_IMETHOD SetPostHeader(const char* name, const char* value) = 0; - - NS_IMETHOD SetPostData(nsIInputStream* input) = 0; - - NS_IMETHOD GetContentLength(PRInt32 *len) = 0; - - NS_IMETHOD GetServerStatus(PRInt32 *status) = 0; - - /** Write the URL to aString, overwriting previous contents. */ - NS_IMETHOD ToString(PRUnichar* *aString) const = 0; -}; - -// XXXwhh (re)move these... - -/** Create a new URL, interpreting aSpec as relative to aURL (if non-null). */ -extern NS_NET nsresult NS_NewURL(nsIURI** aInstancePtrResult, - const nsString& aSpec, - const nsIURI* aBaseURL = nsnull, - nsISupports* aContainer = nsnull, - nsILoadGroup* aGroup = nsnull); - -/** - * Utility routine to take a url (may be nsnull) and a base url (may - * be empty), and a url spec and combine them properly into a new - * absolute url. - */ -extern NS_NET nsresult NS_MakeAbsoluteURL(nsIURI* aURL, - const nsString& aBaseURL, - const nsString& aSpec, - nsString& aResult); - -extern NS_NET nsresult NS_OpenURL(nsIURI* aURL, nsIStreamListener* aConsumer); - -extern NS_NET nsresult NS_OpenURL(nsIURI* aURL, nsIInputStream* *aNewStream, - nsIStreamListener* aConsumer = nsnull); - -#endif /* nsIURL_h___ */ diff --git a/mozilla/network/util/MANIFEST b/mozilla/network/util/MANIFEST deleted file mode 100644 index 51fc96dd9c1..00000000000 --- a/mozilla/network/util/MANIFEST +++ /dev/null @@ -1,4 +0,0 @@ -# -# This is a list of local files which get copied to the mozilla:dist directory -# - diff --git a/mozilla/network/util/Makefile.in b/mozilla/network/util/Makefile.in deleted file mode 100644 index 9f5823d2b84..00000000000 --- a/mozilla/network/util/Makefile.in +++ /dev/null @@ -1,39 +0,0 @@ -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): -# - -DEPTH = ../.. -topsrcdir = @top_srcdir@ -srcdir = @srcdir@ -VPATH = @srcdir@ - -include $(DEPTH)/config/autoconf.mk - -MODULE = network -LIBRARY_NAME = netutil - -REQUIRES = network xp - -CSRCS = mkbuf.c - -EXPORTS = $(srcdir)/mkbuf.h - -include $(topsrcdir)/config/rules.mk - diff --git a/mozilla/network/util/makefile.win b/mozilla/network/util/makefile.win deleted file mode 100644 index 4b459868062..00000000000 --- a/mozilla/network/util/makefile.win +++ /dev/null @@ -1,94 +0,0 @@ -#!gmake -# -# The contents of this file are subject to the Netscape Public -# License Version 1.1 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.mozilla.org/NPL/ -# -# Software distributed under the License is distributed on an "AS -# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# The Original Code is mozilla.org code. -# -# The Initial Developer of the Original Code is Netscape -# Communications Corporation. Portions created by Netscape are -# Copyright (C) 1998 Netscape Communications Corporation. All -# Rights Reserved. -# -# Contributor(s): - - -# - -#------------------------------------------------------------------------ -# -# Makefile to build the Network LIB -# -#------------------------------------------------------------------------ - - -# -# Make sure we have MOZILLA_CLIENT defined so we get the -# proper JS includes -# -MAPFILE=netutil.map -LCFLAGS = $(LCFLAGS) -DMOZILLA_CLIENT - -!ifdef BUILD_DEBUG_GC -LCFLAGS = $(LCFLAGS) -DDEBUG_GC -!endif - -LLIBS= \ - $(NULL) - -OBJS= \ -!if defined(SMART_MAIL) - .\$(OBJDIR)\mkbuf.obj \ -!endif - $(NULL) - - -CSRCS = \ -!if defined(SMART_MAIL) - mkbuf.c \ -!endif - $(NULL) - -MODULE=network -DEPTH=..\.. - -LIBRARY_NAME=netutil - -EXTRA_LIBS= - -REQUIRES= network -EXPORTS= \ -!if defined(SMART_MAIL) - mkbuf.h \ -!endif - $(NULL); - -C_OBJS = \ - $(NULL) - - -# use LINCS on win32 for now since REQUIRES seems to be broken -#!if "$(MOZ_BITS)" != "16" -LINCS= \ - -I$(PUBLIC)\network \ -!if defined(SMART_MAIL) - -I$(DEPTH)\lib\xp \ -!endif - $(NULL) -#!endif - -include <$(DEPTH)\config\rules.mak> - -install:: $(LIBRARY) - $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib - -symbols:: - @echo "LIBRARY_NAME is $(LIBRARY_NAME)" - @echo "LIBRARY is $(LIBRARY)" diff --git a/mozilla/network/util/mkbuf.c b/mozilla/network/util/mkbuf.c deleted file mode 100644 index ae88ad50a7e..00000000000 --- a/mozilla/network/util/mkbuf.c +++ /dev/null @@ -1,180 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -/* mkbuf.c --- a netlib stream that buffers data before passing it along. - This is used by libmime and libmsg to undo the effects of line-buffering, - and to pass along larger chunks of data to various stream handlers (e.g., - layout.) - - This stuff used to be in libmsg/msgutils.c, but it's really not - mail-specific. And I had to move it to get libmime to work in the - absence of libmsg, so in the meantime, I changed the prefix from MSG_ - to NET_. - - This depends on XP_ReBuffer (xp_linebuf.c) to do its dirty work. - - Created: Jamie Zawinski <jwz@mozilla.org>, 8-Aug-98. -*/ - -#include "xp_mcom.h" -#include "net.h" -#include "xp_linebuf.h" -#include "mkbuf.h" - -struct net_rebuffering_stream_data -{ - uint32 desired_size; - char *buffer; - uint32 buffer_size; - uint32 buffer_fp; - NET_StreamClass *next_stream; -}; - -#undef FREEIF -#define FREEIF(obj) do { if (obj) { XP_FREE (obj); obj = 0; }} while (0) - - -static int32 -net_rebuffering_stream_write_next_chunk (char *buffer, uint32 buffer_size, - void *closure) -{ - struct net_rebuffering_stream_data *sd = - (struct net_rebuffering_stream_data *) closure; - XP_ASSERT (sd); - if (!sd) return -1; - if (!sd->next_stream) return -1; - return (*sd->next_stream->put_block) (sd->next_stream, - buffer, buffer_size); -} - -static int -net_rebuffering_stream_write_chunk (NET_StreamClass *stream, - const char* net_buffer, - int32 net_buffer_size) -{ - struct net_rebuffering_stream_data *sd = - (struct net_rebuffering_stream_data *) stream->data_object; - XP_ASSERT (sd); - if (!sd) return -1; - return XP_ReBuffer (net_buffer, net_buffer_size, - sd->desired_size, - &sd->buffer, &sd->buffer_size, &sd->buffer_fp, - net_rebuffering_stream_write_next_chunk, - sd); -} - - -/* ValidateDocData() isn't implemented anywhere, it used to be part - of the old parser in lib/libparse/pa_parse.c. There are 8+ - instances of this function being stubbed out, let's stop the - insanity and put the stub here, since net_rebuffering_stream_abort() - seems to be the only caller of ValidateDocData(). */ -XP_Bool ValidateDocData(MWContext *window_id) -{ - return PR_TRUE; -} - -static void -net_rebuffering_stream_abort (NET_StreamClass *stream, int status) -{ - struct net_rebuffering_stream_data *sd = - (struct net_rebuffering_stream_data *) stream->data_object; - if (!sd) return; - FREEIF (sd->buffer); - if (sd->next_stream) - { - if (ValidateDocData(sd->next_stream->window_id)) /* otherwise doc_data - is gone ! */ - (*sd->next_stream->abort) (sd->next_stream, status); - XP_FREE (sd->next_stream); - } - XP_FREE (sd); -} - -static void -net_rebuffering_stream_complete (NET_StreamClass *stream) -{ - struct net_rebuffering_stream_data *sd = - (struct net_rebuffering_stream_data *) stream->data_object; - if (!sd) return; - sd->desired_size = 0; - net_rebuffering_stream_write_chunk (stream, "", 0); - FREEIF (sd->buffer); - if (sd->next_stream) - { - (*sd->next_stream->complete) (sd->next_stream); - XP_FREE (sd->next_stream); - } - XP_FREE (sd); -} - -static unsigned int -net_rebuffering_stream_write_ready (NET_StreamClass *stream) -{ - struct net_rebuffering_stream_data *sd = - (struct net_rebuffering_stream_data *) stream->data_object; - if (sd && sd->next_stream) - return ((*sd->next_stream->is_write_ready) - (sd->next_stream)); - else - return (MAX_WRITE_READY); -} - -NET_StreamClass * -NET_MakeRebufferingStream (NET_StreamClass *next_stream, - URL_Struct *url, - MWContext *context) -{ - NET_StreamClass *stream; - struct net_rebuffering_stream_data *sd; - - XP_ASSERT (next_stream); - - /* TRACEMSG(("Setting up rebuffering stream. Have URL: %s\n", url->address)); */ - - stream = XP_NEW (NET_StreamClass); - if (!stream) return 0; - - sd = XP_NEW (struct net_rebuffering_stream_data); - if (! sd) - { - XP_FREE (stream); - return 0; - } - - XP_MEMSET (sd, 0, sizeof(*sd)); - XP_MEMSET (stream, 0, sizeof(*stream)); - - sd->next_stream = next_stream; - sd->desired_size = 10240; - - stream->name = "ReBuffering Stream"; - stream->complete = net_rebuffering_stream_complete; - stream->abort = net_rebuffering_stream_abort; - stream->put_block = net_rebuffering_stream_write_chunk; - stream->is_write_ready = net_rebuffering_stream_write_ready; - stream->data_object = sd; - stream->window_id = context; - - return stream; -} diff --git a/mozilla/network/util/mkbuf.h b/mozilla/network/util/mkbuf.h deleted file mode 100644 index 221c2e042d8..00000000000 --- a/mozilla/network/util/mkbuf.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * - * The contents of this file are subject to the Netscape Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is Mozilla Communicator client code. - * - * The Initial Developer of the Original Code is Netscape Communications - * Corporation. Portions created by Netscape are - * Copyright (C) 1998 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - */ - - -/* mkbuf.h --- a netlib stream that buffers data before passing it along. - This is used by libmime and libmsg to undo the effects of line-buffering, - and to pass along larger chunks of data to various stream handlers (e.g., - layout.) - - Created: Jamie Zawinski <jwz@mozilla.org>, 8-Aug-98. -*/ - -#ifndef __MKBUF_H__ -#define __MKBUF_H__ - -#include "ntypes.h" - -XP_BEGIN_PROTOS - -extern NET_StreamClass *NET_MakeRebufferingStream (NET_StreamClass *next, - URL_Struct *url, - MWContext *context); - -XP_END_PROTOS - -#endif /* __MKBUF_H__ */