Bug 486182, Land NSS 3.12.3 final in mozilla-central

r=nelson
This commit is contained in:
Kai Engert 2009-04-07 03:36:45 +02:00
Родитель 266fc4ea3d
Коммит a29c237bb0
457 изменённых файлов: 22999 добавлений и 2980 удалений

Просмотреть файл

@ -1,26 +0,0 @@
#if defined(__WATCOMC__) || defined(__WATCOM_CPLUSPLUS__)
#ifndef __WATCOM_FIX_H__
#define __WATCOM_FIX_H__ 1
/*
* WATCOM's C compiler doesn't default to "__cdecl" conventions for external
* symbols and functions. Rather than adding an explicit __cdecl modifier to
* every external symbol and function declaration and definition, we use the
* following pragma to (attempt to) change WATCOM c's default to __cdecl.
* These pragmas were taken from pages 180-181, 266 & 269 of the
* Watcom C/C++ version 11 User's Guide, 3rd edition.
*/
#if defined(XP_WIN16) || defined(WIN16)
#pragma aux default "_*" \
parm caller [] \
value struct float struct routine [ax] \
modify [ax bx cx dx es]
#else
#pragma aux default "_*" \
parm caller [] \
value struct float struct routine [eax] \
modify [eax ecx edx]
#endif
#pragma aux default far
#endif /* once */
#endif /* WATCOM compiler */

Просмотреть файл

@ -33,8 +33,6 @@
static char sccsid[] = "@(#)db.c 8.4 (Berkeley) 2/21/94"; static char sccsid[] = "@(#)db.c 8.4 (Berkeley) 2/21/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#ifndef __DBINTERFACE_PRIVATE #ifndef __DBINTERFACE_PRIVATE
#define __DBINTERFACE_PRIVATE #define __DBINTERFACE_PRIVATE
#endif #endif

Просмотреть файл

@ -36,8 +36,6 @@
static char sccsid[] = "@(#)hash_bigkey.c 8.3 (Berkeley) 5/31/94"; static char sccsid[] = "@(#)hash_bigkey.c 8.3 (Berkeley) 5/31/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
/* /*
* PACKAGE: hash * PACKAGE: hash
* DESCRIPTION: * DESCRIPTION:

Просмотреть файл

@ -36,8 +36,6 @@
static char sccsid[] = "@(#)hash_func.c 8.2 (Berkeley) 2/21/94"; static char sccsid[] = "@(#)hash_func.c 8.2 (Berkeley) 2/21/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#ifndef macintosh #ifndef macintosh
#include <sys/types.h> #include <sys/types.h>
#endif #endif

Просмотреть файл

@ -36,8 +36,6 @@
static char sccsid[] = "@(#)hash_log2.c 8.2 (Berkeley) 5/31/94"; static char sccsid[] = "@(#)hash_log2.c 8.2 (Berkeley) 5/31/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#include <stdio.h> #include <stdio.h>
#ifndef macintosh #ifndef macintosh
#include <sys/types.h> #include <sys/types.h>

Просмотреть файл

@ -43,8 +43,6 @@ extern long new_lseek(int fd, long pos, int start);
static char sccsid[] = "@(#)hash_page.c 8.7 (Berkeley) 8/16/94"; static char sccsid[] = "@(#)hash_page.c 8.7 (Berkeley) 8/16/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
/* /*
* PACKAGE: hashing * PACKAGE: hashing
* *

Просмотреть файл

@ -36,8 +36,6 @@
static char sccsid[] = "@(#)hash.c 8.9 (Berkeley) 6/16/94"; static char sccsid[] = "@(#)hash.c 8.9 (Berkeley) 6/16/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) #if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh)
#include <sys/param.h> #include <sys/param.h>
#endif #endif

Просмотреть файл

@ -36,8 +36,6 @@
static char sccsid[] = "@(#)hash_buf.c 8.5 (Berkeley) 7/15/94"; static char sccsid[] = "@(#)hash_buf.c 8.5 (Berkeley) 7/15/94";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
/* /*
* PACKAGE: hash * PACKAGE: hash
* *

Просмотреть файл

@ -37,8 +37,6 @@
static char sccsid[] = "@(#)bcopy.c 8.1 (Berkeley) 6/4/93"; static char sccsid[] = "@(#)bcopy.c 8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#ifdef HAVE_SYS_CDEFS_H #ifdef HAVE_SYS_CDEFS_H
#include <sys/cdefs.h> #include <sys/cdefs.h>
#else #else

Просмотреть файл

@ -33,8 +33,6 @@
static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93"; static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#ifdef macintosh #ifdef macintosh
#include <unix.h> #include <unix.h>
#else #else

Просмотреть файл

@ -1,6 +1,5 @@
#ifndef HAVE_SNPRINTF #ifndef HAVE_SNPRINTF
#include "watcomfx.h"
#include <sys/types.h> #include <sys/types.h>
#include <stddef.h> #include <stddef.h>
#include <stdio.h> #include <stdio.h>

Просмотреть файл

@ -33,8 +33,6 @@
static char sccsid[] = "@(#)strerror.c 8.1 (Berkeley) 6/4/93"; static char sccsid[] = "@(#)strerror.c 8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include "watcomfx.h"
#include <string.h> #include <string.h>
#ifdef _DLL #ifdef _DLL

Просмотреть файл

@ -50,7 +50,11 @@ CPU_ARCH := $(shell uname -p)
endif endif
ifeq (,$(filter-out i%86,$(CPU_ARCH))) ifeq (,$(filter-out i%86,$(CPU_ARCH)))
ifdef USE_64
CC += -arch x86_64
else
OS_REL_CFLAGS = -Di386 OS_REL_CFLAGS = -Di386
endif
else else
OS_REL_CFLAGS = -Dppc OS_REL_CFLAGS = -Dppc
endif endif

0
security/coreconf/OpenVMS.mk Normal file → Executable file
Просмотреть файл

0
security/coreconf/OpenVMSV7.1-2.mk Normal file → Executable file
Просмотреть файл

0
security/coreconf/SunOS5.10_i86pc.mk Normal file → Executable file
Просмотреть файл

0
security/coreconf/SunOS5.9.mk Normal file → Executable file
Просмотреть файл

0
security/coreconf/SunOS5.9_i86pc.mk Normal file → Executable file
Просмотреть файл

Просмотреть файл

@ -1,213 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# win16_3.11.mk -- Make configuration for Win16
#
# This file configures gmake to build the Win16 variant of
# NSPR 2.0. This file has the function of two files commonly
# used on other platforms, for example: winnt.mk and
# winnt4.0.mk. ... The packaging is easier and there is only
# one variant of the Win16 target.
#
# Win16 is built using the Watcom C/C++ version 11.0
# compiler. You gotta set up the compiler first.
# The Watcom compiler depends on a few environment
# variables; these environment variables define where the
# compiler components are installed; they must be set before
# running the make.
#
# Notes:
# OS_CFLAGS is the command line options for the compiler when
# building the .DLL object files.
# OS_EXE_CFLAGS is the command line options for the compiler
# when building the .EXE object files; this is for the test
# programs.
# the macro OS_CFLAGS is set to OS_EXE_CFLAGS inside of the
# makefile for the pr/tests directory. ... Hack.
#
#
#
#
# -- configuration -----------------------------------------
DEFAULT_COMPILER = wcc
CC = wcc
CCC = wcl
LINK = wlink
AR = wlib
AR += -q $@
RC = wrc.exe
RC += /r /dWIN16=1 /bt=windows
RANLIB = echo
BSDECHO = echo
NSINSTALL_DIR = $(CORE_DEPTH)/coreconf/nsinstall
NSINSTALL = nsinstall
INSTALL = $(NSINSTALL)
MAKE_OBJDIR = mkdir
MAKE_OBJDIR += $(OBJDIR)
XP_DEFINE += -DXP_PC
LIB_SUFFIX = lib
DLL_SUFFIX = dll
ifdef BUILD_OPT
OPTIMIZER = -oneatx -oh -oi -ei -3 -fpi87 -fp3
else
OPTIMIZER += -d2 -hc -DDEBUG
# OPTIMIZER += -d2 -hw -DDEBUG
# LDFLAGS += -DEBUG -DEBUGTYPE:CV
endif
#
# $(CPU_ARCH) has been commented out so that its contents
# are not added to the WIN16_?.OBJ names thus expanding
# them beyond the 8.3 character limit for this platform.
#
#CPU_ARCH = x386
#
# added "-s" to avoid dependency on watcom's libs (e.g. on _STK)
# added "-zt3" for compatibility with MSVC's "/Gt3" option
#
OS_CFLAGS += -ml -3 -bd -zc -zu -bt=windows -s -zt3 -d_X86_ -dWIN16 -d_WINDLL
#OS_EXE_CFLAGS += -ml -3 -bt=windows -d_X86_ -dWIN16
OS_LIB_FLAGS = -c -iro
# Name of the binary code directories
OS_DLL_OPTION = CASEEXACT
OS_DLLFLAGS =
OS_LIBS =
W16_EXPORTS = #
ifdef MAPFILE
# Add LD options to restrict exported symbols to those in the map file
endif
# Change PROCESS to put the mapfile in the correct format for this platform
PROCESS_MAP_FILE = copy $< $@
#
# The following is NOT needed for the NSPR 2.0 library.
#
OS_CFLAGS += -d_WINDOWS -d_MSC_VER=700
#
# override the definitions of RELEASE_TREE found in tree.mk
#
ifndef RELEASE_TREE
ifdef BUILD_SHIP
ifdef USE_SHIPS
RELEASE_TREE = $(NTBUILD_SHIP)
else
RELEASE_TREE = //redbuild/components
endif
else
RELEASE_TREE = //redbuild/components
endif
endif
#
# override the definitions of LIB_PREFIX and DLL_PREFIX in prefix.mk
#
ifndef LIB_PREFIX
LIB_PREFIX = $(NULL)
endif
ifndef DLL_PREFIX
DLL_PREFIX = $(NULL)
endif
#
# override the definitions of various _SUFFIX symbols in suffix.mk
#
#
# Object suffixes
#
ifndef OBJ_SUFFIX
OBJ_SUFFIX = .obj
endif
#
# Assembler source suffixes
#
ifndef ASM_SUFFIX
ASM_SUFFIX = .asm
endif
#
# Library suffixes
#
ifndef IMPORT_LIB_SUFFIX
IMPORT_LIB_SUFFIX = .$(LIB_SUFFIX)
endif
ifndef DYNAMIC_LIB_SUFFIX_FOR_LINKING
DYNAMIC_LIB_SUFFIX_FOR_LINKING = $(IMPORT_LIB_SUFFIX)
endif
#
# Program suffixes
#
ifndef PROG_SUFFIX
PROG_SUFFIX = .exe
endif
#
# When the processor is NOT 386-based on Windows NT, override the
# value of $(CPU_TAG). For WinNT, 95, 16, not CE.
#
ifneq ($(CPU_ARCH),x386)
CPU_TAG = _$(CPU_ARCH)
endif
#
# override ruleset.mk, removing the "lib" prefix for library names, and
# adding the "32" after the LIBRARY_VERSION.
#
ifdef LIBRARY_NAME
SHARED_LIBRARY = $(OBJDIR)/$(LIBRARY_NAME)$(LIBRARY_VERSION)32$(JDK_DEBUG_SUFFIX).dll
IMPORT_LIBRARY = $(OBJDIR)/$(LIBRARY_NAME)$(LIBRARY_VERSION)32$(JDK_DEBUG_SUFFIX).lib
endif
#
# override the TARGETS defined in ruleset.mk, adding IMPORT_LIBRARY
#
ifndef TARGETS
TARGETS = $(LIBRARY) $(SHARED_LIBRARY) $(IMPORT_LIBRARY) $(PROGRAM)
endif

Просмотреть файл

@ -62,6 +62,10 @@ else
BSDECHO = echo BSDECHO = echo
RC = rc.exe RC = rc.exe
MT = mt.exe MT = mt.exe
# Determine compiler version
_MSC_VER_6 = 1200 # MSVC 6
_MSC_VER := $(shell $(CC) 2>&1 | sed -ne \
's/.*[^0-9.]\([0-9]\{1,\}\)\.\([0-9]\{1,\}\).*/\1\2/p' )
endif endif
ifdef BUILD_TREE ifdef BUILD_TREE
@ -103,12 +107,6 @@ ifdef NS_USE_GCC
OPTIMIZER += -O2 OPTIMIZER += -O2
endif endif
DEFINES += -UDEBUG -U_DEBUG -DNDEBUG DEFINES += -UDEBUG -U_DEBUG -DNDEBUG
#
# Add symbolic information for a profiler
#
ifdef MOZ_PROFILE
OPTIMIZER += -g
endif
else else
OPTIMIZER += -g OPTIMIZER += -g
NULLSTRING := NULLSTRING :=
@ -118,6 +116,13 @@ ifdef NS_USE_GCC
DEFINES += -DDEBUG -D_DEBUG -UNDEBUG -DDEBUG_$(USERNAME) DEFINES += -DDEBUG -D_DEBUG -UNDEBUG -DDEBUG_$(USERNAME)
endif endif
else # !NS_USE_GCC else # !NS_USE_GCC
OS_CFLAGS += -W3 -nologo -D_CRT_SECURE_NO_WARNINGS
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifeq ($(_MSC_VER),$(_MSC_VER_6))
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
endif
ifdef BUILD_OPT ifdef BUILD_OPT
OS_CFLAGS += -MD OS_CFLAGS += -MD
ifeq (11,$(ALLOW_OPT_CODE_SIZE)$(OPT_CODE_SIZE)) ifeq (11,$(ALLOW_OPT_CODE_SIZE)$(OPT_CODE_SIZE))
@ -127,16 +132,8 @@ else # !NS_USE_GCC
endif endif
DEFINES += -UDEBUG -U_DEBUG -DNDEBUG DEFINES += -UDEBUG -U_DEBUG -DNDEBUG
DLLFLAGS += -OUT:"$@" DLLFLAGS += -OUT:"$@"
#
# Add symbolic information for a profiler
#
ifdef MOZ_PROFILE
OPTIMIZER += -Z7
endif
ifdef MOZ_DEBUG_SYMBOLS ifdef MOZ_DEBUG_SYMBOLS
OPTIMIZER += -Zi OPTIMIZER += -Zi -Fd$(OBJDIR)/
endif
ifneq (,$(MOZ_PROFILE)$(MOZ_DEBUG_SYMBOLS))
DLLFLAGS += -DEBUG -OPT:REF DLLFLAGS += -DEBUG -OPT:REF
LDFLAGS += -DEBUG -OPT:REF LDFLAGS += -DEBUG -OPT:REF
endif endif
@ -150,8 +147,7 @@ else # !NS_USE_GCC
else else
OS_CFLAGS += -MD OS_CFLAGS += -MD
endif endif
OPTIMIZER += -Od -Z7 OPTIMIZER += -Zi -Fd$(OBJDIR)/ -Od
#OPTIMIZER += -Zi -Fd$(OBJDIR)/ -Od
NULLSTRING := NULLSTRING :=
SPACE := $(NULLSTRING) # end of the line SPACE := $(NULLSTRING) # end of the line
USERNAME := $(subst $(SPACE),_,$(USERNAME)) USERNAME := $(subst $(SPACE),_,$(USERNAME))
@ -159,16 +155,20 @@ else # !NS_USE_GCC
DEFINES += -DDEBUG -D_DEBUG -UNDEBUG -DDEBUG_$(USERNAME) DEFINES += -DDEBUG -D_DEBUG -UNDEBUG -DDEBUG_$(USERNAME)
DLLFLAGS += -DEBUG -OUT:"$@" DLLFLAGS += -DEBUG -OUT:"$@"
LDFLAGS += -DEBUG LDFLAGS += -DEBUG
ifeq ($(_MSC_VER),$(_MSC_VER_6))
ifndef MOZ_DEBUG_SYMBOLS ifndef MOZ_DEBUG_SYMBOLS
LDFLAGS += -PDB:NONE LDFLAGS += -PDB:NONE
endif
endif endif
# Purify requires /FIXED:NO when linking EXEs. # Purify requires /FIXED:NO when linking EXEs.
LDFLAGS += /FIXED:NO LDFLAGS += /FIXED:NO
endif endif
ifneq ($(_MSC_VER),$(_MSC_VER_6))
# Convert certain deadly warnings to errors (see list at end of file) # Convert certain deadly warnings to errors (see list at end of file)
OS_CFLAGS += -we4002 -we4003 -we4004 -we4006 -we4009 \ OS_CFLAGS += -we4002 -we4003 -we4004 -we4006 -we4009 -we4013 \
-we4013 -we4015 -we4033 -we4035 -we4045 -we4053 -we4054 -we4063 \ -we4015 -we4028 -we4033 -we4035 -we4045 -we4047 -we4053 -we4054 -we4063 \
-we4064 -we4078 -we4087 -we4098 -we4390 -we4551 -we4553 -we4715 -we4064 -we4078 -we4087 -we4098 -we4390 -we4551 -we4553 -we4715
endif # !MSVC6
endif # NS_USE_GCC endif # NS_USE_GCC
ifdef USE_64 ifdef USE_64
@ -177,6 +177,17 @@ else
DEFINES += -DWIN32 DEFINES += -DWIN32
endif endif
ifeq ($(CPU_ARCH), x386)
ifdef USE_64
DEFINES += -D_AMD64_
else
DEFINES += -D_X86_
endif
endif
ifeq ($(CPU_ARCH), ALPHA)
DEFINES += -D_ALPHA_=1
endif
ifdef MAPFILE ifdef MAPFILE
ifndef NS_USE_GCC ifndef NS_USE_GCC
DLLFLAGS += -DEF:$(MAPFILE) DLLFLAGS += -DEF:$(MAPFILE)
@ -196,10 +207,15 @@ DEFINES += -D_WINDOWS
ifdef NS_USE_GCC ifdef NS_USE_GCC
AS = $(CC) AS = $(CC)
ASFLAGS = $(INCLUDES) ASFLAGS = $(INCLUDES)
else
ifdef USE_64
AS = ml64.exe
ASFLAGS = -Cp -Sn -Zi $(INCLUDES)
else else
AS = ml.exe AS = ml.exe
ASFLAGS = -Cp -Sn -Zi -coff $(INCLUDES) ASFLAGS = -Cp -Sn -Zi -coff $(INCLUDES)
endif endif
endif
# #
# override the definitions of RELEASE_TREE found in tree.mk # override the definitions of RELEASE_TREE found in tree.mk
@ -317,9 +333,11 @@ endif
# 4006: #undef expected an identifier # 4006: #undef expected an identifier
# 4009: string too big; trailing characters truncated # 4009: string too big; trailing characters truncated
# 4015: 'identifier' : type of bit field must be integral # 4015: 'identifier' : type of bit field must be integral
# 4028: formal parameter different from declaration
# 4033: 'function' must return a value # 4033: 'function' must return a value
# 4035: 'function' : no return value # 4035: 'function' : no return value
# 4045: 'identifier' : array bounds overflow # 4045: 'identifier' : array bounds overflow
# 4047: 'function' : 'type 1' differs in levels of indirection from 'type 2'
# 4053: one void operand for '?:' # 4053: one void operand for '?:'
# 4054: 'conversion' : from function pointer 'type1' to data pointer 'type2' # 4054: 'conversion' : from function pointer 'type1' to data pointer 'type2'
# 4059: pascal string too big, length byte is length % 256 # 4059: pascal string too big, length byte is length % 256

Просмотреть файл

@ -16,7 +16,7 @@
# #
# The Initial Developer of the Original Code is # The Initial Developer of the Original Code is
# Netscape Communications Corporation. # Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2000 # Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved. # the Initial Developer. All Rights Reserved.
# #
# Contributor(s): # Contributor(s):
@ -35,9 +35,13 @@
# #
# ***** END LICENSE BLOCK ***** # ***** END LICENSE BLOCK *****
libfreebl_3.so { #
global: # Config stuff for OS_TARGET=WIN95
FREEBL_GetVector; #
local:
*; include $(CORE_DEPTH)/coreconf/WIN32.mk
};
DEFINES += -DWIN95
# WINNT uses the lib prefix, Win95 and WinCE don't
NSPR31_LIB_PREFIX = $(NULL)

Просмотреть файл

@ -36,38 +36,17 @@
# ***** END LICENSE BLOCK ***** # ***** END LICENSE BLOCK *****
# #
# Config stuff for WINNT 4.0 # Config stuff for OS_TARGET=WINNT
# #
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk include $(CORE_DEPTH)/coreconf/WIN32.mk
ifeq ($(CPU_ARCH), x386) DEFINES += -DWINNT
OS_CFLAGS += -W3 -nologo
DEFINES += -D_X86_
else
ifeq ($(CPU_ARCH), MIPS)
#OS_CFLAGS += -W3 -nologo
#DEFINES += -D_MIPS_
OS_CFLAGS += -W3 -nologo
else
ifeq ($(CPU_ARCH), ALPHA)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_ALPHA_=1
endif
endif
endif
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
# #
# Win NT needs -GT so that fibers can work # Win NT needs -GT so that fibers can work
# #
OS_CFLAGS += -GT OS_CFLAGS += -GT
DEFINES += -DWINNT
# WINNT uses the lib prefix, Win95 and WinCE don't
NSPR31_LIB_PREFIX = lib NSPR31_LIB_PREFIX = lib

Просмотреть файл

@ -1,71 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# Config stuff for WINNT 3.51
#
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
# It has the following internal variables:
# OS_PROC_CFLAGS and OS_WIN_CFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk
ifeq ($(CPU_ARCH), x386)
OS_PROC_CFLAGS += -D_X86_
else
ifeq ($(CPU_ARCH), MIPS)
OS_PROC_CFLAGS += -D_MIPS_
else
ifeq ($(CPU_ARCH), ALPHA)
OS_PROC_CFLAGS += -D_ALPHA_
endif
endif
endif
OS_WIN_CFLAGS += -W3
OS_CFLAGS += -nologo $(OS_WIN_CFLAGS) $(OS_PROC_CFLAGS)
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
#
# Win NT needs -GT so that fibers can work
#
OS_CFLAGS += -GT
OS_CFLAGS += -DWINNT

Просмотреть файл

@ -1,73 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# Config stuff for WINNT 5.0 (Windows 2000)
#
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk
ifeq ($(CPU_ARCH), x386)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_X86_
else
ifeq ($(CPU_ARCH), MIPS)
#OS_CFLAGS += -W3 -nologo
#DEFINES += -D_MIPS_
OS_CFLAGS += -W3 -nologo
else
ifeq ($(CPU_ARCH), ALPHA)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_ALPHA_=1
endif
endif
endif
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
#
# Win NT needs -GT so that fibers can work
#
OS_CFLAGS += -GT
DEFINES += -DWINNT
NSPR31_LIB_PREFIX = lib

Просмотреть файл

@ -1,73 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# Config stuff for WINNT 5.1 (Windows XP)
#
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk
ifeq ($(CPU_ARCH), x386)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_X86_
else
ifeq ($(CPU_ARCH), MIPS)
#OS_CFLAGS += -W3 -nologo
#DEFINES += -D_MIPS_
OS_CFLAGS += -W3 -nologo
else
ifeq ($(CPU_ARCH), ALPHA)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_ALPHA_=1
endif
endif
endif
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
#
# Win NT needs -GT so that fibers can work
#
OS_CFLAGS += -GT
DEFINES += -DWINNT
NSPR31_LIB_PREFIX = lib

Просмотреть файл

@ -1,77 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# Config stuff for WINNT 5.2 (Windows Server 2003)
#
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk
ifeq ($(CPU_ARCH), x386)
OS_CFLAGS += -W3 -nologo
ifdef USE_64
DEFINES += -D_AMD64_
else
DEFINES += -D_X86_
endif
else
ifeq ($(CPU_ARCH), MIPS)
#OS_CFLAGS += -W3 -nologo
#DEFINES += -D_MIPS_
OS_CFLAGS += -W3 -nologo
else
ifeq ($(CPU_ARCH), ALPHA)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_ALPHA_=1
endif
endif
endif
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
#
# Win NT needs -GT so that fibers can work
#
OS_CFLAGS += -GT
DEFINES += -DWINNT
NSPR31_LIB_PREFIX = lib

Просмотреть файл

@ -1,78 +0,0 @@
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1994-2000
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Robert Longson <longsonr@gmail.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# Config stuff for WINNT 6.0 (Windows Vista)
#
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk
ifeq ($(CPU_ARCH), x386)
OS_CFLAGS += -W3 -nologo
ifdef USE_64
DEFINES += -D_AMD64_
else
DEFINES += -D_X86_
endif
else
ifeq ($(CPU_ARCH), MIPS)
#OS_CFLAGS += -W3 -nologo
#DEFINES += -D_MIPS_
OS_CFLAGS += -W3 -nologo
else
ifeq ($(CPU_ARCH), ALPHA)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_ALPHA_=1
endif
endif
endif
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif
#
# Win NT needs -GT so that fibers can work
#
OS_CFLAGS += -GT
DEFINES += -DWINNT
NSPR31_LIB_PREFIX = lib

Просмотреть файл

@ -183,9 +183,6 @@ endif
# at lesser performance (the Win95 target uses threads; the WinNT target # at lesser performance (the Win95 target uses threads; the WinNT target
# uses fibers). # uses fibers).
# #
# When OS_TARGET=WIN16 is specified, then a Windows 3.11 (16bit) target
# is built. See: win16_3.11.mk for lots more about the Win16 target.
#
# If OS_TARGET is not specified, it defaults to $(OS_ARCH), i.e., no # If OS_TARGET is not specified, it defaults to $(OS_ARCH), i.e., no
# cross-compilation. # cross-compilation.
# #
@ -298,11 +295,6 @@ ifeq ($(OS_TARGET), WIN95)
OS_RELEASE = 4.0 OS_RELEASE = 4.0
endif endif
ifeq ($(OS_TARGET), WIN16)
OS_RELEASE =
# OS_RELEASE = _3.11
endif
ifdef OS_TARGET_RELEASE ifdef OS_TARGET_RELEASE
OS_RELEASE = $(OS_TARGET_RELEASE) OS_RELEASE = $(OS_TARGET_RELEASE)
endif endif
@ -319,24 +311,12 @@ OS_CONFIG = $(OS_TARGET)$(OS_RELEASE)
# #
ifdef BUILD_OPT ifdef BUILD_OPT
ifeq ($(OS_TARGET),WIN16) OBJDIR_TAG = $(64BIT_TAG)_OPT
OBJDIR_TAG = _O
else
OBJDIR_TAG = $(64BIT_TAG)_OPT
endif
else else
ifdef BUILD_IDG ifdef BUILD_IDG
ifeq ($(OS_TARGET),WIN16) OBJDIR_TAG = $(64BIT_TAG)_IDG
OBJDIR_TAG = _I
else
OBJDIR_TAG = $(64BIT_TAG)_IDG
endif
else else
ifeq ($(OS_TARGET),WIN16) OBJDIR_TAG = $(64BIT_TAG)_DBG
OBJDIR_TAG = _D
else
OBJDIR_TAG = $(64BIT_TAG)_DBG
endif
endif endif
endif endif
@ -351,7 +331,7 @@ endif
OBJDIR_NAME = $(OS_TARGET)$(OS_RELEASE)$(CPU_TAG)$(COMPILER_TAG)$(LIBC_TAG)$(IMPL_STRATEGY)$(OBJDIR_TAG).OBJ OBJDIR_NAME = $(OS_TARGET)$(OS_RELEASE)$(CPU_TAG)$(COMPILER_TAG)$(LIBC_TAG)$(IMPL_STRATEGY)$(OBJDIR_TAG).OBJ
ifeq (,$(filter-out WINNT WIN95 WINCE,$(OS_TARGET))) # list omits WIN16 ifeq (,$(filter-out WIN%,$(OS_TARGET)))
ifndef BUILD_OPT ifndef BUILD_OPT
# #
# Define USE_DEBUG_RTL if you want to use the debug runtime library # Define USE_DEBUG_RTL if you want to use the debug runtime library

Просмотреть файл

@ -63,7 +63,7 @@ endif
####################################################################### #######################################################################
TARGET_OSES = FreeBSD BSD_OS NetBSD OpenUNIX OS2 QNX Darwin BeOS OpenBSD \ TARGET_OSES = FreeBSD BSD_OS NetBSD OpenUNIX OS2 QNX Darwin BeOS OpenBSD \
OpenVMS AIX RISCOS WINCE OpenVMS AIX RISCOS WINNT WIN95 WINCE
ifeq (,$(filter-out $(TARGET_OSES),$(OS_TARGET))) ifeq (,$(filter-out $(TARGET_OSES),$(OS_TARGET)))
include $(CORE_DEPTH)/coreconf/$(OS_TARGET).mk include $(CORE_DEPTH)/coreconf/$(OS_TARGET).mk

Просмотреть файл

@ -44,11 +44,7 @@
# (xp) include paths # (xp) include paths
# #
INCLUDES += -I$(SOURCE_MDHEADERS_DIR) INCLUDES += -I$(SOURCE_MDHEADERS_DIR) -I$(SOURCE_XPHEADERS_DIR)
ifneq ($(OS_TARGET),WIN16)
INCLUDES += -I$(SOURCE_XPHEADERS_DIR)
endif
# #
# Only append source-side private cross-platform include paths for # Only append source-side private cross-platform include paths for

Просмотреть файл

@ -35,43 +35,59 @@
# #
# ***** END LICENSE BLOCK ***** # ***** END LICENSE BLOCK *****
# DEPTH = ../..
# Config stuff for WIN95 CORE_DEPTH = ../..
#
# This makefile defines the following variables:
# OS_CFLAGS and OS_DLLFLAGS.
include $(CORE_DEPTH)/coreconf/WIN32.mk MODULE = coreconf
ifeq ($(CPU_ARCH), x386) CSRCS = \
ifndef NS_USE_GCC cppsetup.c \
OS_CFLAGS += -W3 -nologo ifparser.c \
endif include.c \
ifdef USE_64 main.c \
DEFINES += -D_AMD64_ parse.c \
pr.c
PROGRAM = mkdepend
# Indicate that this directory builds build tools.
INTERNAL_TOOLS = 1
include $(DEPTH)/coreconf/config.mk
TARGETS = $(PROGRAM)
ifeq (,$(filter-out OS2 WIN%,$(OS_TARGET)))
DEFINES += -DNO_X11
else else
DEFINES += -D_X86_ INSTALL = true
endif
else
ifeq ($(CPU_ARCH), MIPS)
#OS_CFLAGS += -W3 -nologo
#DEFINES += -D_MIPS_
OS_CFLAGS += -W3 -nologo
else
ifeq ($(CPU_ARCH), ALPHA)
OS_CFLAGS += -W3 -nologo
DEFINES += -D_ALPHA_=1
endif
endif
endif endif
ifndef NS_USE_GCC ifdef NATIVE_CC
OS_DLLFLAGS += -nologo -DLL -SUBSYSTEM:WINDOWS CC=$(NATIVE_CC)
ifndef MOZ_DEBUG_SYMBOLS
OS_DLLFLAGS += -PDB:NONE
endif endif
endif
DEFINES += -DWIN95
# WINNT uses the lib prefix, Win95 and WinCE don't ifdef NATIVE_FLAGS
NSPR31_LIB_PREFIX = $(NULL) OS_CFLAGS=$(NATIVE_FLAGS)
endif
include $(DEPTH)/coreconf/rules.mk
ifdef GNU_CC
OPTIMIZER = -O3
else
ifeq ($(OS_ARCH),SunOS)
OPTIMIZER = -fast
endif
ifeq ($(OS_ARCH),WINNT)
OPTIMIZER = -Ox
endif
endif
DEFINES += -DINCLUDEDIR=\"/usr/include\" -DOBJSUFFIX=\".$(OBJ_SUFFIX)\"
# Redefine MAKE_OBJDIR for just this directory
define MAKE_OBJDIR
if test ! -d $(@D); then rm -rf $(@D); mkdir $(@D); fi
endef

Просмотреть файл

@ -0,0 +1,233 @@
/* $Xorg: cppsetup.c,v 1.5 2001/02/09 02:03:16 xorgcvs Exp $ */
/*
Copyright (c) 1993, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/config/makedepend/cppsetup.c,v 3.11 2001/12/17 20:52:22 dawes Exp $ */
#include "def.h"
#ifdef CPP
/*
* This file is strictly for the sake of cpy.y and yylex.c (if
* you indeed have the source for cpp).
*/
#define IB 1
#define SB 2
#define NB 4
#define CB 8
#define QB 16
#define WB 32
#define SALT '#'
#if defined(pdp11) || defined(vax) || defined(ns16000) || defined(mc68000) || defined(ibm032)
#define COFF 128
#else
#define COFF 0
#endif
/*
* These variables used by cpy.y and yylex.c
*/
extern char *outp, *inp, *newp, *pend;
extern char *ptrtab;
extern char fastab[];
extern char slotab[];
/*
* cppsetup
*/
struct filepointer *currentfile;
struct inclist *currentinc;
int
cppsetup(char *line, struct filepointer *filep, struct inclist *inc)
{
char *p, savec;
static boolean setupdone = FALSE;
boolean value;
if (!setupdone) {
cpp_varsetup();
setupdone = TRUE;
}
currentfile = filep;
currentinc = inc;
inp = newp = line;
for (p=newp; *p; p++)
;
/*
* put a newline back on the end, and set up pend, etc.
*/
*p++ = '\n';
savec = *p;
*p = '\0';
pend = p;
ptrtab = slotab+COFF;
*--inp = SALT;
outp=inp;
value = yyparse();
*p = savec;
return(value);
}
struct symtab **lookup(symbol)
char *symbol;
{
static struct symtab *undefined;
struct symtab **sp;
sp = isdefined(symbol, currentinc, NULL);
if (sp == NULL) {
sp = &undefined;
(*sp)->s_value = NULL;
}
return (sp);
}
pperror(tag, x0,x1,x2,x3,x4)
int tag,x0,x1,x2,x3,x4;
{
warning("\"%s\", line %d: ", currentinc->i_file, currentfile->f_line);
warning(x0,x1,x2,x3,x4);
}
yyerror(s)
register char *s;
{
fatalerr("Fatal error: %s\n", s);
}
#else /* not CPP */
#include "ifparser.h"
struct _parse_data {
struct filepointer *filep;
struct inclist *inc;
char *filename;
const char *line;
};
static const char *
my_if_errors (IfParser *ip, const char *cp, const char *expecting)
{
struct _parse_data *pd = (struct _parse_data *) ip->data;
int lineno = pd->filep->f_line;
char *filename = pd->filename;
char prefix[300];
int prefixlen;
int i;
sprintf (prefix, "\"%s\":%d", filename, lineno);
prefixlen = strlen(prefix);
fprintf (stderr, "%s: %s", prefix, pd->line);
i = cp - pd->line;
if (i > 0 && pd->line[i-1] != '\n') {
putc ('\n', stderr);
}
for (i += prefixlen + 3; i > 0; i--) {
putc (' ', stderr);
}
fprintf (stderr, "^--- expecting %s\n", expecting);
return NULL;
}
#define MAXNAMELEN 256
static struct symtab **
lookup_variable (IfParser *ip, const char *var, int len)
{
char tmpbuf[MAXNAMELEN + 1];
struct _parse_data *pd = (struct _parse_data *) ip->data;
if (len > MAXNAMELEN)
return 0;
strncpy (tmpbuf, var, len);
tmpbuf[len] = '\0';
return isdefined (tmpbuf, pd->inc, NULL);
}
static int
my_eval_defined (IfParser *ip, const char *var, int len)
{
if (lookup_variable (ip, var, len))
return 1;
else
return 0;
}
#define isvarfirstletter(ccc) (isalpha(ccc) || (ccc) == '_')
static long
my_eval_variable (IfParser *ip, const char *var, int len)
{
long val;
struct symtab **s;
s = lookup_variable (ip, var, len);
if (!s)
return 0;
do {
var = (*s)->s_value;
if (!isvarfirstletter(*var) || !strcmp((*s)->s_name, var))
break;
s = lookup_variable (ip, var, strlen(var));
} while (s);
var = ParseIfExpression(ip, var, &val);
if (var && *var) debug(4, ("extraneous: '%s'\n", var));
return val;
}
int
cppsetup(char *filename,
char *line,
struct filepointer *filep,
struct inclist *inc)
{
IfParser ip;
struct _parse_data pd;
long val = 0;
pd.filep = filep;
pd.inc = inc;
pd.line = line;
pd.filename = filename;
ip.funcs.handle_error = my_if_errors;
ip.funcs.eval_defined = my_eval_defined;
ip.funcs.eval_variable = my_eval_variable;
ip.data = (char *) &pd;
(void) ParseIfExpression (&ip, line, &val);
if (val)
return IF;
else
return IFFALSE;
}
#endif /* CPP */

Просмотреть файл

@ -0,0 +1,184 @@
/* $Xorg: def.h,v 1.4 2001/02/09 02:03:16 xorgcvs Exp $ */
/*
Copyright (c) 1993, 1994, 1998 The Open Group.
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/config/makedepend/def.h,v 3.14 2003/01/17 17:09:49 tsi Exp $ */
#ifndef NO_X11
#include <X11/Xos.h>
#include <X11/Xfuncproto.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#if 0
#ifndef X_NOT_POSIX
#ifndef _POSIX_SOURCE
#define _POSIX_SOURCE
#endif
#endif
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#define MAXDEFINES 512
#define MAXFILES 1024
#define MAXINCFILES 256 /* "-include" files */
#define MAXDIRS 1024
#define SYMTABINC 10 /* must be > 1 for define() to work right */
#define TRUE 1
#define FALSE 0
/* the following must match the directives table in main.c */
#define IF 0
#define IFDEF 1
#define IFNDEF 2
#define ELSE 3
#define ENDIF 4
#define DEFINE 5
#define UNDEF 6
#define INCLUDE 7
#define LINE 8
#define PRAGMA 9
#define ERROR 10
#define IDENT 11
#define SCCS 12
#define ELIF 13
#define EJECT 14
#define WARNING 15
#define INCLUDENEXT 16
#define IFFALSE 17 /* pseudo value --- never matched */
#define ELIFFALSE 18 /* pseudo value --- never matched */
#define INCLUDEDOT 19 /* pseudo value --- never matched */
#define IFGUESSFALSE 20 /* pseudo value --- never matched */
#define ELIFGUESSFALSE 21 /* pseudo value --- never matched */
#define INCLUDENEXTDOT 22 /* pseudo value --- never matched */
#ifdef DEBUG
extern int _debugmask;
/*
* debug levels are:
*
* 0 show ifn*(def)*,endif
* 1 trace defined/!defined
* 2 show #include
* 3 show #include SYMBOL
* 4-6 unused
*/
#define debug(level,arg) { if (_debugmask & (1 << level)) warning arg; }
#else
#define debug(level,arg) /**/
#endif /* DEBUG */
typedef unsigned char boolean;
struct symtab {
char *s_name;
char *s_value;
};
/* possible i_flag */
#define DEFCHECKED (1<<0) /* whether defines have been checked */
#define NOTIFIED (1<<1) /* whether we have revealed includes */
#define MARKED (1<<2) /* whether it's in the makefile */
#define SEARCHED (1<<3) /* whether we have read this */
#define FINISHED (1<<4) /* whether we are done reading this */
#define INCLUDED_SYM (1<<5) /* whether #include SYMBOL was found
Can't use i_list if TRUE */
struct inclist {
char *i_incstring; /* string from #include line */
char *i_file; /* path name of the include file */
struct inclist **i_list; /* list of files it itself includes */
int i_listlen; /* length of i_list */
struct symtab **i_defs; /* symbol table for this file and its
children when merged */
int i_ndefs; /* current # defines */
boolean *i_merged; /* whether we have merged child
defines */
unsigned char i_flags;
};
struct filepointer {
char *f_name;
char *f_p;
char *f_base;
char *f_end;
long f_len;
long f_line;
long cmdinc_count;
char **cmdinc_list;
long cmdinc_line;
};
#include <stdlib.h>
#if defined(macII) && !defined(__STDC__) /* stdlib.h fails to define these */
char *malloc(), *realloc();
#endif /* macII */
char *copy(char *str);
int match(char *str, char **list);
char *base_name(char *file);
char *getnextline(struct filepointer *fp);
struct symtab **slookup(char *symbol, struct inclist *file);
struct symtab **isdefined(char *symbol, struct inclist *file,
struct inclist **srcfile);
struct symtab **fdefined(char *symbol, struct inclist *file,
struct inclist **srcfile);
struct filepointer *getfile(char *file);
void included_by(struct inclist *ip,
struct inclist *newfile);
struct inclist *newinclude(char *newfile, char *incstring);
void inc_clean (void);
struct inclist *inc_path(char *file, char *include, int type);
void freefile(struct filepointer *fp);
void define2(char *name, char *val, struct inclist *file);
void define(char *def, struct inclist *file);
void undefine(char *symbol, struct inclist *file);
int find_includes(struct filepointer *filep,
struct inclist *file,
struct inclist *file_red,
int recursion, boolean failOK);
void recursive_pr_include(struct inclist *head,
char *file, char *base);
void add_include(struct filepointer *filep,
struct inclist *file,
struct inclist *file_red,
char *include, int type,
boolean failOK);
int cppsetup(char *filename,
char *line,
struct filepointer *filep,
struct inclist *inc);
extern void fatalerr(char *, ...);
extern void warning(char *, ...);
extern void warning1(char *, ...);

Просмотреть файл

@ -0,0 +1,551 @@
/*
* $Xorg: ifparser.c,v 1.3 2000/08/17 19:41:50 cpqbld Exp $
*
* Copyright 1992 Network Computing Devices, Inc.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Network Computing Devices may not be
* used in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. Network Computing Devices makes
* no representations about the suitability of this software for any purpose.
* It is provided ``as is'' without express or implied warranty.
*
* NETWORK COMPUTING DEVICES DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
* IN NO EVENT SHALL NETWORK COMPUTING DEVICES BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* Author: Jim Fulton
* Network Computing Devices, Inc.
*
* Simple if statement processor
*
* This module can be used to evaluate string representations of C language
* if constructs. It accepts the following grammar:
*
* EXPRESSION := VALUE
* | VALUE BINOP EXPRESSION
* | VALUE '?' EXPRESSION ':' EXPRESSION
*
* VALUE := '(' EXPRESSION ')'
* | '!' VALUE
* | '-' VALUE
* | '+' VALUE
* | '~' VALUE
* | 'defined' '(' variable ')'
* | 'defined' variable
* | # variable '(' variable-list ')'
* | variable
* | number
*
* BINOP := '*' | '/' | '%'
* | '+' | '-'
* | '<<' | '>>'
* | '<' | '>' | '<=' | '>='
* | '==' | '!='
* | '&' | '^' | '|'
* | '&&' | '||'
*
* The normal C order of precedence is supported.
*
*
* External Entry Points:
*
* ParseIfExpression parse a string for #if
*/
/* $XFree86: xc/config/makedepend/ifparser.c,v 3.11 2002/09/23 01:48:08 tsi Exp $ */
#include "ifparser.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/****************************************************************************
Internal Macros and Utilities for Parser
****************************************************************************/
#define DO(val) if (!(val)) return NULL
#define CALLFUNC(ggg,fff) (*((ggg)->funcs.fff))
#define SKIPSPACE(ccc) while (isspace(*ccc)) ccc++
#define isvarfirstletter(ccc) (isalpha(ccc) || (ccc) == '_')
static const char *
parse_variable (IfParser *g, const char *cp, const char **varp)
{
SKIPSPACE (cp);
if (!isvarfirstletter (*cp))
return CALLFUNC(g, handle_error) (g, cp, "variable name");
*varp = cp;
/* EMPTY */
for (cp++; isalnum(*cp) || *cp == '_'; cp++) ;
return cp;
}
static const char *
parse_number (IfParser *g, const char *cp, long *valp)
{
long base = 10;
SKIPSPACE (cp);
if (!isdigit(*cp))
return CALLFUNC(g, handle_error) (g, cp, "number");
*valp = 0;
if (*cp == '0') {
cp++;
if ((*cp == 'x') || (*cp == 'X')) {
base = 16;
cp++;
} else {
base = 8;
}
}
/* Ignore overflows and assume ASCII, what source is usually written in */
while (1) {
int increment = -1;
if (base == 8) {
if ((*cp >= '0') && (*cp <= '7'))
increment = *cp++ - '0';
} else if (base == 16) {
if ((*cp >= '0') && (*cp <= '9'))
increment = *cp++ - '0';
else if ((*cp >= 'A') && (*cp <= 'F'))
increment = *cp++ - ('A' - 10);
else if ((*cp >= 'a') && (*cp <= 'f'))
increment = *cp++ - ('a' - 10);
} else { /* Decimal */
if ((*cp >= '0') && (*cp <= '9'))
increment = *cp++ - '0';
}
if (increment < 0)
break;
*valp = (*valp * base) + increment;
}
/* Skip trailing qualifiers */
while (*cp == 'U' || *cp == 'u' || *cp == 'L' || *cp == 'l') cp++;
return cp;
}
static const char *
parse_character (IfParser *g, const char *cp, long *valp)
{
char val;
SKIPSPACE (cp);
if (*cp == '\\')
switch (cp[1]) {
case 'n': val = '\n'; break;
case 't': val = '\t'; break;
case 'v': val = '\v'; break;
case 'b': val = '\b'; break;
case 'r': val = '\r'; break;
case 'f': val = '\f'; break;
case 'a': val = '\a'; break;
case '\\': val = '\\'; break;
case '?': val = '\?'; break;
case '\'': val = '\''; break;
case '\"': val = '\"'; break;
case 'x': val = (char) strtol (cp + 2, NULL, 16); break;
default: val = (char) strtol (cp + 1, NULL, 8); break;
}
else
val = *cp;
while (*cp != '\'') cp++;
*valp = (long) val;
return cp;
}
static const char *
parse_value (IfParser *g, const char *cp, long *valp)
{
const char *var, *varend;
*valp = 0;
SKIPSPACE (cp);
if (!*cp)
return cp;
switch (*cp) {
case '(':
DO (cp = ParseIfExpression (g, cp + 1, valp));
SKIPSPACE (cp);
if (*cp != ')')
return CALLFUNC(g, handle_error) (g, cp, ")");
return cp + 1; /* skip the right paren */
case '!':
DO (cp = parse_value (g, cp + 1, valp));
*valp = !(*valp);
return cp;
case '-':
DO (cp = parse_value (g, cp + 1, valp));
*valp = -(*valp);
return cp;
case '+':
DO (cp = parse_value (g, cp + 1, valp));
return cp;
case '~':
DO (cp = parse_value (g, cp + 1, valp));
*valp = ~(*valp);
return cp;
case '#':
DO (cp = parse_variable (g, cp + 1, &var));
SKIPSPACE (cp);
if (*cp != '(')
return CALLFUNC(g, handle_error) (g, cp, "(");
do {
DO (cp = parse_variable (g, cp + 1, &var));
SKIPSPACE (cp);
} while (*cp && *cp != ')');
if (*cp != ')')
return CALLFUNC(g, handle_error) (g, cp, ")");
*valp = 1; /* XXX */
return cp + 1;
case '\'':
DO (cp = parse_character (g, cp + 1, valp));
if (*cp != '\'')
return CALLFUNC(g, handle_error) (g, cp, "'");
return cp + 1;
case 'd':
if (strncmp (cp, "defined", 7) == 0 && !isalnum(cp[7])) {
int paren = 0;
int len;
cp += 7;
SKIPSPACE (cp);
if (*cp == '(') {
paren = 1;
cp++;
}
DO (cp = parse_variable (g, cp, &var));
len = cp - var;
SKIPSPACE (cp);
if (paren && *cp != ')')
return CALLFUNC(g, handle_error) (g, cp, ")");
*valp = (*(g->funcs.eval_defined)) (g, var, len);
return cp + paren; /* skip the right paren */
}
/* fall out */
}
if (isdigit(*cp)) {
DO (cp = parse_number (g, cp, valp));
} else if (!isvarfirstletter(*cp))
return CALLFUNC(g, handle_error) (g, cp, "variable or number");
else {
DO (cp = parse_variable (g, cp, &var));
varend = cp;
SKIPSPACE(cp);
if (*cp != '(') {
*valp = (*(g->funcs.eval_variable)) (g, var, varend - var);
} else {
do {
long dummy;
DO (cp = ParseIfExpression (g, cp + 1, &dummy));
SKIPSPACE(cp);
if (*cp == ')')
break;
if (*cp != ',')
return CALLFUNC(g, handle_error) (g, cp, ",");
} while (1);
*valp = 1; /* XXX */
cp++;
}
}
return cp;
}
static const char *
parse_product (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_value (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '*':
DO (cp = parse_product (g, cp + 1, &rightval));
*valp = (*valp * rightval);
break;
case '/':
DO (cp = parse_product (g, cp + 1, &rightval));
if (rightval == 0)
return CALLFUNC(g, handle_error) (g, cp, "0");
*valp = (*valp / rightval);
break;
case '%':
DO (cp = parse_product (g, cp + 1, &rightval));
*valp = (*valp % rightval);
break;
}
return cp;
}
static const char *
parse_sum (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_product (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '+':
DO (cp = parse_sum (g, cp + 1, &rightval));
*valp = (*valp + rightval);
break;
case '-':
DO (cp = parse_sum (g, cp + 1, &rightval));
*valp = (*valp - rightval);
break;
}
return cp;
}
static const char *
parse_shift (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_sum (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '<':
if (cp[1] == '<') {
DO (cp = parse_shift (g, cp + 2, &rightval));
*valp = (*valp << rightval);
}
break;
case '>':
if (cp[1] == '>') {
DO (cp = parse_shift (g, cp + 2, &rightval));
*valp = (*valp >> rightval);
}
break;
}
return cp;
}
static const char *
parse_inequality (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_shift (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '<':
if (cp[1] == '=') {
DO (cp = parse_inequality (g, cp + 2, &rightval));
*valp = (*valp <= rightval);
} else {
DO (cp = parse_inequality (g, cp + 1, &rightval));
*valp = (*valp < rightval);
}
break;
case '>':
if (cp[1] == '=') {
DO (cp = parse_inequality (g, cp + 2, &rightval));
*valp = (*valp >= rightval);
} else {
DO (cp = parse_inequality (g, cp + 1, &rightval));
*valp = (*valp > rightval);
}
break;
}
return cp;
}
static const char *
parse_equality (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_inequality (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '=':
if (cp[1] == '=')
cp++;
DO (cp = parse_equality (g, cp + 1, &rightval));
*valp = (*valp == rightval);
break;
case '!':
if (cp[1] != '=')
break;
DO (cp = parse_equality (g, cp + 2, &rightval));
*valp = (*valp != rightval);
break;
}
return cp;
}
static const char *
parse_band (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_equality (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '&':
if (cp[1] != '&') {
DO (cp = parse_band (g, cp + 1, &rightval));
*valp = (*valp & rightval);
}
break;
}
return cp;
}
static const char *
parse_bxor (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_band (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '^':
DO (cp = parse_bxor (g, cp + 1, &rightval));
*valp = (*valp ^ rightval);
break;
}
return cp;
}
static const char *
parse_bor (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_bxor (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '|':
if (cp[1] != '|') {
DO (cp = parse_bor (g, cp + 1, &rightval));
*valp = (*valp | rightval);
}
break;
}
return cp;
}
static const char *
parse_land (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_bor (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '&':
if (cp[1] != '&')
return CALLFUNC(g, handle_error) (g, cp, "&&");
DO (cp = parse_land (g, cp + 2, &rightval));
*valp = (*valp && rightval);
break;
}
return cp;
}
static const char *
parse_lor (IfParser *g, const char *cp, long *valp)
{
long rightval;
DO (cp = parse_land (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '|':
if (cp[1] != '|')
return CALLFUNC(g, handle_error) (g, cp, "||");
DO (cp = parse_lor (g, cp + 2, &rightval));
*valp = (*valp || rightval);
break;
}
return cp;
}
static const char *
parse_cond(IfParser *g, const char *cp, long *valp)
{
long trueval, falseval;
DO (cp = parse_lor (g, cp, valp));
SKIPSPACE (cp);
switch (*cp) {
case '?':
DO (cp = parse_cond (g, cp + 1, &trueval));
SKIPSPACE (cp);
if (*cp != ':')
return CALLFUNC(g, handle_error) (g, cp, ":");
DO (cp = parse_cond (g, cp + 1, &falseval));
*valp = (*valp ? trueval : falseval);
break;
}
return cp;
}
/****************************************************************************
External Entry Points
****************************************************************************/
const char *
ParseIfExpression (IfParser *g, const char *cp, long *valp)
{
return parse_cond (g, cp, valp);
}

Просмотреть файл

@ -0,0 +1,83 @@
/*
* $Xorg: ifparser.h,v 1.3 2000/08/17 19:41:51 cpqbld Exp $
*
* Copyright 1992 Network Computing Devices, Inc.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Network Computing Devices may not be
* used in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. Network Computing Devices makes
* no representations about the suitability of this software for any purpose.
* It is provided ``as is'' without express or implied warranty.
*
* NETWORK COMPUTING DEVICES DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
* IN NO EVENT SHALL NETWORK COMPUTING DEVICES BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* Author: Jim Fulton
* Network Computing Devices, Inc.
*
* Simple if statement processor
*
* This module can be used to evaluate string representations of C language
* if constructs. It accepts the following grammar:
*
* EXPRESSION := VALUE
* | VALUE BINOP EXPRESSION
* | VALUE '?' EXPRESSION ':' EXPRESSION
*
* VALUE := '(' EXPRESSION ')'
* | '!' VALUE
* | '-' VALUE
* | '~' VALUE
* | 'defined' '(' variable ')'
* | variable
* | number
*
* BINOP := '*' | '/' | '%'
* | '+' | '-'
* | '<<' | '>>'
* | '<' | '>' | '<=' | '>='
* | '==' | '!='
* | '&' | '^' | '|'
* | '&&' | '||'
*
* The normal C order of precedence is supported.
*
*
* External Entry Points:
*
* ParseIfExpression parse a string for #if
*/
/* $XFree86: xc/config/makedepend/ifparser.h,v 3.5 2001/07/25 15:04:40 dawes Exp $ */
#include <stdio.h>
typedef int Bool;
#define False 0
#define True 1
typedef struct _if_parser {
struct { /* functions */
const char *(*handle_error) (struct _if_parser *, const char *,
const char *);
long (*eval_variable) (struct _if_parser *, const char *, int);
int (*eval_defined) (struct _if_parser *, const char *, int);
} funcs;
char *data;
} IfParser;
const char *ParseIfExpression (
IfParser *,
const char *,
long *
);

Просмотреть файл

@ -0,0 +1,782 @@
/* $XConsortium: imakemdep.h,v 1.83 95/04/07 19:47:46 kaleb Exp $ */
/* $XFree86: xc/config/imake/imakemdep.h,v 3.12 1995/07/08 10:22:17 dawes Exp $ */
/*
Copyright (c) 1993, 1994 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*/
/*
* This file contains machine-dependent constants for the imake utility.
* When porting imake, read each of the steps below and add in any necessary
* definitions. In general you should *not* edit ccimake.c or imake.c!
*/
#ifdef CCIMAKE
/*
* Step 1: imake_ccflags
* Define any special flags that will be needed to get imake.c to compile.
* These will be passed to the compile along with the contents of the
* make variable BOOTSTRAPCFLAGS.
*/
#ifdef hpux
#ifdef hp9000s800
#define imake_ccflags "-DSYSV"
#else
#define imake_ccflags "-Wc,-Nd4000,-Ns3000 -DSYSV"
#endif
#endif
#if defined(macII) || defined(_AUX_SOURCE)
#define imake_ccflags "-DmacII -DSYSV"
#endif
#ifdef stellar
#define imake_ccflags "-DSYSV"
#endif
#if defined(USL) || defined(Oki) || defined(NCR)
#define imake_ccflags "-Xc -DSVR4"
#endif
#ifdef sony
#if defined(SYSTYPE_SYSV) || defined(_SYSTYPE_SYSV)
#define imake_ccflags "-DSVR4"
#else
#include <sys/param.h>
#if NEWSOS < 41
#define imake_ccflags "-Dbsd43 -DNOSTDHDRS"
#else
#if NEWSOS < 42
#define imake_ccflags "-Dbsd43"
#endif
#endif
#endif
#endif
#ifdef _CRAY
#define imake_ccflags "-DSYSV -DUSG"
#endif
#if defined(_IBMR2) || defined(aix)
#define imake_ccflags "-Daix -DSYSV"
#endif
#ifdef Mips
# if defined(SYSTYPE_BSD) || defined(BSD) || defined(BSD43)
# define imake_ccflags "-DBSD43"
# else
# define imake_ccflags "-DSYSV"
# endif
#endif
#ifdef is68k
#define imake_ccflags "-Dluna -Duniosb"
#endif
#ifdef SYSV386
# ifdef SVR4
# define imake_ccflags "-Xc -DSVR4"
# else
# define imake_ccflags "-DSYSV"
# endif
#endif
#ifdef SVR4
# ifdef i386
# define imake_ccflags "-Xc -DSVR4"
# endif
#endif
#ifdef SYSV
# ifdef i386
# define imake_ccflags "-DSYSV"
# endif
#endif
#ifdef __convex__
#define imake_ccflags "-fn -tm c1"
#endif
#ifdef apollo
#define imake_ccflags "-DX_NOT_POSIX"
#endif
#ifdef WIN32
#define imake_ccflags "-nologo -batch -D__STDC__"
#endif
#ifdef __uxp__
#define imake_ccflags "-DSVR4 -DANSICPP"
#endif
#ifdef __sxg__
#define imake_ccflags "-DSYSV -DUSG -DNOSTDHDRS"
#endif
#ifdef sequent
#define imake_ccflags "-DX_NOT_STDC_ENV -DX_NOT_POSIX"
#endif
#ifdef _SEQUENT_
#define imake_ccflags "-DSYSV -DUSG"
#endif
#if defined(SX) || defined(PC_UX)
#define imake_ccflags "-DSYSV"
#endif
#ifdef nec_ews_svr2
#define imake_ccflags "-DUSG"
#endif
#if defined(nec_ews_svr4) || defined(_nec_ews_svr4) || defined(_nec_up) || defined(_nec_ft)
#define imake_ccflags "-DSVR4"
#endif
#ifdef MACH
#define imake_ccflags "-DNOSTDHDRS"
#endif
/* this is for OS/2 under EMX. This won't work with DOS */
#if defined(__EMX__)
#define imake_ccflags "-DBSD43"
#endif
#else /* not CCIMAKE */
#ifndef MAKEDEPEND
/*
* Step 2: dup2
* If your OS doesn't have a dup2() system call to duplicate one file
* descriptor onto another, define such a mechanism here (if you don't
* already fall under the existing category(ies).
*/
#if defined(SYSV) && !defined(_CRAY) && !defined(Mips) && !defined(_SEQUENT_)
#define dup2(fd1,fd2) ((fd1 == fd2) ? fd1 : (close(fd2), \
fcntl(fd1, F_DUPFD, fd2)))
#endif
/*
* Step 3: FIXUP_CPP_WHITESPACE
* If your cpp collapses tabs macro expansions into a single space and
* replaces escaped newlines with a space, define this symbol. This will
* cause imake to attempt to patch up the generated Makefile by looking
* for lines that have colons in them (this is why the rules file escapes
* all colons). One way to tell if you need this is to see whether or not
* your Makefiles have no tabs in them and lots of @@ strings.
*/
#if defined(sun) || defined(SYSV) || defined(SVR4) || defined(hcx) || defined(WIN32) || (defined(AMOEBA) && defined(CROSS_COMPILE))
#define FIXUP_CPP_WHITESPACE
#endif
#ifdef WIN32
#define REMOVE_CPP_LEADSPACE
#define INLINE_SYNTAX
#define MAGIC_MAKE_VARS
#endif
#ifdef __minix_vmd
#define FIXUP_CPP_WHITESPACE
#endif
/*
* Step 4: USE_CC_E, DEFAULT_CC, DEFAULT_CPP
* If you want to use cc -E instead of cpp, define USE_CC_E.
* If use cc -E but want a different compiler, define DEFAULT_CC.
* If the cpp you need is not in /lib/cpp, define DEFAULT_CPP.
*/
#ifdef hpux
#define USE_CC_E
#endif
#ifdef WIN32
#define USE_CC_E
#define DEFAULT_CC "cl"
#endif
#ifdef apollo
#define DEFAULT_CPP "/usr/lib/cpp"
#endif
#if defined(_IBMR2) && !defined(DEFAULT_CPP)
#define DEFAULT_CPP "/usr/lpp/X11/Xamples/util/cpp/cpp"
#endif
#if defined(sun) && defined(SVR4)
#define DEFAULT_CPP "/usr/ccs/lib/cpp"
#endif
#ifdef __bsdi__
#define DEFAULT_CPP "/usr/bin/cpp"
#endif
#ifdef __uxp__
#define DEFAULT_CPP "/usr/ccs/lib/cpp"
#endif
#ifdef __sxg__
#define DEFAULT_CPP "/usr/lib/cpp"
#endif
#ifdef _CRAY
#define DEFAULT_CPP "/lib/pcpp"
#endif
#if defined(__386BSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#define DEFAULT_CPP "/usr/libexec/cpp"
#endif
#ifdef MACH
#define USE_CC_E
#endif
#ifdef __minix_vmd
#define DEFAULT_CPP "/usr/lib/cpp"
#endif
#if defined(__EMX__)
/* expects cpp in PATH */
#define DEFAULT_CPP "cpp"
#endif
/*
* Step 5: cpp_argv
* The following table contains the flags that should be passed
* whenever a Makefile is being generated. If your preprocessor
* doesn't predefine any unique symbols, choose one and add it to the
* end of this table. Then, do the following:
*
* a. Use this symbol in Imake.tmpl when setting MacroFile.
* b. Put this symbol in the definition of BootstrapCFlags in your
* <platform>.cf file.
* c. When doing a make World, always add "BOOTSTRAPCFLAGS=-Dsymbol"
* to the end of the command line.
*
* Note that you may define more than one symbol (useful for platforms
* that support multiple operating systems).
*/
#define ARGUMENTS 50 /* number of arguments in various arrays */
char *cpp_argv[ARGUMENTS] = {
"cc", /* replaced by the actual program to exec */
"-I.", /* add current directory to include path */
#ifdef unix
"-Uunix", /* remove unix symbol so that filename unix.c okay */
#endif
#if defined(__386BSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(MACH)
# ifdef __i386__
"-D__i386__",
# endif
# ifdef __x86_64__
"-D__x86_64__",
# endif
# ifdef __GNUC__
"-traditional",
# endif
#endif
#ifdef M4330
"-DM4330", /* Tektronix */
#endif
#ifdef M4310
"-DM4310", /* Tektronix */
#endif
#if defined(macII) || defined(_AUX_SOURCE)
"-DmacII", /* Apple A/UX */
#endif
#ifdef USL
"-DUSL", /* USL */
#endif
#ifdef sony
"-Dsony", /* Sony */
#if !defined(SYSTYPE_SYSV) && !defined(_SYSTYPE_SYSV) && NEWSOS < 42
"-Dbsd43",
#endif
#endif
#ifdef _IBMR2
"-D_IBMR2", /* IBM RS-6000 (we ensured that aix is defined above */
#ifndef aix
#define aix /* allow BOOTSTRAPCFLAGS="-D_IBMR2" */
#endif
#endif /* _IBMR2 */
#ifdef aix
"-Daix", /* AIX instead of AOS */
#ifndef ibm
#define ibm /* allow BOOTSTRAPCFLAGS="-Daix" */
#endif
#endif /* aix */
#ifdef ibm
"-Dibm", /* IBM PS/2 and RT under both AOS and AIX */
#endif
#ifdef luna
"-Dluna", /* OMRON luna 68K and 88K */
#ifdef luna1
"-Dluna1",
#endif
#ifdef luna88k /* need not on UniOS-Mach Vers. 1.13 */
"-traditional", /* for some older version */
#endif /* instead of "-DXCOMM=\\#" */
#ifdef uniosb
"-Duniosb",
#endif
#ifdef uniosu
"-Duniosu",
#endif
#endif /* luna */
#ifdef _CRAY /* Cray */
"-Ucray",
#endif
#ifdef Mips
"-DMips", /* Define and use Mips for Mips Co. OS/mach. */
# if defined(SYSTYPE_BSD) || defined(BSD) || defined(BSD43)
"-DBSD43", /* Mips RISCOS supports two environments */
# else
"-DSYSV", /* System V environment is the default */
# endif
#endif /* Mips */
#ifdef MOTOROLA
"-DMOTOROLA", /* Motorola Delta Systems */
# ifdef SYSV
"-DSYSV",
# endif
# ifdef SVR4
"-DSVR4",
# endif
#endif /* MOTOROLA */
#ifdef i386
"-Di386",
# ifdef SVR4
"-DSVR4",
# endif
# ifdef SYSV
"-DSYSV",
# ifdef ISC
"-DISC",
# ifdef ISC40
"-DISC40", /* ISC 4.0 */
# else
# ifdef ISC202
"-DISC202", /* ISC 2.0.2 */
# else
# ifdef ISC30
"-DISC30", /* ISC 3.0 */
# else
"-DISC22", /* ISC 2.2.1 */
# endif
# endif
# endif
# endif
# ifdef SCO
"-DSCO",
# ifdef SCO324
"-DSCO324",
# endif
# endif
# endif
# ifdef ESIX
"-DESIX",
# endif
# ifdef ATT
"-DATT",
# endif
# ifdef DELL
"-DDELL",
# endif
#endif
#ifdef SYSV386 /* System V/386 folks, obsolete */
"-Di386",
# ifdef SVR4
"-DSVR4",
# endif
# ifdef ISC
"-DISC",
# ifdef ISC40
"-DISC40", /* ISC 4.0 */
# else
# ifdef ISC202
"-DISC202", /* ISC 2.0.2 */
# else
# ifdef ISC30
"-DISC30", /* ISC 3.0 */
# else
"-DISC22", /* ISC 2.2.1 */
# endif
# endif
# endif
# endif
# ifdef SCO
"-DSCO",
# ifdef SCO324
"-DSCO324",
# endif
# endif
# ifdef ESIX
"-DESIX",
# endif
# ifdef ATT
"-DATT",
# endif
# ifdef DELL
"-DDELL",
# endif
#endif
#ifdef __osf__
"-D__osf__",
# ifdef __mips__
"-D__mips__",
# endif
# ifdef __alpha
"-D__alpha",
# endif
# ifdef __i386__
"-D__i386__",
# endif
# ifdef __GNUC__
"-traditional",
# endif
#endif
#ifdef Oki
"-DOki",
#endif
#ifdef sun
#ifdef SVR4
"-DSVR4",
#endif
#endif
#ifdef WIN32
"-DWIN32",
"-nologo",
"-batch",
"-D__STDC__",
#endif
#ifdef NCR
"-DNCR", /* NCR */
#endif
#ifdef linux
"-traditional",
"-Dlinux",
#endif
#ifdef __uxp__
"-D__uxp__",
#endif
#ifdef __sxg__
"-D__sxg__",
#endif
#ifdef nec_ews_svr2
"-Dnec_ews_svr2",
#endif
#ifdef AMOEBA
"-DAMOEBA",
# ifdef CROSS_COMPILE
"-DCROSS_COMPILE",
# ifdef CROSS_i80386
"-Di80386",
# endif
# ifdef CROSS_sparc
"-Dsparc",
# endif
# ifdef CROSS_mc68000
"-Dmc68000",
# endif
# else
# ifdef i80386
"-Di80386",
# endif
# ifdef sparc
"-Dsparc",
# endif
# ifdef mc68000
"-Dmc68000",
# endif
# endif
#endif
#ifdef __minix_vmd
"-Dminix",
#endif
#if defined(__EMX__)
"-traditional",
"-Demxos2",
#endif
};
#else /* else MAKEDEPEND */
/*
* Step 6: predefs
* If your compiler and/or preprocessor define any specific symbols, add
* them to the the following table. The definition of struct symtab is
* in util/makedepend/def.h.
*/
#define QUOTEIT(x) #x
#define QUOTEEXPANSION(x) QUOTEIT(x)
struct symtab predefs[] = {
#ifdef apollo
{"apollo", "1"},
#endif
#ifdef ibm032
{"ibm032", "1"},
#endif
#ifdef ibm
{"ibm", "1"},
#endif
#ifdef aix
{"aix", "1"},
#endif
#ifdef sun
{"sun", "1"},
#endif
#ifdef sun2
{"sun2", "1"},
#endif
#ifdef sun3
{"sun3", "1"},
#endif
#ifdef sun4
{"sun4", "1"},
#endif
#ifdef sparc
{"sparc", "1"},
#endif
#ifdef __sparc__
{"__sparc__", "1"},
#endif
#ifdef hpux
{"hpux", "1"},
#endif
#ifdef __hpux
{"__hpux", "1"},
#endif
#ifdef __hp9000s800
{"__hp9000s800", "1"},
#endif
#ifdef __hp9000s700
{"__hp9000s700", "1"},
#endif
#ifdef vax
{"vax", "1"},
#endif
#ifdef VMS
{"VMS", "1"},
#endif
#ifdef cray
{"cray", "1"},
#endif
#ifdef CRAY
{"CRAY", "1"},
#endif
#ifdef _CRAY
{"_CRAY", "1"},
#endif
#ifdef att
{"att", "1"},
#endif
#ifdef mips
{"mips", "1"},
#endif
#ifdef __mips__
{"__mips__", "1"},
#endif
#ifdef ultrix
{"ultrix", "1"},
#endif
#ifdef stellar
{"stellar", "1"},
#endif
#ifdef mc68000
{"mc68000", "1"},
#endif
#ifdef mc68020
{"mc68020", "1"},
#endif
#ifdef __GNUC__
{"__GNUC__", "1"},
#endif
#if __STDC__
{"__STDC__", "1"},
#endif
#ifdef __HIGHC__
{"__HIGHC__", "1"},
#endif
#ifdef CMU
{"CMU", "1"},
#endif
#ifdef luna
{"luna", "1"},
#ifdef luna1
{"luna1", "1"},
#endif
#ifdef luna2
{"luna2", "1"},
#endif
#ifdef luna88k
{"luna88k", "1"},
#endif
#ifdef uniosb
{"uniosb", "1"},
#endif
#ifdef uniosu
{"uniosu", "1"},
#endif
#endif
#ifdef ieeep754
{"ieeep754", "1"},
#endif
#ifdef is68k
{"is68k", "1"},
#endif
#ifdef m68k
{"m68k", "1"},
#endif
#ifdef m88k
{"m88k", "1"},
#endif
#ifdef __m88k__
{"__m88k__", "1"},
#endif
#ifdef bsd43
{"bsd43", "1"},
#endif
#ifdef hcx
{"hcx", "1"},
#endif
#ifdef sony
{"sony", "1"},
#ifdef SYSTYPE_SYSV
{"SYSTYPE_SYSV", "1"},
#endif
#ifdef _SYSTYPE_SYSV
{"_SYSTYPE_SYSV", "1"},
#endif
#endif
#ifdef __OSF__
{"__OSF__", "1"},
#endif
#ifdef __osf__
{"__osf__", "1"},
#endif
#ifdef __alpha
{"__alpha", "1"},
#endif
#ifdef __DECC
{"__DECC", "1"},
#endif
#ifdef __decc
{"__decc", "1"},
#endif
#ifdef __uxp__
{"__uxp__", "1"},
#endif
#ifdef __sxg__
{"__sxg__", "1"},
#endif
#ifdef _SEQUENT_
{"_SEQUENT_", "1"},
{"__STDC__", "1"},
#endif
#ifdef __bsdi__
{"__bsdi__", "1"},
#endif
#ifdef nec_ews_svr2
{"nec_ews_svr2", "1"},
#endif
#ifdef nec_ews_svr4
{"nec_ews_svr4", "1"},
#endif
#ifdef _nec_ews_svr4
{"_nec_ews_svr4", "1"},
#endif
#ifdef _nec_up
{"_nec_up", "1"},
#endif
#ifdef SX
{"SX", "1"},
#endif
#ifdef nec
{"nec", "1"},
#endif
#ifdef _nec_ft
{"_nec_ft", "1"},
#endif
#ifdef PC_UX
{"PC_UX", "1"},
#endif
#ifdef sgi
{"sgi", "1"},
#endif
#ifdef __sgi
{"__sgi", "1"},
#endif
#ifdef __FreeBSD__
{"__FreeBSD__", "1"},
#endif
#ifdef __NetBSD__
{"__NetBSD__", "1"},
#endif
#ifdef __OpenBSD__
{"__OpenBSD__", "1"},
#endif
#ifdef __EMX__
{"__EMX__", "1"},
#endif
/* ADDED THE FOLLOWING SYMBOLS FOR WINDOWS */
#ifdef _WIN32
{"_WIN32", QUOTEEXPANSION(_WIN32) },
#endif
#ifdef _WIN64
{"_WIN64", QUOTEEXPANSION(_WIN64) },
#endif
#ifdef _X86
{"_X86", QUOTEEXPANSION(_X86) },
#endif
#ifdef _X86_
{"_X86_", QUOTEEXPANSION(_X86_) },
#endif
#ifdef _X86_64
{"_X86_64", QUOTEEXPANSION(_X86_64) },
#endif
#ifdef _X86_64_
{"_X86_64_", QUOTEEXPANSION(_X86_64_) },
#endif
#ifdef _DEBUG
{"_DEBUG", QUOTEEXPANSION(_DEBUG) },
#endif
#ifdef _DLL
{"_DLL", QUOTEEXPANSION(_DLL) },
#endif
#ifdef _M_IX86
{"_M_IX86", QUOTEEXPANSION(_M_IX86) },
#endif
#ifdef _M_X64
{"_M_X64", QUOTEEXPANSION(_M_X64) },
#endif
#ifdef _MSC_FULL_VER
{"_MSC_FULL_VER", QUOTEEXPANSION(_MSC_FULL_VER) },
#endif
#ifdef _MSC_VER
{"_MSC_VER", QUOTEEXPANSION(_MSC_VER) },
#endif
#ifdef _MSVC_RUNTIME_CHECKS
{"_MSVC_RUNTIME_CHECKS", QUOTEEXPANSION(_MSVC_RUNTIME_CHECKS) },
#endif
#ifdef _MT
{"_MT", QUOTEEXPANSION(_MT) },
#endif
#ifdef _CHAR_UNSIGNED
{"_CHAR_UNSIGNED", QUOTEEXPANSION(_CHAR_UNSIGNED) },
#endif
/* add any additional symbols before this line */
{NULL, NULL}
};
#endif /* MAKEDEPEND */
#endif /* CCIMAKE */

Просмотреть файл

@ -0,0 +1,337 @@
/* $Xorg: include.c,v 1.4 2001/02/09 02:03:16 xorgcvs Exp $ */
/*
Copyright (c) 1993, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/config/makedepend/include.c,v 3.7 2001/12/14 19:53:20 dawes Exp $ */
#include "def.h"
#ifdef _MSC_VER
#include <windows.h>
static int
does_file_exist(char *file)
{
WIN32_FILE_ATTRIBUTE_DATA data;
BOOL b = GetFileAttributesExA(file, GetFileExInfoStandard, &data);
if (!b)
return 0;
return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
#else
static int
does_file_exist(char *file)
{
struct stat sb;
return stat(file, &sb) == 0 && !S_ISDIR(sb.st_mode);
}
#endif
extern struct inclist inclist[ MAXFILES ],
*inclistp, *inclistnext;
extern char *includedirs[ ],
**includedirsnext;
extern char *notdotdot[ ];
extern boolean show_where_not;
extern boolean warn_multiple;
static boolean
isdot(char *p)
{
if(p && *p++ == '.' && *p++ == '\0')
return(TRUE);
return(FALSE);
}
static boolean
isdotdot(char *p)
{
if(p && *p++ == '.' && *p++ == '.' && *p++ == '\0')
return(TRUE);
return(FALSE);
}
static boolean
issymbolic(char *dir, char *component)
{
#ifdef S_IFLNK
struct stat st;
char buf[ BUFSIZ ], **pp;
sprintf(buf, "%s%s%s", dir, *dir ? "/" : "", component);
for (pp=notdotdot; *pp; pp++)
if (strcmp(*pp, buf) == 0)
return (TRUE);
if (lstat(buf, &st) == 0
&& (st.st_mode & S_IFMT) == S_IFLNK) {
*pp++ = copy(buf);
if (pp >= &notdotdot[ MAXDIRS ])
fatalerr("out of .. dirs, increase MAXDIRS\n");
return(TRUE);
}
#endif
return(FALSE);
}
/*
* Occasionally, pathnames are created that look like .../x/../y
* Any of the 'x/..' sequences within the name can be eliminated.
* (but only if 'x' is not a symbolic link!!)
*/
static void
remove_dotdot(char *path)
{
register char *end, *from, *to, **cp;
char *components[ MAXFILES ],
newpath[ BUFSIZ ];
boolean component_copied;
/*
* slice path up into components.
*/
to = newpath;
if (*path == '/')
*to++ = '/';
*to = '\0';
cp = components;
for (from=end=path; *end; end++)
if (*end == '/') {
while (*end == '/')
*end++ = '\0';
if (*from)
*cp++ = from;
from = end;
}
*cp++ = from;
*cp = NULL;
/*
* Recursively remove all 'x/..' component pairs.
*/
cp = components;
while(*cp) {
if (!isdot(*cp) && !isdotdot(*cp) && isdotdot(*(cp+1))
&& !issymbolic(newpath, *cp))
{
char **fp = cp + 2;
char **tp = cp;
do
*tp++ = *fp; /* move all the pointers down */
while (*fp++);
if (cp != components)
cp--; /* go back and check for nested ".." */
} else {
cp++;
}
}
/*
* Concatenate the remaining path elements.
*/
cp = components;
component_copied = FALSE;
while(*cp) {
if (component_copied)
*to++ = '/';
component_copied = TRUE;
for (from = *cp; *from; )
*to++ = *from++;
*to = '\0';
cp++;
}
*to++ = '\0';
/*
* copy the reconstituted path back to our pointer.
*/
strcpy(path, newpath);
}
/*
* Add an include file to the list of those included by 'file'.
*/
struct inclist *
newinclude(char *newfile, char *incstring)
{
register struct inclist *ip;
/*
* First, put this file on the global list of include files.
*/
ip = inclistp++;
if (inclistp == inclist + MAXFILES - 1)
fatalerr("out of space: increase MAXFILES\n");
ip->i_file = copy(newfile);
if (incstring == NULL)
ip->i_incstring = ip->i_file;
else
ip->i_incstring = copy(incstring);
inclistnext = inclistp;
return(ip);
}
void
included_by(struct inclist *ip, struct inclist *newfile)
{
register int i;
if (ip == NULL)
return;
/*
* Put this include file (newfile) on the list of files included
* by 'file'. If 'file' is NULL, then it is not an include
* file itself (i.e. was probably mentioned on the command line).
* If it is already on the list, don't stick it on again.
*/
if (ip->i_list == NULL) {
ip->i_list = (struct inclist **)
malloc(sizeof(struct inclist *) * ++ip->i_listlen);
ip->i_merged = (boolean *)
malloc(sizeof(boolean) * ip->i_listlen);
} else {
for (i=0; i<ip->i_listlen; i++)
if (ip->i_list[ i ] == newfile) {
i = strlen(newfile->i_file);
if (!(ip->i_flags & INCLUDED_SYM) &&
!(i > 2 &&
newfile->i_file[i-1] == 'c' &&
newfile->i_file[i-2] == '.'))
{
/* only bitch if ip has */
/* no #include SYMBOL lines */
/* and is not a .c file */
if (warn_multiple)
{
warning("%s includes %s more than once!\n",
ip->i_file, newfile->i_file);
warning1("Already have\n");
for (i=0; i<ip->i_listlen; i++)
warning1("\t%s\n", ip->i_list[i]->i_file);
}
}
return;
}
ip->i_list = (struct inclist **) realloc(ip->i_list,
sizeof(struct inclist *) * ++ip->i_listlen);
ip->i_merged = (boolean *)
realloc(ip->i_merged, sizeof(boolean) * ip->i_listlen);
}
ip->i_list[ ip->i_listlen-1 ] = newfile;
ip->i_merged[ ip->i_listlen-1 ] = FALSE;
}
void
inc_clean (void)
{
register struct inclist *ip;
for (ip = inclist; ip < inclistp; ip++) {
ip->i_flags &= ~MARKED;
}
}
struct inclist *
inc_path(char *file, char *include, int type)
{
static char path[ BUFSIZ ];
register char **pp, *p;
register struct inclist *ip;
/*
* Check all previously found include files for a path that
* has already been expanded.
*/
if ((type == INCLUDE) || (type == INCLUDEDOT))
inclistnext = inclist;
ip = inclistnext;
for (; ip->i_file; ip++) {
if ((strcmp(ip->i_incstring, include) == 0) &&
!(ip->i_flags & INCLUDED_SYM)) {
inclistnext = ip + 1;
return ip;
}
}
if (inclistnext == inclist) {
/*
* If the path was surrounded by "" or is an absolute path,
* then check the exact path provided.
*/
if ((type == INCLUDEDOT) ||
(type == INCLUDENEXTDOT) ||
(*include == '/')) {
if (does_file_exist(include))
return newinclude(include, include);
if (show_where_not)
warning1("\tnot in %s\n", include);
}
/*
* If the path was surrounded by "" see if this include file is
* in the directory of the file being parsed.
*/
if ((type == INCLUDEDOT) || (type == INCLUDENEXTDOT)) {
for (p=file+strlen(file); p>file; p--)
if (*p == '/')
break;
if (p == file) {
strcpy(path, include);
} else {
strncpy(path, file, (p-file) + 1);
path[ (p-file) + 1 ] = '\0';
strcpy(path + (p-file) + 1, include);
}
remove_dotdot(path);
if (does_file_exist(path))
return newinclude(path, include);
if (show_where_not)
warning1("\tnot in %s\n", path);
}
}
/*
* Check the include directories specified. Standard include dirs
* should be at the end.
*/
if ((type == INCLUDE) || (type == INCLUDEDOT))
includedirsnext = includedirs;
pp = includedirsnext;
for (; *pp; pp++) {
sprintf(path, "%s/%s", *pp, include);
remove_dotdot(path);
if (does_file_exist(path)) {
includedirsnext = pp + 1;
return newinclude(path, include);
}
if (show_where_not)
warning1("\tnot in %s\n", path);
}
return NULL;
}

Просмотреть файл

@ -0,0 +1,870 @@
/* $Xorg: main.c,v 1.5 2001/02/09 02:03:16 xorgcvs Exp $ */
/*
Copyright (c) 1993, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/config/makedepend/main.c,v 3.32 2003/03/26 20:43:48 tsi Exp $ */
#include "def.h"
#ifdef hpux
#define sigvec sigvector
#endif /* hpux */
#ifdef X_POSIX_C_SOURCE
#define _POSIX_C_SOURCE X_POSIX_C_SOURCE
#include <signal.h>
#undef _POSIX_C_SOURCE
#else
#if defined(X_NOT_POSIX) || defined(_POSIX_SOURCE)
#include <signal.h>
#else
#define _POSIX_SOURCE
#include <signal.h>
#undef _POSIX_SOURCE
#endif
#endif
#include <stdarg.h>
#ifdef _WIN32
#include <io.h>
#endif
#ifdef MINIX
#define USE_CHMOD 1
#endif
#ifdef DEBUG
int _debugmask;
#endif
/* #define DEBUG_DUMP */
#ifdef DEBUG_DUMP
#define DBG_PRINT(file, fmt, args) fprintf(file, fmt, args)
#else
#define DBG_PRINT(file, fmt, args) /* empty */
#endif
#define DASH_INC_PRE "#include \""
#define DASH_INC_POST "\""
char *ProgramName;
char *directives[] = {
"if",
"ifdef",
"ifndef",
"else",
"endif",
"define",
"undef",
"include",
"line",
"pragma",
"error",
"ident",
"sccs",
"elif",
"eject",
"warning",
"include_next",
NULL
};
#define MAKEDEPEND
#include "imakemdep.h" /* from config sources */
#undef MAKEDEPEND
struct inclist inclist[ MAXFILES ],
*inclistp = inclist,
*inclistnext = inclist,
maininclist;
static char *filelist[ MAXFILES ];
char *includedirs[ MAXDIRS + 1 ],
**includedirsnext = includedirs;
char *notdotdot[ MAXDIRS ];
static int cmdinc_count = 0;
static char *cmdinc_list[ 2 * MAXINCFILES ];
char *objprefix = "";
char *objsuffix = OBJSUFFIX;
static char *startat = "# DO NOT DELETE";
int width = 78;
static boolean append = FALSE;
boolean printed = FALSE;
boolean verbose = FALSE;
boolean show_where_not = FALSE;
/* Warn on multiple includes of same file */
boolean warn_multiple = FALSE;
static void setfile_cmdinc(struct filepointer *filep, long count, char **list);
static void redirect(char *line, char *makefile);
static
#ifdef SIGNALRETURNSINT
int
#else
void
#endif
catch (int sig)
{
fflush (stdout);
fatalerr ("got signal %d\n", sig);
}
#if defined(USG) || (defined(i386) && defined(SYSV)) || defined(WIN32) || defined(__UNIXOS2__) || defined(Lynx_22) || defined(__CYGWIN__)
#define USGISH
#endif
#ifndef USGISH
#ifdef X_NOT_POSIX
#define sigaction sigvec
#define sa_handler sv_handler
#define sa_mask sv_mask
#define sa_flags sv_flags
#endif
struct sigaction sig_act;
#endif /* USGISH */
int
main(int argc, char *argv[])
{
char **fp = filelist;
char **incp = includedirs;
char *p;
struct inclist *ip;
char *makefile = NULL;
struct filepointer *filecontent;
struct symtab *psymp = predefs;
char *endmarker = NULL;
char *defincdir = NULL;
char **undeflist = NULL;
int numundefs = 0, i;
register char offset;
ProgramName = argv[0];
while (psymp->s_name)
{
define2(psymp->s_name, psymp->s_value, &maininclist);
psymp++;
}
if (argc == 2 && argv[1][0] == '@') {
struct stat ast;
int afd;
char *args;
char **nargv;
int nargc;
char quotechar = '\0';
nargc = 1;
if ((afd = open(argv[1]+1, O_RDONLY)) < 0)
fatalerr("cannot open \"%s\"\n", argv[1]+1);
fstat(afd, &ast);
args = (char *)malloc(ast.st_size + 1);
if ((ast.st_size = read(afd, args, ast.st_size)) < 0)
fatalerr("failed to read %s\n", argv[1]+1);
args[ast.st_size] = '\0';
close(afd);
for (p = args; *p; p++) {
if (quotechar) {
if (quotechar == '\\' ||
(*p == quotechar && p[-1] != '\\'))
quotechar = '\0';
continue;
}
switch (*p) {
case '\\':
case '"':
case '\'':
quotechar = *p;
break;
case ' ':
case '\n':
*p = '\0';
if (p > args && p[-1])
nargc++;
break;
}
}
if (p[-1])
nargc++;
nargv = (char **)malloc(nargc * sizeof(char *));
nargv[0] = argv[0];
argc = 1;
for (p = args; argc < nargc; p += strlen(p) + 1)
if (*p) nargv[argc++] = p;
argv = nargv;
}
for(argc--, argv++; argc; argc--, argv++) {
/* if looking for endmarker then check before parsing */
if (endmarker && strcmp (endmarker, *argv) == 0) {
endmarker = NULL;
continue;
}
if (**argv != '-') {
/* treat +thing as an option for C++ */
if (endmarker && **argv == '+')
continue;
*fp++ = argv[0];
continue;
}
switch(argv[0][1]) {
case '-':
endmarker = &argv[0][2];
if (endmarker[0] == '\0') endmarker = "--";
break;
case 'D':
offset = 2;
if (argv[0][2] == '\0') {
argv++;
argc--;
offset = 0;
}
/* offset +1 here since first def letter
* cannot be `=`
*/
for (p = argv[0] + offset + 1; *p; p++)
if (*p == '=') {
*p = ' ';
break;
}
define(argv[0] + offset, &maininclist);
break;
case 'I':
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many -I flags.\n");
*incp++ = argv[0]+2;
if (**(incp-1) == '\0') {
*(incp-1) = *(++argv);
argc--;
}
break;
case 'U':
/* Undef's override all -D's so save them up */
numundefs++;
if (numundefs == 1)
undeflist = malloc(sizeof(char *));
else
undeflist = realloc(undeflist,
numundefs * sizeof(char *));
offset = 2;
if (argv[0][2] == '\0') {
argv++;
argc--;
offset = 0;
}
undeflist[numundefs - 1] = argv[0] + offset;
break;
case 'Y':
defincdir = argv[0]+2;
break;
/* do not use if endmarker processing */
case 'a':
if (endmarker) break;
append = TRUE;
break;
case 'w':
if (endmarker) break;
if (argv[0][2] == '\0') {
argv++;
argc--;
width = atoi(argv[0]);
} else
width = atoi(argv[0]+2);
break;
case 'o':
if (endmarker) break;
if (argv[0][2] == '\0') {
argv++;
argc--;
objsuffix = argv[0];
} else
objsuffix = argv[0]+2;
break;
case 'p':
if (endmarker) break;
if (argv[0][2] == '\0') {
argv++;
argc--;
objprefix = argv[0];
} else
objprefix = argv[0]+2;
break;
case 'v':
if (endmarker) break;
verbose = TRUE;
#ifdef DEBUG
if (argv[0][2])
_debugmask = atoi(argv[0]+2);
#endif
break;
case 's':
if (endmarker) break;
startat = argv[0]+2;
if (*startat == '\0') {
startat = *(++argv);
argc--;
}
if (*startat != '#')
fatalerr("-s flag's value should start %s\n",
"with '#'.");
break;
case 'f':
if (endmarker) break;
makefile = argv[0]+2;
if (*makefile == '\0') {
makefile = *(++argv);
argc--;
}
break;
case 'm':
warn_multiple = TRUE;
break;
/* Ignore -O, -g so we can just pass ${CFLAGS} to
makedepend
*/
case 'O':
case 'g':
break;
case 'i':
if (strcmp(&argv[0][1],"include") == 0) {
char *buf;
if (argc<2)
fatalerr("option -include is a "
"missing its parameter\n");
if (cmdinc_count >= MAXINCFILES)
fatalerr("Too many -include flags.\n");
argc--;
argv++;
buf = malloc(strlen(DASH_INC_PRE) +
strlen(argv[0]) +
strlen(DASH_INC_POST) + 1);
if(!buf)
fatalerr("out of memory at "
"-include string\n");
cmdinc_list[2 * cmdinc_count + 0] = argv[0];
cmdinc_list[2 * cmdinc_count + 1] = buf;
cmdinc_count++;
break;
}
/* intentional fall through */
default:
if (endmarker) break;
/* fatalerr("unknown opt = %s\n", argv[0]); */
warning("ignoring option %s\n", argv[0]);
}
}
/* Now do the undefs from the command line */
for (i = 0; i < numundefs; i++)
undefine(undeflist[i], &maininclist);
if (numundefs > 0)
free(undeflist);
if (!defincdir) {
#ifdef PREINCDIR
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many -I flags.\n");
*incp++ = PREINCDIR;
#endif
#if defined(__UNIXOS2__) || defined(_MSC_VER)
{
#if defined(_MSC_VER)
char *includepath = getenv("INCLUDE");
#else
char *includepath = getenv("C_INCLUDE_PATH");
#endif
/* can have more than one component */
if (includepath) {
char *beg, *end;
beg= (char*)strdup(includepath);
for (;;) {
end = (char*)strchr(beg,';');
if (end) *end = 0;
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many include dirs\n");
*incp++ = beg;
if (!end) break;
beg = end+1;
}
}
}
#else /* !__UNIXOS2__ && !_MSC_VER, does not use INCLUDEDIR at all */
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many -I flags.\n");
*incp++ = INCLUDEDIR;
#endif
#ifdef EXTRAINCDIR
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many -I flags.\n");
*incp++ = EXTRAINCDIR;
#endif
#ifdef POSTINCDIR
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many -I flags.\n");
*incp++ = POSTINCDIR;
#endif
} else if (*defincdir) {
if (incp >= includedirs + MAXDIRS)
fatalerr("Too many -I flags.\n");
*incp++ = defincdir;
}
redirect(startat, makefile);
/*
* catch signals.
*/
#ifdef USGISH
/* should really reset SIGINT to SIG_IGN if it was. */
#ifdef SIGHUP
signal (SIGHUP, catch);
#endif
signal (SIGINT, catch);
#ifdef SIGQUIT
signal (SIGQUIT, catch);
#endif
signal (SIGILL, catch);
#ifdef SIGBUS
signal (SIGBUS, catch);
#endif
signal (SIGSEGV, catch);
#ifdef SIGSYS
signal (SIGSYS, catch);
#endif
#else
sig_act.sa_handler = catch;
#if defined(_POSIX_SOURCE) || !defined(X_NOT_POSIX)
sigemptyset(&sig_act.sa_mask);
sigaddset(&sig_act.sa_mask, SIGINT);
sigaddset(&sig_act.sa_mask, SIGQUIT);
#ifdef SIGBUS
sigaddset(&sig_act.sa_mask, SIGBUS);
#endif
sigaddset(&sig_act.sa_mask, SIGILL);
sigaddset(&sig_act.sa_mask, SIGSEGV);
sigaddset(&sig_act.sa_mask, SIGHUP);
sigaddset(&sig_act.sa_mask, SIGPIPE);
#ifdef SIGSYS
sigaddset(&sig_act.sa_mask, SIGSYS);
#endif
#else
sig_act.sa_mask = ((1<<(SIGINT -1))
|(1<<(SIGQUIT-1))
#ifdef SIGBUS
|(1<<(SIGBUS-1))
#endif
|(1<<(SIGILL-1))
|(1<<(SIGSEGV-1))
|(1<<(SIGHUP-1))
|(1<<(SIGPIPE-1))
#ifdef SIGSYS
|(1<<(SIGSYS-1))
#endif
);
#endif /* _POSIX_SOURCE */
sig_act.sa_flags = 0;
sigaction(SIGHUP, &sig_act, (struct sigaction *)0);
sigaction(SIGINT, &sig_act, (struct sigaction *)0);
sigaction(SIGQUIT, &sig_act, (struct sigaction *)0);
sigaction(SIGILL, &sig_act, (struct sigaction *)0);
#ifdef SIGBUS
sigaction(SIGBUS, &sig_act, (struct sigaction *)0);
#endif
sigaction(SIGSEGV, &sig_act, (struct sigaction *)0);
#ifdef SIGSYS
sigaction(SIGSYS, &sig_act, (struct sigaction *)0);
#endif
#endif /* USGISH */
/*
* now peruse through the list of files.
*/
for(fp=filelist; *fp; fp++) {
DBG_PRINT(stderr,"file: %s\n",*fp);
filecontent = getfile(*fp);
setfile_cmdinc(filecontent, cmdinc_count, cmdinc_list);
ip = newinclude(*fp, (char *)NULL);
find_includes(filecontent, ip, ip, 0, FALSE);
freefile(filecontent);
recursive_pr_include(ip, ip->i_file, base_name(*fp));
inc_clean();
}
if (printed)
printf("\n");
return 0;
}
#ifdef __UNIXOS2__
/*
* eliminate \r chars from file
*/
static int
elim_cr(char *buf, int sz)
{
int i,wp;
for (i= wp = 0; i<sz; i++) {
if (buf[i] != '\r')
buf[wp++] = buf[i];
}
return wp;
}
#endif
struct filepointer *
getfile(char *file)
{
int fd;
struct filepointer *content;
struct stat st;
content = (struct filepointer *)malloc(sizeof(struct filepointer));
content->f_name = file;
if ((fd = open(file, O_RDONLY)) < 0) {
warning("cannot open \"%s\"\n", file);
content->f_p = content->f_base = content->f_end = (char *)malloc(1);
*content->f_p = '\0';
return(content);
}
fstat(fd, &st);
content->f_base = (char *)malloc(st.st_size+1);
if (content->f_base == NULL)
fatalerr("cannot allocate mem\n");
if ((st.st_size = read(fd, content->f_base, st.st_size)) < 0)
fatalerr("failed to read %s\n", file);
#ifdef __UNIXOS2__
st.st_size = elim_cr(content->f_base,st.st_size);
#endif
close(fd);
content->f_len = st.st_size+1;
content->f_p = content->f_base;
content->f_end = content->f_base + st.st_size;
*content->f_end = '\0';
content->f_line = 0;
content->cmdinc_count = 0;
content->cmdinc_list = NULL;
content->cmdinc_line = 0;
return(content);
}
void
setfile_cmdinc(struct filepointer* filep, long count, char** list)
{
filep->cmdinc_count = count;
filep->cmdinc_list = list;
filep->cmdinc_line = 0;
}
void
freefile(struct filepointer *fp)
{
free(fp->f_base);
free(fp);
}
char *copy(char *str)
{
char *p = (char *)malloc(strlen(str) + 1);
strcpy(p, str);
return(p);
}
int
match(char *str, char **list)
{
int i;
for (i=0; *list; i++, list++)
if (strcmp(str, *list) == 0)
return(i);
return(-1);
}
/*
* Get the next line. We only return lines beginning with '#' since that
* is all this program is ever interested in.
*/
char *getnextline(struct filepointer *filep)
{
char *p, /* walking pointer */
*eof, /* end of file pointer */
*bol; /* beginning of line pointer */
int lineno; /* line number */
boolean whitespace = FALSE;
/*
* Fake the "-include" line files in form of #include to the
* start of each file.
*/
if (filep->cmdinc_line < filep->cmdinc_count) {
char *inc = filep->cmdinc_list[2 * filep->cmdinc_line + 0];
char *buf = filep->cmdinc_list[2 * filep->cmdinc_line + 1];
filep->cmdinc_line++;
sprintf(buf,"%s%s%s",DASH_INC_PRE,inc,DASH_INC_POST);
DBG_PRINT(stderr,"%s\n",buf);
return(buf);
}
p = filep->f_p;
eof = filep->f_end;
if (p >= eof)
return((char *)NULL);
lineno = filep->f_line;
for (bol = p--; ++p < eof; ) {
if ((bol == p) && ((*p == ' ') || (*p == '\t')))
{
/* Consume leading white-spaces for this line */
while (((p+1) < eof) && ((*p == ' ') || (*p == '\t')))
{
p++;
bol++;
}
whitespace = TRUE;
}
if (*p == '/' && (p+1) < eof && *(p+1) == '*') {
/* Consume C comments */
*(p++) = ' ';
*(p++) = ' ';
while (p < eof && *p) {
if (*p == '*' && (p+1) < eof && *(p+1) == '/') {
*(p++) = ' ';
*(p++) = ' ';
break;
}
if (*p == '\n')
lineno++;
*(p++) = ' ';
}
--p;
}
else if (*p == '/' && (p+1) < eof && *(p+1) == '/') {
/* Consume C++ comments */
*(p++) = ' ';
*(p++) = ' ';
while (p < eof && *p) {
if (*p == '\\' && (p+1) < eof &&
*(p+1) == '\n') {
*(p++) = ' ';
lineno++;
}
else if (*p == '?' && (p+3) < eof &&
*(p+1) == '?' &&
*(p+2) == '/' &&
*(p+3) == '\n') {
*(p++) = ' ';
*(p++) = ' ';
*(p++) = ' ';
lineno++;
}
else if (*p == '\n')
break; /* to process end of line */
*(p++) = ' ';
}
--p;
}
else if (*p == '\\' && (p+1) < eof && *(p+1) == '\n') {
/* Consume backslash line terminations */
*(p++) = ' ';
*p = ' ';
lineno++;
}
else if (*p == '?' && (p+3) < eof &&
*(p+1) == '?' && *(p+2) == '/' && *(p+3) == '\n') {
/* Consume trigraph'ed backslash line terminations */
*(p++) = ' ';
*(p++) = ' ';
*(p++) = ' ';
*p = ' ';
lineno++;
}
else if (*p == '\n') {
lineno++;
if (*bol == '#') {
char *cp;
*(p++) = '\0';
/* punt lines with just # (yacc generated) */
for (cp = bol+1;
*cp && (*cp == ' ' || *cp == '\t'); cp++);
if (*cp) goto done;
--p;
}
bol = p+1;
whitespace = FALSE;
}
}
if (*bol != '#')
bol = NULL;
done:
#if !defined(__UNIXOS2__) && !defined(_MSC_VER) && !defined(_WIN32)
/* Don't print warnings for system header files */
if (bol && whitespace && !strstr(filep->f_name, INCLUDEDIR)) {
warning("%s: non-portable whitespace encountered at line %d\n",
filep->f_name, lineno);
}
#endif
filep->f_p = p;
filep->f_line = lineno;
#ifdef DEBUG_DUMP
if (bol)
DBG_PRINT(stderr,"%s\n",bol);
#endif
return(bol);
}
/*
* Strip the file name down to what we want to see in the Makefile.
* It will have objprefix and objsuffix around it.
*/
char *base_name(char *file)
{
char *p;
file = copy(file);
for(p=file+strlen(file); p>file && *p != '.'; p--) ;
if (*p == '.')
*p = '\0';
return(file);
}
#if defined(USG) && !defined(CRAY) && !defined(SVR4) && !defined(__UNIXOS2__) && !defined(clipper) && !defined(__clipper__)
int rename (char *from, char *to)
{
(void) unlink (to);
if (link (from, to) == 0) {
unlink (from);
return 0;
} else {
return -1;
}
}
#endif /* USGISH */
void
redirect(char *line, char *makefile)
{
struct stat st;
FILE *fdin, *fdout;
char backup[ BUFSIZ ],
buf[ BUFSIZ ];
boolean found = FALSE;
int len;
/*
* if makefile is "-" then let it pour onto stdout.
*/
if (makefile && *makefile == '-' && *(makefile+1) == '\0') {
puts(line);
return;
}
/*
* use a default makefile is not specified.
*/
if (!makefile) {
if (stat("Makefile", &st) == 0)
makefile = "Makefile";
else if (stat("makefile", &st) == 0)
makefile = "makefile";
else
fatalerr("[mM]akefile is not present\n");
}
else
stat(makefile, &st);
if ((fdin = fopen(makefile, "r")) == NULL)
fatalerr("cannot open \"%s\"\n", makefile);
sprintf(backup, "%s.bak", makefile);
unlink(backup);
#if defined(WIN32) || defined(__UNIXOS2__) || defined(__CYGWIN__)
fclose(fdin);
#endif
if (rename(makefile, backup) < 0)
fatalerr("cannot rename %s to %s\n", makefile, backup);
#if defined(WIN32) || defined(__UNIXOS2__) || defined(__CYGWIN__)
if ((fdin = fopen(backup, "r")) == NULL)
fatalerr("cannot open \"%s\"\n", backup);
#endif
if ((fdout = freopen(makefile, "w", stdout)) == NULL)
fatalerr("cannot open \"%s\"\n", backup);
len = strlen(line);
while (!found && fgets(buf, BUFSIZ, fdin)) {
if (*buf == '#' && strncmp(line, buf, len) == 0)
found = TRUE;
fputs(buf, fdout);
}
if (!found) {
if (verbose)
warning("Adding new delimiting line \"%s\" and dependencies...\n",
line);
puts(line); /* same as fputs(fdout); but with newline */
} else if (append) {
while (fgets(buf, BUFSIZ, fdin)) {
fputs(buf, fdout);
}
}
fflush(fdout);
#if defined(USGISH) || defined(_SEQUENT_) || defined(USE_CHMOD)
chmod(makefile, st.st_mode);
#else
fchmod(fileno(fdout), st.st_mode);
#endif /* USGISH */
}
void
fatalerr(char *msg, ...)
{
va_list args;
fprintf(stderr, "%s: error: ", ProgramName);
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
exit (1);
}
void
warning(char *msg, ...)
{
va_list args;
fprintf(stderr, "%s: warning: ", ProgramName);
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
}
void
warning1(char *msg, ...)
{
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
}

Просмотреть файл

@ -0,0 +1,382 @@
.\" $Xorg: mkdepend.man,v 1.5 2001/02/09 02:03:16 xorgcvs Exp $
.\" Copyright (c) 1993, 1994, 1998 The Open Group
.\"
.\" Permission to use, copy, modify, distribute, and sell this software and its
.\" documentation for any purpose is hereby granted without fee, provided that
.\" the above copyright notice appear in all copies and that both that
.\" copyright notice and this permission notice appear in supporting
.\" documentation.
.\"
.\" The above copyright notice and this permission notice shall be included in
.\" all copies or substantial portions of the Software.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
.\" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
.\" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
.\" THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
.\" WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
.\" OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
.\" SOFTWARE.
.\"
.\" Except as contained in this notice, the name of The Open Group shall not
.\" be used in advertising or otherwise to promote the sale, use or other
.\" dealing in this Software without prior written authorization from The
.\" Open Group.
.\"
.\" $XFree86: xc/config/makedepend/mkdepend.man,v 1.7 2002/12/14 02:39:45 dawes Exp $
.\"
.TH MAKEDEPEND 1 __xorgversion__
.UC 4
.SH NAME
makedepend \- create dependencies in makefiles
.SH SYNOPSIS
.B makedepend
[
.BI \-D name\fB=\fPdef
] [
.BI \-D name
] [
.BI \-I includedir
] [
.BI \-Y includedir
] [
.B \-a
] [
.BI \-f makefile
] [
.BI \-include \ file
] [
.BI \-o objsuffix
] [
.BI \-p objprefix
] [
.BI \-s string
] [
.BI \-w width
] [
.B \-v
] [
.B \-m
] [
\-\^\-
.I otheroptions
\-\^\-
]
.I sourcefile
\&.\|.\|.
.br
.SH DESCRIPTION
The
.B makedepend
program reads each
.I sourcefile
in sequence and parses it like a C-preprocessor,
processing all
.I #include,
.I #define,
.I #undef,
.I #ifdef,
.I #ifndef,
.I #endif,
.I #if,
.I #elif
and
.I #else
directives so that it can correctly tell which
.I #include,
directives would be used in a compilation.
Any
.I #include,
directives can reference files having other
.I #include
directives, and parsing will occur in these files as well.
.PP
Every file that a
.I sourcefile
includes,
directly or indirectly,
is what
.B makedepend
calls a \fIdependency.\fP
These dependencies are then written to a
.I makefile
in such a way that
.B make(1)
will know which object files must be recompiled when a dependency has changed.
.PP
By default,
.B makedepend
places its output in the file named
.I makefile
if it exists, otherwise
.I Makefile.
An alternate makefile may be specified with the
.B \-f
option.
It first searches the makefile for
the line
.sp
\& # DO NOT DELETE THIS LINE \-\^\- make depend depends on it.
.sp
or one provided with the
.B \-s
option,
as a delimiter for the dependency output.
If it finds it, it will delete everything
following this to the end of the makefile
and put the output after this line.
If it doesn't find it, the program
will append the string to the end of the makefile
and place the output following that.
For each
.I sourcefile
appearing on the command line,
.B makedepend
puts lines in the makefile of the form
.sp
sourcefile.o:\0dfile .\|.\|.
.sp
Where \fIsourcefile.o\fP is the name from the command
line with its suffix replaced with ``.o'',
and \fIdfile\fP is a dependency discovered in a
.I #include
directive while parsing
.I sourcefile
or one of the files it included.
.SH EXAMPLE
Normally,
.B makedepend
will be used in a makefile target so that typing ``make depend'' will
bring the dependencies up to date for the makefile.
For example,
.nf
SRCS\0=\0file1.c\0file2.c\0.\|.\|.
CFLAGS\0=\0\-O\0\-DHACK\0\-I\^.\^.\^/foobar\0\-xyz
depend:
makedepend\0\-\^\-\0$(CFLAGS)\0\-\^\-\0$(SRCS)
.fi
.SH OPTIONS
The program
will ignore any option that it does not understand so that you may use
the same arguments that you would for
.B cc(1).
.TP 5
.B \-D\fIname\fP=\fIdef\fP \fRor\fP \-D\fIname\fP
Define.
This places a definition for
.I name
in
.B makedepend's
symbol table.
Without
.I =def\|
the symbol becomes defined as ``1''.
.TP 5
.B \-I\fIincludedir\fP
Include directory.
This option tells
.B makedepend
to prepend
.I includedir
to its list of directories to search when it encounters
a
.I #include
directive.
By default,
.B makedepend
only searches the standard include directories (usually /usr/include
and possibly a compiler-dependent directory).
.TP 5
.B \-Y\fIincludedir\fP
Replace all of the standard include directories with the single specified
include directory; you can omit the
.I includedir
to simply prevent searching the standard include directories.
.TP 5
.B \-a
Append the dependencies to the end of the file instead of replacing them.
.TP 5
.B \-f\fImakefile\fP
Filename.
This allows you to specify an alternate makefile in which
.B makedepend
can place its output.
Specifying ``\-'' as the file name (i.e., \fB\-f\-\fP) sends the
output to standard output instead of modifying an existing file.
.TP 5
.B \-include \fIfile\fP
Process file as input, and include all the resulting output
before processing the regular input file. This has the same
affect as if the specified file is an include statement that
appears before the very first line of the regular input file.
.TP 5
.B \-o\fIobjsuffix\fP
Object file suffix.
Some systems may have object files whose suffix is something other
than ``.o''.
This option allows you to specify another suffix, such as
``.b'' with
.I \-o.b
or ``:obj''
with
.I \-o:obj
and so forth.
.TP 5
.B \-p\fIobjprefix\fP
Object file prefix.
The prefix is prepended to the name of the object file. This is
usually used to designate a different directory for the object file.
The default is the empty string.
.TP 5
.B \-s\fIstring\fP
Starting string delimiter.
This option permits you to specify
a different string for
.B makedepend
to look for in the makefile.
.TP 5
.B \-w\fIwidth\fP
Line width.
Normally,
.B makedepend
will ensure that every output line that it writes will be no wider than
78 characters for the sake of readability.
This option enables you to change this width.
.TP 5
.B \-v
Verbose operation.
This option causes
.B makedepend
to emit the list of files included by each input file.
.TP 5
.B \-m
Warn about multiple inclusion.
This option causes
.B makedepend
to produce a warning if any input file includes another file more than
once. In previous versions of
.B makedepend
this was the default behavior; the default has been changed to better
match the behavior of the C compiler, which does not consider multiple
inclusion to be an error. This option is provided for backward
compatibility, and to aid in debugging problems related to multiple
inclusion.
.TP 5
.B "\-\^\- \fIoptions\fP \-\^\-"
If
.B makedepend
encounters a double hyphen (\-\^\-) in the argument list,
then any unrecognized argument following it
will be silently ignored; a second double hyphen terminates this
special treatment.
In this way,
.B makedepend
can be made to safely ignore esoteric compiler arguments that might
normally be found in a CFLAGS
.B make
macro (see the
.B EXAMPLE
section above).
All options that
.B makedepend
recognizes and appear between the pair of double hyphens
are processed normally.
.SH ALGORITHM
The approach used in this program enables it to run an order of magnitude
faster than any other ``dependency generator'' I have ever seen.
Central to this performance are two assumptions:
that all files compiled by a single
makefile will be compiled with roughly the same
.I \-I
and
.I \-D
options;
and that most files in a single directory will include largely the
same files.
.PP
Given these assumptions,
.B makedepend
expects to be called once for each makefile, with
all source files that are maintained by the
makefile appearing on the command line.
It parses each source and include
file exactly once, maintaining an internal symbol table
for each.
Thus, the first file on the command line will take an amount of time
proportional to the amount of time that a normal C preprocessor takes.
But on subsequent files, if it encounters an include file
that it has already parsed, it does not parse it again.
.PP
For example,
imagine you are compiling two files,
.I file1.c
and
.I file2.c,
they each include the header file
.I header.h,
and the file
.I header.h
in turn includes the files
.I def1.h
and
.I def2.h.
When you run the command
.sp
makedepend\0file1.c\0file2.c
.sp
.B makedepend
will parse
.I file1.c
and consequently,
.I header.h
and then
.I def1.h
and
.I def2.h.
It then decides that the dependencies for this file are
.sp
file1.o:\0header.h\0def1.h\0def2.h
.sp
But when the program parses
.I file2.c
and discovers that it, too, includes
.I header.h,
it does not parse the file,
but simply adds
.I header.h,
.I def1.h
and
.I def2.h
to the list of dependencies for
.I file2.o.
.SH "SEE ALSO"
cc(1), make(1)
.SH BUGS
.B makedepend
parses, but does not currently evaluate, the SVR4 #predicate(token-list)
preprocessor expression; such expressions are simply assumed to be true.
This may cause the wrong
.I #include
directives to be evaluated.
.PP
Imagine you are parsing two files,
say
.I file1.c
and
.I file2.c,
each includes the file
.I def.h.
The list of files that
.I def.h
includes might truly be different when
.I def.h
is included by
.I file1.c
than when it is included by
.I file2.c.
But once
.B makedepend
arrives at a list of dependencies for a file,
it is cast in concrete.
.SH AUTHOR
Todd Brunhoff, Tektronix, Inc. and MIT Project Athena

Просмотреть файл

@ -0,0 +1,686 @@
/* $Xorg: parse.c,v 1.6 2001/02/09 02:03:16 xorgcvs Exp $ */
/*
Copyright (c) 1993, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/config/makedepend/parse.c,v 1.12 2002/02/26 05:09:10 tsi Exp $ */
#include "def.h"
extern char *directives[];
extern struct inclist inclist[ MAXFILES ],
*inclistnext,
maininclist;
extern char *includedirs[ ],
**includedirsnext;
static int deftype (char *line, struct filepointer *filep,
struct inclist *file_red, struct inclist *file,
int parse_it);
static int zero_value(char *filename, char *exp, struct filepointer *filep,
struct inclist *file_red);
static int merge2defines(struct inclist *file1, struct inclist *file2);
static int
gobble(struct filepointer *filep, struct inclist *file,
struct inclist *file_red)
{
char *line;
int type;
while ((line = getnextline(filep))) {
switch(type = deftype(line, filep, file_red, file, FALSE)) {
case IF:
case IFFALSE:
case IFGUESSFALSE:
case IFDEF:
case IFNDEF:
type = gobble(filep, file, file_red);
while ((type == ELIF) || (type == ELIFFALSE) ||
(type == ELIFGUESSFALSE))
type = gobble(filep, file, file_red);
if (type == ELSE)
(void)gobble(filep, file, file_red);
break;
case ELSE:
case ENDIF:
debug(0,("%s, line %d: #%s\n",
file->i_file, filep->f_line,
directives[type]));
return(type);
case DEFINE:
case UNDEF:
case INCLUDE:
case INCLUDEDOT:
case PRAGMA:
case ERROR:
case IDENT:
case SCCS:
case EJECT:
case WARNING:
case INCLUDENEXT:
case INCLUDENEXTDOT:
break;
case ELIF:
case ELIFFALSE:
case ELIFGUESSFALSE:
return(type);
case -1:
warning("%s", file_red->i_file);
if (file_red != file)
warning1(" (reading %s)", file->i_file);
warning1(", line %d: unknown directive == \"%s\"\n",
filep->f_line, line);
break;
}
}
return(-1);
}
/*
* Decide what type of # directive this line is.
*/
static int
deftype (char *line, struct filepointer *filep,
struct inclist *file_red, struct inclist *file, int parse_it)
{
register char *p;
char *directive, savechar, *q;
register int ret;
/*
* Parse the directive...
*/
directive=line+1;
while (*directive == ' ' || *directive == '\t')
directive++;
p = directive;
while ((*p == '_') || (*p >= 'a' && *p <= 'z'))
p++;
savechar = *p;
*p = '\0';
ret = match(directive, directives);
*p = savechar;
/* If we don't recognize this compiler directive or we happen to just
* be gobbling up text while waiting for an #endif or #elif or #else
* in the case of an #elif we must check the zero_value and return an
* ELIF or an ELIFFALSE.
*/
if (ret == ELIF && !parse_it)
{
while (*p == ' ' || *p == '\t')
p++;
/*
* parse an expression.
*/
debug(0,("%s, line %d: #elif %s ",
file->i_file, filep->f_line, p));
ret = zero_value(file->i_file, p, filep, file_red);
if (ret != IF)
{
debug(0,("false...\n"));
if (ret == IFFALSE)
return(ELIFFALSE);
else
return(ELIFGUESSFALSE);
}
else
{
debug(0,("true...\n"));
return(ELIF);
}
}
if (ret < 0 || ! parse_it)
return(ret);
/*
* now decide how to parse the directive, and do it.
*/
while (*p == ' ' || *p == '\t')
p++;
q = p + strlen(p);
do {
q--;
} while (*q == ' ' || *q == '\t');
q[1] = '\0';
switch (ret) {
case IF:
/*
* parse an expression.
*/
ret = zero_value(file->i_file, p, filep, file_red);
debug(0,("%s, line %d: %s #if %s\n",
file->i_file, filep->f_line, ret?"false":"true", p));
break;
case IFDEF:
case IFNDEF:
debug(0,("%s, line %d: #%s %s\n",
file->i_file, filep->f_line, directives[ret], p));
case UNDEF:
/*
* separate the name of a single symbol.
*/
while (isalnum(*p) || *p == '_')
*line++ = *p++;
*line = '\0';
break;
case INCLUDE:
case INCLUDENEXT:
debug(2,("%s, line %d: #include%s %s\n",
file->i_file, filep->f_line,
(ret == INCLUDE) ? "" : "_next", p));
/* Support ANSI macro substitution */
while (1) {
struct symtab **sym;
if (!*p || *p == '"' || *p == '<')
break;
sym = isdefined(p, file_red, NULL);
if (!sym)
break;
p = (*sym)->s_value;
debug(3,("%s : #includes SYMBOL %s = %s\n",
file->i_incstring,
(*sym) -> s_name,
(*sym) -> s_value));
/* mark file as having included a 'soft include' */
file->i_flags |= INCLUDED_SYM;
}
/*
* Separate the name of the include file.
*/
while (*p && *p != '"' && *p != '<')
p++;
if (! *p)
return(-2);
if (*p++ == '"') {
if (ret == INCLUDE)
ret = INCLUDEDOT;
else
ret = INCLUDENEXTDOT;
while (*p && *p != '"')
*line++ = *p++;
} else
while (*p && *p != '>')
*line++ = *p++;
*line = '\0';
break;
case DEFINE:
/*
* copy the definition back to the beginning of the line.
*/
strcpy (line, p);
break;
case ELSE:
case ENDIF:
case ELIF:
case PRAGMA:
case ERROR:
case IDENT:
case SCCS:
case EJECT:
case WARNING:
debug(0,("%s, line %d: #%s\n",
file->i_file, filep->f_line, directives[ret]));
/*
* nothing to do.
*/
break;
}
return(ret);
}
struct symtab **
fdefined(char *symbol, struct inclist *file, struct inclist **srcfile)
{
struct inclist **ip;
struct symtab **val;
int i;
static int recurse_lvl = 0;
if (file->i_flags & DEFCHECKED)
return(NULL);
debug(2,("Looking for %s in %s\n", symbol, file->i_file));
file->i_flags |= DEFCHECKED;
if ((val = slookup(symbol, file)))
debug(1,("%s defined in %s as %s\n",
symbol, file->i_file, (*val)->s_value));
if (val == NULL && file->i_list)
{
for (ip = file->i_list, i=0; i < file->i_listlen; i++, ip++)
if (file->i_merged[i]==FALSE) {
val = fdefined(symbol, *ip, srcfile);
file->i_merged[i]=merge2defines(file,*ip);
if (val!=NULL) break;
}
}
else if (val != NULL && srcfile != NULL) *srcfile = file;
recurse_lvl--;
file->i_flags &= ~DEFCHECKED;
return(val);
}
struct symtab **
isdefined(char *symbol, struct inclist *file, struct inclist **srcfile)
{
struct symtab **val;
if ((val = slookup(symbol, &maininclist))) {
debug(1,("%s defined on command line\n", symbol));
if (srcfile != NULL) *srcfile = &maininclist;
return(val);
}
if ((val = fdefined(symbol, file, srcfile)))
return(val);
debug(1,("%s not defined in %s\n", symbol, file->i_file));
return(NULL);
}
/*
* Return type based on if the #if expression evaluates to 0
*/
static int
zero_value(char *filename,
char *exp,
struct filepointer *filep,
struct inclist *file_red)
{
if (cppsetup(filename, exp, filep, file_red))
return(IFFALSE);
else
return(IF);
}
void
define2(char *name, char *val, struct inclist *file)
{
int first, last, below;
register struct symtab **sp = NULL, **dest;
struct symtab *stab;
/* Make space if it's needed */
if (file->i_defs == NULL)
{
file->i_defs = (struct symtab **)
malloc(sizeof (struct symtab*) * SYMTABINC);
file->i_ndefs = 0;
}
else if (!(file->i_ndefs % SYMTABINC))
file->i_defs = (struct symtab **)
realloc(file->i_defs,
sizeof(struct symtab*)*(file->i_ndefs+SYMTABINC));
if (file->i_defs == NULL)
fatalerr("malloc()/realloc() failure in insert_defn()\n");
below = first = 0;
last = file->i_ndefs - 1;
while (last >= first)
{
/* Fast inline binary search */
register char *s1;
register char *s2;
register int middle = (first + last) / 2;
/* Fast inline strchr() */
s1 = name;
s2 = file->i_defs[middle]->s_name;
while (*s1++ == *s2++)
if (s2[-1] == '\0') break;
/* If exact match, set sp and break */
if (*--s1 == *--s2)
{
sp = file->i_defs + middle;
break;
}
/* If name > i_defs[middle] ... */
if (*s1 > *s2)
{
below = first;
first = middle + 1;
}
/* else ... */
else
{
below = last = middle - 1;
}
}
/* Search is done. If we found an exact match to the symbol name,
just replace its s_value */
if (sp != NULL)
{
debug(1,("redefining %s from %s to %s in file %s\n",
name, (*sp)->s_value, val, file->i_file));
free((*sp)->s_value);
(*sp)->s_value = copy(val);
return;
}
sp = file->i_defs + file->i_ndefs++;
dest = file->i_defs + below + 1;
while (sp > dest)
{
*sp = sp[-1];
sp--;
}
stab = (struct symtab *) malloc(sizeof (struct symtab));
if (stab == NULL)
fatalerr("malloc()/realloc() failure in insert_defn()\n");
debug(1,("defining %s to %s in file %s\n", name, val, file->i_file));
stab->s_name = copy(name);
stab->s_value = copy(val);
*sp = stab;
}
void
define(char *def, struct inclist *file)
{
char *val;
/* Separate symbol name and its value */
val = def;
while (isalnum(*val) || *val == '_')
val++;
if (*val)
*val++ = '\0';
while (*val == ' ' || *val == '\t')
val++;
if (!*val)
val = "1";
define2(def, val, file);
}
struct symtab **
slookup(char *symbol, struct inclist *file)
{
register int first = 0;
register int last = file->i_ndefs - 1;
if (file) while (last >= first)
{
/* Fast inline binary search */
register char *s1;
register char *s2;
register int middle = (first + last) / 2;
/* Fast inline strchr() */
s1 = symbol;
s2 = file->i_defs[middle]->s_name;
while (*s1++ == *s2++)
if (s2[-1] == '\0') break;
/* If exact match, we're done */
if (*--s1 == *--s2)
{
return file->i_defs + middle;
}
/* If symbol > i_defs[middle] ... */
if (*s1 > *s2)
{
first = middle + 1;
}
/* else ... */
else
{
last = middle - 1;
}
}
return(NULL);
}
static int
merge2defines(struct inclist *file1, struct inclist *file2)
{
int i;
if ((file1==NULL) || (file2==NULL) ||
!(file2->i_flags & FINISHED))
return 0;
for (i=0; i < file2->i_listlen; i++)
if (file2->i_merged[i]==FALSE)
return 0;
{
int first1 = 0;
int last1 = file1->i_ndefs - 1;
int first2 = 0;
int last2 = file2->i_ndefs - 1;
int first=0;
struct symtab** i_defs = NULL;
int deflen=file1->i_ndefs+file2->i_ndefs;
debug(2,("merging %s into %s\n",
file2->i_file, file1->i_file));
if (deflen>0)
{
/* make sure deflen % SYMTABINC == 0 is still true */
deflen += (SYMTABINC - deflen % SYMTABINC) % SYMTABINC;
i_defs=(struct symtab**)
malloc(deflen*sizeof(struct symtab*));
if (i_defs==NULL) return 0;
}
while ((last1 >= first1) && (last2 >= first2))
{
char *s1=file1->i_defs[first1]->s_name;
char *s2=file2->i_defs[first2]->s_name;
if (strcmp(s1,s2) < 0)
i_defs[first++]=file1->i_defs[first1++];
else if (strcmp(s1,s2) > 0)
i_defs[first++]=file2->i_defs[first2++];
else /* equal */
{
i_defs[first++]=file2->i_defs[first2++];
first1++;
}
}
while (last1 >= first1)
{
i_defs[first++]=file1->i_defs[first1++];
}
while (last2 >= first2)
{
i_defs[first++]=file2->i_defs[first2++];
}
if (file1->i_defs) free(file1->i_defs);
file1->i_defs=i_defs;
file1->i_ndefs=first;
return 1;
}
}
void
undefine(char *symbol, struct inclist *file)
{
register struct symtab **ptr;
struct inclist *srcfile;
while ((ptr = isdefined(symbol, file, &srcfile)) != NULL)
{
srcfile->i_ndefs--;
for (; ptr < srcfile->i_defs + srcfile->i_ndefs; ptr++)
*ptr = ptr[1];
}
}
int
find_includes(struct filepointer *filep, struct inclist *file,
struct inclist *file_red, int recursion, boolean failOK)
{
struct inclist *inclistp;
char **includedirsp;
register char *line;
register int type;
boolean recfailOK;
while ((line = getnextline(filep))) {
switch(type = deftype(line, filep, file_red, file, TRUE)) {
case IF:
doif:
type = find_includes(filep, file,
file_red, recursion+1, failOK);
while ((type == ELIF) || (type == ELIFFALSE) ||
(type == ELIFGUESSFALSE))
type = gobble(filep, file, file_red);
if (type == ELSE)
gobble(filep, file, file_red);
break;
case IFFALSE:
case IFGUESSFALSE:
doiffalse:
if (type == IFGUESSFALSE || type == ELIFGUESSFALSE)
recfailOK = TRUE;
else
recfailOK = failOK;
type = gobble(filep, file, file_red);
if (type == ELSE)
find_includes(filep, file,
file_red, recursion+1, recfailOK);
else
if (type == ELIF)
goto doif;
else
if ((type == ELIFFALSE) || (type == ELIFGUESSFALSE))
goto doiffalse;
break;
case IFDEF:
case IFNDEF:
if ((type == IFDEF && isdefined(line, file_red, NULL))
|| (type == IFNDEF && !isdefined(line, file_red, NULL))) {
debug(1,(type == IFNDEF ?
"line %d: %s !def'd in %s via %s%s\n" : "",
filep->f_line, line,
file->i_file, file_red->i_file, ": doit"));
type = find_includes(filep, file,
file_red, recursion+1, failOK);
while (type == ELIF || type == ELIFFALSE || type == ELIFGUESSFALSE)
type = gobble(filep, file, file_red);
if (type == ELSE)
gobble(filep, file, file_red);
}
else {
debug(1,(type == IFDEF ?
"line %d: %s !def'd in %s via %s%s\n" : "",
filep->f_line, line,
file->i_file, file_red->i_file, ": gobble"));
type = gobble(filep, file, file_red);
if (type == ELSE)
find_includes(filep, file,
file_red, recursion+1, failOK);
else if (type == ELIF)
goto doif;
else if (type == ELIFFALSE || type == ELIFGUESSFALSE)
goto doiffalse;
}
break;
case ELSE:
case ELIFFALSE:
case ELIFGUESSFALSE:
case ELIF:
if (!recursion)
gobble(filep, file, file_red);
case ENDIF:
if (recursion)
return(type);
case DEFINE:
define(line, file);
break;
case UNDEF:
if (!*line) {
warning("%s", file_red->i_file);
if (file_red != file)
warning1(" (reading %s)", file->i_file);
warning1(", line %d: incomplete undef == \"%s\"\n",
filep->f_line, line);
break;
}
undefine(line, file_red);
break;
case INCLUDE:
case INCLUDEDOT:
case INCLUDENEXT:
case INCLUDENEXTDOT:
inclistp = inclistnext;
includedirsp = includedirsnext;
debug(2,("%s, reading %s, includes %s\n",
file_red->i_file, file->i_file, line));
add_include(filep, file, file_red, line, type, failOK);
inclistnext = inclistp;
includedirsnext = includedirsp;
break;
case ERROR:
case WARNING:
warning("%s", file_red->i_file);
if (file_red != file)
warning1(" (reading %s)", file->i_file);
warning1(", line %d: %s\n",
filep->f_line, line);
break;
case PRAGMA:
case IDENT:
case SCCS:
case EJECT:
break;
case -1:
warning("%s", file_red->i_file);
if (file_red != file)
warning1(" (reading %s)", file->i_file);
warning1(", line %d: unknown directive == \"%s\"\n",
filep->f_line, line);
break;
case -2:
warning("%s", file_red->i_file);
if (file_red != file)
warning1(" (reading %s)", file->i_file);
warning1(", line %d: incomplete include == \"%s\"\n",
filep->f_line, line);
break;
}
}
file->i_flags |= FINISHED;
debug(2,("finished with %s\n", file->i_file));
return(-1);
}

Просмотреть файл

@ -0,0 +1,124 @@
/* $Xorg: pr.c,v 1.4 2001/02/09 02:03:16 xorgcvs Exp $ */
/*
Copyright (c) 1993, 1994, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
/* $XFree86: xc/config/makedepend/pr.c,v 1.5 2001/12/14 19:53:21 dawes Exp $ */
#include "def.h"
extern struct inclist inclist[ MAXFILES ],
*inclistp;
extern char *objprefix;
extern char *objsuffix;
extern int width;
extern boolean printed;
extern boolean verbose;
extern boolean show_where_not;
void
add_include(struct filepointer *filep, struct inclist *file,
struct inclist *file_red, char *include, int type,
boolean failOK)
{
register struct inclist *newfile;
register struct filepointer *content;
/*
* First decide what the pathname of this include file really is.
*/
newfile = inc_path(file->i_file, include, type);
if (newfile == NULL) {
if (failOK)
return;
if (file != file_red)
warning("%s (reading %s, line %d): ",
file_red->i_file, file->i_file, filep->f_line);
else
warning("%s, line %d: ", file->i_file, filep->f_line);
warning1("cannot find include file \"%s\"\n", include);
show_where_not = TRUE;
newfile = inc_path(file->i_file, include, type);
show_where_not = FALSE;
}
if (newfile) {
included_by(file, newfile);
if (!(newfile->i_flags & SEARCHED)) {
newfile->i_flags |= SEARCHED;
content = getfile(newfile->i_file);
find_includes(content, newfile, file_red, 0, failOK);
freefile(content);
}
}
}
static void
pr(struct inclist *ip, char *file, char *base)
{
static char *lastfile;
static int current_len;
register int len, i;
char buf[ BUFSIZ ];
printed = TRUE;
len = strlen(ip->i_file)+1;
if (current_len + len > width || file != lastfile) {
lastfile = file;
sprintf(buf, "\n%s%s%s: %s", objprefix, base, objsuffix,
ip->i_file);
len = current_len = strlen(buf);
}
else {
buf[0] = ' ';
strcpy(buf+1, ip->i_file);
current_len += len;
}
fwrite(buf, len, 1, stdout);
/*
* If verbose is set, then print out what this file includes.
*/
if (! verbose || ip->i_list == NULL || ip->i_flags & NOTIFIED)
return;
ip->i_flags |= NOTIFIED;
lastfile = NULL;
printf("\n# %s includes:", ip->i_file);
for (i=0; i<ip->i_listlen; i++)
printf("\n#\t%s", ip->i_list[ i ]->i_incstring);
}
void
recursive_pr_include(struct inclist *head, char *file, char *base)
{
int i;
if (head->i_flags & MARKED)
return;
head->i_flags |= MARKED;
if (head->i_file != file)
pr(head, file, base);
for (i=0; i<head->i_listlen; i++)
recursive_pr_include(head->i_list[ i ], file, base);
}

Просмотреть файл

@ -39,7 +39,7 @@
# Master "Core Components" file system "release" prefixes # # Master "Core Components" file system "release" prefixes #
####################################################################### #######################################################################
# Windows platforms override this. See WIN32.mk or WIN16.mk. # Windows platforms override this. See WIN32.mk.
ifndef RELEASE_TREE ifndef RELEASE_TREE
ifdef BUILD_SHIP ifdef BUILD_SHIP
ifdef USE_SHIPS ifdef USE_SHIPS

Просмотреть файл

@ -52,7 +52,7 @@ PURE_LIBRARY =
PROGRAM = PROGRAM =
ifdef SHARED_LIBRARY ifdef SHARED_LIBRARY
ifeq (,$(filter-out WINNT WIN95 WINCE,$(OS_TARGET))) # list omits WIN16 ifeq (,$(filter-out WIN%,$(OS_TARGET)))
DLLBASE=/BASE:0x30000000 DLLBASE=/BASE:0x30000000
RES=$(OBJDIR)/dbm.res RES=$(OBJDIR)/dbm.res
RESNAME=../include/dbm.rc RESNAME=../include/dbm.rc

Просмотреть файл

@ -27,7 +27,7 @@
* LS30 HPFS386 requires a count greater than 2, or some files * LS30 HPFS386 requires a count greater than 2, or some files
* are missing (those starting with a character less that '.'). * are missing (those starting with a character less that '.').
* *
* Novell looses entries which overflow the buffer. In previous * Novell loses entries which overflow the buffer. In previous
* versions of dirent2, this could have lead to missing files * versions of dirent2, this could have lead to missing files
* when the average length of 100 directory entries was 40 bytes * when the average length of 100 directory entries was 40 bytes
* or more (quite unlikely for files on a Novell server). * or more (quite unlikely for files on a Novell server).

Просмотреть файл

@ -667,8 +667,10 @@ typedef enum {
bltestRC2_ECB, /* . */ bltestRC2_ECB, /* . */
bltestRC2_CBC, /* . */ bltestRC2_CBC, /* . */
bltestRC4, /* . */ bltestRC4, /* . */
#ifdef NSS_SOFTOKEN_DOES_RC5
bltestRC5_ECB, /* . */ bltestRC5_ECB, /* . */
bltestRC5_CBC, /* . */ bltestRC5_CBC, /* . */
#endif
bltestAES_ECB, /* . */ bltestAES_ECB, /* . */
bltestAES_CBC, /* . */ bltestAES_CBC, /* . */
bltestCAMELLIA_ECB, /* . */ bltestCAMELLIA_ECB, /* . */
@ -698,8 +700,10 @@ static char *mode_strings[] =
"rc2_ecb", "rc2_ecb",
"rc2_cbc", "rc2_cbc",
"rc4", "rc4",
#ifdef NSS_SOFTOKEN_DOES_RC5
"rc5_ecb", "rc5_ecb",
"rc5_cbc", "rc5_cbc",
#endif
"aes_ecb", "aes_ecb",
"aes_cbc", "aes_cbc",
"camellia_ecb", "camellia_ecb",
@ -862,7 +866,10 @@ cipher_requires_IV(bltestCipherMode mode)
{ {
/* change as needed! */ /* change as needed! */
if (mode == bltestDES_CBC || mode == bltestDES_EDE_CBC || if (mode == bltestDES_CBC || mode == bltestDES_EDE_CBC ||
mode == bltestRC2_CBC || mode == bltestRC5_CBC || mode == bltestRC2_CBC ||
#ifdef NSS_SOFTOKEN_DOES_RC5
mode == bltestRC5_CBC ||
#endif
mode == bltestAES_CBC || mode == bltestCAMELLIA_CBC|| mode == bltestAES_CBC || mode == bltestCAMELLIA_CBC||
mode == bltestSEED_CBC) mode == bltestSEED_CBC)
return PR_TRUE; return PR_TRUE;
@ -1288,7 +1295,7 @@ bltest_rc4_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
SECStatus SECStatus
bltest_rc5_init(bltestCipherInfo *cipherInfo, PRBool encrypt) bltest_rc5_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
{ {
#if NSS_SOFTOKEN_DOES_RC5 #ifdef NSS_SOFTOKEN_DOES_RC5
PRIntervalTime time1, time2; PRIntervalTime time1, time2;
bltestRC5Params *rc5p = &cipherInfo->params.rc5; bltestRC5Params *rc5p = &cipherInfo->params.rc5;
int minorMode; int minorMode;
@ -1979,9 +1986,9 @@ cipherInit(bltestCipherInfo *cipherInfo, PRBool encrypt)
cipherInfo->input.pBuf.len); cipherInfo->input.pBuf.len);
return bltest_rc4_init(cipherInfo, encrypt); return bltest_rc4_init(cipherInfo, encrypt);
break; break;
#ifdef NSS_SOFTOKEN_DOES_RC5
case bltestRC5_ECB: case bltestRC5_ECB:
case bltestRC5_CBC: case bltestRC5_CBC:
#if NSS_SOFTOKEN_DOES_RC5
SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
cipherInfo->input.pBuf.len); cipherInfo->input.pBuf.len);
#endif #endif
@ -2470,7 +2477,7 @@ cipherFinish(bltestCipherInfo *cipherInfo)
case bltestRC4: case bltestRC4:
RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE); RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE);
break; break;
#if NSS_SOFTOKEN_DOES_RC5 #ifdef NSS_SOFTOKEN_DOES_RC5
case bltestRC5_ECB: case bltestRC5_ECB:
case bltestRC5_CBC: case bltestRC5_CBC:
RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE); RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE);
@ -2623,7 +2630,7 @@ print_td:
else else
fprintf(stdout, "%8d", 8*info->params.sk.key.buf.len); fprintf(stdout, "%8d", 8*info->params.sk.key.buf.len);
break; break;
#if NSS_SOFTOKEN_DOES_RC5 #ifdef NSS_SOFTOKEN_DOES_RC5
case bltestRC5_ECB: case bltestRC5_ECB:
case bltestRC5_CBC: case bltestRC5_CBC:
if (info->params.sk.key.buf.len > 0) if (info->params.sk.key.buf.len > 0)
@ -2747,7 +2754,7 @@ get_params(PRArenaPool *arena, bltestParams *params,
{ {
char filename[256]; char filename[256];
char *modestr = mode_strings[mode]; char *modestr = mode_strings[mode];
#if NSS_SOFTOKEN_DOES_RC5 #ifdef NSS_SOFTOKEN_DOES_RC5
FILE *file; FILE *file;
char *mark, *param, *val; char *mark, *param, *val;
int index = 0; int index = 0;
@ -2771,7 +2778,7 @@ get_params(PRArenaPool *arena, bltestParams *params,
sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
load_file_data(arena, &params->sk.key, filename, bltestBinary); load_file_data(arena, &params->sk.key, filename, bltestBinary);
break; break;
#if NSS_SOFTOKEN_DOES_RC5 #ifdef NSS_SOFTOKEN_DOES_RC5
case bltestRC5_ECB: case bltestRC5_ECB:
case bltestRC5_CBC: case bltestRC5_CBC:
sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j); sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j);
@ -2918,7 +2925,6 @@ blapi_selftest(bltestCipherMode *modes, int numModes, int inoff, int outoff,
finished = PR_FALSE; finished = PR_FALSE;
nummodes = (numModes == 0) ? NUMMODES : numModes; nummodes = (numModes == 0) ? NUMMODES : numModes;
for (i=0; i < nummodes && !finished; i++) { for (i=0; i < nummodes && !finished; i++) {
if (i == bltestRC5_ECB || i == bltestRC5_CBC) continue;
if (numModes > 0) if (numModes > 0)
mode = modes[i]; mode = modes[i];
else else
@ -3542,9 +3548,11 @@ int main(int argc, char **argv)
char *ivstr = NULL; char *ivstr = NULL;
bltestSymmKeyParams *skp; bltestSymmKeyParams *skp;
file = NULL; file = NULL;
#ifdef NSS_SOFTOKEN_DOES_RC5
if (cipherInfo->mode == bltestRC5_CBC) if (cipherInfo->mode == bltestRC5_CBC)
skp = (bltestSymmKeyParams *)&params->rc5; skp = (bltestSymmKeyParams *)&params->rc5;
else else
#endif
skp = &params->sk; skp = &params->sk;
if (bltest.options[opt_IV].activated) { if (bltest.options[opt_IV].activated) {
if (bltest.options[opt_CmdLine].activated) { if (bltest.options[opt_CmdLine].activated) {
@ -3734,3 +3742,4 @@ int main(int argc, char **argv)
return SECSuccess; return SECSuccess;
} }

Просмотреть файл

@ -278,49 +278,121 @@ GetYesNo(char *prompt)
return (buffPrt && (buf[0] == 'y' || buf[0] == 'Y')) ? PR_TRUE : PR_FALSE; return (buffPrt && (buf[0] == 'y' || buf[0] == 'Y')) ? PR_TRUE : PR_FALSE;
} }
/* Parses comma separated values out of the string pointed by nextPos.
* Parsed value is compared to an array of possible values(valueArray).
* If match is found, a value index is returned, otherwise returns SECFailue.
* nextPos is set to the token after found comma separator or to NULL.
* NULL in nextPos should be used as indication of the last parsed token.
* A special value "critical" can be parsed out from the supplied sting.*/
static SECStatus
parseNextCmdInput(const char * const *valueArray, int *value, char **nextPos,
PRBool *critical)
{
char *thisPos = *nextPos;
int keyLen = 0;
int arrIndex = 0;
if (!valueArray || !value || !nextPos || !critical) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
while (1) {
if ((*nextPos = strchr(thisPos, ',')) == NULL) {
keyLen = strlen(thisPos);
} else {
keyLen = *nextPos - thisPos;
*nextPos += 1;
}
/* if critical keyword is found, go for another loop,
* but check, if it is the last keyword of
* the string.*/
if (!strncmp("critical", thisPos, keyLen)) {
*critical = PR_TRUE;
if (*nextPos == NULL) {
return SECSuccess;
}
thisPos = *nextPos;
continue;
}
break;
}
for (arrIndex = 0; valueArray[arrIndex]; arrIndex++) {
if (!strncmp(valueArray[arrIndex], thisPos, keyLen)) {
*value = arrIndex;
return SECSuccess;
}
}
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
static const char * const
keyUsageKeyWordArray[] = { "digitalSignature",
"nonRepudiation",
"keyEncipherment",
"dataEncipherment",
"keyAgreement",
"certSigning",
"crlSigning",
NULL};
static SECStatus static SECStatus
AddKeyUsage (void *extHandle) AddKeyUsage (void *extHandle, const char *userSuppliedValue)
{ {
SECItem bitStringValue; SECItem bitStringValue;
unsigned char keyUsage = 0x0; unsigned char keyUsage = 0x0;
char buffer[5]; char buffer[5];
int value; int value;
PRBool yesNoAns; char *nextPos = (char*)userSuppliedValue;
PRBool isCriticalExt = PR_FALSE;
while (1) { if (!userSuppliedValue) {
if (PrintChoicesAndGetAnswer( while (1) {
"\t\t0 - Digital Signature\n" if (PrintChoicesAndGetAnswer(
"\t\t1 - Non-repudiation\n" "\t\t0 - Digital Signature\n"
"\t\t2 - Key encipherment\n" "\t\t1 - Non-repudiation\n"
"\t\t3 - Data encipherment\n" "\t\t2 - Key encipherment\n"
"\t\t4 - Key agreement\n" "\t\t3 - Data encipherment\n"
"\t\t5 - Cert signing key\n" "\t\t4 - Key agreement\n"
"\t\t6 - CRL signing key\n" "\t\t5 - Cert signing key\n"
"\t\tOther to finish\n", "\t\t6 - CRL signing key\n"
buffer, sizeof(buffer)) == SECFailure) { "\t\tOther to finish\n",
return SECFailure; buffer, sizeof(buffer)) == SECFailure) {
} return SECFailure;
value = PORT_Atoi (buffer);
if (value < 0 || value > 6)
break;
if (value == 0) {
/* Checking that zero value of variable 'value'
* corresponds to '0' input made by user */
char *chPtr = strchr(buffer, '0');
if (chPtr == NULL) {
continue;
} }
value = PORT_Atoi (buffer);
if (value < 0 || value > 6)
break;
if (value == 0) {
/* Checking that zero value of variable 'value'
* corresponds to '0' input made by user */
char *chPtr = strchr(buffer, '0');
if (chPtr == NULL) {
continue;
}
}
keyUsage |= (0x80 >> value);
}
isCriticalExt = GetYesNo("Is this a critical extension [y/N]?");
} else {
while (1) {
if (parseNextCmdInput(keyUsageKeyWordArray, &value, &nextPos,
&isCriticalExt) == SECFailure) {
return SECFailure;
}
keyUsage |= (0x80 >> value);
if (!nextPos)
break;
} }
keyUsage |= (0x80 >> value);
} }
bitStringValue.data = &keyUsage; bitStringValue.data = &keyUsage;
bitStringValue.len = 1; bitStringValue.len = 1;
yesNoAns = GetYesNo("Is this a critical extension [y/N]?");
return (CERT_EncodeAndAddBitStrExtension return (CERT_EncodeAndAddBitStrExtension
(extHandle, SEC_OID_X509_KEY_USAGE, &bitStringValue, (extHandle, SEC_OID_X509_KEY_USAGE, &bitStringValue,
yesNoAns)); isCriticalExt));
} }
@ -378,6 +450,10 @@ AddOidToSequence(CERTOidSequence *os, SECOidTag oidTag)
} }
for( oids = os->oids; (SECItem *)NULL != *oids; oids++ ) { for( oids = os->oids; (SECItem *)NULL != *oids; oids++ ) {
if (*oids == &od->oid) {
/* We already have this oid */
return SECSuccess;
}
count++; count++;
} }
@ -432,42 +508,60 @@ loser:
return (SECItem *)NULL; return (SECItem *)NULL;
} }
static const char * const
extKeyUsageKeyWordArray[] = { "serverAuth",
"clientAuth",
"codeSigning",
"emailProtection",
"timeStamp",
"ocspResponder",
"stepUp",
NULL};
static SECStatus static SECStatus
AddExtKeyUsage (void *extHandle) AddExtKeyUsage (void *extHandle, const char *userSuppliedValue)
{ {
char buffer[5]; char buffer[5];
int value; int value;
CERTOidSequence *os; CERTOidSequence *os;
SECStatus rv; SECStatus rv;
SECItem *item; SECItem *item;
PRBool yesNoAns; PRBool isCriticalExt = PR_FALSE;
char *nextPos = (char*)userSuppliedValue;
os = CreateOidSequence(); os = CreateOidSequence();
if( (CERTOidSequence *)NULL == os ) { if( (CERTOidSequence *)NULL == os ) {
return SECFailure; return SECFailure;
} }
while (1) { while (1) {
if (PrintChoicesAndGetAnswer( if (!userSuppliedValue) {
"\t\t0 - Server Auth\n" if (PrintChoicesAndGetAnswer(
"\t\t1 - Client Auth\n" "\t\t0 - Server Auth\n"
"\t\t2 - Code Signing\n" "\t\t1 - Client Auth\n"
"\t\t3 - Email Protection\n" "\t\t2 - Code Signing\n"
"\t\t4 - Timestamp\n" "\t\t3 - Email Protection\n"
"\t\t5 - OCSP Responder\n" "\t\t4 - Timestamp\n"
"\t\t6 - Step-up\n" "\t\t5 - OCSP Responder\n"
"\t\tOther to finish\n", "\t\t6 - Step-up\n"
buffer, sizeof(buffer)) == SECFailure) { "\t\tOther to finish\n",
GEN_BREAK(SECFailure); buffer, sizeof(buffer)) == SECFailure) {
} GEN_BREAK(SECFailure);
value = PORT_Atoi(buffer); }
value = PORT_Atoi(buffer);
if (value == 0) {
/* Checking that zero value of variable 'value' if (value == 0) {
* corresponds to '0' input made by user */ /* Checking that zero value of variable 'value'
char *chPtr = strchr(buffer, '0'); * corresponds to '0' input made by user */
if (chPtr == NULL) { char *chPtr = strchr(buffer, '0');
continue; if (chPtr == NULL) {
continue;
}
}
} else {
if (parseNextCmdInput(extKeyUsageKeyWordArray, &value, &nextPos,
&isCriticalExt) == SECFailure) {
return SECFailure;
} }
} }
@ -497,66 +591,95 @@ AddExtKeyUsage (void *extHandle)
goto endloop; goto endloop;
} }
if( SECSuccess != rv ) goto loser; if (userSuppliedValue && !nextPos)
break;
if( SECSuccess != rv )
goto loser;
} }
endloop: endloop:
item = EncodeOidSequence(os); item = EncodeOidSequence(os);
yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); if (!userSuppliedValue) {
isCriticalExt = GetYesNo("Is this a critical extension [y/N]?");
}
rv = CERT_AddExtension(extHandle, SEC_OID_X509_EXT_KEY_USAGE, item, rv = CERT_AddExtension(extHandle, SEC_OID_X509_EXT_KEY_USAGE, item,
yesNoAns, PR_TRUE); isCriticalExt, PR_TRUE);
/*FALLTHROUGH*/ /*FALLTHROUGH*/
loser: loser:
DestroyOidSequence(os); DestroyOidSequence(os);
return rv; return rv;
} }
static const char * const
nsCertTypeKeyWordArray[] = { "sslClient",
"sslServer",
"smime",
"objectSigning",
"Not!Used",
"sslCA",
"smimeCA",
"objectSigningCA",
NULL };
static SECStatus static SECStatus
AddNscpCertType (void *extHandle) AddNscpCertType (void *extHandle, const char *userSuppliedValue)
{ {
SECItem bitStringValue; SECItem bitStringValue;
unsigned char keyUsage = 0x0; unsigned char keyUsage = 0x0;
char buffer[5]; char buffer[5];
int value; int value;
PRBool yesNoAns; char *nextPos = (char*)userSuppliedValue;
PRBool isCriticalExt = PR_FALSE;
while (1) { if (!userSuppliedValue) {
if (PrintChoicesAndGetAnswer( while (1) {
"\t\t0 - SSL Client\n" if (PrintChoicesAndGetAnswer(
"\t\t1 - SSL Server\n" "\t\t0 - SSL Client\n"
"\t\t2 - S/MIME\n" "\t\t1 - SSL Server\n"
"\t\t3 - Object Signing\n" "\t\t2 - S/MIME\n"
"\t\t4 - Reserved for future use\n" "\t\t3 - Object Signing\n"
"\t\t5 - SSL CA\n" "\t\t4 - Reserved for future use\n"
"\t\t6 - S/MIME CA\n" "\t\t5 - SSL CA\n"
"\t\t7 - Object Signing CA\n" "\t\t6 - S/MIME CA\n"
"\t\tOther to finish\n", "\t\t7 - Object Signing CA\n"
buffer, sizeof(buffer)) == SECFailure) { "\t\tOther to finish\n",
return SECFailure; buffer, sizeof(buffer)) == SECFailure) {
} return SECFailure;
value = PORT_Atoi (buffer);
if (value < 0 || value > 7)
break;
if (value == 0) {
/* Checking that zero value of variable 'value'
* corresponds to '0' input made by user */
char *chPtr = strchr(buffer, '0');
if (chPtr == NULL) {
continue;
} }
value = PORT_Atoi (buffer);
if (value < 0 || value > 7)
break;
if (value == 0) {
/* Checking that zero value of variable 'value'
* corresponds to '0' input made by user */
char *chPtr = strchr(buffer, '0');
if (chPtr == NULL) {
continue;
}
}
keyUsage |= (0x80 >> value);
}
isCriticalExt = GetYesNo("Is this a critical extension [y/N]?");
} else {
while (1) {
if (parseNextCmdInput(nsCertTypeKeyWordArray, &value, &nextPos,
&isCriticalExt) == SECFailure) {
return SECFailure;
}
keyUsage |= (0x80 >> value);
if (!nextPos)
break;
} }
keyUsage |= (0x80 >> value);
} }
bitStringValue.data = &keyUsage; bitStringValue.data = &keyUsage;
bitStringValue.len = 1; bitStringValue.len = 1;
yesNoAns = GetYesNo("Is this a critical extension [y/N]?");
return (CERT_EncodeAndAddBitStrExtension return (CERT_EncodeAndAddBitStrExtension
(extHandle, SEC_OID_NS_CERT_EXT_CERT_TYPE, &bitStringValue, (extHandle, SEC_OID_NS_CERT_EXT_CERT_TYPE, &bitStringValue,
yesNoAns)); isCriticalExt));
} }
@ -571,7 +694,6 @@ AddSubjectAltNames(PRArenaPool *arena, CERTGeneralName **existingListp,
char *tbuf; char *tbuf;
SECStatus rv = SECSuccess; SECStatus rv = SECSuccess;
/* /*
* walk down the comma separated list of names. NOTE: there is * walk down the comma separated list of names. NOTE: there is
* no sanity checks to see if the email address look like * no sanity checks to see if the email address look like
@ -1557,8 +1679,8 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
do { do {
/* Add key usage extension */ /* Add key usage extension */
if (extList[ext_keyUsage]) { if (extList[ext_keyUsage].activated) {
rv = AddKeyUsage(extHandle); rv = AddKeyUsage(extHandle, extList[ext_keyUsage].arg);
if (rv) { if (rv) {
errstring = "KeyUsage"; errstring = "KeyUsage";
break; break;
@ -1566,8 +1688,8 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
/* Add extended key usage extension */ /* Add extended key usage extension */
if (extList[ext_extKeyUsage]) { if (extList[ext_extKeyUsage].activated) {
rv = AddExtKeyUsage(extHandle); rv = AddExtKeyUsage(extHandle, extList[ext_extKeyUsage].arg);
if (rv) { if (rv) {
errstring = "ExtendedKeyUsage"; errstring = "ExtendedKeyUsage";
break; break;
@ -1575,7 +1697,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
/* Add basic constraint extension */ /* Add basic constraint extension */
if (extList[ext_basicConstraint]) { if (extList[ext_basicConstraint].activated) {
rv = AddBasicConstraint(extHandle); rv = AddBasicConstraint(extHandle);
if (rv) { if (rv) {
errstring = "BasicConstraint"; errstring = "BasicConstraint";
@ -1583,7 +1705,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_authorityKeyID]) { if (extList[ext_authorityKeyID].activated) {
rv = AddAuthKeyID(extHandle); rv = AddAuthKeyID(extHandle);
if (rv) { if (rv) {
errstring = "AuthorityKeyID"; errstring = "AuthorityKeyID";
@ -1591,7 +1713,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_subjectKeyID]) { if (extList[ext_subjectKeyID].activated) {
rv = AddSubjKeyID(extHandle); rv = AddSubjKeyID(extHandle);
if (rv) { if (rv) {
errstring = "SubjectKeyID"; errstring = "SubjectKeyID";
@ -1599,7 +1721,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_CRLDistPts]) { if (extList[ext_CRLDistPts].activated) {
rv = AddCrlDistPoint(extHandle); rv = AddCrlDistPoint(extHandle);
if (rv) { if (rv) {
errstring = "CRLDistPoints"; errstring = "CRLDistPoints";
@ -1607,24 +1729,25 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_NSCertType]) { if (extList[ext_NSCertType].activated) {
rv = AddNscpCertType(extHandle); rv = AddNscpCertType(extHandle, extList[ext_extKeyUsage].arg);
if (rv) { if (rv) {
errstring = "NSCertType"; errstring = "NSCertType";
break; break;
} }
} }
if (extList[ext_authInfoAcc] || extList[ext_subjInfoAcc]) { if (extList[ext_authInfoAcc].activated ||
rv = AddInfoAccess(extHandle, extList[ext_subjInfoAcc], extList[ext_subjInfoAcc].activated) {
extList[ext_basicConstraint]); rv = AddInfoAccess(extHandle, extList[ext_subjInfoAcc].activated,
extList[ext_basicConstraint].activated);
if (rv) { if (rv) {
errstring = "InformationAccess"; errstring = "InformationAccess";
break; break;
} }
} }
if (extList[ext_certPolicies]) { if (extList[ext_certPolicies].activated) {
rv = AddCertPolicies(extHandle); rv = AddCertPolicies(extHandle);
if (rv) { if (rv) {
errstring = "Policies"; errstring = "Policies";
@ -1632,7 +1755,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_policyMappings]) { if (extList[ext_policyMappings].activated) {
rv = AddPolicyMappings(extHandle); rv = AddPolicyMappings(extHandle);
if (rv) { if (rv) {
errstring = "PolicyMappings"; errstring = "PolicyMappings";
@ -1640,7 +1763,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_policyConstr]) { if (extList[ext_policyConstr].activated) {
rv = AddPolicyConstraints(extHandle); rv = AddPolicyConstraints(extHandle);
if (rv) { if (rv) {
errstring = "PolicyConstraints"; errstring = "PolicyConstraints";
@ -1648,7 +1771,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,
} }
} }
if (extList[ext_inhibitAnyPolicy]) { if (extList[ext_inhibitAnyPolicy].activated) {
rv = AddInhibitAnyPolicy(extHandle); rv = AddInhibitAnyPolicy(extHandle);
if (rv) { if (rv) {
errstring = "InhibitAnyPolicy"; errstring = "InhibitAnyPolicy";

Просмотреть файл

@ -177,19 +177,26 @@ AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts,
GEN_BREAK(SECFailure); GEN_BREAK(SECFailure);
} }
if (PK11_IsFIPS() || !PK11_IsInternal(slot)) {
rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.",
PK11_GetTokenName(slot));
GEN_BREAK(SECFailure);
}
}
rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE); rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE);
if (rv != SECSuccess) { if (rv != SECSuccess) {
SECU_PrintError(progName, "could not add certificate to token or database"); /* sigh, PK11_Import Cert and CERT_ChangeCertTrust should have
GEN_BREAK(SECFailure); * been coded to take a password arg. */
if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) {
rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName,
"could not authenticate to token %s.",
PK11_GetTokenName(slot));
GEN_BREAK(SECFailure);
}
rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE,
name, PR_FALSE);
}
if (rv != SECSuccess) {
SECU_PrintError(progName,
"could not add certificate to token or database");
GEN_BREAK(SECFailure);
}
} }
rv = CERT_ChangeCertTrust(handle, cert, trust); rv = CERT_ChangeCertTrust(handle, cert, trust);
@ -197,8 +204,9 @@ AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts,
if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) {
rv = PK11_Authenticate(slot, PR_TRUE, pwdata); rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
if (rv != SECSuccess) { if (rv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.", SECU_PrintError(progName,
PK11_GetTokenName(slot)); "could not authenticate to token %s.",
PK11_GetTokenName(slot));
GEN_BREAK(SECFailure); GEN_BREAK(SECFailure);
} }
rv = CERT_ChangeCertTrust(handle, cert, trust); rv = CERT_ChangeCertTrust(handle, cert, trust);
@ -940,8 +948,11 @@ Usage(char *progName)
FPS "\t%s -B -i batch-file\n", progName); FPS "\t%s -B -i batch-file\n", progName);
FPS "\t%s -C [-c issuer-name | -x] -i cert-request-file -o cert-file\n" FPS "\t%s -C [-c issuer-name | -x] -i cert-request-file -o cert-file\n"
"\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n" "\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n"
"\t\t [-f pwfile] [-d certdir] [-P dbprefix] [-1] [-2] [-3] [-4] [-5]\n" "\t\t [-f pwfile] [-d certdir] [-P dbprefix]\n"
"\t\t [-6] [-7 emailAddrs] [-8 dns-names] [-a]\n", "\t\t [-1 | --keyUsage [keyUsageKeyword,..]] [-2] [-3] [-4]\n"
"\t\t [-5 | --nsCertType [nsCertTypeKeyword,...]]\n"
"\t\t [-6 | --extKeyUsage [extKeyUsageKeyword,...]] [-7 emailAddrs]\n"
"\t\t [-8 dns-names] [-a]\n",
progName); progName);
FPS "\t%s -D -n cert-name [-d certdir] [-P dbprefix]\n", progName); FPS "\t%s -D -n cert-name [-d certdir] [-P dbprefix]\n", progName);
FPS "\t%s -E -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n", FPS "\t%s -E -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n",
@ -1049,18 +1060,29 @@ static void LongUsage(char *progName)
" -d certdir"); " -d certdir");
FPS "%-20s Cert & Key database prefix\n", FPS "%-20s Cert & Key database prefix\n",
" -P dbprefix"); " -P dbprefix");
FPS "%-20s Create key usage extension\n", FPS "%-20s \n"
" -1 "); "%-20s Create key usage extension. Possible keywords:\n"
"%-20s \"digitalSignature\", \"nonRepudiation\", \"keyEncipherment\",\n"
"%-20s \"dataEncipherment\", \"keyAgreement\", \"certSigning\",\n"
"%-20s \"crlSigning\", \"critical\"\n",
" -1 | --keyUsage keyword,keyword,...", "", "", "", "");
FPS "%-20s Create basic constraint extension\n", FPS "%-20s Create basic constraint extension\n",
" -2 "); " -2 ");
FPS "%-20s Create authority key ID extension\n", FPS "%-20s Create authority key ID extension\n",
" -3 "); " -3 ");
FPS "%-20s Create crl distribution point extension\n", FPS "%-20s Create crl distribution point extension\n",
" -4 "); " -4 ");
FPS "%-20s Create netscape cert type extension\n", FPS "%-20s \n"
" -5 "); "%-20s Create netscape cert type extension. Possible keywords:\n"
FPS "%-20s Create extended key usage extension\n", "%-20s \"sslClient\", \"sslServer\", \"smime\", \"objectSigning\",\n"
" -6 "); "%-20s \"sslCA\", \"smimeCA\", \"objectSigningCA\", \"critical\".\n",
" -5 | -nsCertType keyword,keyword,... ", "", "", "");
FPS "%-20s \n"
"%-20s Create extended key usage extension. Possible keywords:\n"
"%-20s \"serverAuth\", \"clientAuth\",\"codeSigning\",\n"
"%-20s \"emailProtection\", \"timeStamp\",\"ocspResponder\",\n"
"%-20s \"stepUp\", \"critical\"\n",
" -6 | --extKeyUsage keyword,keyword,...", "", "", "", "");
FPS "%-20s Create an email subject alt name extension\n", FPS "%-20s Create an email subject alt name extension\n",
" -7 emailAddrs"); " -7 emailAddrs");
FPS "%-20s Create an dns subject alt name extension\n", FPS "%-20s Create an dns subject alt name extension\n",
@ -1803,6 +1825,9 @@ enum certutilOpts {
opt_AddPolicyConstrExt, opt_AddPolicyConstrExt,
opt_AddInhibAnyExt, opt_AddInhibAnyExt,
opt_AddSubjectKeyIDExt, opt_AddSubjectKeyIDExt,
opt_AddCmdKeyUsageExt,
opt_AddCmdNSCertTypeExt,
opt_AddCmdExtKeyUsageExt,
opt_SourceDir, opt_SourceDir,
opt_SourcePrefix, opt_SourcePrefix,
opt_UpgradeID, opt_UpgradeID,
@ -1888,6 +1913,13 @@ secuCommandFlag options_init[] =
{ /* opt_AddInhibAnyExt */ 0, PR_FALSE, 0, PR_FALSE, "extIA" }, { /* opt_AddInhibAnyExt */ 0, PR_FALSE, 0, PR_FALSE, "extIA" },
{ /* opt_AddSubjectKeyIDExt */ 0, PR_FALSE, 0, PR_FALSE, { /* opt_AddSubjectKeyIDExt */ 0, PR_FALSE, 0, PR_FALSE,
"extSKID" }, "extSKID" },
{ /* opt_AddCmdKeyUsageExt */ 0, PR_TRUE, 0, PR_FALSE,
"keyUsage" },
{ /* opt_AddCmdNSCertTypeExt */ 0, PR_TRUE, 0, PR_FALSE,
"nsCertType" },
{ /* opt_AddCmdExtKeyUsageExt*/ 0, PR_TRUE, 0, PR_FALSE,
"extKeyUsage" },
{ /* opt_SourceDir */ 0, PR_TRUE, 0, PR_FALSE, { /* opt_SourceDir */ 0, PR_TRUE, 0, PR_FALSE,
"source-dir"}, "source-dir"},
{ /* opt_SourcePrefix */ 0, PR_TRUE, 0, PR_FALSE, { /* opt_SourcePrefix */ 0, PR_TRUE, 0, PR_FALSE,
@ -2551,14 +2583,6 @@ merge_fail:
} }
/* Modify trust attribute for cert (-M) */ /* Modify trust attribute for cert (-M) */
if (certutil.commands[cmd_ModifyCertTrust].activated) { if (certutil.commands[cmd_ModifyCertTrust].activated) {
if (PK11_IsFIPS() || !PK11_IsFriendly(slot)) {
rv = PK11_Authenticate(slot, PR_TRUE, &pwdata);
if (rv != SECSuccess) {
SECU_PrintError(progName, "could not authenticate to token %s.",
PK11_GetTokenName(slot));
goto shutdown;
}
}
rv = ChangeTrustAttributes(certHandle, slot, name, rv = ChangeTrustAttributes(certHandle, slot, name,
certutil.options[opt_Trust].arg, &pwdata); certutil.options[opt_Trust].arg, &pwdata);
goto shutdown; goto shutdown;
@ -2676,31 +2700,54 @@ merge_fail:
if (certutil.commands[cmd_CertReq].activated || if (certutil.commands[cmd_CertReq].activated ||
certutil.commands[cmd_CreateAndAddCert].activated || certutil.commands[cmd_CreateAndAddCert].activated ||
certutil.commands[cmd_CreateNewCert].activated) { certutil.commands[cmd_CreateNewCert].activated) {
certutil_extns[ext_keyUsage] = certutil_extns[ext_keyUsage].activated =
certutil.options[opt_AddKeyUsageExt].activated; certutil.options[opt_AddCmdKeyUsageExt].activated;
certutil_extns[ext_basicConstraint] = if (!certutil_extns[ext_keyUsage].activated) {
certutil_extns[ext_keyUsage].activated =
certutil.options[opt_AddKeyUsageExt].activated;
} else {
certutil_extns[ext_keyUsage].arg =
certutil.options[opt_AddCmdKeyUsageExt].arg;
}
certutil_extns[ext_basicConstraint].activated =
certutil.options[opt_AddBasicConstraintExt].activated; certutil.options[opt_AddBasicConstraintExt].activated;
certutil_extns[ext_authorityKeyID] = certutil_extns[ext_authorityKeyID].activated =
certutil.options[opt_AddAuthorityKeyIDExt].activated; certutil.options[opt_AddAuthorityKeyIDExt].activated;
certutil_extns[ext_subjectKeyID] = certutil_extns[ext_subjectKeyID].activated =
certutil.options[opt_AddSubjectKeyIDExt].activated; certutil.options[opt_AddSubjectKeyIDExt].activated;
certutil_extns[ext_CRLDistPts] = certutil_extns[ext_CRLDistPts].activated =
certutil.options[opt_AddCRLDistPtsExt].activated; certutil.options[opt_AddCRLDistPtsExt].activated;
certutil_extns[ext_NSCertType] = certutil_extns[ext_NSCertType].activated =
certutil.options[opt_AddNSCertTypeExt].activated; certutil.options[opt_AddCmdNSCertTypeExt].activated;
certutil_extns[ext_extKeyUsage] = if (!certutil_extns[ext_NSCertType].activated) {
certutil.options[opt_AddExtKeyUsageExt].activated; certutil_extns[ext_NSCertType].activated =
certutil_extns[ext_authInfoAcc] = certutil.options[opt_AddNSCertTypeExt].activated;
} else {
certutil_extns[ext_NSCertType].arg =
certutil.options[opt_AddCmdNSCertTypeExt].arg;
}
certutil_extns[ext_extKeyUsage].activated =
certutil.options[opt_AddCmdExtKeyUsageExt].activated;
if (!certutil_extns[ext_extKeyUsage].activated) {
certutil_extns[ext_extKeyUsage].activated =
certutil.options[opt_AddExtKeyUsageExt].activated;
} else {
certutil_extns[ext_extKeyUsage].arg =
certutil.options[opt_AddCmdExtKeyUsageExt].arg;
}
certutil_extns[ext_authInfoAcc].activated =
certutil.options[opt_AddAuthInfoAccExt].activated; certutil.options[opt_AddAuthInfoAccExt].activated;
certutil_extns[ext_subjInfoAcc] = certutil_extns[ext_subjInfoAcc].activated =
certutil.options[opt_AddSubjInfoAccExt].activated; certutil.options[opt_AddSubjInfoAccExt].activated;
certutil_extns[ext_certPolicies] = certutil_extns[ext_certPolicies].activated =
certutil.options[opt_AddCertPoliciesExt].activated; certutil.options[opt_AddCertPoliciesExt].activated;
certutil_extns[ext_policyMappings] = certutil_extns[ext_policyMappings].activated =
certutil.options[opt_AddPolicyMapExt].activated; certutil.options[opt_AddPolicyMapExt].activated;
certutil_extns[ext_policyConstr] = certutil_extns[ext_policyConstr].activated =
certutil.options[opt_AddPolicyConstrExt].activated; certutil.options[opt_AddPolicyConstrExt].activated;
certutil_extns[ext_inhibitAnyPolicy] = certutil_extns[ext_inhibitAnyPolicy].activated =
certutil.options[opt_AddInhibAnyExt].activated; certutil.options[opt_AddInhibAnyExt].activated;
} }
/* /*
@ -2730,7 +2777,7 @@ merge_fail:
* and output the cert to another file. * and output the cert to another file.
*/ */
if (certutil.commands[cmd_CreateAndAddCert].activated) { if (certutil.commands[cmd_CreateAndAddCert].activated) {
static certutilExtnList nullextnlist = {PR_FALSE}; static certutilExtnList nullextnlist = {{PR_FALSE, NULL}};
rv = CertReq(privkey, pubkey, keytype, hashAlgTag, subject, rv = CertReq(privkey, pubkey, keytype, hashAlgTag, subject,
certutil.options[opt_PhoneNumber].arg, certutil.options[opt_PhoneNumber].arg,
certutil.options[opt_ASCIIForIO].activated, certutil.options[opt_ASCIIForIO].activated,

Просмотреть файл

@ -67,7 +67,12 @@ enum certutilExtns {
ext_End ext_End
}; };
typedef PRBool certutilExtnList[ext_End]; typedef struct ExtensionEntryStr {
PRBool activated;
const char *arg;
} ExtensionEntry;
typedef ExtensionEntry certutilExtnList[ext_End];
extern SECStatus extern SECStatus
AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames, AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames,

Просмотреть файл

@ -604,12 +604,12 @@ CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size,
pwdata /*wincx*/); pwdata /*wincx*/);
/* free up the params */ /* free up the params */
switch (keytype) { switch (keytype) {
case rsaKey: /* nothing to free */ break;
case dsaKey: if (dsaparams) CERTUTIL_DestroyParamsPQG(dsaparams); case dsaKey: if (dsaparams) CERTUTIL_DestroyParamsPQG(dsaparams);
break; break;
#ifdef NSS_ENABLE_ECC #ifdef NSS_ENABLE_ECC
case ecKey: SECITEM_FreeItem((SECItem *)params, PR_TRUE); break; case ecKey: SECITEM_FreeItem((SECItem *)params, PR_TRUE); break;
#endif #endif
default: /* nothing to free */ break;
} }
return privKey; return privKey;
} }

Просмотреть файл

@ -542,7 +542,7 @@ int main(int argc, char **argv)
/* Check if self-signed */ /* Check if self-signed */
selfSigned = (CERT_CompareName(&cert->issuer, &cert->subject) == 0); selfSigned = (CERT_CompareName(&cert->issuer, &cert->subject) == 0);
if (selfSigned) { if (selfSigned) {
printf("INFO: Certificate is self-signed.\n"); printf("INFO: Certificate is self signed.\n");
} else { } else {
printf("INFO: Certificate is NOT self-signed.\n"); printf("INFO: Certificate is NOT self-signed.\n");
} }

Просмотреть файл

@ -479,7 +479,7 @@ formatCMMFResponse(char *nickname, char *base64Response)
} }
printf("true);\n" printf("true);\n"
"if(retVal == '') {\n" "if(retVal == '') {\n"
"\tdocument.write(\"<h1>New Certificate Succesfully Imported.</h1>\");\n" "\tdocument.write(\"<h1>New Certificate Successfully Imported.</h1>\");\n"
"} else {\n" "} else {\n"
"\tdocument.write(\"<h2>Unable to import New Certificate</h2>\");\n" "\tdocument.write(\"<h2>Unable to import New Certificate</h2>\");\n"
"\tdocument.write(\"crypto.importUserCertificates returned <b>\");\n" "\tdocument.write(\"crypto.importUserCertificates returned <b>\");\n"

0
security/nss/cmd/ecperf/manifest.mn Normal file → Executable file
Просмотреть файл

Просмотреть файл

@ -2564,6 +2564,304 @@ loser:
} }
#endif /* NSS_ENABLE_ECC */ #endif /* NSS_ENABLE_ECC */
/*
* Read a value from the test and allocate the result.
*/
static unsigned char *
alloc_value(char *buf, int *len)
{
unsigned char * value;
int i, count;
if (strncmp(buf, "<None>", 6) == 0) {
*len = 0;
return NULL;
}
/* find the length of the number */
for (count = 0; isxdigit(buf[count]); count++);
*len = count/2;
if (*len == 0) {
return NULL;
}
value = PORT_Alloc(*len);
if (!value) {
*len = 0;
return NULL;
}
for (i=0; i<*len; buf+=2 , i++) {
hex_to_byteval(buf, &value[i]);
}
return value;
}
PRBool
isblankline(char *b)
{
while (isspace(*b)) b++;
if ((*b == '\n') || (*b == 0)) {
return PR_TRUE;
}
return PR_FALSE;
}
/*
* Perform the Hash_DRBG (CAVS) for the RNG algorithm
*
* reqfn is the pathname of the REQUEST file.
*
* The output RESPONSE file is written to stdout.
*/
void
drbg(char *reqfn)
{
char buf[2000]; /* test case has some very long lines, returned bits
* as high as 800 bytes (6400 bits). That 1600 byte
* plus a tag */
char buf2[2000];
FILE *rngreq; /* input stream from the REQUEST file */
FILE *rngresp; /* output stream to the RESPONSE file */
unsigned int i;
unsigned char *entropy = NULL;
int entropy_len = 0;
unsigned char *nonce = NULL;
int nonce_len = 0;
unsigned char *personalization_string = NULL;
int ps_len = 0;
unsigned char *return_bytes = NULL;
unsigned char *predicted_return_bytes = NULL;
int return_bytes_len = 0;
unsigned char *additional_input = NULL;
int additional_len = 0;
enum { NONE, INSTANTIATE, GENERATE, RESEED, UNINSTANTIATE } command =
NONE;
SECStatus rv;
rngreq = fopen(reqfn, "r");
rngresp = stdout;
while (fgets(buf, sizeof buf, rngreq) != NULL) {
/* a comment, skip it. */
if (buf[0] == '#') {
fputs(buf, rngresp);
continue;
}
if (isblankline(buf)) {
switch (command) {
case INSTANTIATE:
rv = PRNGTEST_Instantiate(entropy, entropy_len,
nonce, nonce_len,
personalization_string, ps_len);
if (rv != SECSuccess) {
goto loser;
}
/* clear */
if (entropy) {
PORT_ZFree(entropy, entropy_len);
entropy = NULL;
entropy_len = 0;
}
if (nonce) {
PORT_ZFree(nonce, nonce_len);
nonce = NULL;
nonce_len = 0;
}
if (personalization_string) {
PORT_ZFree(personalization_string, ps_len);
personalization_string = NULL;
ps_len = 0;
}
break;
case GENERATE:
rv = PRNGTEST_Generate(return_bytes, return_bytes_len,
additional_input, additional_len);
if (rv != SECSuccess) {
goto loser;
}
/* clear */
if (predicted_return_bytes) {
fputc('+', rngresp);
}
fputs("Returned bits = ", rngresp);
to_hex_str(buf2, return_bytes, return_bytes_len);
fputs(buf2, rngresp);
fputc('\n', rngresp);
if (predicted_return_bytes) {
if (memcmp(return_bytes,
predicted_return_bytes, return_bytes_len) != 0) {
fprintf(stderr, "Generate failed:\n");
fputs( " predicted=", stderr);
to_hex_str(buf, predicted_return_bytes,
return_bytes_len);
fputs(buf, stderr);
fputs("\n actual = ", stderr);
fputs(buf2, stderr);
fputc('\n', stderr);
}
PORT_ZFree(predicted_return_bytes, return_bytes_len);
predicted_return_bytes = NULL;
}
if (return_bytes) {
PORT_ZFree(return_bytes, return_bytes_len);
return_bytes = NULL;
return_bytes_len = 0;
}
if (additional_input) {
PORT_ZFree(additional_input, additional_len);
additional_input = NULL;
additional_len = 0;
}
break;
case RESEED:
rv = PRNGTEST_Reseed(entropy, entropy_len,
additional_input, additional_len);
if (rv != SECSuccess) {
goto loser;
}
/* clear */
if (entropy) {
PORT_ZFree(entropy, entropy_len);
entropy = NULL;
entropy_len = 0;
}
if (additional_input) {
PORT_ZFree(additional_input, additional_len);
additional_input = NULL;
additional_len = 0;
}
break;
case UNINSTANTIATE:
rv = PRNGTEST_Uninstantiate();
if (rv != SECSuccess) {
goto loser;
}
break;
}
fputs(buf, rngresp);
command = NONE;
continue;
}
/* [Hash - SHA256] */
if (buf[0] == '[') {
fputs(buf, rngresp);
continue;
}
/* INSTANTIATE */
if (strncmp(buf, "INSTANTIATE", 11) == 0) {
i = 11;
command = INSTANTIATE;
fputs(buf, rngresp);
continue;
}
/* Generate bytes */
if (strncmp(buf, "GENERATE", 8) == 0) {
i = 8;
while (isspace(buf[i])) {
i++;
}
return_bytes_len = atoi(&buf[i])/8;
return_bytes = PORT_Alloc(return_bytes_len);
command = GENERATE;
fputs(buf, rngresp);
continue;
}
if (strncmp(buf, "RESEED", 6) == 0) {
i = 6;
command = RESEED;
fputs(buf, rngresp);
continue;
}
if (strncmp(buf, "UNINSTANTIATE", 13) == 0) {
i = 13;
command = UNINSTANTIATE;
fputs(buf, rngresp);
continue;
}
/* Entropy input = ... */
if (strncmp(buf, "Entropy input", 13) == 0) {
i = 13;
while (isspace(buf[i]) || buf[i] == '=') {
i++;
}
if ((command == INSTANTIATE) || (command == RESEED)) {
entropy = alloc_value(&buf[i], &entropy_len);
}
fputs(buf, rngresp);
continue;
}
/* Nonce = ... */
if (strncmp(buf, "Nonce", 5) == 0) {
i = 5;
while (isspace(buf[i]) || buf[i] == '=') {
i++;
}
if (command == INSTANTIATE) {
nonce = alloc_value(&buf[i], &nonce_len);
}
fputs(buf, rngresp);
continue;
}
/* Personalization string = ... */
if (strncmp(buf, "Personalization string", 22) == 0) {
i = 22;
while (isspace(buf[i]) || buf[i] == '=') {
i++;
}
if (command == INSTANTIATE) {
personalization_string = alloc_value(&buf[i], &ps_len);
}
fputs(buf, rngresp);
continue;
}
/* Returned bits = ... */
if (strncmp(buf, "Returned bits", 13) == 0) {
i = 13;
while (isspace(buf[i]) || buf[i] == '=') {
i++;
}
if (command == GENERATE) {
int len;
predicted_return_bytes = alloc_value(&buf[i], &len);
}
fputs(buf, rngresp);
continue;
}
/* Additional input = ... */
if (strncmp(buf, "Additional input", 16) == 0) {
i = 16;
while (isspace(buf[i]) || buf[i] == '=') {
i++;
}
if ((command == GENERATE) || (command = RESEED)) {
additional_input = alloc_value(&buf[i], &additional_len);
}
fputs(buf, rngresp);
continue;
}
}
loser:
fclose(rngreq);
}
/* /*
* Perform the RNG Variable Seed Test (VST) for the RNG algorithm * Perform the RNG Variable Seed Test (VST) for the RNG algorithm
* "DSA - Generation of X", used both as specified and as a generic * "DSA - Generation of X", used both as specified and as a generic
@ -4597,6 +4895,9 @@ int main(int argc, char **argv)
/* Monte Carlo Test */ /* Monte Carlo Test */
rng_mct(argv[3]); rng_mct(argv[3]);
} }
} else if (strcmp(argv[1], "drbg") == 0) {
/* Variable Seed Test */
drbg(argv[2]);
} }
return 0; return 0;
} }

Просмотреть файл

@ -8,22 +8,12 @@
# directory where the REQUEST (.req) files reside. The script generates the # directory where the REQUEST (.req) files reside. The script generates the
# RESPONSE (.rsp) files in the same directory. # RESPONSE (.rsp) files in the same directory.
vst_requests=" drbg_requests="
FIPS186_VST.req SHA256_DRBG.req
FIPS186_VSTGEN.req
"
mct_requests="
FIPS186_MCT.req
FIPS186_MCTGEN.req
" "
for request in $vst_requests; do for request in $drbg_requests; do
response=`echo $request | sed -e "s/req/rsp/"` response=`echo $request | sed -e "s/req/rsp/"`
echo $request $response echo $request $response
fipstest rng vst $request > $response fipstest drbg $request > $response
done
for request in $mct_requests; do
response=`echo $request | sed -e "s/req/rsp/"`
echo $request $response
fipstest rng mct $request > $response
done done

Просмотреть файл

@ -47,6 +47,7 @@ PRIVATE_EXPORTS = secutil.h \
NSPRerrs.h \ NSPRerrs.h \
SECerrs.h \ SECerrs.h \
SSLerrs.h \ SSLerrs.h \
pk11table.h \
$(NULL) $(NULL)
CSRCS = secutil.c \ CSRCS = secutil.c \
@ -56,6 +57,7 @@ CSRCS = secutil.c \
pppolicy.c \ pppolicy.c \
secerror.c \ secerror.c \
ffs.c \ ffs.c \
pk11table.c \
$(NULL) $(NULL)
REQUIRES = dbm REQUIRES = dbm

Просмотреть файл

@ -34,8 +34,7 @@
* *
* ***** END LICENSE BLOCK ***** */ * ***** END LICENSE BLOCK ***** */
#include <pkcs11.h> #include "pk11table.h"
#include "pk11util.h"
const char *_valueString[] = { const char *_valueString[] = {
"None", "None",
@ -483,6 +482,14 @@ const Constant _consts[] = {
mkEntry(CKM_CAMELLIA_MAC, Mechanism), mkEntry(CKM_CAMELLIA_MAC, Mechanism),
mkEntry(CKM_CAMELLIA_MAC_GENERAL, Mechanism), mkEntry(CKM_CAMELLIA_MAC_GENERAL, Mechanism),
mkEntry(CKM_CAMELLIA_CBC_PAD, Mechanism), mkEntry(CKM_CAMELLIA_CBC_PAD, Mechanism),
mkEntry(CKM_SEED_KEY_GEN, Mechanism),
mkEntry(CKM_SEED_ECB, Mechanism),
mkEntry(CKM_SEED_CBC, Mechanism),
mkEntry(CKM_SEED_MAC, Mechanism),
mkEntry(CKM_SEED_MAC_GENERAL, Mechanism),
mkEntry(CKM_SEED_CBC_PAD, Mechanism),
mkEntry(CKM_SEED_ECB_ENCRYPT_DATA, Mechanism),
mkEntry(CKM_SEED_CBC_ENCRYPT_DATA, Mechanism),
mkEntry(CKM_DSA_PARAMETER_GEN, Mechanism), mkEntry(CKM_DSA_PARAMETER_GEN, Mechanism),
mkEntry(CKM_DH_PKCS_PARAMETER_GEN, Mechanism), mkEntry(CKM_DH_PKCS_PARAMETER_GEN, Mechanism),
mkEntry(CKM_NETSCAPE_AES_KEY_WRAP, Mechanism), mkEntry(CKM_NETSCAPE_AES_KEY_WRAP, Mechanism),
@ -1405,7 +1412,38 @@ const Topics _topics[] = {
}, },
}; };
const Topics *topics=&_topics[0]; const Topics *topics= &_topics[0];
const int topicCount = sizeof(_topics)/sizeof(_topics[0]); const int topicCount = sizeof(_topics) / sizeof(_topics[0]);
const char *
getName(CK_ULONG value, ConstType type)
{
int i;
for (i=0; i < constCount; i++) {
if (consts[i].type == type && consts[i].value == value) {
return consts[i].name;
}
if (type == ConstNone && consts[i].value == value) {
return consts[i].name;
}
}
return NULL;
}
const char *
getNameFromAttribute(CK_ATTRIBUTE_TYPE type)
{
return getName(type, ConstAttribute);
}
int totalKnownType(ConstType type) {
int count = 0;
int i;
for (i=0; i < constCount; i++) {
if (consts[i].type == type) count++;
}
return count;
}

Просмотреть файл

@ -1,3 +1,40 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1994-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef _PK11_TABLE_H_
#define _PK11_TABLE_H_
/* /*
* Supported functions.. * Supported functions..
@ -163,3 +200,13 @@ extern const int commandCount;
extern const Topics *topics; extern const Topics *topics;
extern const int topicCount; extern const int topicCount;
extern const char *
getName(CK_ULONG value, ConstType type);
extern const char *
getNameFromAttribute(CK_ATTRIBUTE_TYPE type);
extern int totalKnownType(ConstType type);
#endif /* _PK11_TABLE_H_ */

Просмотреть файл

@ -3252,7 +3252,7 @@ SECU_PrintTrustFlags(FILE *out, CERTCertTrust *trust, char *m, int level)
printFlags(out, trust->objectSigningFlags, level+2); printFlags(out, trust->objectSigningFlags, level+2);
} }
int SECU_PrintSignedData(FILE *out, SECItem *der, char *m, int SECU_PrintSignedData(FILE *out, SECItem *der, const char *m,
int level, SECU_PPFunc inner) int level, SECU_PPFunc inner)
{ {
PRArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); PRArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);

Просмотреть файл

@ -286,8 +286,8 @@ extern int SECU_PrintPKCS7ContentInfo(FILE *out, SECItem *der, char *m,
extern SECStatus SECU_PKCS11Init(PRBool readOnly); extern SECStatus SECU_PKCS11Init(PRBool readOnly);
/* Dump contents of signed data */ /* Dump contents of signed data */
extern int SECU_PrintSignedData(FILE *out, SECItem *der, char *m, int level, extern int SECU_PrintSignedData(FILE *out, SECItem *der, const char *m,
SECU_PPFunc inner); int level, SECU_PPFunc inner);
/* Print cert data and its trust flags */ /* Print cert data and its trust flags */
extern SECStatus SEC_PrintCertificateAndTrust(CERTCertificate *cert, extern SECStatus SEC_PrintCertificateAndTrust(CERTCertificate *cert,

0
security/nss/cmd/libpkix/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/perf/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/certsel/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/checker/manifest.mn Normal file → Executable file
Просмотреть файл

Просмотреть файл

0
security/nss/cmd/libpkix/pkix/crlsel/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/params/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/results/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/store/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/store/test_store.c Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/top/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix/util/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix_pl/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix_pl/module/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix_pl/pki/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkix_pl/system/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkixlibs.mk Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/pkixrules.mk Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/sample_apps/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/testutil/manifest.mn Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/testutil/testutil.c Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/testutil/testutil.h Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/testutil/testutil_nss.c Normal file → Executable file
Просмотреть файл

0
security/nss/cmd/libpkix/testutil/testutil_nss.h Normal file → Executable file
Просмотреть файл

4
security/nss/cmd/pk11mode/Makefile Normal file → Executable file
Просмотреть файл

@ -56,6 +56,8 @@ include $(CORE_DEPTH)/coreconf/config.mk
# (4) Include "local" platform-dependent assignments (OPTIONAL). # # (4) Include "local" platform-dependent assignments (OPTIONAL). #
####################################################################### #######################################################################
include ../platlibs.mk
ifeq ($(OS_ARCH), WINNT) ifeq ($(OS_ARCH), WINNT)
EXTRA_LIBS += \ EXTRA_LIBS += \
@ -91,3 +93,5 @@ include $(CORE_DEPTH)/coreconf/rules.mk
# (7) Execute "local" rules. (OPTIONAL). # # (7) Execute "local" rules. (OPTIONAL). #
####################################################################### #######################################################################
include ../platrules.mk

Просмотреть файл

@ -45,4 +45,4 @@ CSRCS = pk11mode.c
PROGRAM = pk11mode PROGRAM = pk11mode
REQUIRES = REQUIRES = seccmd

Просмотреть файл

@ -67,8 +67,7 @@
#include "plgetopt.h" #include "plgetopt.h"
#include "prenv.h" #include "prenv.h"
#include "pkcs11.h" #include "pk11table.h"
#define NUM_ELEM(array) (sizeof(array)/sizeof(array[0])) #define NUM_ELEM(array) (sizeof(array)/sizeof(array[0]))
@ -76,154 +75,17 @@
#define NULL_PTR 0 #define NULL_PTR 0
#endif #endif
struct tuple_str {
CK_RV errNum;
const char * errString;
};
typedef struct tuple_str tuple_str;
static const tuple_str errStrings[] = {
{CKR_OK , "CKR_OK "},
{CKR_CANCEL , "CKR_CANCEL "},
{CKR_HOST_MEMORY , "CKR_HOST_MEMORY "},
{CKR_SLOT_ID_INVALID , "CKR_SLOT_ID_INVALID "},
{CKR_GENERAL_ERROR , "CKR_GENERAL_ERROR "},
{CKR_FUNCTION_FAILED , "CKR_FUNCTION_FAILED "},
{CKR_ARGUMENTS_BAD , "CKR_ARGUMENTS_BAD "},
{CKR_NO_EVENT , "CKR_NO_EVENT "},
{CKR_NEED_TO_CREATE_THREADS , "CKR_NEED_TO_CREATE_THREADS "},
{CKR_CANT_LOCK , "CKR_CANT_LOCK "},
{CKR_ATTRIBUTE_READ_ONLY , "CKR_ATTRIBUTE_READ_ONLY "},
{CKR_ATTRIBUTE_SENSITIVE , "CKR_ATTRIBUTE_SENSITIVE "},
{CKR_ATTRIBUTE_TYPE_INVALID , "CKR_ATTRIBUTE_TYPE_INVALID "},
{CKR_ATTRIBUTE_VALUE_INVALID , "CKR_ATTRIBUTE_VALUE_INVALID "},
{CKR_DATA_INVALID , "CKR_DATA_INVALID "},
{CKR_DATA_LEN_RANGE , "CKR_DATA_LEN_RANGE "},
{CKR_DEVICE_ERROR , "CKR_DEVICE_ERROR "},
{CKR_DEVICE_MEMORY , "CKR_DEVICE_MEMORY "},
{CKR_DEVICE_REMOVED , "CKR_DEVICE_REMOVED "},
{CKR_ENCRYPTED_DATA_INVALID , "CKR_ENCRYPTED_DATA_INVALID "},
{CKR_ENCRYPTED_DATA_LEN_RANGE , "CKR_ENCRYPTED_DATA_LEN_RANGE "},
{CKR_FUNCTION_CANCELED , "CKR_FUNCTION_CANCELED "},
{CKR_FUNCTION_NOT_PARALLEL , "CKR_FUNCTION_NOT_PARALLEL "},
{CKR_FUNCTION_NOT_SUPPORTED , "CKR_FUNCTION_NOT_SUPPORTED "},
{CKR_KEY_HANDLE_INVALID , "CKR_KEY_HANDLE_INVALID "},
{CKR_KEY_SIZE_RANGE , "CKR_KEY_SIZE_RANGE "},
{CKR_KEY_TYPE_INCONSISTENT , "CKR_KEY_TYPE_INCONSISTENT "},
{CKR_KEY_NOT_NEEDED , "CKR_KEY_NOT_NEEDED "},
{CKR_KEY_CHANGED , "CKR_KEY_CHANGED "},
{CKR_KEY_NEEDED , "CKR_KEY_NEEDED "},
{CKR_KEY_INDIGESTIBLE , "CKR_KEY_INDIGESTIBLE "},
{CKR_KEY_FUNCTION_NOT_PERMITTED , "CKR_KEY_FUNCTION_NOT_PERMITTED "},
{CKR_KEY_NOT_WRAPPABLE , "CKR_KEY_NOT_WRAPPABLE "},
{CKR_KEY_UNEXTRACTABLE , "CKR_KEY_UNEXTRACTABLE "},
{CKR_MECHANISM_INVALID , "CKR_MECHANISM_INVALID "},
{CKR_MECHANISM_PARAM_INVALID , "CKR_MECHANISM_PARAM_INVALID "},
{CKR_OBJECT_HANDLE_INVALID , "CKR_OBJECT_HANDLE_INVALID "},
{CKR_OPERATION_ACTIVE , "CKR_OPERATION_ACTIVE "},
{CKR_OPERATION_NOT_INITIALIZED , "CKR_OPERATION_NOT_INITIALIZED "},
{CKR_PIN_INCORRECT , "CKR_PIN_INCORRECT "},
{CKR_PIN_INVALID , "CKR_PIN_INVALID "},
{CKR_PIN_LEN_RANGE , "CKR_PIN_LEN_RANGE "},
{CKR_PIN_EXPIRED , "CKR_PIN_EXPIRED "},
{CKR_PIN_LOCKED , "CKR_PIN_LOCKED "},
{CKR_SESSION_CLOSED , "CKR_SESSION_CLOSED "},
{CKR_SESSION_COUNT , "CKR_SESSION_COUNT "},
{CKR_SESSION_HANDLE_INVALID , "CKR_SESSION_HANDLE_INVALID "},
{CKR_SESSION_PARALLEL_NOT_SUPPORTED , "CKR_SESSION_PARALLEL_NOT_SUPPORTED "},
{CKR_SESSION_READ_ONLY , "CKR_SESSION_READ_ONLY "},
{CKR_SESSION_EXISTS , "CKR_SESSION_EXISTS "},
{CKR_SESSION_READ_ONLY_EXISTS , "CKR_SESSION_READ_ONLY_EXISTS "},
{CKR_SESSION_READ_WRITE_SO_EXISTS , "CKR_SESSION_READ_WRITE_SO_EXISTS "},
{CKR_SIGNATURE_INVALID , "CKR_SIGNATURE_INVALID "},
{CKR_SIGNATURE_LEN_RANGE , "CKR_SIGNATURE_LEN_RANGE "},
{CKR_TEMPLATE_INCOMPLETE , "CKR_TEMPLATE_INCOMPLETE "},
{CKR_TEMPLATE_INCONSISTENT , "CKR_TEMPLATE_INCONSISTENT "},
{CKR_TOKEN_NOT_PRESENT , "CKR_TOKEN_NOT_PRESENT "},
{CKR_TOKEN_NOT_RECOGNIZED , "CKR_TOKEN_NOT_RECOGNIZED "},
{CKR_TOKEN_WRITE_PROTECTED , "CKR_TOKEN_WRITE_PROTECTED "},
{CKR_UNWRAPPING_KEY_HANDLE_INVALID , "CKR_UNWRAPPING_KEY_HANDLE_INVALID "},
{CKR_UNWRAPPING_KEY_SIZE_RANGE , "CKR_UNWRAPPING_KEY_SIZE_RANGE "},
{CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT, "CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT"},
{CKR_USER_ALREADY_LOGGED_IN , "CKR_USER_ALREADY_LOGGED_IN "},
{CKR_USER_NOT_LOGGED_IN , "CKR_USER_NOT_LOGGED_IN "},
{CKR_USER_PIN_NOT_INITIALIZED , "CKR_USER_PIN_NOT_INITIALIZED "},
{CKR_USER_TYPE_INVALID , "CKR_USER_TYPE_INVALID "},
{CKR_USER_ANOTHER_ALREADY_LOGGED_IN , "CKR_USER_ANOTHER_ALREADY_LOGGED_IN "},
{CKR_USER_TOO_MANY_TYPES , "CKR_USER_TOO_MANY_TYPES "},
{CKR_WRAPPED_KEY_INVALID , "CKR_WRAPPED_KEY_INVALID "},
{CKR_WRAPPED_KEY_LEN_RANGE , "CKR_WRAPPED_KEY_LEN_RANGE "},
{CKR_WRAPPING_KEY_HANDLE_INVALID , "CKR_WRAPPING_KEY_HANDLE_INVALID "},
{CKR_WRAPPING_KEY_SIZE_RANGE , "CKR_WRAPPING_KEY_SIZE_RANGE "},
{CKR_WRAPPING_KEY_TYPE_INCONSISTENT , "CKR_WRAPPING_KEY_TYPE_INCONSISTENT "},
{CKR_RANDOM_SEED_NOT_SUPPORTED , "CKR_RANDOM_SEED_NOT_SUPPORTED "},
{CKR_RANDOM_NO_RNG , "CKR_RANDOM_NO_RNG "},
{CKR_DOMAIN_PARAMS_INVALID , "CKR_DOMAIN_PARAMS_INVALID "},
{CKR_BUFFER_TOO_SMALL , "CKR_BUFFER_TOO_SMALL "},
{CKR_SAVED_STATE_INVALID , "CKR_SAVED_STATE_INVALID "},
{CKR_INFORMATION_SENSITIVE , "CKR_INFORMATION_SENSITIVE "},
{CKR_STATE_UNSAVEABLE , "CKR_STATE_UNSAVEABLE "},
{CKR_CRYPTOKI_NOT_INITIALIZED , "CKR_CRYPTOKI_NOT_INITIALIZED "},
{CKR_CRYPTOKI_ALREADY_INITIALIZED , "CKR_CRYPTOKI_ALREADY_INITIALIZED "},
{CKR_MUTEX_BAD , "CKR_MUTEX_BAD "},
{CKR_MUTEX_NOT_LOCKED , "CKR_MUTEX_NOT_LOCKED "},
{CKR_FUNCTION_REJECTED , "CKR_FUNCTION_REJECTED "},
{CKR_VENDOR_DEFINED , "CKR_VENDOR_DEFINED "},
{0xCE534351 , "CKR_NETSCAPE_CERTDB_FAILED "},
{0xCE534352 , "CKR_NETSCAPE_KEYDB_FAILED "}
};
static const CK_ULONG numStrings = sizeof(errStrings) / sizeof(tuple_str);
/* Returns constant error string for "CRV". /* Returns constant error string for "CRV".
* Returns "unknown error" if errNum is unknown. * Returns "unknown error" if errNum is unknown.
*/ */
const char * const char *
PKM_CK_RVtoStr(CK_RV errNum) { PKM_CK_RVtoStr(CK_RV errNum) {
CK_ULONG low = 1; const char * err;
CK_ULONG high = numStrings - 1;
CK_ULONG i;
CK_RV num;
static int initDone;
/* make sure table is in ascending order. err = getName(errNum, ConstResult);
* binary search depends on it.
*/ if (err) return err;
if (!initDone) {
CK_RV lastNum = CKR_OK;
for (i = low; i <= high; ++i) {
num = errStrings[i].errNum;
if (num <= lastNum) {
fprintf(stderr,
"sequence error in error strings at item %d\n"
"error %d (%s)\n"
"should come after \n"
"error %d (%s)\n",
(int) i, (int) lastNum, errStrings[i-1].errString,
(int) num, errStrings[i].errString);
}
lastNum = num;
}
initDone = 1;
}
/* Do binary search of table. */
while (low + 1 < high) {
i = (low + high) / 2;
num = errStrings[i].errNum;
if (errNum == num)
return errStrings[i].errString;
if (errNum < num)
high = i;
else
low = i;
}
if (errNum == errStrings[low].errNum)
return errStrings[low].errString;
if (errNum == errStrings[high].errNum)
return errStrings[high].errString;
return "unknown error"; return "unknown error";
} }
@ -251,81 +113,6 @@ typedef struct CK_C_INITIALIZE_ARGS_NSS {
#include "pkcs11u.h" #include "pkcs11u.h"
static CK_ATTRIBUTE_TYPE all_known_attribute_types[] = {
CKA_CLASS,
CKA_TOKEN,
CKA_PRIVATE,
CKA_LABEL,
CKA_APPLICATION,
CKA_VALUE,
CKA_CERTIFICATE_TYPE,
CKA_ISSUER,
CKA_SERIAL_NUMBER,
CKA_KEY_TYPE,
CKA_SUBJECT,
CKA_ID,
CKA_SENSITIVE,
CKA_ENCRYPT,
CKA_DECRYPT,
CKA_WRAP,
CKA_UNWRAP,
CKA_SIGN,
CKA_SIGN_RECOVER,
CKA_VERIFY,
CKA_VERIFY_RECOVER,
CKA_DERIVE,
CKA_START_DATE,
CKA_END_DATE,
CKA_MODULUS,
CKA_MODULUS_BITS,
CKA_PUBLIC_EXPONENT,
CKA_PRIVATE_EXPONENT,
CKA_PRIME_1,
CKA_PRIME_2,
CKA_EXPONENT_1,
CKA_EXPONENT_2,
CKA_COEFFICIENT,
CKA_PRIME,
CKA_SUBPRIME,
CKA_BASE,
CKA_VALUE_BITS,
CKA_VALUE_LEN,
CKA_EXTRACTABLE,
CKA_LOCAL,
CKA_NEVER_EXTRACTABLE,
CKA_ALWAYS_SENSITIVE,
CKA_MODIFIABLE,
#ifdef CKA_NETSCAPE
CKA_NETSCAPE_URL,
CKA_NETSCAPE_EMAIL,
CKA_NETSCAPE_SMIME_INFO,
CKA_NETSCAPE_SMIME_TIMESTAMP,
CKA_NETSCAPE_PKCS8_SALT,
CKA_NETSCAPE_PASSWORD_CHECK,
CKA_NETSCAPE_EXPIRES,
#endif /* CKA_NETSCAPE */
#ifdef CKA_TRUST
CKA_TRUST_DIGITAL_SIGNATURE,
CKA_TRUST_NON_REPUDIATION,
CKA_TRUST_KEY_ENCIPHERMENT,
CKA_TRUST_DATA_ENCIPHERMENT,
CKA_TRUST_KEY_AGREEMENT,
CKA_TRUST_KEY_CERT_SIGN,
CKA_TRUST_CRL_SIGN,
CKA_TRUST_SERVER_AUTH,
CKA_TRUST_CLIENT_AUTH,
CKA_TRUST_CODE_SIGNING,
CKA_TRUST_EMAIL_PROTECTION,
CKA_TRUST_IPSEC_END_SYSTEM,
CKA_TRUST_IPSEC_TUNNEL,
CKA_TRUST_IPSEC_USER,
CKA_TRUST_TIME_STAMPING,
#endif /* CKA_TRUST */
};
static int number_of_all_known_attribute_types =
(sizeof(all_known_attribute_types)/sizeof(all_known_attribute_types[0]));
#define MAX_SIG_SZ 128 #define MAX_SIG_SZ 128
#define MAX_CIPHER_SZ 128 #define MAX_CIPHER_SZ 128
#define MAX_DATA_SZ 64 #define MAX_DATA_SZ 64
@ -1824,7 +1611,7 @@ void PKM_LogIt(const char *fmt, ...) {
printf("NON FIPS MODE: "); printf("NON FIPS MODE: ");
} else if (MODE == HYBRIDMODE) { } else if (MODE == HYBRIDMODE) {
printf("Hybrid MODE: "); printf("Hybrid MODE: ");
} else printf ("NO MODE: "); }
vprintf(fmt, args); vprintf(fmt, args);
va_end(args); va_end(args);
} }
@ -1903,7 +1690,7 @@ CK_RV PKM_InitPWforDB(CK_FUNCTION_LIST_PTR pFunctionList,
} }
if (MODE == FIPSMODE) { if (MODE == FIPSMODE) {
crv = pFunctionList->C_InitPIN(hSession, (CK_UTF8CHAR *) weakPin, crv = pFunctionList->C_InitPIN(hSession, (CK_UTF8CHAR *) weakPin,
sizeof(weakPin)); strlen((char *)weakPin));
if (crv == CKR_OK) { if (crv == CKR_OK) {
PKM_Error( "C_InitPIN with a weak password succeeded\n"); PKM_Error( "C_InitPIN with a weak password succeeded\n");
return crv; return crv;
@ -1913,7 +1700,7 @@ CK_RV PKM_InitPWforDB(CK_FUNCTION_LIST_PTR pFunctionList,
} }
} }
crv = pFunctionList->C_InitPIN(hSession, (CK_UTF8CHAR *) testPin, crv = pFunctionList->C_InitPIN(hSession, (CK_UTF8CHAR *) testPin,
sizeof(testPin)); strlen((char *)testPin));
if (crv == CKR_OK) { if (crv == CKR_OK) {
PKM_LogIt("C_InitPIN succeeded\n"); PKM_LogIt("C_InitPIN succeeded\n");
} else { } else {
@ -2303,7 +2090,8 @@ CK_RV PKM_Mechanism(CK_FUNCTION_LIST_PTR pFunctionList,
CK_MECHANISM_TYPE *pMechanismList; CK_MECHANISM_TYPE *pMechanismList;
CK_ULONG mechanismCount; CK_ULONG mechanismCount;
CK_ULONG i; CK_ULONG i;
const char * mechName = NULL;
NUMTESTS++; /* increment NUMTESTS */ NUMTESTS++; /* increment NUMTESTS */
/* Get the mechanism list */ /* Get the mechanism list */
@ -2331,13 +2119,21 @@ CK_RV PKM_Mechanism(CK_FUNCTION_LIST_PTR pFunctionList,
} }
PKM_LogIt("C_GetMechanismList returned the mechanism types:\n"); PKM_LogIt("C_GetMechanismList returned the mechanism types:\n");
if (verbose) { if (verbose) {
for (i = 0; i < mechanismCount; i++) { for (i = 1; i <= mechanismCount; i++) {
printf(" 0x%08lX", pMechanismList[i]); mechName = getName(pMechanismList[(i-1)], ConstMechanism);
if ((i != 0) && ((i % 4) == 0 )) printf("\n");
/* output two mechanism name on each line */
/* currently the longest known mechansim name length is 37 */
if (mechName) {
printf("%-40s",mechName);
} else {
printf("Unknown mechanism: 0x%08lX ", pMechanismList[i]);
}
if ((i != 0) && ((i % 2) == 0 )) printf("\n");
} }
printf("\n"); printf("\n\n");
} }
for ( i = 0; i < mechanismCount; i++ ) { for ( i = 0; i < mechanismCount; i++ ) {
CK_MECHANISM_INFO minfo; CK_MECHANISM_INFO minfo;
@ -2351,7 +2147,10 @@ CK_RV PKM_Mechanism(CK_FUNCTION_LIST_PTR pFunctionList,
return crv; return crv;
} }
PKM_LogIt( " [%lu]: CK_MECHANISM_TYPE = %lu\n", (i+1), mechName = getName(pMechanismList[i], ConstMechanism);
if (!mechName) mechName = "Unknown mechanism";
PKM_LogIt( " [%lu]: CK_MECHANISM_TYPE = %s 0x%08lX\n", (i+1),
mechName,
pMechanismList[i]); pMechanismList[i]);
PKM_LogIt( " ulMinKeySize = %lu\n", minfo.ulMinKeySize); PKM_LogIt( " ulMinKeySize = %lu\n", minfo.ulMinKeySize);
PKM_LogIt( " ulMaxKeySize = %lu\n", minfo.ulMaxKeySize); PKM_LogIt( " ulMaxKeySize = %lu\n", minfo.ulMaxKeySize);
@ -3263,8 +3062,6 @@ CK_RV PKM_PubKeySign(CK_FUNCTION_LIST_PTR pFunctionList,
} }
CK_RV PKM_PublicKey(CK_FUNCTION_LIST_PTR pFunctionList, CK_RV PKM_PublicKey(CK_FUNCTION_LIST_PTR pFunctionList,
CK_SLOT_ID * pSlotList, CK_SLOT_ID * pSlotList,
CK_ULONG slotID, CK_UTF8CHAR_PTR pwd, CK_ULONG slotID, CK_UTF8CHAR_PTR pwd,
@ -3737,7 +3534,10 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
CK_SESSION_INFO sinfo; CK_SESSION_INFO sinfo;
CK_ATTRIBUTE_PTR pTemplate; CK_ATTRIBUTE_PTR pTemplate;
CK_ULONG tnObjects = 0; CK_ULONG tnObjects = 0;
int curMode;
int i;
int number_of_all_known_attribute_types = totalKnownType(ConstAttribute);
NUMTESTS++; /* increment NUMTESTS */ NUMTESTS++; /* increment NUMTESTS */
crv = pFunctionList->C_OpenSession(pSlotList[slotID], CKF_SERIAL_SESSION, crv = pFunctionList->C_OpenSession(pSlotList[slotID], CKF_SERIAL_SESSION,
@ -3789,13 +3589,16 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
pTemplate = (CK_ATTRIBUTE_PTR)calloc(number_of_all_known_attribute_types, pTemplate = (CK_ATTRIBUTE_PTR)calloc(number_of_all_known_attribute_types,
sizeof(CK_ATTRIBUTE)); sizeof(CK_ATTRIBUTE));
if ( (CK_ATTRIBUTE_PTR)NULL == pTemplate ) { if ( (CK_ATTRIBUTE_PTR)NULL == pTemplate ) {
PKM_Error( "[memory allocation of %lu bytes failed]\n", PKM_Error( "[pTemplate memory allocation of %lu bytes failed]\n",
number_of_all_known_attribute_types * number_of_all_known_attribute_types *
sizeof(CK_ATTRIBUTE)); sizeof(CK_ATTRIBUTE));
return crv; return crv;
} }
PKM_LogIt( " All objects:\n"); PKM_LogIt( " All objects:\n");
/* Printing table set to NOMODE */
curMode = MODE;
MODE = NOMODE;
while (1) { while (1) {
CK_OBJECT_HANDLE o = (CK_OBJECT_HANDLE)0; CK_OBJECT_HANDLE o = (CK_OBJECT_HANDLE)0;
@ -3804,6 +3607,7 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
CK_ULONG nAttributes = 0; CK_ULONG nAttributes = 0;
CK_ATTRIBUTE_PTR pT2; CK_ATTRIBUTE_PTR pT2;
CK_ULONG l; CK_ULONG l;
const char * attName = NULL;
crv = pFunctionList->C_FindObjects(h, &o, 1, &nObjects); crv = pFunctionList->C_FindObjects(h, &o, 1, &nObjects);
if ( CKR_OK != crv ) { if ( CKR_OK != crv ) {
@ -3821,10 +3625,15 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
PKM_LogIt( " OBJECT HANDLE %lu:\n", o); PKM_LogIt( " OBJECT HANDLE %lu:\n", o);
for ( k = 0; k < (CK_ULONG)number_of_all_known_attribute_types; k++ ) { k = 0;
pTemplate[k].type = all_known_attribute_types[k]; for (i=0; i < constCount; i++) {
pTemplate[k].pValue = (CK_VOID_PTR) NULL; if (consts[i].type == ConstAttribute) {
pTemplate[k].ulValueLen = 0; pTemplate[k].type = consts[i].value;
pTemplate[k].pValue = (CK_VOID_PTR) NULL;
pTemplate[k].ulValueLen = 0;
k++;
}
assert(k <= number_of_all_known_attribute_types);
} }
crv = pFunctionList->C_GetAttributeValue(h, o, pTemplate, crv = pFunctionList->C_GetAttributeValue(h, o, pTemplate,
@ -3848,38 +3657,44 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
nAttributes++; nAttributes++;
} }
} }
if ( 1 ) { PKM_LogIt( " %lu attributes:\n", nAttributes);
PKM_LogIt( " %lu attributes:\n", nAttributes); for ( k = 0; k < (CK_ULONG) number_of_all_known_attribute_types;
for ( k = 0; k < (CK_ULONG) number_of_all_known_attribute_types; k++ ) {
k++ ) { if ( -1 != (CK_LONG)pTemplate[k].ulValueLen ) {
if ( -1 != (CK_LONG)pTemplate[k].ulValueLen ) { attName = getNameFromAttribute(pTemplate[k].type);
PKM_LogIt( " 0x%08x (len = %lu)\n", if (!attName) {
pTemplate[k].type, PKM_Error("Unable to find attribute name update pk11table.c\n");
pTemplate[k].ulValueLen);
} }
PKM_LogIt( " %s 0x%08x (len = %lu)\n",
attName,
pTemplate[k].type,
pTemplate[k].ulValueLen);
} }
PKM_LogIt( "\n");
} }
PKM_LogIt( "\n");
pT2 = (CK_ATTRIBUTE_PTR)calloc(nAttributes, sizeof(CK_ATTRIBUTE)); pT2 = (CK_ATTRIBUTE_PTR)calloc(nAttributes, sizeof(CK_ATTRIBUTE));
if ( (CK_ATTRIBUTE_PTR)NULL == pT2 ) { if ( (CK_ATTRIBUTE_PTR)NULL == pT2 ) {
PKM_Error( "[memory allocation of %lu bytes failed]\n", PKM_Error( "[pT2 memory allocation of %lu bytes failed]\n",
nAttributes * sizeof(CK_ATTRIBUTE)); nAttributes * sizeof(CK_ATTRIBUTE));
return crv; return crv;
} }
/* allocate memory for the attribute values */
for ( l = 0, k = 0; k < (CK_ULONG) number_of_all_known_attribute_types; for ( l = 0, k = 0; k < (CK_ULONG) number_of_all_known_attribute_types;
k++ ) { k++ ) {
if ( -1 != (CK_LONG)pTemplate[k].ulValueLen ) { if ( -1 != (CK_LONG)pTemplate[k].ulValueLen ) {
pT2[l].type = pTemplate[k].type; pT2[l].type = pTemplate[k].type;
pT2[l].ulValueLen = pTemplate[k].ulValueLen; pT2[l].ulValueLen = pTemplate[k].ulValueLen;
pT2[l].pValue = (CK_VOID_PTR)malloc(pT2[l].ulValueLen); if (pT2[l].ulValueLen > 0) {
if ( (CK_VOID_PTR)NULL == pT2[l].pValue ) { pT2[l].pValue = (CK_VOID_PTR)malloc(pT2[l].ulValueLen);
PKM_Error( "[memory allocation of %lu bytes failed]\n", if ( (CK_VOID_PTR)NULL == pT2[l].pValue ) {
pT2[l].ulValueLen); PKM_Error( "pValue memory allocation of %lu bytes failed]\n",
return crv; pT2[l].ulValueLen);
} return crv;
}
} else pT2[l].pValue = (CK_VOID_PTR) NULL;
l++; l++;
} }
} }
@ -3901,8 +3716,11 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
} }
for ( l = 0; l < nAttributes; l++ ) { for ( l = 0; l < nAttributes; l++ ) {
PKM_LogIt( " type = 0x%08x, len = %ld", pT2[l].type, attName = getNameFromAttribute(pT2[l].type);
(CK_LONG)pT2[l].ulValueLen); if (!attName) attName = "unknown attribute";
PKM_LogIt( " type = %s len = %ld",
attName, (CK_LONG)pT2[l].ulValueLen);
if ( -1 == (CK_LONG)pT2[l].ulValueLen ) { if ( -1 == (CK_LONG)pT2[l].ulValueLen ) {
; ;
} else { } else {
@ -3936,11 +3754,15 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
PKM_LogIt( "\n"); PKM_LogIt( "\n");
for ( l = 0; l < nAttributes; l++ ) { for ( l = 0; l < nAttributes; l++ ) {
free(pT2[l].pValue); if (pT2[l].pValue) {
free(pT2[l].pValue);
}
} }
free(pT2); free(pT2);
} /* while(1) */ } /* while(1) */
MODE = curMode; /* reset the logging MODE */
crv = pFunctionList->C_FindObjectsFinal(h); crv = pFunctionList->C_FindObjectsFinal(h);
if ( CKR_OK != crv ) { if ( CKR_OK != crv ) {
PKM_Error( "C_FindObjectsFinal(%lu) returned 0x%08X, %-26s\n", h, crv, PKM_Error( "C_FindObjectsFinal(%lu) returned 0x%08X, %-26s\n", h, crv,
@ -5362,7 +5184,7 @@ CK_RV PKM_Digest(CK_FUNCTION_LIST_PTR pFunctionList,
if ( (digest1Len == digest2Len) if ( (digest1Len == digest2Len)
&& (memcmp(digest1, digest2, digest1Len) == 0) ) { && (memcmp(digest1, digest2, digest1Len) == 0) ) {
PKM_LogIt("Single and Multiple-part message digest " PKM_LogIt("Single and Multiple-part message digest "
"operations succesful\n"); "operations successful\n");
} else { } else {
PKM_Error("Single and Multiple-part message digest " PKM_Error("Single and Multiple-part message digest "
"operations failed\n"); "operations failed\n");
@ -5370,7 +5192,7 @@ CK_RV PKM_Digest(CK_FUNCTION_LIST_PTR pFunctionList,
} else { } else {
if (digest1Len == digest2Len) { if (digest1Len == digest2Len) {
PKM_LogIt("PKM_Digest Single and Multiple-part message digest " PKM_LogIt("PKM_Digest Single and Multiple-part message digest "
"operations succesful\n"); "operations successful\n");
} else { } else {
PKM_Error("PKM_Digest Single and Multiple-part message digest " PKM_Error("PKM_Digest Single and Multiple-part message digest "
"operations failed\n"); "operations failed\n");
@ -5453,7 +5275,6 @@ CK_RV PKM_ForkCheck(int expected, CK_FUNCTION_LIST_PTR fList,
CK_RV crv = CKR_OK; CK_RV crv = CKR_OK;
#ifndef NO_FORK_CHECK #ifndef NO_FORK_CHECK
int rc = -1; int rc = -1;
int retStatus = 0;
NUMTESTS++; /* increment NUMTESTS */ NUMTESTS++; /* increment NUMTESTS */
if (forkAssert) { if (forkAssert) {
putenv("NSS_STRICT_NOFORK=1"); putenv("NSS_STRICT_NOFORK=1");
@ -5476,7 +5297,7 @@ CK_RV PKM_ForkCheck(int expected, CK_FUNCTION_LIST_PTR fList,
* If it was initialized in the parent, the fork check should * If it was initialized in the parent, the fork check should
* kick in, and make it return CKR_DEVICE_ERROR. * kick in, and make it return CKR_DEVICE_ERROR.
*/ */
CK_RV child_crv = fList->C_GetTokenInfo(NULL, NULL); CK_RV child_crv = fList->C_GetTokenInfo(0, NULL);
exit(child_crv & 255); exit(child_crv & 255);
} else { } else {
/* If softoken is loaded, make a PKCS#11 call to C_Initialize /* If softoken is loaded, make a PKCS#11 call to C_Initialize
@ -5498,7 +5319,7 @@ CK_RV PKM_ForkCheck(int expected, CK_FUNCTION_LIST_PTR fList,
pid_t ret = wait(&rc); pid_t ret = wait(&rc);
if (ret != child || (!WIFEXITED(rc)) || if (ret != child || (!WIFEXITED(rc)) ||
( (expected & 255) != (WEXITSTATUS(rc) & 255)) ) { ( (expected & 255) != (WEXITSTATUS(rc) & 255)) ) {
int retstatus = -1; int retStatus = -1;
if (WIFEXITED(rc)) { if (WIFEXITED(rc)) {
retStatus = WEXITSTATUS(rc); retStatus = WEXITSTATUS(rc);
} }

Просмотреть файл

@ -42,7 +42,7 @@ DEFINES += -DNSPR20
# MODULE public and private header directories are implicitly REQUIRED. # MODULE public and private header directories are implicitly REQUIRED.
MODULE = nss MODULE = nss
CSRCS = pk11util.c pk11table.c CSRCS = pk11util.c
#CSRCS = symkeytest.c #CSRCS = symkeytest.c
# The MODULE is always implicitly required. # The MODULE is always implicitly required.

Просмотреть файл

@ -60,7 +60,7 @@
#include "pkcs11.h" #include "pkcs11.h"
#include "pk11util.h" #include "pk11table.h"
#ifndef O_BINARY #ifndef O_BINARY
#define O_BINARY 0 #define O_BINARY 0
@ -381,7 +381,7 @@ handleArray(char *vname, int *error)
if (*error == 1) { if (*error == 1) {
return INVALID_INDEX; return INVALID_INDEX;
} else if (index == INVALID_INDEX) { } else if (index == INVALID_INDEX) {
fprintf(stderr, "%s: 0x%x is an invalid index\n",vname,index); fprintf(stderr, "%s: 0x%lx is an invalid index\n",vname,index);
*error = 1; *error = 1;
} }
} }
@ -395,7 +395,7 @@ makeArrayTarget(const char *vname, const Value *value, CK_ULONG index)
CK_ULONG elementSize; CK_ULONG elementSize;
if (index >= (CK_ULONG)value->arraySize) { if (index >= (CK_ULONG)value->arraySize) {
fprintf(stderr, "%s[%d]: index larger than array size (%d)\n", fprintf(stderr, "%s[%lu]: index larger than array size (%d)\n",
vname, index, value->arraySize); vname, index, value->arraySize);
return NULL; return NULL;
} }
@ -1046,19 +1046,23 @@ printArg(Value *ptr,int arg_number)
printf(" Cryptoki Version: %d.%02d\n", printf(" Cryptoki Version: %d.%02d\n",
VERSION(info->cryptokiVersion)); VERSION(info->cryptokiVersion));
printf(" Manufacturer ID: "); printf(" Manufacturer ID: ");
printChars(info->manufacturerID,sizeof(info->manufacturerID)); printChars((char *)info->manufacturerID,
sizeof(info->manufacturerID));
printFlags(" Flags: ", info->flags, ConstInfoFlags); printFlags(" Flags: ", info->flags, ConstInfoFlags);
printf(" Library Description: "); printf(" Library Description: ");
printChars(info->libraryDescription,sizeof(info->libraryDescription)); printChars((char *)info->libraryDescription,
sizeof(info->libraryDescription));
printf(" Library Version: %d.%02d\n", printf(" Library Version: %d.%02d\n",
VERSION(info->libraryVersion)); VERSION(info->libraryVersion));
break; break;
case ArgSlotInfo: case ArgSlotInfo:
slotInfo = (CK_SLOT_INFO *)ptr->data; slotInfo = (CK_SLOT_INFO *)ptr->data;
printf(" Slot Description: "); printf(" Slot Description: ");
printChars(slotInfo->slotDescription,sizeof(slotInfo->slotDescription)); printChars((char *)slotInfo->slotDescription,
sizeof(slotInfo->slotDescription));
printf(" Manufacturer ID: "); printf(" Manufacturer ID: ");
printChars(slotInfo->manufacturerID,sizeof(slotInfo->manufacturerID)); printChars((char *)slotInfo->manufacturerID,
sizeof(slotInfo->manufacturerID));
printFlags(" Flags: ", slotInfo->flags, ConstSlotFlags); printFlags(" Flags: ", slotInfo->flags, ConstSlotFlags);
printf(" Hardware Version: %d.%02d\n", printf(" Hardware Version: %d.%02d\n",
VERSION(slotInfo->hardwareVersion)); VERSION(slotInfo->hardwareVersion));
@ -1068,13 +1072,15 @@ printArg(Value *ptr,int arg_number)
case ArgTokenInfo: case ArgTokenInfo:
tokenInfo = (CK_TOKEN_INFO *)ptr->data; tokenInfo = (CK_TOKEN_INFO *)ptr->data;
printf(" Label: "); printf(" Label: ");
printChars(tokenInfo->label,sizeof(tokenInfo->label)); printChars((char *) tokenInfo->label,sizeof(tokenInfo->label));
printf(" Manufacturer ID: "); printf(" Manufacturer ID: ");
printChars(tokenInfo->manufacturerID,sizeof(tokenInfo->manufacturerID)); printChars((char *)tokenInfo->manufacturerID,
sizeof(tokenInfo->manufacturerID));
printf(" Model: "); printf(" Model: ");
printChars(tokenInfo->model,sizeof(tokenInfo->model)); printChars((char *)tokenInfo->model,sizeof(tokenInfo->model));
printf(" Serial Number: "); printf(" Serial Number: ");
printChars(tokenInfo->serialNumber,sizeof(tokenInfo->serialNumber)); printChars((char *)tokenInfo->serialNumber,
sizeof(tokenInfo->serialNumber));
printFlags(" Flags: ", tokenInfo->flags, ConstTokenFlags); printFlags(" Flags: ", tokenInfo->flags, ConstTokenFlags);
printf(" Max Session Count: "); printf(" Max Session Count: ");
printConst(tokenInfo->ulMaxSessionCount, ConstAvailableSizes, 1); printConst(tokenInfo->ulMaxSessionCount, ConstAvailableSizes, 1);
@ -1099,7 +1105,7 @@ printArg(Value *ptr,int arg_number)
printf(" Firmware Version: %d.%02d\n", printf(" Firmware Version: %d.%02d\n",
VERSION(tokenInfo->firmwareVersion)); VERSION(tokenInfo->firmwareVersion));
printf(" UTC Time: "); printf(" UTC Time: ");
printChars(tokenInfo->utcTime,sizeof(tokenInfo->utcTime)); printChars((char *)tokenInfo->utcTime,sizeof(tokenInfo->utcTime));
break; break;
case ArgSessionInfo: case ArgSessionInfo:
sessionInfo = (CK_SESSION_INFO *)ptr->data; sessionInfo = (CK_SESSION_INFO *)ptr->data;
@ -1148,7 +1154,7 @@ printArg(Value *ptr,int arg_number)
initArgs = (CK_C_INITIALIZE_ARGS *)ptr->data; initArgs = (CK_C_INITIALIZE_ARGS *)ptr->data;
printFlags(" Flags: ", initArgs->flags, ConstInitializeFlags); printFlags(" Flags: ", initArgs->flags, ConstInitializeFlags);
if (initArgs->LibraryParameters) { if (initArgs->LibraryParameters) {
printf("Params: %s\n",initArgs->LibraryParameters); printf("Params: %s\n",(char *)initArgs->LibraryParameters);
} }
case ArgFunctionList: case ArgFunctionList:
functionList = (CK_FUNCTION_LIST *)ptr->data; functionList = (CK_FUNCTION_LIST *)ptr->data;
@ -1609,7 +1615,7 @@ do_func(int index, Value **a)
if (!func) return CKR_CRYPTOKI_NOT_INITIALIZED; if (!func) return CKR_CRYPTOKI_NOT_INITIALIZED;
return func->C_GetSlotList((CK_BBOOL)*(CK_ULONG *)a[0]->data, return func->C_GetSlotList((CK_BBOOL)*(CK_ULONG *)a[0]->data,
(CK_SLOT_ID *)a[1]->data, (CK_SLOT_ID *)a[1]->data,
(CK_LONG *)a[2]->data); (CK_ULONG *)a[2]->data);
case F_C_GetSlotInfo: case F_C_GetSlotInfo:
if (!func) return CKR_CRYPTOKI_NOT_INITIALIZED; if (!func) return CKR_CRYPTOKI_NOT_INITIALIZED;
return func->C_GetSlotInfo(*(CK_ULONG *)a[0]->data, return func->C_GetSlotInfo(*(CK_ULONG *)a[0]->data,

Просмотреть файл

@ -1114,7 +1114,7 @@ handle_connection(
char * fnEnd; char * fnEnd;
PRFileInfo info; PRFileInfo info;
/* try to open the file named. /* try to open the file named.
* If succesful, then write it to the client. * If successful, then write it to the client.
*/ */
fnEnd = strpbrk(fnBegin, " \r\n"); fnEnd = strpbrk(fnBegin, " \r\n");
if (fnEnd) { if (fnEnd) {

Просмотреть файл

@ -66,7 +66,7 @@
#include "cert.h" #include "cert.h"
#include "sslproto.h" #include "sslproto.h"
#define VERSIONSTRING "$Revision: 1.12 $ ($Date: 2008/05/07 15:42:59 $) $Author: wtc%google.com $" #define VERSIONSTRING "$Revision: 1.13 $ ($Date: 2009/03/13 02:24:07 $) $Author: nelson%bolyard.com $"
struct _DataBufferList; struct _DataBufferList;
@ -76,6 +76,10 @@ typedef struct _DataBufferList {
struct _DataBuffer *first,*last; struct _DataBuffer *first,*last;
int size; int size;
int isEncrypted; int isEncrypted;
char * msgBuf;
int msgBufOffset;
int msgBufSize;
int hMACsize;
} DataBufferList; } DataBufferList;
typedef struct _DataBuffer { typedef struct _DataBuffer {
@ -86,9 +90,6 @@ typedef struct _DataBuffer {
} DataBuffer; } DataBuffer;
DataBufferList
clientstream = {NULL, NULL, 0, 0},
serverstream = {NULL, NULL, 0, 0};
struct sslhandshake { struct sslhandshake {
PRUint8 type; PRUint8 type;
@ -133,13 +134,15 @@ typedef struct _ClientMasterKeyV2 {
} ClientMasterKeyV2; } ClientMasterKeyV2;
/* forward declaration */
void showErr(const char * msg);
#define TAPBUFSIZ 16384 #define TAPBUFSIZ 16384
#define DEFPORT 1924 #define DEFPORT 1924
#include <ctype.h> #include <ctype.h>
const char * progName;
int hexparse=0; int hexparse=0;
int sslparse=0; int sslparse=0;
int sslhexparse=0; int sslhexparse=0;
@ -147,7 +150,7 @@ int looparound=0;
int fancy=0; int fancy=0;
int isV2Session=0; int isV2Session=0;
int currentcipher=0; int currentcipher=0;
int hMACsize=0; DataBufferList clientstream, serverstream;
#define PR_FPUTS(x) PR_fprintf(PR_STDOUT, x ) #define PR_FPUTS(x) PR_fprintf(PR_STDOUT, x )
@ -172,13 +175,16 @@ int hMACsize=0;
void print_hex(int amt, unsigned char *buf); void print_hex(int amt, unsigned char *buf);
void read_stream_bytes(unsigned char *d, DataBufferList *db, int length); void read_stream_bytes(unsigned char *d, DataBufferList *db, int length);
void myhalt(int dblsize,int collectedsize) { void myhalt(int dblsize,int collectedsize)
{
while(1) ;
PR_fprintf(PR_STDERR,"HALTED\n");
PR_ASSERT(dblsize == collectedsize);
exit(13);
} }
const char *get_error_text(int error) { const char *get_error_text(int error)
{
switch (error) { switch (error) {
case PR_IO_TIMEOUT_ERROR: case PR_IO_TIMEOUT_ERROR:
return "Timeout"; return "Timeout";
@ -207,7 +213,8 @@ const char *get_error_text(int error) {
void check_integrity(DataBufferList *dbl) { void check_integrity(DataBufferList *dbl)
{
DataBuffer *db; DataBuffer *db;
int i; int i;
@ -235,15 +242,16 @@ free_head(DataBufferList *dbl)
if (dbl->first == NULL) { if (dbl->first == NULL) {
dbl->last = NULL; dbl->last = NULL;
} }
PR_Free(db->buffer); PORT_Free(db->buffer);
PR_Free(db); PORT_Free(db);
db = dbl->first; db = dbl->first;
} }
return db; return db;
} }
void void
read_stream_bytes(unsigned char *d, DataBufferList *dbl, int length) { read_stream_bytes(unsigned char *d, DataBufferList *dbl, int length)
{
int copied = 0; int copied = 0;
DataBuffer *db = dbl->first; DataBuffer *db = dbl->first;
@ -284,10 +292,18 @@ flush_stream(DataBufferList *dbl)
} }
dbl->size = 0; dbl->size = 0;
check_integrity(dbl); check_integrity(dbl);
if (dbl->msgBuf) {
PORT_Free(dbl->msgBuf);
dbl->msgBuf = NULL;
}
dbl->msgBufOffset = 0;
dbl->msgBufSize = 0;
dbl->hMACsize = 0;
} }
const char * V2CipherString(int cs_int) { const char * V2CipherString(int cs_int)
{
char *cs_str; char *cs_str;
cs_str = NULL; cs_str = NULL;
switch (cs_int) { switch (cs_int) {
@ -442,7 +458,8 @@ const char * V2CipherString(int cs_int) {
return cs_str; return cs_str;
} }
const char * helloExtensionNameString(int ex_num) { const char * helloExtensionNameString(int ex_num)
{
const char *ex_name = NULL; const char *ex_name = NULL;
static char buf[10]; static char buf[10];
@ -505,7 +522,7 @@ char * get_time_string(void)
return cp; return cp;
} }
void print_sslv2(DataBufferList *s, unsigned char *tbuf, unsigned int alloclen) void print_sslv2(DataBufferList *s, unsigned char *recordBuf, unsigned int recordLen)
{ {
ClientHelloV2 *chv2; ClientHelloV2 *chv2;
ServerHelloV2 *shv2; ServerHelloV2 *shv2;
@ -514,8 +531,8 @@ void print_sslv2(DataBufferList *s, unsigned char *tbuf, unsigned int alloclen)
unsigned int q; unsigned int q;
PRUint32 len; PRUint32 len;
chv2 = (ClientHelloV2 *)tbuf; chv2 = (ClientHelloV2 *)recordBuf;
shv2 = (ServerHelloV2 *)tbuf; shv2 = (ServerHelloV2 *)recordBuf;
if (s->isEncrypted) { if (s->isEncrypted) {
PR_fprintf(PR_STDOUT," [ssl2] Encrypted {...}\n"); PR_fprintf(PR_STDOUT," [ssl2] Encrypted {...}\n");
return; return;
@ -616,7 +633,7 @@ void print_sslv2(DataBufferList *s, unsigned char *tbuf, unsigned int alloclen)
pos += 2; /* skip length header */ pos += 2; /* skip length header */
pos += 11; /* position pointer to Certificate data area */ pos += 11; /* position pointer to Certificate data area */
q = GET_SHORT(&shv2->certlength); q = GET_SHORT(&shv2->certlength);
if (q >alloclen) { if (q >recordLen) {
goto eosh; goto eosh;
} }
pos += q; /* skip certificate */ pos += q; /* skip certificate */
@ -711,9 +728,10 @@ unsigned int print_hello_extension(unsigned char * hsdata,
} }
void print_ssl3_handshake(unsigned char *tbuf, void print_ssl3_handshake(unsigned char *recordBuf,
unsigned int alloclen, unsigned int recordLen,
SSLRecord * sr) SSLRecord * sr,
DataBufferList *s)
{ {
struct sslhandshake sslh; struct sslhandshake sslh;
unsigned char * hsdata; unsigned char * hsdata;
@ -721,12 +739,34 @@ void print_ssl3_handshake(unsigned char *tbuf,
PR_fprintf(PR_STDOUT," handshake {\n"); PR_fprintf(PR_STDOUT," handshake {\n");
while (offset + hMACsize < alloclen) { if (s->msgBufOffset && s->msgBuf) {
sslh.type = tbuf[offset]; /* append recordBuf to msgBuf, then use msgBuf */
sslh.length = GET_24(tbuf+offset+1); if (s->msgBufOffset + recordLen > s->msgBufSize) {
hsdata= &tbuf[offset+4]; int newSize = s->msgBufOffset + recordLen;
char * newBuf = PORT_Realloc(s->msgBuf, newSize);
if (!newBuf) {
PR_ASSERT(newBuf);
showErr( "Realloc failed");
exit(10);
}
s->msgBuf = newBuf;
s->msgBufSize = newSize;
}
memcpy(s->msgBuf + s->msgBufOffset, recordBuf, recordLen);
s->msgBufOffset += recordLen;
recordLen = s->msgBufOffset;
recordBuf = s->msgBuf;
}
while (offset + 4 + s->hMACsize <= recordLen) {
sslh.type = recordBuf[offset];
sslh.length = GET_24(recordBuf+offset+1);
if (offset + 4 + sslh.length + s->hMACsize > recordLen)
break;
/* finally have a complete message */
if (sslhexparse)
print_hex(4,recordBuf+offset);
if (sslhexparse) print_hex(4,tbuf+offset); hsdata = &recordBuf[offset+4];
PR_fprintf(PR_STDOUT," type = %d (",sslh.type); PR_fprintf(PR_STDOUT," type = %d (",sslh.type);
switch(sslh.type) { switch(sslh.type) {
@ -909,26 +949,27 @@ void print_ssl3_handshake(unsigned char *tbuf,
PR_fprintf(PR_STDOUT," Certificate {\n"); PR_fprintf(PR_STDOUT," Certificate {\n");
PR_fprintf(PR_STDOUT," size = %d (0x%04x)\n", PR_fprintf(PR_STDOUT," size = %d (0x%04x)\n",
certlength,certlength); certlength,certlength);
certbytesread += certlength+3;
PR_snprintf(certFileName, sizeof certFileName, "cert.%03d", if (certbytesread <= certslength) {
++certFileNumber); PR_snprintf(certFileName, sizeof certFileName, "cert.%03d",
cfd = PR_Open(certFileName, PR_WRONLY|PR_CREATE_FILE|PR_TRUNCATE, ++certFileNumber);
0664); cfd = PR_Open(certFileName, PR_WRONLY|PR_CREATE_FILE|PR_TRUNCATE,
if (!cfd) { 0664);
PR_fprintf(PR_STDOUT, if (!cfd) {
" data = { couldn't save file '%s' }\n", PR_fprintf(PR_STDOUT,
certFileName); " data = { couldn't save file '%s' }\n",
} else { certFileName);
PR_Write(cfd, (hsdata+pos), certlength); } else {
PR_fprintf(PR_STDOUT, PR_Write(cfd, (hsdata+pos), certlength);
" data = { saved in file '%s' }\n", PR_fprintf(PR_STDOUT,
certFileName); " data = { saved in file '%s' }\n",
PR_Close(cfd); certFileName);
PR_Close(cfd);
}
} }
PR_fprintf(PR_STDOUT," }\n"); PR_fprintf(PR_STDOUT," }\n");
pos += certlength; pos += certlength;
certbytesread += certlength+3;
} }
PR_fprintf(PR_STDOUT," }\n"); PR_fprintf(PR_STDOUT," }\n");
} }
@ -1015,11 +1056,11 @@ void print_ssl3_handshake(unsigned char *tbuf,
if (sslhexparse) print_hex(sslh.length, hsdata); if (sslhexparse) print_hex(sslh.length, hsdata);
PR_fprintf(PR_STDOUT," }\n"); PR_fprintf(PR_STDOUT," }\n");
if (!isNULLmac(currentcipher) && !hMACsize) { if (!isNULLmac(currentcipher) && !s->hMACsize) {
/* To calculate the size of MAC, we subtract the number /* To calculate the size of MAC, we subtract the number
* of known bytes of message from the number of remaining * of known bytes of message from the number of remaining
* bytes in the record. */ * bytes in the record. */
hMACsize = alloclen - (sslh.length + 4); s->hMACsize = recordLen - (sslh.length + 4);
} }
break; break;
@ -1032,17 +1073,35 @@ void print_ssl3_handshake(unsigned char *tbuf,
} }
} /* end of switch sslh.type */ } /* end of switch sslh.type */
offset += sslh.length + 4; /* +4 because of length (3 bytes) and type (1 byte) */ offset += sslh.length + 4;
} /* while */ } /* while */
if (hMACsize) { if (offset + s->hMACsize < recordLen) { /* stuff left over */
/* at this point offset should be at the first byte of MAC */ int newMsgLen = recordLen - (offset + s->hMACsize);
if (offset + hMACsize > alloclen) { if (!s->msgBuf) {
PR_fprintf(PR_STDOUT,"BAD RECORD: content + MAC ends beyond " s->msgBuf = PORT_Alloc(newMsgLen);
"allocated limit.\n"); if (!s->msgBuf) {
} else { PR_ASSERT(s->msgBuf);
PR_fprintf(PR_STDOUT," MAC = {...}\n"); showErr( "Malloc failed");
if (sslhexparse) print_hex(hMACsize, hsdata); exit(11);
} }
s->msgBufSize = newMsgLen;
memcpy(s->msgBuf, recordBuf + offset, newMsgLen);
} else if (newMsgLen > s->msgBufSize) {
char * newBuf = PORT_Realloc(s->msgBuf, newMsgLen);
if (!newBuf) {
PR_ASSERT(newBuf);
showErr( "Realloc failed");
exit(12);
}
s->msgBuf = newBuf;
s->msgBufSize = newMsgLen;
} else if (offset || s->msgBuf != recordBuf) {
memmove(s->msgBuf, recordBuf + offset, newMsgLen);
}
s->msgBufOffset = newMsgLen;
PR_fprintf(PR_STDOUT," [incomplete handshake message]\n");
} else {
s->msgBufOffset = 0;
} }
PR_fprintf(PR_STDOUT," }\n"); PR_fprintf(PR_STDOUT," }\n");
} }
@ -1070,7 +1129,7 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
db = PR_NEW(struct _DataBuffer); db = PR_NEW(struct _DataBuffer);
db->buffer = (unsigned char*)PR_Malloc(length); db->buffer = (unsigned char*)PORT_Alloc(length);
db->length = length; db->length = length;
db->offset = 0; db->offset = 0;
memcpy(db->buffer, buffer, length); memcpy(db->buffer, buffer, length);
@ -1090,10 +1149,10 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
decode */ decode */
while (s->size > 0 ) { while (s->size > 0 ) {
unsigned char *tbuf = NULL; unsigned char *recordBuf = NULL;
SSLRecord sr; SSLRecord sr;
unsigned alloclen; unsigned recordLen;
unsigned recordsize; unsigned recordsize;
check_integrity(s); check_integrity(s);
@ -1103,7 +1162,7 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
exit(9); exit(9);
} }
/* in the case of an SSL 2 client-hello (which is all ssltap supports) */ /* in the case of an SSL 2 client-hello */
/* will have the high-bit set, whereas an SSL 3 client-hello will not */ /* will have the high-bit set, whereas an SSL 3 client-hello will not */
/* SSL2 can also send records that begin with the high bit clear. /* SSL2 can also send records that begin with the high bit clear.
* This code will incorrectly handle them. XXX * This code will incorrectly handle them. XXX
@ -1121,15 +1180,15 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
/* read the first two bytes off the stream. */ /* read the first two bytes off the stream. */
read_stream_bytes(lenbuf, s, sizeof(lenbuf)); read_stream_bytes(lenbuf, s, sizeof(lenbuf));
alloclen = ((unsigned int)(lenbuf[0] & 0x7f) << 8) + lenbuf[1] + recordLen = ((unsigned int)(lenbuf[0] & 0x7f) << 8) + lenbuf[1] +
((lenbuf[0] & 0x80) ? 2 : 3); ((lenbuf[0] & 0x80) ? 2 : 3);
PR_fprintf(PR_STDOUT, "alloclen = %u bytes\n", alloclen); PR_fprintf(PR_STDOUT, "recordLen = %u bytes\n", recordLen);
/* put 'em back on the head of the stream. */ /* put 'em back on the head of the stream. */
db = PR_NEW(struct _DataBuffer); db = PR_NEW(struct _DataBuffer);
db->length = sizeof lenbuf; db->length = sizeof lenbuf;
db->buffer = (unsigned char*) PR_Malloc(db->length); db->buffer = (unsigned char*) PORT_Alloc(db->length);
db->offset = 0; db->offset = 0;
memcpy(db->buffer, lenbuf, sizeof lenbuf); memcpy(db->buffer, lenbuf, sizeof lenbuf);
@ -1140,19 +1199,19 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
s->size += db->length; s->size += db->length;
/* if there wasn't enough, go back for more. */ /* if there wasn't enough, go back for more. */
if (s->size < alloclen) { if (s->size < recordLen) {
check_integrity(s); check_integrity(s);
partial_packet(length, s->size, alloclen); partial_packet(length, s->size, recordLen);
return; return;
} }
partial_packet(length, s->size, alloclen); partial_packet(length, s->size, recordLen);
/* read in the whole record. */ /* read in the whole record. */
tbuf = PR_Malloc(alloclen); recordBuf = PORT_Alloc(recordLen);
read_stream_bytes(tbuf, s, alloclen); read_stream_bytes(recordBuf, s, recordLen);
print_sslv2(s, tbuf, alloclen); print_sslv2(s, recordBuf, recordLen);
PR_FREEIF(tbuf); PR_FREEIF(recordBuf);
check_integrity(s); check_integrity(s);
continue; continue;
@ -1163,7 +1222,7 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
/***********************************************************/ /***********************************************************/
check_integrity(s); check_integrity(s);
if (s->size < sizeof(SSLRecord)) { if (s->size < sizeof sr) {
partial_packet(length, s->size, sizeof(SSLRecord)); partial_packet(length, s->size, sizeof(SSLRecord));
return; return;
} }
@ -1180,7 +1239,7 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
db = PR_NEW(struct _DataBuffer); db = PR_NEW(struct _DataBuffer);
db->length = sizeof sr; db->length = sizeof sr;
db->buffer = (unsigned char*) PR_Malloc(db->length); db->buffer = (unsigned char*) PORT_Alloc(db->length);
db->offset = 0; db->offset = 0;
memcpy(db->buffer, &sr, sizeof sr); memcpy(db->buffer, &sr, sizeof sr);
db->next = s->first; db->next = s->first;
@ -1230,32 +1289,32 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
(PRUint32)GET_SHORT(sr.length), (PRUint32)GET_SHORT(sr.length)); (PRUint32)GET_SHORT(sr.length), (PRUint32)GET_SHORT(sr.length));
alloclen = recordsize; recordLen = recordsize;
PR_ASSERT(s->size >= alloclen); PR_ASSERT(s->size >= recordLen);
if (s->size >= alloclen) { if (s->size >= recordLen) {
tbuf = (unsigned char*) PR_Malloc(alloclen); recordBuf = (unsigned char*) PORT_Alloc(recordLen);
read_stream_bytes(tbuf, s, alloclen); read_stream_bytes(recordBuf, s, recordLen);
if (s->isEncrypted) { if (s->isEncrypted) {
PR_fprintf(PR_STDOUT," < encrypted >\n"); PR_fprintf(PR_STDOUT," < encrypted >\n");
} else } else { /* not encrypted */
switch(sr.type) { switch(sr.type) {
case 20 : /* change_cipher_spec */ case 20 : /* change_cipher_spec */
if (sslhexparse) print_hex(alloclen,tbuf); if (sslhexparse) print_hex(recordLen - s->hMACsize,recordBuf);
/* mark to say we can only dump hex form now on /* mark to say we can only dump hex form now on
* if it is not one on a null cipher */ * if it is not one on a null cipher */
s->isEncrypted = isNULLcipher(currentcipher) ? 0 : 1; s->isEncrypted = isNULLcipher(currentcipher) ? 0 : 1;
break; break;
case 21 : /* alert */ case 21 : /* alert */
switch(tbuf[0]) { switch(recordBuf[0]) {
case 1: PR_fprintf(PR_STDOUT, " warning: "); break; case 1: PR_fprintf(PR_STDOUT, " warning: "); break;
case 2: PR_fprintf(PR_STDOUT, " fatal: "); break; case 2: PR_fprintf(PR_STDOUT, " fatal: "); break;
default: PR_fprintf(PR_STDOUT, " unknown level %d: ", tbuf[0]); break; default: PR_fprintf(PR_STDOUT, " unknown level %d: ", recordBuf[0]); break;
} }
switch(tbuf[1]) { switch(recordBuf[1]) {
case 0: PR_FPUTS("close_notify\n" ); break; case 0: PR_FPUTS("close_notify\n" ); break;
case 10: PR_FPUTS("unexpected_message\n" ); break; case 10: PR_FPUTS("unexpected_message\n" ); break;
case 20: PR_FPUTS("bad_record_mac\n" ); break; case 20: PR_FPUTS("bad_record_mac\n" ); break;
@ -1286,41 +1345,42 @@ void print_ssl(DataBufferList *s, int length, unsigned char *buffer)
case 113: PR_FPUTS("bad_certificate_status_response\n" ); break; case 113: PR_FPUTS("bad_certificate_status_response\n" ); break;
case 114: PR_FPUTS("bad_certificate_hash_value\n" ); break; case 114: PR_FPUTS("bad_certificate_hash_value\n" ); break;
default: PR_fprintf(PR_STDOUT, "unknown alert %d\n", tbuf[1]); break; default: PR_fprintf(PR_STDOUT, "unknown alert %d\n", recordBuf[1]);
break;
} }
if (sslhexparse) print_hex(alloclen,tbuf); if (sslhexparse) print_hex(recordLen - s->hMACsize,recordBuf);
break; break;
case 22 : /* handshake */ case 22 : /* handshake */
print_ssl3_handshake( tbuf, alloclen, &sr ); print_ssl3_handshake( recordBuf, recordLen - s->hMACsize, &sr, s );
break; break;
case 23 : /* application data */ case 23 : /* application data */
if (hMACsize) { print_hex(recordLen - s->hMACsize,recordBuf);
print_hex(alloclen - hMACsize,tbuf);
PR_fprintf(PR_STDOUT," MAC = {...}\n");
if (sslhexparse) {
unsigned char *offset = tbuf + (alloclen - hMACsize);
print_hex(hMACsize, offset);
}
} else {
print_hex(alloclen,tbuf);
}
break; break;
default: default:
print_hex(alloclen,tbuf); print_hex(recordLen - s->hMACsize,recordBuf);
break; break;
} }
if (s->hMACsize) {
PR_fprintf(PR_STDOUT," MAC = {...}\n");
if (sslhexparse) {
unsigned char *offset = recordBuf + (recordLen - s->hMACsize);
print_hex(s->hMACsize, offset);
}
}
} /* not encrypted */
} }
PR_fprintf(PR_STDOUT,"}\n"); PR_fprintf(PR_STDOUT,"}\n");
PR_FREEIF(tbuf); PR_FREEIF(recordBuf);
check_integrity(s); check_integrity(s);
} }
} }
void print_hex(int amt, unsigned char *buf) { void print_hex(int amt, unsigned char *buf)
{
int i,j,k; int i,j,k;
char t[20]; char t[20];
static char string[5000]; static char string[5000];
@ -1377,7 +1437,8 @@ void print_hex(int amt, unsigned char *buf) {
} }
} }
void Usage(void) { void Usage(void)
{
PR_fprintf(PR_STDERR, "SSLTAP (C) 1997, 1998 Netscape Communications Corporation.\n"); PR_fprintf(PR_STDERR, "SSLTAP (C) 1997, 1998 Netscape Communications Corporation.\n");
PR_fprintf(PR_STDERR, "Usage: ssltap [-vhfsxl] [-p port] hostname:port\n"); PR_fprintf(PR_STDERR, "Usage: ssltap [-vhfsxl] [-p port] hostname:port\n");
PR_fprintf(PR_STDERR, " -v [prints version string]\n"); PR_fprintf(PR_STDERR, " -v [prints version string]\n");
@ -1392,7 +1453,8 @@ void Usage(void) {
} }
void void
showErr(const char * msg) { showErr(const char * msg)
{
PRErrorCode err = PR_GetError(); PRErrorCode err = PR_GetError();
const char * errString; const char * errString;
@ -1402,7 +1464,7 @@ showErr(const char * msg) {
if (!errString) if (!errString)
errString = "(no text available)"; errString = "(no text available)";
PR_fprintf(PR_STDERR, "Error %d: %s: %s", err, errString, msg); PR_fprintf(PR_STDERR, "%s: Error %d: %s: %s", progName, err, errString, msg);
} }
int main(int argc, char *argv[]) int main(int argc, char *argv[])
@ -1419,6 +1481,7 @@ int main(int argc, char *argv[])
PLOptStatus status; PLOptStatus status;
SECStatus rv; SECStatus rv;
progName = argv[0];
optstate = PL_CreateOptState(argc,argv,"fvxhslp:"); optstate = PL_CreateOptState(argc,argv,"fvxhslp:");
while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
switch (optstate->option) { switch (optstate->option) {
@ -1686,9 +1749,6 @@ int main(int argc, char *argv[])
flush_stream(&serverstream); flush_stream(&serverstream);
/* Connection is closed, so reset the current cipher */ /* Connection is closed, so reset the current cipher */
currentcipher = 0; currentcipher = 0;
/* Reset MAC size */
hMACsize = 0;
c_count++; c_count++;
PR_fprintf(PR_STDERR,"Connection %d Complete [%s]\n", c_count, PR_fprintf(PR_STDERR,"Connection %d Complete [%s]\n", c_count,
get_time_string() ); get_time_string() );

Просмотреть файл

@ -114,7 +114,6 @@
#include "sslerr.h" #include "sslerr.h"
#include "sslproto.h" #include "sslproto.h"
#include "sslt.h" #include "sslt.h"
#include "watcomfx.h"
int main() int main()
{ {

Просмотреть файл

@ -87,6 +87,7 @@ Usage(const char *progName)
"\t-a\t\t Following certfile is base64 encoded\n" "\t-a\t\t Following certfile is base64 encoded\n"
"\t-b YYMMDDHHMMZ\t Validate date (default: now)\n" "\t-b YYMMDDHHMMZ\t Validate date (default: now)\n"
"\t-d directory\t Database directory\n" "\t-d directory\t Database directory\n"
"\t-i number of consecutive verifications\n"
"\t-f \t\t Enable cert fetching from AIA URL\n" "\t-f \t\t Enable cert fetching from AIA URL\n"
"\t-o oid\t\t Set policy OID for cert validation(Format OID.1.2.3)\n" "\t-o oid\t\t Set policy OID for cert validation(Format OID.1.2.3)\n"
"\t-p \t\t Use PKIX Library to validate certificate by calling:\n" "\t-p \t\t Use PKIX Library to validate certificate by calling:\n"
@ -457,12 +458,13 @@ main(int argc, char *argv[], char *envp[])
int revDataIndex = 0; int revDataIndex = 0;
PRBool ocsp_fetchingFailureIsAFailure = PR_TRUE; PRBool ocsp_fetchingFailureIsAFailure = PR_TRUE;
PRBool useDefaultRevFlags = PR_TRUE; PRBool useDefaultRevFlags = PR_TRUE;
int vfyCounts = 1;
PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
progName = PL_strdup(argv[0]); progName = PL_strdup(argv[0]);
optstate = PL_CreateOptState(argc, argv, "ab:c:d:efg:h:m:o:prs:tu:vw:W:"); optstate = PL_CreateOptState(argc, argv, "ab:c:d:efg:h:i:m:o:prs:tu:vw:W:");
while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
switch(optstate->option) { switch(optstate->option) {
case 0 : /* positional parameter */ goto breakout; case 0 : /* positional parameter */ goto breakout;
@ -489,6 +491,8 @@ main(int argc, char *argv[], char *envp[])
case 'h' : case 'h' :
revMethodsData[revDataIndex]. revMethodsData[revDataIndex].
testFlagsStr = PL_strdup(optstate->value);break; testFlagsStr = PL_strdup(optstate->value);break;
case 'i' : vfyCounts = PORT_Atoi(optstate->value); break;
break;
case 'm' : case 'm' :
if (revMethodsData[revDataIndex].methodTypeStr) { if (revMethodsData[revDataIndex].methodTypeStr) {
revDataIndex += 1; revDataIndex += 1;
@ -599,171 +603,175 @@ breakout:
if (status == PL_OPT_BAD || !firstCert) if (status == PL_OPT_BAD || !firstCert)
Usage(progName); Usage(progName);
if (!time)
time = PR_Now();
/* Initialize log structure */ /* Initialize log structure */
log.arena = PORT_NewArena(512); log.arena = PORT_NewArena(512);
log.head = log.tail = NULL; log.head = log.tail = NULL;
log.count = 0; log.count = 0;
if (usePkix < 2) { do {
/* NOW, verify the cert chain. */ if (usePkix < 2) {
if (usePkix) { /* NOW, verify the cert chain. */
/* Use old API with libpkix validation lib */ if (usePkix) {
CERT_SetUsePKIXForValidation(PR_TRUE); /* Use old API with libpkix validation lib */
} CERT_SetUsePKIXForValidation(PR_TRUE);
defaultDB = CERT_GetDefaultCertDB(); }
secStatus = CERT_VerifyCertificate(defaultDB, firstCert, if (!time)
PR_TRUE /* check sig */, time = PR_Now();
certUsage,
time, defaultDB = CERT_GetDefaultCertDB();
&pwdata, /* wincx */ secStatus = CERT_VerifyCertificate(defaultDB, firstCert,
&log, /* error log */ PR_TRUE /* check sig */,
certUsage,
time,
&pwdata, /* wincx */
&log, /* error log */
NULL);/* returned usages */ NULL);/* returned usages */
} else do { } else do {
static CERTValOutParam cvout[4]; static CERTValOutParam cvout[4];
static CERTValInParam cvin[6]; static CERTValInParam cvin[6];
SECOidTag oidTag; SECOidTag oidTag;
int inParamIndex = 0; int inParamIndex = 0;
static PRUint64 revFlagsLeaf[2]; static PRUint64 revFlagsLeaf[2];
static PRUint64 revFlagsChain[2]; static PRUint64 revFlagsChain[2];
static CERTRevocationFlags rev; static CERTRevocationFlags rev;
if (oidStr) {
PRArenaPool *arena;
SECOidData od;
memset(&od, 0, sizeof od);
od.offset = SEC_OID_UNKNOWN;
od.desc = "User Defined Policy OID";
od.mechanism = CKM_INVALID_MECHANISM;
od.supportedExtension = INVALID_CERT_EXTENSION;
if (oidStr) { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
PRArenaPool *arena; if ( !arena ) {
SECOidData od; fprintf(stderr, "out of memory");
memset(&od, 0, sizeof od); goto punt;
od.offset = SEC_OID_UNKNOWN; }
od.desc = "User Defined Policy OID";
od.mechanism = CKM_INVALID_MECHANISM; secStatus = SEC_StringToOID(arena, &od.oid, oidStr, 0);
od.supportedExtension = INVALID_CERT_EXTENSION; if (secStatus != SECSuccess) {
PORT_FreeArena(arena, PR_FALSE);
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); fprintf(stderr, "Can not encode oid: %s(%s)\n", oidStr,
if ( !arena ) { SECU_Strerror(PORT_GetError()));
fprintf(stderr, "out of memory"); break;
goto punt; }
}
oidTag = SECOID_AddEntry(&od);
secStatus = SEC_StringToOID(arena, &od.oid, oidStr, 0); PORT_FreeArena(arena, PR_FALSE);
if (secStatus != SECSuccess) { if (oidTag == SEC_OID_UNKNOWN) {
PORT_FreeArena(arena, PR_FALSE); fprintf(stderr, "Can not add new oid to the dynamic "
fprintf(stderr, "Can not encode oid: %s(%s)\n", oidStr, "table: %s\n", oidStr);
SECU_Strerror(PORT_GetError())); secStatus = SECFailure;
break; break;
} }
oidTag = SECOID_AddEntry(&od); cvin[inParamIndex].type = cert_pi_policyOID;
PORT_FreeArena(arena, PR_FALSE); cvin[inParamIndex].value.arraySize = 1;
if (oidTag == SEC_OID_UNKNOWN) { cvin[inParamIndex].value.array.oids = &oidTag;
fprintf(stderr, "Can not add new oid to the dynamic "
"table: %s\n", oidStr); inParamIndex++;
secStatus = SECFailure;
break;
}
cvin[inParamIndex].type = cert_pi_policyOID;
cvin[inParamIndex].value.arraySize = 1;
cvin[inParamIndex].value.array.oids = &oidTag;
inParamIndex++;
}
if (trustedCertList) {
cvin[inParamIndex].type = cert_pi_trustAnchors;
cvin[inParamIndex].value.pointer.chain = trustedCertList;
inParamIndex++;
}
cvin[inParamIndex].type = cert_pi_useAIACertFetch;
cvin[inParamIndex].value.scalar.b = certFetching;
inParamIndex++;
rev.leafTests.cert_rev_flags_per_method = revFlagsLeaf;
rev.chainTests.cert_rev_flags_per_method = revFlagsChain;
secStatus = configureRevocationParams(&rev);
if (secStatus) {
fprintf(stderr, "Can not config revocation parameters ");
break;
}
cvin[inParamIndex].type = cert_pi_revocationFlags;
cvin[inParamIndex].value.pointer.revocation = &rev;
inParamIndex++;
cvin[inParamIndex].type = cert_pi_date;
cvin[inParamIndex].value.scalar.time = time;
inParamIndex++;
cvin[inParamIndex].type = cert_pi_end;
cvout[0].type = cert_po_trustAnchor;
cvout[0].value.pointer.cert = NULL;
cvout[1].type = cert_po_certList;
cvout[1].value.pointer.chain = NULL;
/* setting pointer to CERTVerifyLog. Initialized structure
* will be used CERT_PKIXVerifyCert */
cvout[2].type = cert_po_errorLog;
cvout[2].value.pointer.log = &log;
cvout[3].type = cert_po_end;
secStatus = CERT_PKIXVerifyCert(firstCert, certUsage,
cvin, cvout, &pwdata);
if (secStatus != SECSuccess) {
break;
}
issuerCert = cvout[0].value.pointer.cert;
builtChain = cvout[1].value.pointer.chain;
} while (0);
/* Display validation results */
if (secStatus != SECSuccess || log.count > 0) {
CERTVerifyLogNode *node = NULL;
PRIntn err = PR_GetError();
fprintf(stderr, "Chain is bad, %d = %s\n", err, SECU_Strerror(err));
SECU_displayVerifyLog(stderr, &log, verbose);
/* Have cert refs in the log only in case of failure.
* Destroy them. */
for (node = log.head; node; node = node->next) {
if (node->cert)
CERT_DestroyCertificate(node->cert);
}
rv = 1;
} else {
fprintf(stderr, "Chain is good!\n");
if (issuerCert) {
if (verbose > 1) {
rv = SEC_PrintCertificateAndTrust(issuerCert, "Root Certificate",
NULL);
if (rv != SECSuccess) {
SECU_PrintError(progName, "problem printing certificate");
}
} else if (verbose > 0) {
SECU_PrintName(stdout, &issuerCert->subject, "Root "
"Certificate Subject:", 0);
}
CERT_DestroyCertificate(issuerCert);
}
if (builtChain) {
CERTCertListNode *node;
int count = 0;
char buff[256];
if (verbose) {
for(node = CERT_LIST_HEAD(builtChain); !CERT_LIST_END(node, builtChain);
node = CERT_LIST_NEXT(node), count++ ) {
sprintf(buff, "Certificate %d Subject", count + 1);
SECU_PrintName(stdout, &node->cert->subject, buff, 0);
} }
if (trustedCertList) {
cvin[inParamIndex].type = cert_pi_trustAnchors;
cvin[inParamIndex].value.pointer.chain = trustedCertList;
inParamIndex++;
}
cvin[inParamIndex].type = cert_pi_useAIACertFetch;
cvin[inParamIndex].value.scalar.b = certFetching;
inParamIndex++;
rev.leafTests.cert_rev_flags_per_method = revFlagsLeaf;
rev.chainTests.cert_rev_flags_per_method = revFlagsChain;
secStatus = configureRevocationParams(&rev);
if (secStatus) {
fprintf(stderr, "Can not config revocation parameters ");
break;
}
cvin[inParamIndex].type = cert_pi_revocationFlags;
cvin[inParamIndex].value.pointer.revocation = &rev;
inParamIndex++;
if (time) {
cvin[inParamIndex].type = cert_pi_date;
cvin[inParamIndex].value.scalar.time = time;
inParamIndex++;
}
cvin[inParamIndex].type = cert_pi_end;
cvout[0].type = cert_po_trustAnchor;
cvout[0].value.pointer.cert = NULL;
cvout[1].type = cert_po_certList;
cvout[1].value.pointer.chain = NULL;
/* setting pointer to CERTVerifyLog. Initialized structure
* will be used CERT_PKIXVerifyCert */
cvout[2].type = cert_po_errorLog;
cvout[2].value.pointer.log = &log;
cvout[3].type = cert_po_end;
secStatus = CERT_PKIXVerifyCert(firstCert, certUsage,
cvin, cvout, &pwdata);
if (secStatus != SECSuccess) {
break;
}
issuerCert = cvout[0].value.pointer.cert;
builtChain = cvout[1].value.pointer.chain;
} while (0);
/* Display validation results */
if (secStatus != SECSuccess || log.count > 0) {
CERTVerifyLogNode *node = NULL;
PRIntn err = PR_GetError();
fprintf(stderr, "Chain is bad, %d = %s\n", err, SECU_Strerror(err));
SECU_displayVerifyLog(stderr, &log, verbose);
/* Have cert refs in the log only in case of failure.
* Destroy them. */
for (node = log.head; node; node = node->next) {
if (node->cert)
CERT_DestroyCertificate(node->cert);
} }
CERT_DestroyCertList(builtChain); rv = 1;
} } else {
rv = 0; fprintf(stderr, "Chain is good!\n");
} if (issuerCert) {
if (verbose > 1) {
rv = SEC_PrintCertificateAndTrust(issuerCert, "Root Certificate",
NULL);
if (rv != SECSuccess) {
SECU_PrintError(progName, "problem printing certificate");
}
} else if (verbose > 0) {
SECU_PrintName(stdout, &issuerCert->subject, "Root "
"Certificate Subject:", 0);
}
CERT_DestroyCertificate(issuerCert);
}
if (builtChain) {
CERTCertListNode *node;
int count = 0;
char buff[256];
if (verbose) {
for(node = CERT_LIST_HEAD(builtChain); !CERT_LIST_END(node, builtChain);
node = CERT_LIST_NEXT(node), count++ ) {
sprintf(buff, "Certificate %d Subject", count + 1);
SECU_PrintName(stdout, &node->cert->subject, buff, 0);
}
}
CERT_DestroyCertList(builtChain);
}
rv = 0;
}
} while (--vfyCounts > 0);
/* Need to destroy CERTVerifyLog arena at the end */ /* Need to destroy CERTVerifyLog arena at the end */
PORT_FreeArena(log.arena, PR_FALSE); PORT_FreeArena(log.arena, PR_FALSE);

Просмотреть файл

@ -102,7 +102,7 @@ static const NameToKind name2kinds[] = {
/* end of IANA registered type names */ /* end of IANA registered type names */
/* legacy keywords */ /* legacy keywords */
{ "E", 128, SEC_OID_PKCS9_EMAIL_ADDRESS,SEC_ASN1_DS}, { "E", 128, SEC_OID_PKCS9_EMAIL_ADDRESS,SEC_ASN1_IA5_STRING},
#if 0 /* removed. Not yet in any IETF draft or RFC. */ #if 0 /* removed. Not yet in any IETF draft or RFC. */
{ "pseudonym", 64, SEC_OID_AVA_PSEUDONYM, SEC_ASN1_DS}, { "pseudonym", 64, SEC_OID_AVA_PSEUDONYM, SEC_ASN1_DS},
@ -111,6 +111,28 @@ static const NameToKind name2kinds[] = {
{ 0, 256, SEC_OID_UNKNOWN , 0}, { 0, 256, SEC_OID_UNKNOWN , 0},
}; };
/* Table facilitates conversion of ASCII hex to binary. */
static const PRInt16 x2b[256] = {
/* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #3x */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
/* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #fx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
#define IS_HEX(c) (x2b[(PRUint8)(c)] >= 0)
#define C_DOUBLE_QUOTE '\042' #define C_DOUBLE_QUOTE '\042'
#define C_BACKSLASH '\134' #define C_BACKSLASH '\134'
@ -140,6 +162,17 @@ static const NameToKind name2kinds[] = {
((c) == '=') || \ ((c) == '=') || \
((c) == '?')) ((c) == '?'))
/* RFC 2253 says we must escape ",+\"\\<>;=" EXCEPT inside a quoted string.
* Inside a quoted string, we only need to escape " and \
* We choose to quote strings containing any of those special characters,
* so we only need to escape " and \
*/
#define NEEDS_ESCAPE(c) \
(c == C_DOUBLE_QUOTE || c == C_BACKSLASH)
#define NEEDS_HEX_ESCAPE(c) \
((PRUint8)c < 0x20 || c == 0x7f)
int int
cert_AVAOidTagToMaxLen(SECOidTag tag) cert_AVAOidTagToMaxLen(SECOidTag tag)
{ {
@ -222,11 +255,12 @@ scanTag(char **pbp, char *endptr, char *tagBuf, int tagBufSize)
return SECSuccess; return SECSuccess;
} }
static SECStatus /* Returns the number of bytes in the value. 0 means failure. */
static int
scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize) scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
{ {
char *bp, *valBufp; char *bp, *valBufp;
int vallen; int vallen = 0;
PRBool isQuoted; PRBool isQuoted;
PORT_Assert(valBufSize > 0); PORT_Assert(valBufSize > 0);
@ -235,7 +269,7 @@ scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
skipSpace(pbp, endptr); skipSpace(pbp, endptr);
if(*pbp == endptr) { if(*pbp == endptr) {
/* nothing left */ /* nothing left */
return SECFailure; return 0;
} }
bp = *pbp; bp = *pbp;
@ -250,7 +284,6 @@ scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
} }
valBufp = valBuf; valBufp = valBuf;
vallen = 0;
while (bp < endptr) { while (bp < endptr) {
char c = *bp; char c = *bp;
if (c == C_BACKSLASH) { if (c == C_BACKSLASH) {
@ -259,7 +292,12 @@ scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
if (bp >= endptr) { if (bp >= endptr) {
/* escape charater must appear with paired char */ /* escape charater must appear with paired char */
*pbp = bp; *pbp = bp;
return SECFailure; return 0;
}
c = *bp;
if (IS_HEX(c) && (endptr - bp) >= 2 && IS_HEX(bp[1])) {
bp++;
c = (char)((x2b[(PRUint8)c] << 4) | x2b[(PRUint8)*bp]);
} }
} else if (c == '#' && bp == *pbp) { } else if (c == '#' && bp == *pbp) {
/* ignore leading #, quotation not required for it. */ /* ignore leading #, quotation not required for it. */
@ -274,27 +312,28 @@ scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
vallen++; vallen++;
if (vallen >= valBufSize) { if (vallen >= valBufSize) {
*pbp = bp; *pbp = bp;
return SECFailure; return 0;
} }
*valBufp++ = *bp++; *valBufp++ = c;
bp++;
} }
/* stip trailing spaces from unquoted values */ /* strip trailing spaces from unquoted values */
if (!isQuoted) { if (!isQuoted) {
if (valBufp > valBuf) { while (valBufp > valBuf) {
valBufp--; char c = valBufp[-1];
while ((valBufp > valBuf) && OPTIONAL_SPACE(*valBufp)) { if (! OPTIONAL_SPACE(c))
valBufp--; break;
} --valBufp;
valBufp++;
} }
vallen = valBufp - valBuf;
} }
if (isQuoted) { if (isQuoted) {
/* insist that we stopped on a double quote */ /* insist that we stopped on a double quote */
if (*bp != C_DOUBLE_QUOTE) { if (*bp != C_DOUBLE_QUOTE) {
*pbp = bp; *pbp = bp;
return SECFailure; return 0;
} }
/* skip over the quote and skip optional space */ /* skip over the quote and skip optional space */
bp++; bp++;
@ -303,37 +342,12 @@ scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
*pbp = bp; *pbp = bp;
if (valBufp == valBuf) {
/* empty value -- not allowed */
return SECFailure;
}
/* null-terminate valBuf -- guaranteed at least one space left */ /* null-terminate valBuf -- guaranteed at least one space left */
*valBufp++ = 0; *valBufp = 0;
return SECSuccess; return vallen;
} }
static const PRInt16 x2b[256] =
{
/* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #3x */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
/* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* #fx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
/* Caller must set error code upon failure */ /* Caller must set error code upon failure */
static SECStatus static SECStatus
hexToBin(PLArenaPool *pool, SECItem * destItem, const char * src, int len) hexToBin(PLArenaPool *pool, SECItem * destItem, const char * src, int len)
@ -379,14 +393,15 @@ ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr)
SECOidTag kind = SEC_OID_UNKNOWN; SECOidTag kind = SEC_OID_UNKNOWN;
SECStatus rv = SECFailure; SECStatus rv = SECFailure;
SECItem derOid = { 0, NULL, 0 }; SECItem derOid = { 0, NULL, 0 };
SECItem derVal = { 0, NULL, 0};
char sep = 0; char sep = 0;
char tagBuf[32]; char tagBuf[32];
char valBuf[384]; char valBuf[384];
PORT_Assert(arena); PORT_Assert(arena);
if (scanTag(pbp, endptr, tagBuf, sizeof(tagBuf)) == SECFailure || if (SECSuccess != scanTag(pbp, endptr, tagBuf, sizeof tagBuf) ||
scanVal(pbp, endptr, valBuf, sizeof(valBuf)) == SECFailure) { !(valLen = scanVal(pbp, endptr, valBuf, sizeof valBuf))) {
goto loser; goto loser;
} }
@ -423,16 +438,13 @@ ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr)
/* Is this a hex encoding of a DER attribute value ? */ /* Is this a hex encoding of a DER attribute value ? */
if ('#' == valBuf[0]) { if ('#' == valBuf[0]) {
/* convert attribute value from hex to binary */ /* convert attribute value from hex to binary */
SECItem derVal = { 0, NULL, 0}; rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1);
valLen = PORT_Strlen(valBuf+1);
rv = hexToBin(arena, &derVal, valBuf + 1, valLen);
if (rv) if (rv)
goto loser; goto loser;
a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal); a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal);
} else { } else {
if (kind == SEC_OID_UNKNOWN) if (kind == SEC_OID_UNKNOWN)
goto loser; goto loser;
valLen = PORT_Strlen(valBuf);
if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2) if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2)
goto loser; goto loser;
if (vt == SEC_ASN1_PRINTABLE_STRING && if (vt == SEC_ASN1_PRINTABLE_STRING &&
@ -446,7 +458,9 @@ ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr)
vt = SEC_ASN1_UTF8_STRING; vt = SEC_ASN1_UTF8_STRING;
} }
a = CERT_CreateAVA(arena, kind, vt, (char *)valBuf); derVal.data = valBuf;
derVal.len = valLen;
a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal);
} }
return a; return a;
@ -580,10 +594,26 @@ AppendStr(stringBuf *bufp, char *str)
return SECSuccess; return SECSuccess;
} }
typedef enum {
minimalEscape = 0, /* only hex escapes, and " and \ */
minimalEscapeAndQuote, /* as above, plus quoting */
fullEscape /* no quoting, full escaping */
} EQMode;
/* Some characters must be escaped as a hex string, e.g. c -> \nn .
* Others must be escaped by preceeding with a '\', e.g. c -> \c , but
* there are certain "special characters" that may be handled by either
* escaping them, or by enclosing the entire attribute value in quotes.
* A NULL value for pEQMode implies selecting minimalEscape mode.
* Some callers will do quoting when needed, others will not.
* If a caller selects minimalEscapeAndQuote, and the string does not
* need quoting, then this function changes it to minimalEscape.
*/
static int static int
cert_RFC1485_GetRequiredLen(const char *src, int srclen, PRBool *pNeedsQuoting) cert_RFC1485_GetRequiredLen(const char *src, int srclen, EQMode *pEQMode)
{ {
int i, reqLen=0; int i, reqLen=0;
EQMode mode = pEQMode ? *pEQMode : minimalEscape;
PRBool needsQuoting = PR_FALSE; PRBool needsQuoting = PR_FALSE;
char lastC = 0; char lastC = 0;
@ -591,70 +621,90 @@ cert_RFC1485_GetRequiredLen(const char *src, int srclen, PRBool *pNeedsQuoting)
for (i = 0; i < srclen; i++) { for (i = 0; i < srclen; i++) {
char c = src[i]; char c = src[i];
reqLen++; reqLen++;
if (!needsQuoting && (SPECIAL_CHAR(c) || if (NEEDS_HEX_ESCAPE(c)) { /* c -> \xx */
(OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)))) { reqLen += 2;
/* entirety will need quoting */ } else if (NEEDS_ESCAPE(c)) { /* c -> \c */
needsQuoting = PR_TRUE;
}
if (c == C_DOUBLE_QUOTE || c == C_BACKSLASH) {
/* this char will need escaping */
reqLen++; reqLen++;
} else if (SPECIAL_CHAR(c)) {
if (mode == minimalEscapeAndQuote) /* quoting is allowed */
needsQuoting = PR_TRUE; /* entirety will need quoting */
else if (mode == fullEscape)
reqLen++; /* MAY escape this character */
} else if (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)) {
if (mode == minimalEscapeAndQuote) /* quoting is allowed */
needsQuoting = PR_TRUE; /* entirety will need quoting */
} }
lastC = c; lastC = c;
} }
/* if it begins or ends in optional space it needs quoting */ /* if it begins or ends in optional space it needs quoting */
if (!needsQuoting && srclen > 0 && if (!needsQuoting && srclen > 0 && mode == minimalEscapeAndQuote &&
(OPTIONAL_SPACE(src[srclen-1]) || OPTIONAL_SPACE(src[0]))) { (OPTIONAL_SPACE(src[srclen-1]) || OPTIONAL_SPACE(src[0]))) {
needsQuoting = PR_TRUE; needsQuoting = PR_TRUE;
} }
if (needsQuoting) if (needsQuoting)
reqLen += 2; reqLen += 2;
if (pNeedsQuoting) if (pEQMode && mode == minimalEscapeAndQuote && !needsQuoting)
*pNeedsQuoting = needsQuoting; *pEQMode = minimalEscape;
return reqLen; return reqLen;
} }
SECStatus static const char hexChars[16] = { "0123456789abcdef" };
CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen)
static SECStatus
escapeAndQuote(char *dst, int dstlen, char *src, int srclen, EQMode *pEQMode)
{ {
int i, reqLen=0; int i, reqLen=0;
char *d = dst; EQMode mode = pEQMode ? *pEQMode : minimalEscape;
PRBool needsQuoting = PR_FALSE;
/* space for terminal null */ /* space for terminal null */
reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &needsQuoting) + 1; reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &mode) + 1;
if (reqLen > dstlen) { if (reqLen > dstlen) {
PORT_SetError(SEC_ERROR_OUTPUT_LEN); PORT_SetError(SEC_ERROR_OUTPUT_LEN);
return SECFailure; return SECFailure;
} }
d = dst; if (mode == minimalEscapeAndQuote)
if (needsQuoting) *d++ = C_DOUBLE_QUOTE; *dst++ = C_DOUBLE_QUOTE;
for (i = 0; i < srclen; i++) { for (i = 0; i < srclen; i++) {
char c = src[i]; char c = src[i];
if (c == C_DOUBLE_QUOTE || c == C_BACKSLASH) { if (NEEDS_HEX_ESCAPE(c)) {
/* escape it */ *dst++ = C_BACKSLASH;
*d++ = C_BACKSLASH; *dst++ = hexChars[ (c >> 4) & 0x0f ];
*dst++ = hexChars[ c & 0x0f ];
} else {
if (NEEDS_ESCAPE(c) || (SPECIAL_CHAR(c) && mode == fullEscape)) {
*dst++ = C_BACKSLASH;
}
*dst++ = c;
} }
*d++ = c;
} }
if (needsQuoting) *d++ = C_DOUBLE_QUOTE; if (mode == minimalEscapeAndQuote)
*d++ = 0; *dst++ = C_DOUBLE_QUOTE;
*dst++ = 0;
if (pEQMode)
*pEQMode = mode;
return SECSuccess; return SECSuccess;
} }
SECStatus
CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen)
{
EQMode mode = minimalEscapeAndQuote;
return escapeAndQuote(dst, dstlen, src, srclen, &mode);
}
/* convert an OID to dotted-decimal representation */ /* convert an OID to dotted-decimal representation */
/* Returns a string that must be freed with PR_smprintf_free(), */ /* Returns a string that must be freed with PR_smprintf_free(), */
char * char *
CERT_GetOidString(const SECItem *oid) CERT_GetOidString(const SECItem *oid)
{ {
PRUint8 *end; PRUint8 *stop; /* points to first byte after OID string */
PRUint8 *d; PRUint8 *first; /* byte of an OID component integer */
PRUint8 *e; PRUint8 *last; /* byte of an OID component integer */
char *a = NULL; char *rvString = NULL;
char *b; char *prefix = NULL;
#define MAX_OID_LEN 1024 /* bytes */ #define MAX_OID_LEN 1024 /* bytes */
@ -663,75 +713,113 @@ CERT_GetOidString(const SECItem *oid)
return NULL; return NULL;
} }
/* d will point to the next sequence of bytes to decode */ /* first will point to the next sequence of bytes to decode */
d = (PRUint8 *)oid->data; first = (PRUint8 *)oid->data;
/* end points to one past the legitimate data */ /* stop points to one past the legitimate data */
end = &d[ oid->len ]; stop = &first[ oid->len ];
/* /*
* Check for our pseudo-encoded single-digit OIDs * Check for our pseudo-encoded single-digit OIDs
*/ */
if( (*d == 0x80) && (2 == oid->len) ) { if ((*first == 0x80) && (2 == oid->len)) {
/* Funky encoding. The second byte is the number */ /* Funky encoding. The second byte is the number */
a = PR_smprintf("%lu", (PRUint32)d[1]); rvString = PR_smprintf("%lu", (PRUint32)first[1]);
if( (char *)NULL == a ) { if (!rvString) {
PORT_SetError(SEC_ERROR_NO_MEMORY); PORT_SetError(SEC_ERROR_NO_MEMORY);
return (char *)NULL;
} }
return a; return rvString;
} }
for( ; d < end; d = &e[1] ) { for (; first < stop; first = last + 1) {
unsigned int bytesBeforeLast;
for( e = d; e < end; e++ ) { for (last = first; last < stop; last++) {
if( 0 == (*e & 0x80) ) { if (0 == (*last & 0x80)) {
break; break;
} }
} }
bytesBeforeLast = (unsigned int)(last - first);
if( ((e-d) > 4) || (((e-d) == 4) && (*d & 0x70)) ) { if (bytesBeforeLast <= 3U) { /* 0-28 bit number */
/* More than a 32-bit number */
} else {
PRUint32 n = 0; PRUint32 n = 0;
PRUint32 c;
switch( e-d ) {
case 4: #define CGET(i, m) \
n |= ((PRUint32)(e[-4] & 0x0f)) << 28; c = last[-i] & m; \
case 3: n |= c << (7 * i)
n |= ((PRUint32)(e[-3] & 0x7f)) << 21;
case 2: #define CASE(i, m) \
n |= ((PRUint32)(e[-2] & 0x7f)) << 14; case i: \
case 1: CGET(i, m); \
n |= ((PRUint32)(e[-1] & 0x7f)) << 7; if (!n) goto unsupported \
case 0: /* fall-through */
n |= ((PRUint32)(e[-0] & 0x7f)) ;
switch (bytesBeforeLast) {
CASE(3, 0x7f);
CASE(2, 0x7f);
CASE(1, 0x7f);
case 0: n |= last[0]; /* most significant bit is zero. */
break;
} }
if( (char *)NULL == a ) { if (!rvString) {
/* This is the first number.. decompose it */ /* This is the first number.. decompose it */
PRUint32 one = PR_MIN(n/40, 2); /* never > 2 */ PRUint32 one = PR_MIN(n/40, 2); /* never > 2 */
PRUint32 two = n - one * 40; PRUint32 two = n - (one * 40);
a = PR_smprintf("OID.%lu.%lu", one, two); rvString = PR_smprintf("OID.%lu.%lu", one, two);
if( (char *)NULL == a ) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
return (char *)NULL;
}
} else { } else {
b = PR_smprintf("%s.%lu", a, n); prefix = rvString;
if( (char *)NULL == b ) { rvString = PR_smprintf("%s.%lu", prefix, n);
PR_smprintf_free(a); }
PORT_SetError(SEC_ERROR_NO_MEMORY); } else if (bytesBeforeLast <= 9U) { /* 29-64 bit number */
return (char *)NULL; PRUint64 n = 0;
} PRUint64 c;
switch (bytesBeforeLast) {
CASE(9, 0x01);
CASE(8, 0x7f);
CASE(7, 0x7f);
CASE(6, 0x7f);
CASE(5, 0x7f);
CASE(4, 0x7f);
CGET(3, 0x7f);
CGET(2, 0x7f);
CGET(1, 0x7f);
n |= last[0]; /* most significant bit is zero. */
break;
}
if (!rvString) {
/* This is the first number.. decompose it */
PRUint64 one = PR_MIN(n/40, 2); /* never > 2 */
PRUint64 two = n - (one * 40);
PR_smprintf_free(a); rvString = PR_smprintf("OID.%llu.%llu", one, two);
a = b; } else {
prefix = rvString;
rvString = PR_smprintf("%s.%llu", prefix, n);
}
} else {
/* More than a 64-bit number, or not minimal encoding. */
unsupported:
if (!rvString)
rvString = PR_smprintf("OID.UNSUPPORTED");
else {
prefix = rvString;
rvString = PR_smprintf("%s.UNSUPPORTED", prefix);
} }
} }
}
return a; if (prefix) {
PR_smprintf_free(prefix);
prefix = NULL;
}
if (!rvString) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
break;
}
}
return rvString;
} }
/* convert DER-encoded hex to a string */ /* convert DER-encoded hex to a string */
@ -826,6 +914,7 @@ AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict)
SECStatus rv; SECStatus rv;
unsigned int len; unsigned int len;
int nameLen, valueLen; int nameLen, valueLen;
EQMode mode = minimalEscapeAndQuote;
NameToKind n2k = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS }; NameToKind n2k = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS };
char tmpBuf[384]; char tmpBuf[384];
@ -907,7 +996,8 @@ AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict)
nameLen = strlen(tagName); nameLen = strlen(tagName);
valueLen = (useHex ? avaValue->len : valueLen = (useHex ? avaValue->len :
cert_RFC1485_GetRequiredLen(avaValue->data, avaValue->len, NULL)); cert_RFC1485_GetRequiredLen(avaValue->data, avaValue->len,
&mode));
len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */ len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */
if (len <= sizeof(tmpBuf)) { if (len <= sizeof(tmpBuf)) {
@ -934,8 +1024,8 @@ AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict)
encodedAVA[nameLen + avaValue->len] = '\0'; encodedAVA[nameLen + avaValue->len] = '\0';
rv = SECSuccess; rv = SECSuccess;
} else } else
rv = CERT_RFC1485_EscapeAndQuote(encodedAVA + nameLen, len - nameLen, rv = escapeAndQuote(encodedAVA + nameLen, len - nameLen,
(char *)avaValue->data, avaValue->len); (char *)avaValue->data, avaValue->len, &mode);
SECITEM_FreeItem(avaValue, PR_TRUE); SECITEM_FreeItem(avaValue, PR_TRUE);
if (rv == SECSuccess) if (rv == SECSuccess)
rv = AppendStr(bufp, encodedAVA); rv = AppendStr(bufp, encodedAVA);
@ -990,7 +1080,7 @@ CERT_NameToAsciiInvertible(CERTName *name, CertStrictnessLevel strict)
first = PR_FALSE; first = PR_FALSE;
} }
/* Add in tag type plus value into buf */ /* Add in tag type plus value into strBuf */
rv = AppendAVA(&strBuf, ava, strict); rv = AppendAVA(&strBuf, ava, strict);
if (rv) goto loser; if (rv) goto loser;
newRDN = PR_FALSE; newRDN = PR_FALSE;
@ -1044,44 +1134,58 @@ loser:
return(retstr); return(retstr);
} }
static char *
avaToString(PRArenaPool *arena, CERTAVA *ava)
{
char * buf = NULL;
SECItem* avaValue;
int valueLen;
avaValue = CERT_DecodeAVAValue(&ava->value);
if(!avaValue) {
return buf;
}
valueLen = cert_RFC1485_GetRequiredLen(avaValue->data, avaValue->len,
NULL) + 1;
if (arena) {
buf = (char *)PORT_ArenaZAlloc(arena, valueLen);
} else {
buf = (char *)PORT_ZAlloc(valueLen);
}
if (buf) {
SECStatus rv = escapeAndQuote(buf, valueLen, (char *)avaValue->data,
avaValue->len, NULL);
if (rv != SECSuccess) {
if (!arena)
PORT_Free(buf);
buf = NULL;
}
}
SECITEM_FreeItem(avaValue, PR_TRUE);
return buf;
}
/* RDNs are sorted from most general to most specific. /* RDNs are sorted from most general to most specific.
* This code returns the FIRST one found, the most general one found. * This code returns the FIRST one found, the most general one found.
*/ */
static char * static char *
CERT_GetNameElement(PRArenaPool *arena, CERTName *name, int wantedTag) CERT_GetNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
{ {
CERTRDN** rdns; CERTRDN** rdns = name->rdns;
CERTRDN *rdn; CERTRDN* rdn;
char *buf = 0; CERTAVA* ava = NULL;
rdns = name->rdns;
while (rdns && (rdn = *rdns++) != 0) { while (rdns && (rdn = *rdns++) != 0) {
CERTAVA** avas = rdn->avas; CERTAVA** avas = rdn->avas;
CERTAVA* ava;
while (avas && (ava = *avas++) != 0) { while (avas && (ava = *avas++) != 0) {
int tag = CERT_GetAVATag(ava); int tag = CERT_GetAVATag(ava);
if ( tag == wantedTag ) { if ( tag == wantedTag ) {
SECItem *decodeItem = CERT_DecodeAVAValue(&ava->value); avas = NULL;
if(!decodeItem) { rdns = NULL; /* break out of all loops */
return NULL;
}
if (arena) {
buf = (char *)PORT_ArenaZAlloc(arena,decodeItem->len + 1);
} else {
buf = (char *)PORT_ZAlloc(decodeItem->len + 1);
}
if ( buf ) {
PORT_Memcpy(buf, decodeItem->data, decodeItem->len);
buf[decodeItem->len] = 0;
}
SECITEM_FreeItem(decodeItem, PR_TRUE);
goto done;
} }
} }
} }
return ava ? avaToString(arena, ava) : NULL;
done:
return buf;
} }
/* RDNs are sorted from most general to most specific. /* RDNs are sorted from most general to most specific.
@ -1091,12 +1195,10 @@ CERT_GetNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
static char * static char *
CERT_GetLastNameElement(PRArenaPool *arena, CERTName *name, int wantedTag) CERT_GetLastNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
{ {
CERTRDN** rdns; CERTRDN** rdns = name->rdns;
CERTRDN *rdn; CERTRDN* rdn;
CERTAVA * lastAva = NULL; CERTAVA* lastAva = NULL;
char *buf = 0;
rdns = name->rdns;
while (rdns && (rdn = *rdns++) != 0) { while (rdns && (rdn = *rdns++) != 0) {
CERTAVA** avas = rdn->avas; CERTAVA** avas = rdn->avas;
CERTAVA* ava; CERTAVA* ava;
@ -1107,24 +1209,7 @@ CERT_GetLastNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
} }
} }
} }
return lastAva ? avaToString(arena, lastAva) : NULL;
if (lastAva) {
SECItem *decodeItem = CERT_DecodeAVAValue(&lastAva->value);
if(!decodeItem) {
return NULL;
}
if (arena) {
buf = (char *)PORT_ArenaZAlloc(arena,decodeItem->len + 1);
} else {
buf = (char *)PORT_ZAlloc(decodeItem->len + 1);
}
if ( buf ) {
PORT_Memcpy(buf, decodeItem->data, decodeItem->len);
buf[decodeItem->len] = 0;
}
SECITEM_FreeItem(decodeItem, PR_TRUE);
}
return buf;
} }
char * char *

Просмотреть файл

@ -37,7 +37,7 @@
/* /*
* cert.h - public data structures and prototypes for the certificate library * cert.h - public data structures and prototypes for the certificate library
* *
* $Id: cert.h,v 1.75 2008/11/21 21:02:38 wtc%google.com Exp $ * $Id: cert.h,v 1.76 2009/03/20 18:03:57 nelson%bolyard.com Exp $
*/ */
#ifndef _CERT_H_ #ifndef _CERT_H_
@ -174,6 +174,17 @@ extern char *CERT_FormatName (CERTName *name);
*/ */
extern char *CERT_Hexify (SECItem *i, int do_colon); extern char *CERT_Hexify (SECItem *i, int do_colon);
/*
** Converts DER string (with explicit length) into zString, if destination
** buffer is big enough to receive it. Does quoting and/or escaping as
** specified in RFC 1485. Input string must be single or multi-byte DER
** character set, (ASCII, UTF8, or ISO 8851-x) not a wide character set.
** Returns SECSuccess or SECFailure with error code set. If output buffer
** is too small, sets error code SEC_ERROR_OUTPUT_LEN.
*/
extern SECStatus
CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen);
/****************************************************************************** /******************************************************************************
* *
* Certificate handling operations * Certificate handling operations

Просмотреть файл

@ -20,6 +20,7 @@
* *
* Contributor(s): * Contributor(s):
* Aaron Spangler <aaron@spangler.ods.org> * Aaron Spangler <aaron@spangler.ods.org>
* Kaspar Brand <mozbugzilla@velox.ch>
* *
* Alternatively, the contents of this file may be used under the terms of * Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or * either the GNU General Public License Version 2 or later (the "GPL"), or
@ -38,7 +39,7 @@
/* /*
* Certificate handling code * Certificate handling code
* *
* $Id: certdb.c,v 1.96 2009/02/09 07:51:30 nelson%bolyard.com Exp $ * $Id: certdb.c,v 1.100 2009/03/23 02:18:19 nelson%bolyard.com Exp $
*/ */
#include "nssilock.h" #include "nssilock.h"
@ -1446,32 +1447,61 @@ CERT_AddOKDomainName(CERTCertificate *cert, const char *hn)
** returns SECFailure with SSL_ERROR_BAD_CERT_DOMAIN if no match, ** returns SECFailure with SSL_ERROR_BAD_CERT_DOMAIN if no match,
** returns SECFailure with some other error code if another error occurs. ** returns SECFailure with some other error code if another error occurs.
** **
** may modify cn, so caller must pass a modifiable copy. ** This function may modify string cn, so caller must pass a modifiable copy.
*/ */
static SECStatus static SECStatus
cert_TestHostName(char * cn, const char * hn) cert_TestHostName(char * cn, const char * hn)
{ {
int regvalid = PORT_RegExpValid(cn); static int useShellExp = -1;
if (regvalid != NON_SXP) {
SECStatus rv;
/* cn is a regular expression, try to match the shexp */
int match = PORT_RegExpCaseSearch(hn, cn);
if ( match == 0 ) { if (useShellExp < 0) {
rv = SECSuccess; useShellExp = (NULL != PR_GetEnv("NSS_USE_SHEXP_IN_CERT_NAME"));
} else { }
PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); if (useShellExp) {
rv = SECFailure; /* Backward compatible code, uses Shell Expressions (SHEXP). */
int regvalid = PORT_RegExpValid(cn);
if (regvalid != NON_SXP) {
SECStatus rv;
/* cn is a regular expression, try to match the shexp */
int match = PORT_RegExpCaseSearch(hn, cn);
if ( match == 0 ) {
rv = SECSuccess;
} else {
PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN);
rv = SECFailure;
}
return rv;
} }
return rv; } else {
} /* New approach conforms to RFC 2818. */
/* cn is not a regular expression */ char *wildcard = PORT_Strchr(cn, '*');
char *firstcndot = PORT_Strchr(cn, '.');
char *secondcndot = firstcndot ? PORT_Strchr(firstcndot+1, '.') : NULL;
char *firsthndot = PORT_Strchr(hn, '.');
/* compare entire hn with cert name */ /* For a cn pattern to be considered valid, the wildcard character...
* - may occur only in a DNS name with at least 3 components, and
* - may occur only as last character in the first component, and
* - may be preceded by additional characters
*/
if (wildcard && secondcndot && secondcndot[1] && firsthndot
&& firstcndot - wildcard == 1
&& secondcndot - firstcndot > 1
&& PORT_Strrchr(cn, '*') == wildcard
&& !PORT_Strncasecmp(cn, hn, wildcard - cn)
&& !PORT_Strcasecmp(firstcndot, firsthndot)) {
/* valid wildcard pattern match */
return SECSuccess;
}
}
/* String cn has no wildcard or shell expression.
* Compare entire string hn with cert name.
*/
if (PORT_Strcasecmp(hn, cn) == 0) { if (PORT_Strcasecmp(hn, cn) == 0) {
return SECSuccess; return SECSuccess;
} }
PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN);
return SECFailure; return SECFailure;
} }
@ -1522,15 +1552,18 @@ cert_VerifySubjectAltName(CERTCertificate *cert, const char *hn)
** so must copy it. ** so must copy it.
*/ */
int cnLen = current->name.other.len; int cnLen = current->name.other.len;
if (cnLen + 1 > cnBufLen) { rv = CERT_RFC1485_EscapeAndQuote(cn, cnBufLen,
cnBufLen = cnLen + 1; current->name.other.data, cnLen);
if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_OUTPUT_LEN) {
cnBufLen = cnLen * 3 + 3; /* big enough for worst case */
cn = (char *)PORT_ArenaAlloc(arena, cnBufLen); cn = (char *)PORT_ArenaAlloc(arena, cnBufLen);
if (!cn) if (!cn)
goto fail; goto fail;
rv = CERT_RFC1485_EscapeAndQuote(cn, cnBufLen,
current->name.other.data, cnLen);
} }
PORT_Memcpy(cn, current->name.other.data, cnLen); if (rv == SECSuccess)
cn[cnLen] = 0; rv = cert_TestHostName(cn ,hn);
rv = cert_TestHostName(cn ,hn);
if (rv == SECSuccess) if (rv == SECSuccess)
goto finish; goto finish;
} }

Просмотреть файл

@ -36,7 +36,7 @@
/* /*
* certi.h - private data structures for the certificate library * certi.h - private data structures for the certificate library
* *
* $Id: certi.h,v 1.27 2008/10/31 23:02:36 alexei.volkov.bugs%sun.com Exp $ * $Id: certi.h,v 1.28 2009/03/17 07:30:11 nelson%bolyard.com Exp $
*/ */
#ifndef _CERTI_H_ #ifndef _CERTI_H_
#define _CERTI_H_ #define _CERTI_H_
@ -249,6 +249,10 @@ extern int cert_AVAOidTagToMaxLen(SECOidTag tag);
extern CERTAVA * CERT_CreateAVAFromRaw(PRArenaPool *pool, extern CERTAVA * CERT_CreateAVAFromRaw(PRArenaPool *pool,
const SECItem * OID, const SECItem * value); const SECItem * OID, const SECItem * value);
/* Make an AVA from binary input specified by SECItem */
extern CERTAVA * CERT_CreateAVAFromSECItem(PRArenaPool *arena, SECOidTag kind,
int valueType, SECItem *value);
/* /*
* get a DPCache object for the given issuer subject and dp * get a DPCache object for the given issuer subject and dp
* Automatically creates the cache object if it doesn't exist yet. * Automatically creates the cache object if it doesn't exist yet.

Просмотреть файл

@ -36,7 +36,7 @@
/* /*
* certt.h - public data structures for the certificate library * certt.h - public data structures for the certificate library
* *
* $Id: certt.h,v 1.48 2008/10/31 23:02:36 alexei.volkov.bugs%sun.com Exp $ * $Id: certt.h,v 1.49 2009/03/21 01:40:34 nelson%bolyard.com Exp $
*/ */
#ifndef _CERTT_H_ #ifndef _CERTT_H_
#define _CERTT_H_ #define _CERTT_H_
@ -1253,6 +1253,12 @@ typedef enum CertStrictnessLevels {
#define CERT_ENABLE_LDAP_FETCH 1 #define CERT_ENABLE_LDAP_FETCH 1
#define CERT_ENABLE_HTTP_FETCH 2 #define CERT_ENABLE_HTTP_FETCH 2
/* This functin pointer type may be used for any function that takes
* a CERTCertificate * and returns an allocated string, which must be
* freed by a call to PORT_Free.
*/
typedef char * (*CERT_StringFromCertFcn)(CERTCertificate *cert);
/* XXX Lisa thinks the template declarations belong in cert.h, not here? */ /* XXX Lisa thinks the template declarations belong in cert.h, not here? */
#include "secasn1t.h" /* way down here because I expect template stuff to #include "secasn1t.h" /* way down here because I expect template stuff to

Просмотреть файл

@ -149,31 +149,30 @@ SetupAVAType(PRArenaPool *arena, SECOidTag type, SECItem *it, unsigned *maxLenp)
} }
static SECStatus static SECStatus
SetupAVAValue(PRArenaPool *arena, int valueType, char *value, SECItem *it, SetupAVAValue(PRArenaPool *arena, int valueType, const SECItem *in,
unsigned maxLen) SECItem *out, unsigned maxLen)
{ {
PRUint8 *value, *cp, *ucs4Val;
unsigned valueLen, valueLenLen, total; unsigned valueLen, valueLenLen, total;
unsigned ucs4Len = 0, ucs4MaxLen; unsigned ucs4Len = 0, ucs4MaxLen;
unsigned char *cp, *ucs4Val;
value = in->data;
valueLen = in->len;
switch (valueType) { switch (valueType) {
case SEC_ASN1_PRINTABLE_STRING: case SEC_ASN1_PRINTABLE_STRING:
case SEC_ASN1_IA5_STRING: case SEC_ASN1_IA5_STRING:
case SEC_ASN1_T61_STRING: case SEC_ASN1_T61_STRING:
case SEC_ASN1_UTF8_STRING: /* no conversion required */ case SEC_ASN1_UTF8_STRING: /* no conversion required */
valueLen = PORT_Strlen(value);
break; break;
case SEC_ASN1_UNIVERSAL_STRING: case SEC_ASN1_UNIVERSAL_STRING:
valueLen = PORT_Strlen(value);
ucs4MaxLen = valueLen * 6; ucs4MaxLen = valueLen * 6;
ucs4Val = (unsigned char *)PORT_ArenaZAlloc(arena, ucs4MaxLen); ucs4Val = (PRUint8 *)PORT_ArenaZAlloc(arena, ucs4MaxLen);
if(!ucs4Val || !PORT_UCS4_UTF8Conversion(PR_TRUE, if(!ucs4Val || !PORT_UCS4_UTF8Conversion(PR_TRUE, value, valueLen,
(unsigned char *)value, valueLen,
ucs4Val, ucs4MaxLen, &ucs4Len)) { ucs4Val, ucs4MaxLen, &ucs4Len)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure; return SECFailure;
} }
value = (char *)ucs4Val; value = ucs4Val;
valueLen = ucs4Len; valueLen = ucs4Len;
maxLen *= 4; maxLen *= 4;
break; break;
@ -189,12 +188,13 @@ SetupAVAValue(PRArenaPool *arena, int valueType, char *value, SECItem *it,
valueLenLen = DER_LengthLength(valueLen); valueLenLen = DER_LengthLength(valueLen);
total = 1 + valueLenLen + valueLen; total = 1 + valueLenLen + valueLen;
it->data = cp = (unsigned char*) PORT_ArenaAlloc(arena, total); cp = (PRUint8*)PORT_ArenaAlloc(arena, total);
if (!cp) { if (!cp) {
return SECFailure; return SECFailure;
} }
it->len = total; out->data = cp;
cp = (unsigned char*) DER_StoreHeader(cp, valueType, valueLen); out->len = total;
cp = (PRUint8 *)DER_StoreHeader(cp, valueType, valueLen);
PORT_Memcpy(cp, value, valueLen); PORT_Memcpy(cp, value, valueLen);
return SECSuccess; return SECSuccess;
} }
@ -220,7 +220,8 @@ CERT_CreateAVAFromRaw(PRArenaPool *pool, const SECItem * OID,
} }
CERTAVA * CERTAVA *
CERT_CreateAVA(PRArenaPool *arena, SECOidTag kind, int valueType, char *value) CERT_CreateAVAFromSECItem(PRArenaPool *arena, SECOidTag kind, int valueType,
SECItem *value)
{ {
CERTAVA *ava; CERTAVA *ava;
int rv; int rv;
@ -231,17 +232,28 @@ CERT_CreateAVA(PRArenaPool *arena, SECOidTag kind, int valueType, char *value)
rv = SetupAVAType(arena, kind, &ava->type, &maxLen); rv = SetupAVAType(arena, kind, &ava->type, &maxLen);
if (rv) { if (rv) {
/* Illegal AVA type */ /* Illegal AVA type */
return 0; return NULL;
} }
rv = SetupAVAValue(arena, valueType, value, &ava->value, maxLen); rv = SetupAVAValue(arena, valueType, value, &ava->value, maxLen);
if (rv) { if (rv) {
/* Illegal value type */ /* Illegal value type */
return 0; return NULL;
} }
} }
return ava; return ava;
} }
CERTAVA *
CERT_CreateAVA(PRArenaPool *arena, SECOidTag kind, int valueType, char *value)
{
SECItem item = { siBuffer, NULL, 0 };
item.data = (PRUint8 *)value;
item.len = PORT_Strlen(value);
return CERT_CreateAVAFromSECItem(arena, kind, valueType, &item);
}
CERTAVA * CERTAVA *
CERT_CopyAVA(PRArenaPool *arena, CERTAVA *from) CERT_CopyAVA(PRArenaPool *arena, CERTAVA *from)
{ {

Просмотреть файл

@ -76,6 +76,7 @@ CERT_VerifySignedDataWithPublicKey(CERTSignedData *sd,
{ {
SECStatus rv; SECStatus rv;
SECItem sig; SECItem sig;
SECOidTag hashAlg = SEC_OID_UNKNOWN;
if ( !pubKey || !sd ) { if ( !pubKey || !sd ) {
PORT_SetError(PR_INVALID_ARGUMENT_ERROR); PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
@ -88,9 +89,18 @@ CERT_VerifySignedDataWithPublicKey(CERTSignedData *sd,
DER_ConvertBitString(&sig); DER_ConvertBitString(&sig);
rv = VFY_VerifyDataWithAlgorithmID(sd->data.data, sd->data.len, pubKey, rv = VFY_VerifyDataWithAlgorithmID(sd->data.data, sd->data.len, pubKey,
&sig, &sd->signatureAlgorithm, NULL, wincx); &sig, &sd->signatureAlgorithm, &hashAlg, wincx);
if (rv == SECSuccess) {
return rv ? SECFailure : SECSuccess; /* Are we honoring signatures for this algorithm? */
PRUint32 policyFlags = 0;
rv = NSS_GetAlgorithmPolicy(hashAlg, &policyFlags);
if (rv == SECSuccess &&
!(policyFlags & NSS_USE_ALG_IN_CERT_SIGNATURE)) {
PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
rv = SECFailure;
}
}
return rv;
} }
/* /*
@ -527,6 +537,7 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert,
case certUsageEmailRecipient: case certUsageEmailRecipient:
case certUsageObjectSigner: case certUsageObjectSigner:
case certUsageVerifyCA: case certUsageVerifyCA:
case certUsageAnyCA:
case certUsageStatusResponder: case certUsageStatusResponder:
if ( CERT_TrustFlagsForCACertUsage(certUsage, &requiredFlags, if ( CERT_TrustFlagsForCACertUsage(certUsage, &requiredFlags,
&trustType) != SECSuccess ) { &trustType) != SECSuccess ) {
@ -735,7 +746,7 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert,
certUsage != certUsageStatusResponder) { certUsage != certUsageStatusResponder) {
/* /*
* check the trust parms of the issuer * XXX This choice of trustType seems arbitrary.
*/ */
if ( certUsage == certUsageVerifyCA ) { if ( certUsage == certUsageVerifyCA ) {
if ( subjectCert->nsCertType & NS_CERT_TYPE_EMAIL_CA ) { if ( subjectCert->nsCertType & NS_CERT_TYPE_EMAIL_CA ) {
@ -748,13 +759,12 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert,
} }
flags = SEC_GET_TRUST_FLAGS(issuerCert->trust, trustType); flags = SEC_GET_TRUST_FLAGS(issuerCert->trust, trustType);
if (( flags & requiredFlags ) == requiredFlags) {
/* we found a trusted one, so return */
rv = rvFinal;
goto done;
}
if (flags & CERTDB_VALID_CA) { if (flags & CERTDB_VALID_CA) {
if ( ( flags & requiredFlags ) == requiredFlags) {
/* we found a trusted one, so return */
rv = rvFinal;
goto done;
}
validCAOverride = PR_TRUE; validCAOverride = PR_TRUE;
} }
} else { } else {
@ -1004,13 +1014,12 @@ CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert,
* check the trust parms of the issuer * check the trust parms of the issuer
*/ */
flags = SEC_GET_TRUST_FLAGS(cert->trust, trustType); flags = SEC_GET_TRUST_FLAGS(cert->trust, trustType);
if ( ( flags & requiredFlags ) == requiredFlags) {
/* we found a trusted one, so return */
rv = rvFinal;
goto done;
}
if (flags & CERTDB_VALID_CA) { if (flags & CERTDB_VALID_CA) {
if ( ( flags & requiredFlags ) == requiredFlags) {
/* we found a trusted one, so return */
rv = rvFinal;
goto done;
}
validCAOverride = PR_TRUE; validCAOverride = PR_TRUE;
} }
} }
@ -1377,6 +1386,7 @@ CERT_VerifyCert(CERTCertDBHandle *handle, CERTCertificate *cert,
} }
break; break;
case certUsageVerifyCA: case certUsageVerifyCA:
case certUsageAnyCA:
requiredKeyUsage = KU_KEY_CERT_SIGN; requiredKeyUsage = KU_KEY_CERT_SIGN;
requiredCertType = NS_CERT_TYPE_CA; requiredCertType = NS_CERT_TYPE_CA;
if ( ! ( certType & NS_CERT_TYPE_CA ) ) { if ( ! ( certType & NS_CERT_TYPE_CA ) ) {
@ -1947,6 +1957,7 @@ CERTCertList *
CERT_GetCertChainFromCert(CERTCertificate *cert, int64 time, SECCertUsage usage) CERT_GetCertChainFromCert(CERTCertificate *cert, int64 time, SECCertUsage usage)
{ {
CERTCertList *chain = NULL; CERTCertList *chain = NULL;
int count = 0;
if (NULL == cert) { if (NULL == cert) {
return NULL; return NULL;
@ -1964,7 +1975,7 @@ CERT_GetCertChainFromCert(CERTCertificate *cert, int64 time, SECCertUsage usage)
return NULL; return NULL;
} }
while (cert != NULL) { while (cert != NULL && ++count <= CERT_MAX_CERT_CHAIN) {
if (SECSuccess != CERT_AddCertToListTail(chain, cert)) { if (SECSuccess != CERT_AddCertToListTail(chain, cert)) {
/* return partial chain */ /* return partial chain */
PORT_SetError(SEC_ERROR_NO_MEMORY); PORT_SetError(SEC_ERROR_NO_MEMORY);

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше