Compare commits

..

38 Commits

Author SHA1 Message Date
dkl%redhat.com
8c591d53e2 Removed some remaining SelectVisible calls in favor of CanSeeBug
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@121533 18797224-902f-48f8-a5cc-f745e15eee43
2002-05-15 18:36:31 +00:00
dkl%redhat.com
c1aa983fd5 Update to HEAD 2002/05/13
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@121401 18797224-902f-48f8-a5cc-f745e15eee43
2002-05-13 21:56:49 +00:00
dkl%redhat.com
3551227412 forgot one
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@121393 18797224-902f-48f8-a5cc-f745e15eee43
2002-05-13 20:49:00 +00:00
dkl%redhat.com
d0cc91f285 Fixed some template inconsistencies with current 2.16 Stable Branch
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@121392 18797224-902f-48f8-a5cc-f745e15eee43
2002-05-13 20:46:50 +00:00
(no author)
65ff7d56b3 This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@121370 18797224-902f-48f8-a5cc-f745e15eee43
2002-05-13 06:24:51 +00:00
dkl%redhat.com
800eccde9a Merge with HEAD 2002/04/26
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@119979 18797224-902f-48f8-a5cc-f745e15eee43
2002-04-26 18:59:37 +00:00
(no author)
5360e5b008 This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@119975 18797224-902f-48f8-a5cc-f745e15eee43
2002-04-26 18:12:55 +00:00
dkl%redhat.com
da759055dd Sync to HEAD 2002/03/21
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@117156 18797224-902f-48f8-a5cc-f745e15eee43
2002-03-22 05:16:48 +00:00
(no author)
1f960bb1bd This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@116669 18797224-902f-48f8-a5cc-f745e15eee43
2002-03-15 23:23:14 +00:00
dkl%redhat.com
e0f4b89db1 Update to HEAD 2002/02/26
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@115395 18797224-902f-48f8-a5cc-f745e15eee43
2002-02-27 01:11:14 +00:00
(no author)
025b6e8e46 This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@115298 18797224-902f-48f8-a5cc-f745e15eee43
2002-02-24 09:28:23 +00:00
dkl%redhat.com
704f46aa53 Update to HEAD 2002/02/04
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@113607 18797224-902f-48f8-a5cc-f745e15eee43
2002-02-04 15:56:15 +00:00
(no author)
f26338df7e This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@113575 18797224-902f-48f8-a5cc-f745e15eee43
2002-02-03 09:28:50 +00:00
dkl%redhat.com
58548c3f0d Update to HEAD 2002/01/30
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@113247 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-30 23:00:13 +00:00
(no author)
9a6b4393ad This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@113166 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-29 23:26:38 +00:00
dkl%redhat.com
4316819604 Fix runtests.sh error on processmail
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@112507 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-21 23:27:24 +00:00
dkl%redhat.com
9d93dfabb8 Fix botched earlier sync with HEAD
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@112499 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-21 20:42:30 +00:00
dkl%redhat.com
d2ddb07675 Update to HEAD 01/18/2002
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@112473 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-18 23:06:43 +00:00
dkl%redhat.com
66d426dc97 Lost the pgsetup.pl file somewhere along the line. Adding back properly.
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111575 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-08 16:13:05 +00:00
dkl%redhat.com
b7e91cb3b6 Changes to CanSeeBug to allow multiple checks in one call for buglist.cgi
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111509 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-07 23:20:15 +00:00
dkl%redhat.com
5ac0899827 Update to HEAD 2002-01-07
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111508 18797224-902f-48f8-a5cc-f745e15eee43
2002-01-07 23:14:41 +00:00
dkl%redhat.com
4f49e57a3b Merge 3 with HEAD: 2001/12/26
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111103 18797224-902f-48f8-a5cc-f745e15eee43
2001-12-27 07:26:12 +00:00
dkl%redhat.com
38c27be28f Merge 2 with HEAD: 2001/12/26
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111102 18797224-902f-48f8-a5cc-f745e15eee43
2001-12-27 06:02:04 +00:00
dkl%redhat.com
d60d3d6121 Merge fix. This is frustrating.
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111101 18797224-902f-48f8-a5cc-f745e15eee43
2001-12-27 05:29:04 +00:00
dkl%redhat.com
db0b87fb6c Merge with HEAD on 2001/12/26
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@111100 18797224-902f-48f8-a5cc-f745e15eee43
2001-12-27 05:09:43 +00:00
(no author)
6e2791a4b7 This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@110404 18797224-902f-48f8-a5cc-f745e15eee43
2001-12-12 22:41:21 +00:00
dkl%redhat.com
14542c62c7 Update to HEAD 2001-12-03
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@109510 18797224-902f-48f8-a5cc-f745e15eee43
2001-12-03 04:06:19 +00:00
dkl%redhat.com
38ebcba576 Fixed error in AddFDef
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@108598 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-20 18:40:38 +00:00
dkl%redhat.com
a5502157a9 Update to HEAD - November 18, 2001
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@108470 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-19 05:57:30 +00:00
(no author)
ba69b37618 This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@108456 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-18 22:20:21 +00:00
dkl%redhat.com
22b863a5e9 Synced up with CVS HEAD and created Bugzilla_PgSQL_branch_sync tag
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@107700 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-08 23:03:10 +00:00
dkl%redhat.com
3e54979994 Fixed conflict in Bug.pm, removal of tabs from lots of files.
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@107385 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-06 01:21:11 +00:00
dkl%redhat.com
d73ca44c76 Add new cpan module dependencies
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@107356 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-05 21:43:11 +00:00
dkl%redhat.com
a4fc52b12e Updates and bug fixes
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@107354 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-05 21:10:15 +00:00
dkl%redhat.com
353baca797 New SQL utility functions. Changes in buglist.cgi to improve queries.
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@106967 18797224-902f-48f8-a5cc-f745e15eee43
2001-11-01 15:35:03 +00:00
dkl%redhat.com
4618ab6c36 Initial checkin of pgsetup.pl. Utility for setting up Bugzilla database in PostgreSQL.
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@106569 18797224-902f-48f8-a5cc-f745e15eee43
2001-10-29 20:15:50 +00:00
justdave%syndicomm.com
faaed9c15f initial commit of PgSQL megapatch v0.2
git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@106532 18797224-902f-48f8-a5cc-f745e15eee43
2001-10-29 07:49:05 +00:00
(no author)
675f64d0ae This commit was manufactured by cvs2svn to create branch
'Bugzilla_PgSQL_branch'.

git-svn-id: svn://10.0.0.236/branches/Bugzilla_PgSQL_branch@106501 18797224-902f-48f8-a5cc-f745e15eee43
2001-10-28 03:41:01 +00:00
378 changed files with 106012 additions and 34389 deletions

View File

@@ -1,132 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
This file overrides all option settings in the IDE. It is an attempt to allow all builds
to have the same options.
Note: We can't use ConditionalMacros.h in this file because it will conflict with
the PowerPlant precompiled headers.
*/
/* warning pragmas */
#pragma warn_hidevirtual on
#pragma warn_emptydecl on
#pragma warn_unusedvar on
#pragma warn_extracomma on
#pragma warn_illpragma on
#pragma warn_possunwant on
#pragma warn_unusedarg off /* turned off to reduce warnings */
#pragma check_header_flags on
/* Language features that must be the same across libraries... */
#pragma enumsalwaysint on
#pragma unsigned_char off
#pragma exceptions on
#pragma bool on
#pragma wchar_type on
#pragma RTTI on
/* Save as much space as possible with strings... */
#pragma pool_strings on
#pragma dont_reuse_strings off
#pragma options align=native
#pragma sym on /* Takes no memory. OK in non-debug. */
#ifdef powerc /* ...generating PowerPC */
#pragma toc_data on
#pragma fp_contract on
#pragma readonly_strings on
#ifdef DEBUG
#pragma profile off /* Turn this on to profile the application. */
/* Look for more details about profiling in nsMacMessagePump.cpp. */
#pragma traceback on
#pragma global_optimizer off
#pragma scheduling off
#pragma peephole off
#pragma optimize_for_size off
#else
#if TARGET_CARBON
#pragma traceback on /* should always be ON for Carbon builds */
#else
#pragma traceback on /* leave on until the final release, so MacsBug logs are interpretable */
#endif
#pragma global_optimizer on
#pragma optimization_level 4
#pragma scheduling 603
#pragma peephole on
#pragma optimize_for_size on
#pragma opt_strength_reduction on
#pragma opt_propagation on
#pragma opt_loop_invariants on
#pragma opt_lifetimes on
#pragma opt_dead_code on
#pragma opt_dead_assignments on
#pragma opt_common_subs on
#endif
#else /* ...generating 68k */
#pragma code68020 on
#pragma code68881 off
/* Far everything... */
#pragma far_code
#pragma far_data on
#pragma far_strings on
#pragma far_vtables on
#pragma fourbyteints on /* 4-byte ints */
#pragma IEEEdoubles on /* 8-byte doubles (as required by Java and NSPR) */
#ifdef DEBUG
#pragma macsbug on
#pragma oldstyle_symbols off
#else
#pragma macsbug off
#endif
#endif

View File

@@ -1,5 +0,0 @@
#
# This is a list of local files which get copied to the mozilla:dist directory
#
IDE_Options.h

View File

@@ -1,59 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* 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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#error "DonÕt use me!"
#define OLDROUTINELOCATIONS 0
#define XP_MAC 1
#define NSPR20 1
#define _NO_FAST_STRING_INLINES_ 1
#define HAVE_BOOLEAN 1
#define NETSCAPE 1
#define OTUNIXERRORS 1 /* We want OpenTransport error codes */
#define OJI 1
/*
This compiles in heap dumping utilities and other good stuff
for developers -- maybe we only want it in for a special SDK
nspr/java runtime(?):
*/
#define DEVELOPER_DEBUG 1
#define MAX(_a,_b) ((_a) < (_b) ? (_b) : (_a))
#define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))

Binary file not shown.

View File

@@ -1,80 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla opt build prefs";
my($config_header_file_name) = ":mozilla:config:mac:DefinesOptions.h";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "¥ Mozilla opt progress",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(0, ":mozilla:dist:viewer:", $config_header_file_name);
my($do_checkout) = 0;
my($do_build) = 1;
RunBuild($do_checkout, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,80 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla debug build prefs";
my($config_header_file_name) = ":mozilla:config:mac:DefinesOptionsDebug.h";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "¥ Mozilla debug progress",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(1, ":mozilla:dist:viewer_debug:", $config_header_file_name);
my($do_pull) = 0; # overridden by flags and prefs
my($do_build) = 1;
RunBuild($do_pull, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,550 +0,0 @@
#!perl -w
package Moz::BuildCore;
require 5.004;
require Exporter;
use strict;
use vars qw( @ISA @EXPORT );
# perl includes
use Cwd;
use POSIX;
use Time::Local;
use File::Basename;
use LWP::Simple;
# homegrown
use Moz::Moz;
use Moz::Jar;
use Moz::BuildFlags;
use Moz::BuildUtils;
use Moz::CodeWarriorLib;
# use MozillaBuildList; # eventually, this should go away, and be replaced by data input
@ISA = qw(Exporter);
@EXPORT = qw(
RunBuild
);
#//--------------------------------------------------------------------------------------------------
#// DoPrebuildCheck
#//
#// Check the build tools etc before running the build.
#//--------------------------------------------------------------------------------------------------
sub DoPrebuildCheck()
{
SanityCheckJarOptions();
# launch codewarrior and persist its location. Have to call this before first
# call to getCodeWarriorPath().
my($ide_path_file) = $main::filepaths{"idepath"};
$ide_path_file = full_path_to($ide_path_file);
LaunchCodeWarrior($ide_path_file);
}
#//--------------------------------------------------------------------------------------------------
#// GenBuildSystemInfo
#//--------------------------------------------------------------------------------------------------
sub GenBuildSystemInfo()
{
# always rebuild the configuration program.
BuildProjectClean(":mozilla:build:mac:tools:BuildSystemInfo:BuildSystemInfo.mcp", "BuildSystemInfo");
# delete the configuration file.
unlink(":mozilla:build:mac:BuildSystemInfo.pm");
# run the program.
system(":mozilla:build:mac:BuildSystemInfo");
# wait for the file to be created.
while (!(-e ":mozilla:build:mac:BuildSystemInfo.pm")) { WaitNextEvent(); }
# wait for BuildSystemInfo to finish, so that we see correct results.
while (IsProcessRunning("BuildSystemInfo")) { WaitNextEvent(); }
# now, evaluate the contents of the file.
open(F, ":mozilla:build:mac:BuildSystemInfo.pm");
while (<F>) { eval; }
close(F);
}
#//--------------------------------------------------------------------------------------------------
#// Make library aliases
#//--------------------------------------------------------------------------------------------------
sub MakeLibAliases()
{
my($dist_dir) = GetBinDirectory();
#// ProfilerLib
if ($main::PROFILE)
{
my($profilerlibpath) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:Profiler:Profiler Common:ProfilerLib");
MakeAlias("$profilerlibpath", "$dist_dir"."Essential Files:");
}
}
#//--------------------------------------------------------------------------------------------------
#// ConfigureBuildSystem
#//
#// defines some build-system configuration variables.
#//--------------------------------------------------------------------------------------------------
sub ConfigureBuildSystem()
{
#// In the future, we may want to do configurations based on the actual build system itself.
#// GenBuildSystemInfo();
#// For now, if we discover a newer header file than existed in Universal Interfaces 3.2,
#// we'll assume that 3.3 or later is in use.
my($universal_interfaces) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:Universal:Interfaces:CIncludes:");
if (-e ($universal_interfaces . "ControlDefinitions.h")) {
$main::UNIVERSAL_INTERFACES_VERSION = 0x0330;
}
#// Rename IC SDK folder in the Mac OS Support folder
my($ic_sdk_folder) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:ICProgKit2.0.2");
if( -e $ic_sdk_folder)
{
my($new_ic_folder_name) = Moz::CodeWarriorLib::getCodeWarriorPath("MacOS Support:(ICProgKit2.0.2)");
rename ($ic_sdk_folder, $new_ic_folder_name);
# note that CodeWarrior doesn't descend into folders with () the name
print "Mozilla no longer needs the Internet Config SDK to build:\n Renaming the 'ICProgKit2.0.2' folder to '(ICProgKit2.0.2)'\n";
}
printf("UNIVERSAL_INTERFACES_VERSION = 0x%04X\n", $main::UNIVERSAL_INTERFACES_VERSION);
# alias required CodeWarrior libs into the Essential Files folder (only the Profiler lib now)
MakeLibAliases();
}
#//--------------------------------------------------------------------------------------------------
#// CheckOutModule. Takes variable number of args; first two are required
#//--------------------------------------------------------------------------------------------------
sub CheckOutModule($$$$)
{
my($session, $module, $revision, $date) = @_;
my($result) = $session->checkout($module, $revision, $date);
# result of 1 is success
if ($result) { return; }
my($checkout_err) = $session->getLastError();
if ($checkout_err == 708) {
die "Error: Checkout was cancelled.\n";
} elsif ($checkout_err == 911) {
die "Error: CVS session settings are incorrect. Check your password, and the CVS root settings.\n";
} elsif ($checkout_err == 703) {
die "Error: CVS checkout failed. Unknown module, unknown tag, bad username, or other CVS error.\n";
} elsif ($checkout_err == 711) {
print "Checkout of '$module' failed.\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// getScriptFolder
#//--------------------------------------------------------------------------------------------------
sub getScriptFolder()
{
return dirname($0);
}
#//--------------------------------------------------------------------------------------------------
#// getScriptFolder
#//--------------------------------------------------------------------------------------------------
sub get_url_contents($)
{
my($url) = @_;
my($url_contents) = LWP::Simple::get($url);
$url_contents =~ s/\r\n/\n/g; # normalize linebreaks
$url_contents =~ s/\r/\n/g; # normalize linebreaks
return $url_contents;
}
#//--------------------------------------------------------------------------------------------------
#// get_files_from_content
#//--------------------------------------------------------------------------------------------------
sub uniq
{
my $lastval;
grep(($_ ne $lastval, $lastval = $_)[$[], @_);
}
#//--------------------------------------------------------------------------------------------------
#// get_files_from_content
#//--------------------------------------------------------------------------------------------------
sub get_files_from_content($)
{
my($content) = @_;
my(@jscalls) = grep (/return js_file_menu[^{]*/, split(/\n/, $content));
my $i;
for ($i = 0; $i < @jscalls ; $i++)
{
$jscalls[$i] =~ s/.*\(|\).*//g;
my(@callparams) = split(/,/, $jscalls[$i]);
my ($repos, $dir, $file, $rev) = grep(s/['\s]//g, @callparams);
$jscalls[$i] = "$dir/$file";
}
&uniq(sort(@jscalls));
}
#//--------------------------------------------------------------------------------------------------
#// getLastUpdateTime
#//
#// Get the last time we updated. Return 0 on failure
#//--------------------------------------------------------------------------------------------------
sub getLastUpdateTime($)
{
my($timestamp_file) = @_;
my($time_string);
local(*TIMESTAMP_FILE);
unless (open(TIMESTAMP_FILE, "< $timestamp_file")) { return 0; }
while (<TIMESTAMP_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
$time_string = $line;
}
# get the epoch seconds
my($last_update_secs) = $time_string;
$last_update_secs =~ s/\s#.+$//;
print "FAST_UPDATE found that you last updated at ".localtime($last_update_secs)."\n";
# how long ago was this, in hours?
my($gm_now) = time();
my($update_hours) = 1 + ceil(($gm_now - $last_update_secs) / (60 * 60));
return $update_hours;
}
#//--------------------------------------------------------------------------------------------------
#// saveCheckoutTimestamp
#//
#// Create a file on disk containing the current time. Param is time(), which is an Epoch seconds
#// (and therefore in GMT).
#//
#//--------------------------------------------------------------------------------------------------
sub saveCheckoutTimestamp($$)
{
my($gm_secs, $timestamp_file) = @_;
local(*TIMESTAMP_FILE);
open(TIMESTAMP_FILE, ">$timestamp_file") || die "Failed to open $timestamp_file\n";
print(TIMESTAMP_FILE "# time of last checkout or update, in GMT. Used by FAST_UPDATE\n");
print(TIMESTAMP_FILE "$gm_secs \# around ".localtime()." local time\n");
close(TIMESTAMP_FILE);
}
#//--------------------------------------------------------------------------------------------------
#// FastUpdate
#//
#// Use Bonsai url data to update only those dirs which have new files
#//
#//--------------------------------------------------------------------------------------------------
sub FastUpdate($$)
{
my($modules, $timestamp_file) = @_; # list of modules to check out
my($num_hours) = getLastUpdateTime($timestamp_file);
if ($num_hours == 0 || $num_hours > 170) {
print "Can't fast_update; last update was too long ago, or never. Doing normal checkout.\n";
return 0;
}
print "Doing fast update, pulling files changed in the last $num_hours hours\n";
my($cvsfile) = AskAndPersistFile($main::filepaths{"sessionpath"});
my($session) = Moz::MacCVS->new( $cvsfile );
unless (defined($session)) { die "Error: Checkout aborted. Cannot create session file: $session" }
# activate MacCVS
ActivateApplication('Mcvs');
my($checkout_start_time) = time();
#print "Time now is $checkout_start_time ($checkout_start_time + 0)\n";
my($this_co);
foreach $this_co (@$modules)
{
my($module, $revision, $date) = ($this_co->[0], $this_co->[1], $this_co->[2]);
# assume that things pulled by date wont change
if ($date ne "") {
print "$module is pulled by date, so ignoring in FastUpdate.\n";
next;
}
my($search_type) = "hours";
my($min_date) = "";
my($max_date) = "";
my($url) = "http://bonsai.mozilla.org/cvsquery.cgi?treeid=default&module=${module}&branch=${revision}&branchtype=match&dir=&file=&filetype=match&who=&whotype=match&sortby=Date&hours=${num_hours}&date=${search_type}&mindate=${min_date}&maxdate=${max_date}&cvsroot=%2Fcvsroot";
if ($revision eq "") {
print "Getting list of checkins to $module from Bonsai...\n";
} else {
print "Getting list of checkins to $module on branch $revision from Bonsai...\n";
}
my(@files) = &get_files_from_content(&get_url_contents($url));
if ($#files > 0)
{
my(@cvs_co_list);
my($co_file);
foreach $co_file (@files)
{
print "Updating $co_file\n";
push(@cvs_co_list, $co_file);
}
my($result) = $session->update($revision, \@cvs_co_list);
# result of 1 is success
if (!$result) { die "Error: Fast update failed\n"; }
} else {
print "No files in this module changed\n";
}
}
saveCheckoutTimestamp($checkout_start_time, $timestamp_file);
return 1;
}
#//--------------------------------------------------------------------------------------------------
#// Checkout
#//--------------------------------------------------------------------------------------------------
sub CheckoutModules($$$)
{
my($modules, $pull_date, $timestamp_file) = @_; # list of modules to check out
my($start_time) = TimeStart();
# assertRightDirectory();
my($cvsfile) = AskAndPersistFile($main::filepaths{"sessionpath"});
my($session) = Moz::MacCVS->new( $cvsfile );
unless (defined($session)) { die "Error: Checkout aborted. Cannot create session file: $session" }
my($checkout_start_time) = time();
# activate MacCVS
ActivateApplication('Mcvs');
my($this_co);
foreach $this_co (@$modules)
{
my($module, $revision, $date) = ($this_co->[0], $this_co->[1], $this_co->[2]);
if ($date eq "") {
$date = $pull_date;
}
CheckOutModule($session, $module, $revision, $date);
# print "Checking out $module with ref $revision, date $date\n";
}
saveCheckoutTimestamp($checkout_start_time, $timestamp_file);
TimeEnd($start_time, "Checkout");
}
#//--------------------------------------------------------------------------------------------------
#// ReadCheckoutModulesFile
#//--------------------------------------------------------------------------------------------------
sub ReadCheckoutModulesFile($$)
{
my($modules_file, $co_list) = @_;
my($checkout_file) = getScriptFolder().":".$modules_file;
local(*CHECKOUT_FILE);
open(CHECKOUT_FILE, "< $checkout_file") || die "Error: failed to open checkout list $checkout_file\n";
while (<CHECKOUT_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
my(@cvs_co) = ["", "", ""];
my($module, $revision, $date) = (0, 1, 2);
if ($line =~ /\s*([^#,\s]+)\s*\,\s*([^#,\s]+)\s*\,\s*([^#]+)/)
{
@cvs_co[$module] = $1;
@cvs_co[$revision] = $2;
@cvs_co[$date] = $3;
}
elsif ($line =~ /\s*([^#,\s]+)\s*\,\s*([^#,\s]+)\s*(#.+)?/)
{
@cvs_co[$module] = $1;
@cvs_co[$revision] = $2;
}
elsif ($line =~ /\s*([^#,\s]+)\s*\,\s*,\s*([^#,]+)/)
{
@cvs_co[$module] = $1;
@cvs_co[$date] = $2;
}
elsif ($line =~ /\s*([^#,\s]+)/)
{
@cvs_co[$module] = $1;
}
else
{
die "Error: unrecognized line '$line' in $modules_file\n";
}
# strip surrounding space from date
@cvs_co[$date] =~ s/^\s*|\s*$//g;
# print "Going to check out '@cvs_co[$module]', '@cvs_co[$revision]', '@cvs_co[$date]'\n";
push(@$co_list, \@cvs_co);
}
close(CHECKOUT_FILE);
}
#//--------------------------------------------------------------------------------------------------
#// PullFromCVS
#//--------------------------------------------------------------------------------------------------
sub PullFromCVS($$)
{
unless ( $main::build{pull} ) { return; }
my($modules_file, $timestamp_file) = @_;
StartBuildModule("pull");
my(@cvs_co_list);
ReadCheckoutModulesFile($modules_file, \@cvs_co_list);
if ($main::FAST_UPDATE && $main::options{pull_by_date})
{
die "Error: you can't use FAST_UPDATE if you are pulling by date.\n";
}
my($did_fast_update) = $main::FAST_UPDATE && FastUpdate(\@cvs_co_list, $timestamp_file);
if (!$did_fast_update)
{
my($pull_date) = "";
if ($main::options{pull_by_date})
{
# acceptable CVS date formats are (in local time):
# ISO8601 (e.g. "1972-09-24 20:05") and Internet (e.g. "24 Sep 1972 20:05").
# Perl's localtime() string format also seems to work.
$pull_date = localtime().""; # force string interp.
print "Pulling by date $pull_date\n";
}
CheckoutModules(\@cvs_co_list, $pull_date, $timestamp_file);
}
EndBuildModule("pull");
}
#//--------------------------------------------------------------------------------------------------
#// RunBuild
#//--------------------------------------------------------------------------------------------------
sub RunBuild($$$$)
{
my($do_pull, $do_build, $input_files, $build_prefs) = @_;
InitBuildProgress($input_files->{"buildprogress"});
# if we are pulling, we probably want to do a full build, so clear the build progress
if ($do_pull) {
ClearBuildProgress();
}
# read local prefs, and the build progress file, and set flags to say what to build
SetupBuildParams(\%main::build,
\%main::options,
\%main::optiondefines,
\%main::filepaths,
$input_files->{"buildflags"},
$build_prefs);
# If we were told to pull, make sure we do, overriding prefs etc.
if ($do_pull)
{
$main::build{"pull"} = 1;
}
# transfer this flag
$CodeWarriorLib::CLOSE_PROJECTS_FIRST = $main::CLOSE_PROJECTS_FIRST;
# setup the build log
SetupBuildLog($main::filepaths{"buildlogfilepath"}, $main::USE_TIMESTAMPED_LOGS);
StopForErrors();
if ($main::LOG_TO_FILE) {
RedirectOutputToFile($main::filepaths{"scriptlogfilepath"});
}
# run a pre-build check to see that the tools etc are in order
DoPrebuildCheck();
# do the pull
PullFromCVS($input_files->{"checkoutdata"}, $input_files->{"checkouttime"});
unless ($do_build) { return; }
my($build_start) = TimeStart();
# check the build environment
ConfigureBuildSystem();
# here we load and call methods in the build module indirectly.
# we have to use indirection because the build module can be named
# differently for different builds.
chdir(dirname($0)); # change to the script dir
my($build_module) = $input_files->{"buildmodule"};
# load the build module
require $build_module;
{ # scope for no strict 'refs'
no strict 'refs';
my($package_name) = $build_module;
$package_name =~ s/\.pm$//;
chdir($main::MOZ_SRC);
&{$package_name."::BuildDist"}();
chdir($main::MOZ_SRC);
&{$package_name."::BuildProjects"}();
}
# the build finished, so clear the build progress state
ClearBuildProgress();
TimeEnd($build_start, "Build");
print "Build complete\n";
}
1;

View File

@@ -1,425 +0,0 @@
#!perl -w
package Moz::BuildFlags;
require 5.004;
require Exporter;
# Package that attempts to read a file from the Preferences folder,
# and get build settings out of it
use strict;
use Exporter;
use Cwd;
use File::Basename;
use Moz::Moz;
use Moz::Prefs;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
SetupBuildParams
InitBuildProgress
WriteBuildProgress
ClearBuildProgress
ReadBuildProgress
);
my(@build_flags);
my(@options_flags);
my(@filepath_flags);
my(%arrays_list) = (
"build_flags", \@build_flags,
"options_flags", \@options_flags,
"filepath_flags", \@filepath_flags
);
my($progress_file) = "¥ÊBuild progress";
#-------------------------------------------------------------------------------
# appendArrayFlag
#
# Set a flag in the array
#-------------------------------------------------------------------------------
sub appendArrayFlag(@)
{
my($array_name) = shift;
my($setting) = shift;
my($value) = shift;
my(@optional_values);
foreach (@_) {
push(@optional_values, $_);
}
my(@this_flag) = [$setting, $value, @optional_values];
my($flags_array) = $arrays_list{$array_name};
if ($flags_array)
{
push(@{$flags_array}, @this_flag) || die "Failed to append\n";
}
else
{
die "Error: unknown build flags array $array_name\n";
}
}
#-------------------------------------------------------------------------------
# readFlagsFile
#
# Read the file of build flags from disk. File path is relative to the
# script directory.
#-------------------------------------------------------------------------------
sub readFlagsFile($)
{
my($flags_file) = @_;
my($file_path) = $0;
$file_path =~ s/[^:]+$/$flags_file/;
print "Reading build flags from '$file_path'\n";
local(*FLAGS_FILE);
open(FLAGS_FILE, "< $file_path") || die "Error: failed to open flags file $file_path\n";
my($cur_array) = "";
while(<FLAGS_FILE>)
{
my($line) = $_;
chomp($line);
# ignore comments and empty lines
if ($line =~ /^\#/ || $line =~ /^\s*$/) {
next;
}
# 1-word line, probably array name
if ($line =~ /^([^#\s]+)\s*$/)
{
$cur_array = $1;
next;
}
elsif ($line =~ /^([^#\s]+)\s+\"(.+)\"(\s+#.+)?$/) # quoted option, possible comment
{
my($flag) = $1;
my($setting) = $2;
appendArrayFlag($cur_array, $flag, $setting);
}
elsif ($line =~ /^([^#\s]+)((\s+[^#\s]+)+)(\s+#.+)?$/) # multiple word line, possible comment
{
my($flag) = $1;
appendArrayFlag($cur_array, $flag, split(' ', $2));
}
else
{
die "Error: unknown build flag at '$line'\n";
}
}
close(FLAGS_FILE);
}
#-------------------------------------------------------------------------------
# flagsArrayToHash
#
# Utility routine to migrate flag from a 2D array to a hash, where
# item[n][0] is the hash entry name, and item[n][1] is the hash entry value.
#-------------------------------------------------------------------------------
sub flagsArrayToHash($$)
{
my($src_array, $dest_hash) = @_;
my($item);
foreach $item (@$src_array)
{
$dest_hash->{$item->[0]} = $item->[1];
}
}
#-----------------------------------------------
# printHash
#
# Utility routine to print a hash
#-----------------------------------------------
sub printHash($)
{
my($hash_ref) = @_;
print "Printing hash:\n";
my($key, $value);
while (($key, $value) = each (%$hash_ref))
{
print " $key $value\n";
}
}
#-----------------------------------------------
# printBuildArray
#
# Utility routine to print a 2D array
#-----------------------------------------------
sub printBuildArray($)
{
my($build_array) = @_;
my($entry);
foreach $entry (@$build_array)
{
print "$entry->[0] = $entry->[1]\n";
}
}
#-------------------------------------------------------------------------------
# SetBuildFlags
#-------------------------------------------------------------------------------
sub SetBuildFlags($)
{
my($build) = @_;
flagsArrayToHash(\@build_flags, $build);
}
#-------------------------------------------------------------------------------
# SetBuildOptions
#-------------------------------------------------------------------------------
sub SetBuildOptions($)
{
my($options) = @_;
flagsArrayToHash(\@options_flags, $options);
}
#-------------------------------------------------------------------------------
# SetFilepathFlags
#-------------------------------------------------------------------------------
sub SetFilepathFlags($)
{
my($filepath) = @_;
flagsArrayToHash(\@filepath_flags, $filepath);
}
#-------------------------------------------------------------------------------
# SetOptionDefines
#-------------------------------------------------------------------------------
sub SetOptionDefines($)
{
my($optiondefines) = @_;
foreach my $entry (@options_flags)
{
if (defined($entry->[2])) {
$optiondefines->{$entry->[0]}{$entry->[2]} = 1;
}
}
}
#-------------------------------------------------------------------------------
# PropagateAllFlags
#-------------------------------------------------------------------------------
sub PropagateAllFlags($)
{
my($build_array) = @_;
# if "all" is set, set all the flags to 1
unless ($build_array->[0][0] eq "all") { die "Error: 'all' must come first in the flags array\n"; }
if ($build_array->[0][1] == 1)
{
my($index);
foreach $index (@$build_array)
{
$index->[1] = 1;
}
}
}
#//--------------------------------------------------------------------------------------------------
#// _getBuildProgressFile
#//--------------------------------------------------------------------------------------------------
sub _getBuildProgressFile()
{
return $progress_file;
}
#//--------------------------------------------------------------------------------------------------
#// setBuildProgressStart
#//
#// This automagically sets $build{"all"} to 0
#//--------------------------------------------------------------------------------------------------
sub setBuildProgressStart($$)
{
my($build_array, $name) = @_;
my($index);
foreach $index (@$build_array)
{
$index->[1] = 0;
if ($index->[0] eq $name) {
last;
}
}
print "Building from module after $name, as specified by build progress\n";
}
#//--------------------------------------------------------------------------------------------------
#// InitBuildProgress
#//--------------------------------------------------------------------------------------------------
sub InitBuildProgress($)
{
my($prog_file) = @_;
if ($prog_file ne "") {
$progress_file = full_path_to($prog_file);
print "Writing build progress to $progress_file\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// WriteBuildProgress
#//--------------------------------------------------------------------------------------------------
sub WriteBuildProgress($)
{
my($module_built) = @_;
my($progress_file) = _getBuildProgressFile();
if ($progress_file ne "")
{
open(PROGRESS_FILE, ">>$progress_file") || die "Failed to open $progress_file\n";
print(PROGRESS_FILE "$module_built\n");
close(PROGRESS_FILE);
}
}
#//--------------------------------------------------------------------------------------------------
#// ClearBuildProgress
#//--------------------------------------------------------------------------------------------------
sub ClearBuildProgress()
{
my($progress_file) = _getBuildProgressFile();
if ($progress_file ne "") {
unlink $progress_file;
}
}
#//--------------------------------------------------------------------------------------------------
#// WipeBuildProgress
#//--------------------------------------------------------------------------------------------------
sub WipeBuildProgress()
{
print "Ignoring build progress\n";
ClearBuildProgress();
$progress_file = "";
}
#//--------------------------------------------------------------------------------------------------
#// ReadBuildProgress
#//--------------------------------------------------------------------------------------------------
sub ReadBuildProgress($)
{
my($build_array) = @_;
my($progress_file) = _getBuildProgressFile();
my($last_module);
if (open(PROGRESS_FILE, "< $progress_file"))
{
print "Getting build progress from $progress_file\n";
while (<PROGRESS_FILE>)
{
my($line) = $_;
chomp($line);
$last_module = $line;
}
close(PROGRESS_FILE);
}
if ($last_module)
{
setBuildProgressStart($build_array, $last_module);
}
}
#-------------------------------------------------------------------------------
# clearOldBuildSettings
#-------------------------------------------------------------------------------
sub clearOldBuildSettings($$$$)
{
my($build, $options, $optiondefines, $filepaths) = @_;
# empty the arrays in case we're being called twice
@build_flags = ();
@options_flags = ();
@filepath_flags = ();
# and empty the hashes
%$build = ();
%$options = ();
%$optiondefines = ();
%$filepaths = ();
}
#-------------------------------------------------------------------------------
# SetupBuildParams
#-------------------------------------------------------------------------------
sub SetupBuildParams($$$$$$)
{
my($build, $options, $optiondefines, $filepaths, $flags_file, $prefs_file) = @_;
# Empty the hashes and arrays, to wipe out any stale data.
# Needed because these structures persist across two build scripts
# called using 'do' from a parent script.
clearOldBuildSettings($build, $options, $optiondefines, $filepaths);
# Read from the flags file, which sets up the various arrays
readFlagsFile($flags_file);
# If 'all' is set in the build array, propagate that to all entries
PropagateAllFlags(\@build_flags);
# read the user pref file, that can change values in the array
ReadMozUserPrefs($prefs_file, \@build_flags, \@options_flags, \@filepath_flags);
# If build progress exists, this clears flags in the array up to a certain point
if ($main::USE_BUILD_PROGRESS) {
ReadBuildProgress(\@build_flags);
} else {
WipeBuildProgress();
}
# printBuildArray(\@build_flags);
# printBuildArray(\@options_flags);
SetBuildFlags($build);
SetBuildOptions($options);
SetOptionDefines($optiondefines);
SetFilepathFlags($filepaths);
# printHash($build);
# printHash($options);
}
1;

View File

@@ -1,775 +0,0 @@
package Moz::BuildUtils;
require 5.004;
require Exporter;
# Package that contains build util functions specific to the Mozilla build
# process.
use strict;
use Exporter;
use Cwd;
use File::Path;
use File::Basename;
use Mac::Events;
use Mac::StandardFile;
use Moz::Moz;
use Moz::BuildFlags;
use Moz::MacCVS;
#use Moz::ProjectXML; #optional; required for static build only
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
SetupDefaultBuildOptions
SetupBuildRootDir
StartBuildModule
EndBuildModule
GetBinDirectory
BuildOneProjectWithOutput
BuildOneProject
BuildProject
BuildProjectClean
BuildIDLProject
BuildFolderResourceAliases
AskAndPersistFile
DelayFor
TimeStart
TimeEnd
EmptyTree
SetupBuildLog
SetBuildNumber
SetTimeBomb
UpdateConfigHeader
);
#//--------------------------------------------------------------------------------------------------
#// SetupDefaultBuildOptions
#//--------------------------------------------------------------------------------------------------
sub SetupDefaultBuildOptions($$$)
{
my($debug, $bin_dir, $config_header_file_name) = @_;
# Here we set up defaults for the various build flags.
# If you want to override any of these, it's best to do
# so via the relevant preferences file, which lives in
# System Folder:Preferences:Mozilla build prefs:{build prefs file}.
# For the name of the prefs file, see the .pl script that you
# run to start this build. The prefs files are created when
# you run the build, and contain some documentation.
#-------------------------------------------------------------
# configuration variables that globally affect what is built
#-------------------------------------------------------------
$main::DEBUG = $debug;
$main::PROFILE = 0;
$main::RUNTIME = 0; # turn on to just build runtime support and NSPR projects
$main::GC_LEAK_DETECTOR = 0; # turn on to use GC leak detection
$main::MOZILLA_OFFICIAL = 0; # generate build number
$main::LOG_TO_FILE = 0; # write perl output to a file
#-------------------------------------------------------------
# configuration variables that affect the manner of building,
# but possibly affecting the outcome.
#-------------------------------------------------------------
$main::ALIAS_SYM_FILES = $main::DEBUG;
$main::CLOBBER_LIBS = 1; # turn on to clobber existing libs and .xSYM files before
# building each project
# The following two options will delete all dist files (if you have $main::build{dist} turned on),
# but leave the directory structure intact.
$main::CLOBBER_DIST_ALL = 1; # turn on to clobber all aliases/files inside dist (headers/xsym/libs)
$main::CLOBBER_DIST_LIBS = 0; # turn on to clobber only aliases/files for libraries/sym files in dist
$main::CLOBBER_IDL_PROJECTS = 0; # turn on to clobber all IDL projects.
$main::CLOBBER_PROJECTS = 0; # turn on to remove object code from each project before building it
$main::UNIVERSAL_INTERFACES_VERSION = 0x0320;
#-------------------------------------------------------------
# configuration variables that are preferences for the build,
# style and do not affect what is built.
#-------------------------------------------------------------
$main::CLOSE_PROJECTS_FIRST = 0;
# 1 = close then make (for development),
# 0 = make then close (for tinderbox).
$main::USE_TIMESTAMPED_LOGS = 0;
$main::USE_BUILD_PROGRESS = 1; # track build progress for restartable builds
#-------------------------------------------------------------
# END OF CONFIG SWITCHES
#-------------------------------------------------------------
$main::BIN_DIRECTORY = $bin_dir;
$main::DEFINESOPTIONS_FILE = $config_header_file_name;
}
#//--------------------------------------------------------------------------------------------------
#// SetupBuildRootDir
#//--------------------------------------------------------------------------------------------------
sub SetupBuildRootDir($)
{
my($rel_path_to_script) = @_;
my($cur_dir) = cwd();
$cur_dir =~ s/$rel_path_to_script$//;
chdir($cur_dir) || die "Error: failed to set build root directory to '$cur_dir'.\nYou probably need to put 'mozilla' one level down (in a folder).\n";
$main::MOZ_SRC = cwd();
}
#//--------------------------------------------------------------------------------------------------
#// StartBuildModule
#//--------------------------------------------------------------------------------------------------
sub StartBuildModule($)
{
my($module) = @_;
print("---- Start of $module ----\n");
}
#//--------------------------------------------------------------------------------------------------
#// EndBuildModule
#//--------------------------------------------------------------------------------------------------
sub EndBuildModule($)
{
my($module) = @_;
WriteBuildProgress($module);
print("---- End of $module ----\n");
}
#--------------------------------------------------------------------------------------------------
# GetBinDirectory
#--------------------------------------------------------------------------------------------------
sub GetBinDirectory()
{
if ($main::BIN_DIRECTORY eq "") { die "Dist directory not set\n"; }
return $main::BIN_DIRECTORY;
}
#--------------------------------------------------------------------------------------------------
# AskAndPersistFile stores the information about the user pick inside
# the file $session_storage
#--------------------------------------------------------------------------------------------------
sub AskAndPersistFile($)
{
my ($sessionStorage) = @_;
my $cvsfile;
if (( -e $sessionStorage) &&
open( SESSIONFILE, $sessionStorage ))
{
# Read in the path if available
$cvsfile = <SESSIONFILE>;
chomp $cvsfile;
close SESSIONFILE;
if ( ! -e $cvsfile )
{
print STDERR "$cvsfile has disappeared\n";
undef $cvsfile;
}
}
unless (defined ($cvsfile))
{
# make sure that MacPerl is a front process
ActivateApplication('McPL');
MacPerl::Answer("Could not find your MacCVS session file. Please choose one", "OK");
# prompt user for the file name, and store it
my $macFile = StandardGetFile( 0, "McvD");
if ( $macFile->sfGood() )
{
$cvsfile = $macFile->sfFile();
# save the choice if we can
if ( open (SESSIONFILE, ">" . $sessionStorage))
{
printf SESSIONFILE $cvsfile, "\n";
close SESSIONFILE;
}
else
{
print STDERR "Could not open storage file $sessionStorage for saving $cvsfile\n";
}
}
}
return $cvsfile;
}
#--------------------------------------------------------------------------------------------------
# BuildIDLProject
#
#--------------------------------------------------------------------------------------------------
sub BuildIDLProject($$)
{
my ($project_path, $module_name) = @_;
if ($main::CLOBBER_IDL_PROJECTS)
{
my($datafolder_path) = $project_path;
$datafolder_path =~ s/\.mcp$/ Data:/; # generate name of the project's data folder.
print STDERR "Deleting IDL data folder: $datafolder_path\n";
EmptyTree($datafolder_path);
}
BuildOneProject($project_path, "headers", 0, 0, 0);
BuildOneProject($project_path, $module_name.".xpt", 1, 0, 1);
}
#--------------------------------------------------------------------------------------------------
# CreateStaticLibTargets
#
#--------------------------------------------------------------------------------------------------
sub CreateXMLStaticLibTargets($)
{
my($xml_path) = @_;
my (@suffix_list) = (".xml");
my ($project_name, $project_dir, $suffix) = fileparse($xml_path, @suffix_list);
if ($suffix eq "") { die "XML munging: $xml_path must end in .xml\n"; }
#sniff the file to see if we need to fix up broken Pro5-exported XML
print "Parsing $xml_path\n";
my $ide_version = Moz::ProjectXML::SniffProjectXMLIDEVersion($xml_path);
if ($ide_version eq "4.0")
{
my $new_file = $project_dir.$project_name."2.xml";
print "Cleaning up Pro 5 xml to $new_file\n";
Moz::ProjectXML::CleanupPro5XML($xml_path, $new_file);
unlink $xml_path;
rename ($new_file, $xml_path);
}
my $doc = Moz::ProjectXML::ParseXMLDocument($xml_path);
my @target_list = Moz::ProjectXML::GetTargetsList($doc);
my $target;
my %target_hash; # for easy lookups below
foreach $target (@target_list) { $target_hash{$target} = 1; }
foreach $target (@target_list)
{
if ($target =~ /(.+).shlb$/) # if this is a shared lib target
{
my $target_base = $1;
my $static_target = $target_base.".o";
# ensure that this does not exist already
if ($target_hash{$static_target}) {
print "Static target $static_target already exists in project. Not making\n";
next;
}
print "Making static target '$static_target' from target '$target'\n";
Moz::ProjectXML::CloneTarget($doc, $target, $static_target);
Moz::ProjectXML::SetAsStaticLibraryTarget($doc, $static_target, $static_target);
}
}
print "Writing XML file to $xml_path\n";
my $temp_path = $project_dir."_".$project_name.".xml";
Moz::ProjectXML::WriteXMLDocument($doc, $temp_path, $ide_version);
Moz::ProjectXML::DisposeXMLDocument($doc);
if (-e $temp_path)
{
unlink $xml_path;
rename ($temp_path, $xml_path);
}
else
{
die "Error: Failed to add new targets to XML project\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// ProcessProjectXML
#//
#// Helper routine to allow for XML pre-processing. This should read in the XML, process it,
#// and replace the original file with the processed version.
#//--------------------------------------------------------------------------------------------------
sub ProcessProjectXML($)
{
my($xml_path) = @_;
# we need to manually load Moz::ProjectXML, becaues not everyone will have the
# required perl modules in their distro.
my($cur_dir) = cwd();
chdir(dirname($0)); # change to the script dir
eval "require Moz::ProjectXML";
if ($@) { die "Error: could not do Project XML munging because you do not have the correct XML modules installed. Error is:\n################\n $@################"; }
chdir($cur_dir);
CreateXMLStaticLibTargets($xml_path);
}
#//--------------------------------------------------------------------------------------------------
#// Build one project, and make the alias. Parameters are project path, target name, shared library
#// name, make shlb alias (boolean), make xSYM alias (boolean), and is component (boolean).
#//--------------------------------------------------------------------------------------------------
sub BuildOneProjectWithOutput($$$$$$)
{
my ($project_path, $target_name, $output_name, $alias_lib, $alias_xSYM, $component) = @_;
unless ($project_path =~ m/^$main::BUILD_ROOT.+/) { return; }
my (@suffix_list) = (".mcp", ".xml");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Project: $project_path must end in .xml or .mcp\n"; }
my($dist_dir) = GetBinDirectory();
# Put libraries in "Essential Files" folder, Components in "Components" folder
my($output_dir) = $component ? "Components:" : "Essential Files:";
my($output_path) = $dist_dir.$output_dir;
if ($main::options{static_build})
{
if ($output_name =~ /\.o$/ || $output_name =~ /\.[Ll]ib$/)
{
$alias_xSYM = 0;
$alias_lib = 1;
$output_path = $main::DEBUG ? ":mozilla:dist:static_libs_debug:" : ":mozilla:dist:static_libs:";
}
}
# if the flag is on to export projects to XML, export and munge them
if ($main::EXPORT_PROJECTS && !($project_path =~ /IDL\.mcp$/))
{
my $xml_out_path = $project_path;
$xml_out_path =~ s/\.mcp$/\.xml/;
# only do this if project is newer?
if (! -e $xml_out_path)
{
ExportProjectToXML(full_path_to($project_path), full_path_to($xml_out_path));
ProcessProjectXML($xml_out_path);
}
}
# if the flag is set to use XML projects, default to XML if the file
# is present.
if ($main::USE_XML_PROJECTS && !($project_path =~ /IDL\.mcp$/))
{
my $xml_project_path = $project_dir.$project_name.".xml";
if (-e $xml_project_path)
{
$project_path = $xml_project_path;
$suffix = ".xml";
}
}
if ($suffix eq ".xml")
{
my($xml_path) = $project_path;
# Prepend an "_" onto the name of the generated project file so it doesn't conflict
$project_path = $project_dir . "_" . $project_name . ".mcp";
my($project_modtime) = (-e $project_path ? GetFileModDate($project_path) : 0);
my($xml_modtime) = (-e $xml_path ? GetFileModDate($xml_path) : 0);
if ($xml_modtime > $project_modtime)
{
print("Importing $project_path from $project_name.xml.\n");
unlink($project_path);
# Might want to delete the "xxx.mcp Data" dir ???
ImportXMLProject(full_path_to($xml_path), full_path_to($project_path));
}
}
if ($main::CLOBBER_LIBS)
{
unlink "$project_dir$output_name"; # it's OK if these fail
unlink "$project_dir$output_name.xSYM";
}
DoBuildProject($project_path, $target_name, $main::CLOBBER_PROJECTS);
$alias_lib ? MakeAlias("$project_dir$output_name", "$output_path") : 0;
$alias_xSYM ? MakeAlias("$project_dir$output_name.xSYM", "$output_path") : 0;
}
#//--------------------------------------------------------------------------------------------------
#// For compatiblity with existing scripts, BuildOneProject now just calls
#// BuildOneProjectWithOutput, with the output name and target name identical.
#// Note that this routine assumes that the target name and the shared libary name
#// are the same.
#//--------------------------------------------------------------------------------------------------
sub BuildOneProject($$$$$)
{
my ($project_path, $target_name, $alias_lib, $alias_xSYM, $component) = @_;
BuildOneProjectWithOutput($project_path, $target_name, $target_name,
$alias_lib, $alias_xSYM, $component);
}
#//--------------------------------------------------------------------------------------------------
#// For compatiblity with existing scripts, BuildProject now just calls
#// BuildOneProjectWithOutput, with the output name and target name identical.
#// Note that this routine assumes that the target name and the shared libary name
#// are the same. No aliases of the output are made.
#//--------------------------------------------------------------------------------------------------
sub BuildProject($$)
{
my ($project_path, $target_name) = @_;
BuildOneProjectWithOutput($project_path, $target_name, $target_name, 0, 0, 0);
}
#//--------------------------------------------------------------------------------------------------
#// Identical to BuildProject but clobbers the project before building it.
#//--------------------------------------------------------------------------------------------------
sub BuildProjectClean($$)
{
my ($project_path, $target_name) = @_;
my ($save_clobber_flag) = $main::CLOBBER_PROJECTS;
$main::CLOBBER_PROJECTS = 1;
BuildOneProjectWithOutput($project_path, $target_name, $target_name, 0, 0, 0);
$main::CLOBBER_PROJECTS = $save_clobber_flag;
}
#//--------------------------------------------------------------------------------------------------
#// Make resource aliases for one directory
#//--------------------------------------------------------------------------------------------------
sub BuildFolderResourceAliases($$)
{
my($src_dir, $dest_dir) = @_;
# get a list of all the resource files
opendir(SRCDIR, $src_dir) || die("can't open $src_dir");
my(@resource_files) = readdir(SRCDIR);
closedir(SRCDIR);
# make aliases for each one into the dest directory
print("Placing aliases to all files from $src_dir in $dest_dir\n");
for ( @resource_files )
{
next if $_ eq "CVS";
#print(" Doing $_\n");
if (-l $src_dir.$_)
{
print(" $_ is an alias\n");
next;
}
my($file_name) = $src_dir . $_;
MakeAlias($file_name, $dest_dir);
}
}
#//--------------------------------------------------------------------------------------------------
#// DelayFor
#//
#// Delay for the given number of seconds, allowing the script to be cancelled
#//--------------------------------------------------------------------------------------------------
sub DelayFor($)
{
my($delay_secs) = @_;
STDOUT->autoflush(1);
my($end_time) = time() + $delay_secs;
my($last_time) = 0;
my($cur_time) = time();
while ($cur_time < $end_time)
{
$cur_time = time();
if ($cur_time > $last_time)
{
print ".";
$last_time = $cur_time;
}
WaitNextEvent();
}
print "\n";
STDOUT->autoflush(0);
}
#//--------------------------------------------------------------------------------------------------
#// TimeStart
#//--------------------------------------------------------------------------------------------------
sub TimeStart()
{
return time();
}
#//--------------------------------------------------------------------------------------------------
#// TimeEnd
#//--------------------------------------------------------------------------------------------------
sub TimeEnd($$)
{
use integer;
my($start_time, $operation_name) = @_;
my($end_time) = time();
my($tot_sec) = $end_time - $start_time;
my($seconds) = $tot_sec;
my($hours) = $seconds / (60 * 60);
$seconds -= $hours * (60 * 60);
my($minutes) = $seconds / 60;
$seconds -= $minutes * 60;
print "$operation_name took $hours hours $minutes minutes and $seconds seconds\n";
}
#//--------------------------------------------------------------------------------------------------
#// Remove all files from a tree, leaving directories intact (except "CVS").
#//--------------------------------------------------------------------------------------------------
sub EmptyTree($)
{
my ($root) = @_;
#print "EmptyTree($root)\n";
opendir(DIR, $root);
my $sub;
foreach $sub (readdir(DIR))
{
my $fullpathname = $root.$sub; # -f, -d only work on full paths
# Don't call empty tree for the alias of a directory.
# -d returns true for the alias of a directory, false for a broken alias)
if (-d $fullpathname)
{
if (-l $fullpathname) # delete aliases
{
unlink $fullpathname;
next;
}
EmptyTree($fullpathname.":");
if ($sub eq "CVS")
{
#print "rmdir $fullpathname\n";
rmdir $fullpathname;
}
}
else
{
unless (unlink $fullpathname) { die "Failed to delete $fullpathname\n"; }
}
}
closedir(DIR);
}
#//--------------------------------------------------------------------------------------------------
#// Recurse through a directory hierarchy, looking for MANIFEST files.
#// Currently unused.
#//--------------------------------------------------------------------------------------------------
sub ScanForManifestFiles($$$$)
{
my($dir, $theme_root, $theme_name, $dist_dir) = @_;
opendir(DIR, $dir) or die "Cannot open dir $dir\n";
my @files = readdir(DIR);
closedir DIR;
my $file;
foreach $file (@files)
{
my $filepath = $dir.":".$file;
if (-d $filepath)
{
# print "Looking for MANIFEST files in $filepath\n";
ScanForManifestFiles($filepath, $theme_root, $theme_name, $dist_dir);
}
elsif ($file eq "MANIFEST")
{
# print "Doing manifest file $filepath\n";
# Get the dest path from the first line of the file
open(MANIFEST, $filepath) || die "Could not open file $file";
# Read in the path if available
my($dest_line) = <MANIFEST>;
chomp $dest_line;
close MANIFEST;
$dest_line =~ s|^#!dest[\t ]+|| || die "No destination line found in $filepath\n";
my($dest_path) = $dist_dir."chrome:skins:$theme_name:$dest_line";
# print " Destination is $dest_path\n";
InstallResources($filepath, "$dest_path", 0);
}
}
}
#-----------------------------------------------
# SetupBuildLog
#-----------------------------------------------
sub SetupBuildLog($$)
{
my($logfile_path, $timestamped_log) = @_;
my($logdir) = "";
my($logfile) = $logfile_path;
if ($logfile_path =~ /(.+?:)([^:]+)$/) # ? for non-greedy match
{
$logdir = $1;
$logfile = $2;
mkpath($logdir);
}
if ($timestamped_log)
{
#Use time-stamped names so that you don't clobber your previous log file!
my $now = localtime();
while ($now =~ s@:@.@) {} # replace all colons by periods
OpenErrorLog("${logdir}${now}");
}
else
{
OpenErrorLog("${logdir}${logfile}");
}
}
#-----------------------------------------------
# SetBuildNumber
#-----------------------------------------------
sub SetBuildNumber($$)
{
my($build_num_file, $files_to_touch) = @_;
# Make sure we add the config dir to search, to pick up mozBDate.pm
# Need to do this dynamically, because this module can be used before
# mozilla/config has been checked out.
my ($inc_path) = $0; # $0 is the path to the parent script
$inc_path =~ s/:build:mac:build_scripts:.+$/:config/;
push(@INC, $inc_path);
require mozBDate;
mozBDate::UpdateBuildNumber($build_num_file, $main::MOZILLA_OFFICIAL);
my($file);
foreach $file (@$files_to_touch)
{
print "Writing build number to $file from ${file}.in\n";
mozBDate::SubstituteBuildNumber($file, $build_num_file, "${file}.in");
}
}
#-----------------------------------------------
# SetBuildNumber
#-----------------------------------------------
sub SetTimeBomb($$)
{
my ($warn_days, $bomb_days) = @_;
system("perl :mozilla:config:mac-set-timebomb.pl $warn_days $bomb_days");
}
#//--------------------------------------------------------------------------------------------------
#// Regenerate a configuration header file if necessary
#//--------------------------------------------------------------------------------------------------
sub UpdateConfigHeader($)
{
my($config_path) = @_;
my($config, $oldconfig) = ("", "");
my($define, $definevalue, $defines);
my($k, $l,);
foreach $k (keys(%main::options))
{
if ($main::options{$k})
{
foreach $l (keys(%{$main::optiondefines{$k}}))
{
$my::defines{$l} = $main::optiondefines{$k}{$l};
print "Setting up my::defines{$l}\n";
}
}
}
my $config_headerfile = current_directory().$config_path;
if (-e $config_headerfile)
{
open(CONFIG_HEADER, "< $config_headerfile") || die "$config_headerfile: $!\n";
my($line);
while ($line = <CONFIG_HEADER>)
{
if ($line =~ m/#define\s+([^\s]*)\s+([^\s]*)\s*\n/)
{
$define = $1;
$definevalue = $2;
#canonicalize so that whitespace changes are not significant
my $canon_value = "#define " . $define . " " . $definevalue . "\n";
$oldconfig .= $canon_value;
if (exists ($my::defines{$define}) and ($my::defines{$define} == $definevalue))
{
delete $my::defines{$define};
$config .= $canon_value;
}
}
}
close(CONFIG_HEADER);
}
if (%my::defines)
{
foreach $k (keys(%my::defines))
{
$config .= "#define " . $k . " " . $my::defines{$k} . "\n";
}
}
my $file_name = basename($config_headerfile);
if (($config ne $oldconfig) || (!-e $config_headerfile))
{
printf("Writing new configuration header $file_name\n");
open(CONFIG_HEADER, "> $config_headerfile") || die "$config_headerfile: $!\n";
print(CONFIG_HEADER "/* This file is auto-generated based on build options. Do not edit. */\n");
print CONFIG_HEADER ($config);
close(CONFIG_HEADER);
MacPerl::SetFileInfo("CWIE", "TEXT", $config_headerfile);
}
else
{
printf("Configuration header $file_name is up-to-date\n");
}
}
1;

View File

@@ -1,660 +0,0 @@
#!perl
package Moz::CodeWarriorLib;
=pod
=head1 NAME
CodeWarriorLib - supply interface to CodeWarrior
=head1 SYNOPSIS
#!perl
use CodeWarriorLib;
CodeWarriorLib::activate();
$had_errors = CodeWarriorLib::build_project(
$project_path, $target_name, $recent_errors_file, $clean_build
);
=head1 DESCRIPTION
Replaces the AppleScript library I<CodeWarriorLib>.
=over 4
=cut
use strict;
use Cwd;
use File::Basename;
use Mac::Types;
use Mac::Events;
use Mac::AppleEvents;
use Mac::AppleEvents::Simple;
use Mac::Processes;
use Mac::MoreFiles;
use Mac::StandardFile;
use vars qw($VERSION);
$VERSION = '1.02';
my($app) = 'CWIE';
my($scriptDir) = cwd(); # could use $0 for this
my($ide_loc_file) = "";
# 0 == don't switch CWIE to front app in do_event(), 1 == do switch
# note: activate() still switches when called
$Mac::AppleEvents::Simple::SWITCH = 0;
# $Mac::AppleEvents::Simple::WARN = 1;
# supply your own path to the source here
#_test('PowerPudgeIV:mozilla:mozilla:');
# If you want to understand the gobbldeygook that's used to build Apple Events,
# you should start by reading the AEGizmos documentation.
=pod
=item _get_project($full_path)
A private routine returning a reference to the open project with the given name,
or else the empty string (when that project is not open)
full_path is a string identifying the project to be built and is of the form,
e.g., "HD:ProjectFolder:MyProject.mcp". It must be supplied.
=cut
sub _get_project ($) {
my(
$full_path, $candidate_projects
) = @_;
$candidate_projects = _doc_named(basename($full_path, '*'));
if ($candidate_projects) {
my($cps) = _get_dobj($candidate_projects);
my($num) = AECountItems($cps);
if ($num) { # is a list
foreach (1 .. AECountItems($cps)) {
my($cp) = AEGetNthDesc($cps, $_);
if (lc $full_path eq lc _full_path($cp)) {
return($cp);
}
}
} else { # is only one, not a list
if (lc $full_path eq lc _full_path($cps)) {
return($cps);
}
}
}
return;
}
=pod
=item build_project
Build a selected target of a project, saving any errors to a file, if supplied.
full_path is a string identifying the project to be built and is of the form,
e.g., "HD:ProjectFolder:MyProject.mcp". It must be supplied.
If target_name is the empty string, the current target of the selected project
will be built, else, target_name should be a string matching a target name in
the selected project.
If error_path is the empty string, errors will not be saved to a file,
else, error_path should be the full path of a file to save error messages into.
=cut
$CodeWarriorLib::CLOSE_PROJECTS_FIRST = 0; # If true we close then make. If false, make then close.
my $last_project_built = "";
my $last_project_was_closed = 0;
sub build_project ($;$$$) {
my(
$full_path, $target_name, $error_path,
$remove_object, $p, $project_was_closed, $had_errors
) = @_;
_close_errors_window();
if ($CodeWarriorLib::CLOSE_PROJECTS_FIRST && ($last_project_built ne $full_path))
{
# If we're in "close first" mode, we don't close if the current project
# is the same as the previous one.
if ($last_project_was_closed) {
$p = _get_project($last_project_built);
_close($p);
}
$last_project_built = $full_path;
$last_project_was_closed = 0; # now refers to the new project
}
$project_was_closed = 0;
while (1) {
$p = _get_project($full_path);
if (!$p) {
if ($project_was_closed) {
print "### Error - request for project document failed after opening\n";
die "### possibly CW Pro 4 bug: be sure to close your Find window\n";
}
$project_was_closed = 1;
$last_project_was_closed = 1;
_open_file($full_path);
} else {
last;
}
}
$had_errors = 0;
if ($target_name eq '') {
if ($remove_object) {_remove_object($p)}
_build($p);
} else {
if ($remove_object) {_remove_object($p, $target_name)}
_build($p, $target_name);
}
if ($error_path ne '') {
_save_errors_window($error_path);
}
$had_errors = _close_errors_window();
if (!$CodeWarriorLib::CLOSE_PROJECTS_FIRST)
{
if ($project_was_closed) {
$p = _get_project($full_path);
_close($p);
}
}
return($had_errors);
}
=pod
=item appIsRunning()
=cut
sub _appIsRunning($)
{
my ($appSignature) = @_;
my ($psi);
my ($found) = 0;
my ($appPSN);
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
return $found;
}
=pod
=item appIsFrontmost()
=cut
sub _appIsFrontmost($)
{
my ($appSignature) = @_;
my ($psi);
my ($found) = 0;
my ($appPSN);
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
return (GetFrontProcess() == $appPSN);
}
=pod
=item activate()
Launches CodeWarrior and brings it to the front.
Once found, path will be saved in $idepath_file for future reference.
Edit or delete this file to change the location of the IDE. If app is
moved, C<activate()> will prompt for a new location.
First looks for an open CodeWarrior app. Second, tries to open previously
saved location in ':idepath.txt'. Third, tries to find it and allow user
to choose it with Navigation Services (if present). Fourth, uses good old
GUSI routines built-in to MacPerl for a Choose Directory dialog box.
=cut
sub activate ($) {
$ide_loc_file = $_[0]; # save in global
my($filepath, $appath, $psi) = ($ide_loc_file);
foreach $psi (values(%Process)) {
if ($psi->processSignature() eq $app) {
$appath = $psi->processAppSpec();
_save_appath($filepath, $appath);
last;
}
}
if (!$appath || !-x $appath) {
$appath = _read_appath($filepath);
}
if (!$appath || ! -x $appath)
{
# make sure that MacPerl is a front process
#ActivateApplication('McPL');
MacPerl::Answer("Please locate the CodeWarrior application.", "OK");
# prompt user for the file name, and store it
my $macFile = StandardGetFile( 0, "APPL");
if ( $macFile->sfGood() )
{
$appath = $macFile->sfFile();
}
else
{
die "Operation canceled\n";
}
# if (eval {require Mac::Navigation}) {
# my($options, $nav);
# Mac::Navigation->import();
# $options = NavGetDefaultDialogOptions();
# $options->message('Where is CodeWarrior IDE?');
# $options->windowTitle('Find CodeWarrior IDE');
# $nav = NavChooseObject($Application{$app}, $options);
# die "CodeWarrior IDE not found.\n" if (!$nav || !$nav->file(1));
# $appath = $nav->file(1);
# } else {
# local(*D);
# my $cwd = `pwd`;
# $appath = _get_folder(
# 'Where is the CW IDE folder?',
# dirname($Application{$app})
# );
# die "CodeWarrior IDE not found.\n" if !$appath;
# opendir(D, $appath) or die $!;
# chdir($appath);
# foreach my $file (sort readdir (D)) {
# my(@app) = MacPerl::GetFileInfo($file);
# if ($app[0] && $app[1] &&
# $app[1] eq 'APPL' && $app[0] eq $app
# ) {
# $appath .= $file;
# last;
# }
# }
# chomp($cwd);
# chdir($cwd);
# }
_save_appath($filepath, $appath);
}
my($lp) = LaunchParam->new(
launchAppSpec => $appath,
launchControlFlags => launchContinue() + launchNoFileFlags()
);
unless (LaunchApplication($lp)) {
unlink($filepath);
die $^E;
}
# wait for CodeWarrior to show up in the list of processes
while (!_appIsRunning('CWIE'))
{
WaitNextEvent();
}
# wait for CodeWarrior to come to the front
while (!_appIsFrontmost('CWIE'))
{
WaitNextEvent();
}
}
=pod
=item getCodeWarriorPath()
Returns a file path relative to the CodeWarrior folder
=cut
sub getCodeWarriorPath($)
{
my($subfolder)=@_;
my($app_path) = _read_appath($ide_loc_file);
if ($app_path eq "") { die "Error: Failed to get CodeWarrior IDE path\n"; }
my($codewarrior_root) = $app_path;
$codewarrior_root =~ s/[^:]*$//;
return ($codewarrior_root . $subfolder);
}
=pod
=item getCodeWarriorIDEName()
Returns the name of the CodeWarrior application
=cut
sub getCodeWarriorIDEName()
{
my($subfolder)=@_;
my($app_path) = _read_appath($ide_loc_file);
if ($app_path eq "") { die "Error: Failed to get CodeWarrior IDE path\n"; }
my(@codewarrior_path) = split(/:/, $app_path);
return pop(@codewarrior_path);
}
=pod
=item quit()
Quits CodeWarrior.
=cut
sub quit() {
$last_project_built = "";
$last_project_was_closed = 0;
my($evt) = do_event(qw/aevt quit/, $app);
}
sub _build ($;$) {
my($evt);
if ($_[1]) {
my($prm) =
q"'----':obj {form:name, want:type(TRGT), seld:TEXT(@), from:" .
AEPrint($_[0]) . '}';
$evt = do_event(qw/CWIE MAKE/, $app, $prm, $_[1]);
} else {
my($prm) = q"'----':" . AEPrint($_[0]);
$evt = do_event(qw/CWIE MAKE/, $app, $prm);
}
}
sub _remove_object ($;$) {
my($evt);
if ($_[1]) {
my($prm) =
q"'----':obj {form:name, want:type(TRGT), seld:TEXT(@), from:" .
AEPrint($_[0]) . '}';
$evt = do_event(qw/CWIE RMOB/, $app, $prm, $_[1]);
} else {
my($prm) = q"'----':" . AEPrint($_[0]);
$evt = do_event(qw/CWIE RMOB/, $app, $prm);
}
}
sub _open_file ($) {
my($prm) =
q"'----':obj {form:name, want:type(alis), " .
q"seld:TEXT(@), from:'null'()}";
do_event(qw/aevt odoc/, $app, $prm, $_[0]);
}
sub import_project ($$) {
my($xml_file, $project_path) = @_;
my($prm) = "kocl:type(PRJD), rtyp:TEXT(@), data:TEXT(@), &subj:'null'()";
my($evt) = do_event(qw/core crel/, $app, $prm, $project_path, $xml_file);
my($result) = _get_event_result($evt);
if ($result eq "") {
_close(_get_project($project_path));
}
return $result;
}
sub export_project ($$) {
my($project_path, $xml_out_path) = @_;
my($p, $project_was_closed);
$project_was_closed = 0;
while (1) {
$p = _get_project($project_path);
if (!$p) {
if ($project_was_closed) {
print "### Error - request for project document failed after opening\n";
die "### possibly CW bug: be sure to close your Find window\n";
}
$project_was_closed = 1;
_open_file($project_path);
} else {
last;
}
}
# avoid problems with the Project Messages window
_close_named_window("Project Messages");
my($prm) =
q"'----':obj {form:indx, want:type(PRJD), " .
q"seld:1, from:'null'()}, kfil:TEXT(@)";
my($evt) = do_event(qw/CWIE EXPT/, $app, $prm, $xml_out_path);
if ($project_was_closed) {
$p = _get_project($project_path);
_close($p);
}
return _get_event_result($evt);
}
sub _doc_named ($) {
my($prm) =
q"'----':obj {form:test, want:type(docu), from:'null'(), " .
q"seld:cmpd{relo:'= ', 'obj1':obj {form:prop, want:type" .
q"(prop), seld:type(pnam), from:'exmn'()}, 'obj2':TEXT(@)}}";
my($evt) = do_event(qw/core getd/, $app, $prm, $_[0]);
return($evt->{REPLY} eq 'aevt\ansr{}' ? undef : $evt);
}
sub _full_path ($) {
my($obj) = $_[0];
my($prm) =
q"'----':obj {form:prop, want:type(prop), seld:type(FILE), " .
q"from:" . AEPrint($_[0]) . q"}, rtyp:type(TEXT)";
my($evt) = do_event(qw/core getd/, $app, $prm);
return MacPerl::MakePath(
MacUnpack('fss ', (
AEGetParamDesc($evt->{REP}, keyDirectObject()))->data()->get()
)
);
}
sub _save_errors_window ($) {
my($prm) =
q"'----':obj {form:name, want:type(alis), seld:TEXT(@), from:'null'()}";
do_event(qw/MMPR SvMs/, $app, $prm, $_[0]);
}
sub _close_errors_window () {
return _close_named_window('Errors & Warnings');
}
sub _close_named_window ($) {
my($window_name) = @_;
my($prm) =
q"'----':obj {form:name, want:type(cwin), " .
q"seld:TEXT(@), from:'null'()}";
my($evt) = do_event(qw/core clos/, $app, $prm, $window_name);
return($evt->{REPLY} eq 'aevt\ansr{}' ? 1 : 0);
}
sub _close () {
my($prm) = q"'----':" . AEPrint($_[0]);
do_event(qw/core clos/, $app, $prm);
}
sub _get_dobj ($) {
return(AEGetParamDesc($_[0]->{REP}, keyDirectObject()));
}
sub _get_folder ($$) {
require 'GUSI.ph';
my($prompt, $default) = @_;
MacPerl::Choose(
GUSI::AF_FILE(), 0, $prompt, '',
GUSI::CHOOSE_DIR() + ($default ? &GUSI::CHOOSE_DEFAULT : 0),
$default
);
}
sub _get_event_result ($)
{
my($evt) = @_;
my($result) = $evt->{ERROR};
if ( $result eq "" && $evt->{ERRNO} != 0 )
{
$result = "unknown error (".$evt->{ERRNO}.")";
}
return $result;
}
sub _save_appath ($$) {
my($cwd) = cwd(); # remember the current working dir
chdir($scriptDir); # change dir to the script dir
local(*F);
open(F, '>' . $_[0]) or die $!;
print F $_[1];
close(F);
chdir($cwd); # restore the cwd
}
sub _read_appath ($) {
my($filepath) = @_;
my($cwd) = cwd(); # remember the current working dir
chdir($scriptDir); # change dir to the script dir
if (! -e $filepath) {
return "";
}
local(*F);
open(F, $filepath);
my($appath) = <F>;
close(F);
chdir($cwd); # restore the cwd
return($appath);
}
sub _test ($) {
activate($ide_loc_file);
my($path) = $_[0];
build_project(
"${path}modules:xml:macbuild:XML.mcp", '',
"${path}build:mac:Mozilla.BuildLog.part"
);
}
1;
=pod
=back
=head1 HISTORY
=over 4
=item v1.02, September 23, 1998
Made fixes in finding and saving location of CodeWarrior IDE.
=item v1.01, June 1, 1998
Made fixes to C<chdir()> in C<activate()>, made C<activate()> more robust
in finding CodeWarrior IDE, added global variable to NOT switch to IDE
for each sent event, a few other fixes.
=item v1.00, May 30, 1998
First shot
=back
=head1 AUTHORS
Chris Nandor F<E<lt>pudge@pobox.comE<gt>>, and the author of the
original I<CodeWarriorLib>, Scott Collins F<E<lt>scc@netscape.comE<gt>>.
=head1 SEE ALSO
BuildProject L<Moz>.
=head1 COPYRIGHT
The contents of this file are subject to the Netscape Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The Original Code is Mozilla Communicator client code, released
March 31, 1998.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998-1999 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
=cut

View File

@@ -1,599 +0,0 @@
#!perl -w
package Moz::Jar;
#
# Module for creating jar files, either using a jar manifest, or
# simply jarring up folders on disk.
#
require 5.004;
require Exporter;
use strict;
use Archive::Zip;
use File::Path;
use Mac::Files;
use Moz::Moz;
use vars qw( @ISA @EXPORT );
@ISA = qw(Exporter);
@EXPORT = qw(
CreateJarFileFromDirectory
CreateJarFromManifest
WriteOutJarFiles
SanityCheckJarOptions
);
#-------------------------------------------------------------------------------
# Add the contents of a directory to the zip file
#
#-------------------------------------------------------------------------------
sub _addDirToJar($$$$)
{
my($dir, $jar_root, $zip, $compress) = @_;
opendir(DIR, $dir) or die "Error: Cannot open dir $dir\n";
my @files = readdir(DIR);
closedir DIR;
my $unix_jar_root = $jar_root;
$unix_jar_root =~ s|:|/|g; # colon to slash conversion
my $file;
foreach $file (@files)
{
my $filepath = $dir.":".$file;
if (-d $filepath)
{
print "Adding files to jar from $filepath\n";
_addDirToJar($filepath, $jar_root, $zip, $compress);
}
else
{
my $member = Archive::Zip::Member->newFromFile($filepath);
die "Error: Failed to create zip file member $filepath\n" unless $member;
my $unixName = $filepath;
$unixName =~ s|:|/|g; # colon to slash conversion
$unixName =~ s|^$unix_jar_root||; # relativise
$member->fileName($unixName);
# print "Adding $file as $unixName\n";
if ($compress) {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_DEFLATED);
} else {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_STORED);
}
$zip->addMember($member);
}
}
}
#-------------------------------------------------------------------------------
# Add the contents of a directory to the zip file
#
#-------------------------------------------------------------------------------
sub CreateJarFileFromDirectory($$$)
{
my($srcdir, $jarpath, $compress) = @_;
my $zip = Archive::Zip->new();
_addDirToJar($srcdir, $srcdir, $zip, $compress);
print "Saving zip file...\n";
my $status = $zip->writeToFileNamed($jarpath);
if ($status == 0) {
print "Zipping completed successfully\n";
} else {
print "Error saving zip file\n";
}
# set the file type/creator to something reasonable
MacPerl::SetFileInfo("ZIP ", "ZIP ", $jarpath);
}
#-------------------------------------------------------------------------------
# SanityCheckJarOptions
#
#-------------------------------------------------------------------------------
sub SanityCheckJarOptions()
{
if (!$main::options{chrome_jars} && !$main::options{chrome_files})
{
print "Both \$options{chrome_jars} and \$options{chrome_files} are off. You won't get any chrome.\n";
return;
}
if (!$main::options{chrome_jars} && $main::options{use_jars})
{
print "\$options{chrome_jars} is off but \$options{use_jars} is on. Your build won't run (expects jars, got files).\n";
return;
}
if (!$main::options{chrome_files} && !$main::options{use_jars})
{
print "\$options{chrome_jars} is off but \$options{chrome_files} is on. Your build won't run (expects files, got jars).\n";
return;
}
}
#-------------------------------------------------------------------------------
# printZipContents
#
#-------------------------------------------------------------------------------
sub printZipContents($)
{
my($zip) = @_;
my(@members) = $zip->memberNames();
print "Zip contains:\n";
my($member);
foreach $member (@members)
{
print " $member\n";
}
}
#-------------------------------------------------------------------------------
# safeSaveJarFile
#
# Archive::Zip has a problem where you cannot save a zip file on top of
# an existing zip file that it has open, because it holds references
# into that zip. So we have to save to a temp file, then do a swap.
#
# Note that the zip will become invalid after this operation.
# If you want to do further operations on it, you'll have to reread it.
#-------------------------------------------------------------------------------
sub safeSaveJarFile($$)
{
my($zip, $full_dest_path) = @_;
my($temp_file_name) = $full_dest_path."_temp";
($zip->writeToFileNamed($temp_file_name) == Archive::Zip::AZ_OK) || die "Error: died writing jar to temp file $temp_file_name\n";
unlink $full_dest_path;
(rename $temp_file_name, $full_dest_path) || die "Error: Failed to rename $temp_file_name\n";
MacPerl::SetFileInfo("ZIP ", "ZIP ", $full_dest_path);
}
#-------------------------------------------------------------------------------
# addToJarFile
#
# Add a file to a jar file
#
# Parameters:
# 1. Jar ID. Unix path of jar file inside chrome.
# 2. Abs path to jar.mn file (i.e. source) (mac breaks)
# 3. File source, relative to jar.mn path (mac breaks)
# 4. Abs path to the resulting .jar file (mac breaks)
# 5. Relative file path within the jar (unix breaks)
# 6. Reference to hash of jar files
#
#-------------------------------------------------------------------------------
sub addToJarFile($$$$$$$)
{
my($jar_id, $jar_man_dir, $file_src, $jar_path, $file_jar_path, $override, $jars) = @_;
# print "addToJarFile with:\n $jar_man_dir\n $file_src\n $jar_path\n $file_jar_path\n";
unless ($jar_path =~ m/(.+:)([^:]+)$/) { die "Error: Bad jar path $jar_path\n"; }
my($target_dir) = $1;
my($jar_name) = $2;
$target_dir =~ s/[^:]+$//;
# print "¥ $target_dir $jar_name\n";
# find the source file
my($src) = $jar_man_dir.":".$file_src;
if ((!-e $src) && ($file_src =~ m/.+:([^:]+)$/)) # src does not exist. Fall back to looking for src in jar.mn dir
{
$file_src = $1;
$src = $jar_man_dir.":".$file_src;
if (!-e $src) {
die "Error: Can't find chrome file $src\n";
}
}
if ($main::options{chrome_jars})
{
my($zip) = $jars->{$jar_id};
unless ($zip) { die "Error: Can't find Zip entry for $jar_id\n"; }
# print "Adding $file_src to jar file $jar_path at $file_jar_path\n";
my($member) = Archive::Zip::Member->newFromFile($src);
unless ($member) { die "Error: Failed to create zip file member $src\n"; }
$member->fileName($file_jar_path);
my($compress) = 1;
if ($compress) {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_DEFLATED);
$member->desiredCompressionLevel(Archive::Zip::COMPRESSION_LEVEL_DEFAULT); # defaults to 6
} else {
$member->desiredCompressionMethod(Archive::Zip::COMPRESSION_STORED);
}
my($old_member) = $zip->memberNamed($file_jar_path);
if ($override)
{
if ($old_member)
{
# print "Overriding $file_jar_path in jar file $jar_id\n";
# need to compare mod dates or use the + here
$zip->removeMember($old_member);
}
$zip->addMember($member);
}
else
{
if ($old_member)
{
#compare dates here
my($member_moddate) = $old_member->lastModTime();
my($file_moddate) = GetFileModDate($src);
if ($file_moddate > $member_moddate)
{
print "Updating older file $file_jar_path in $jar_id\n";
$zip->removeMember($old_member);
$zip->addMember($member);
}
else
{
print "File $file_jar_path in $jar_id is more recent. Not updating.\n";
}
}
else
{
$zip->addMember($member);
}
}
}
if ($main::options{chrome_files}) # we install raw files too
{
my($rel_path) = $file_jar_path;
$rel_path =~ s|/|:|g; # slash to colons
my($dir_name) = $jar_name;
$dir_name =~ s/\.jar$//;
my($dst) = $target_dir.$dir_name.":".$rel_path;
# print "Aliassing $src\n to\n$dst\n";
if ($override)
{
unlink $dst;
MakeAlias($src, $dst); # don't check errors, otherwise we fail on replacement
}
else
{
if (-e $dst)
{
#compare dates here
my($dst_moddate) = GetFileModDate($dst);
my($file_moddate) = GetFileModDate($src);
if ($file_moddate > $dst_moddate)
{
print "Updating older file $rel_path in $dir_name\n";
unlink $dst;
MakeAlias($src, $dst);
}
else
{
print "File $file_jar_path in $jar_id is more recent. Not updating.\n";
}
}
else
{
MakeAlias($src, $dst);
}
}
}
}
#-------------------------------------------------------------------------------
# setupJarFile
#
# setup a zip for writing
#-------------------------------------------------------------------------------
sub setupJarFile($$$)
{
my($jar_id, $dest_path, $jar_hash) = @_;
# print "Creating jar file $jar_id at $jar_path\n";
my($jar_file) = $jar_id;
$jar_file =~ s|/|:|g; # slash to colons
my($full_jar_path) = full_path_to($dest_path.":".$jar_file);
if ($main::options{chrome_jars})
{
my($zip) = $jar_hash->{$jar_id};
if (!$zip) # if we haven't made it already, do so
{
my($zip) = Archive::Zip->new();
$jar_hash->{$jar_id} = $zip;
# does the jar file exist already? If so, read it in
if (-e $full_jar_path)
{
print "Reading in jar file $jar_id\n";
if ($zip->read($full_jar_path) != Archive::Zip::AZ_OK) { die "Error: Failed to re-read $full_jar_path\n"; }
# printZipContents($zip);
}
}
}
else
{
# installing files.
# nothing to do. MakeAlias creates dirs as needed.
# add this jar to the list
$jar_hash->{$jar_id} = 1;
}
}
#-------------------------------------------------------------------------------
# closeJarFile
#
# We're done with this jar file _for this jar.mn_. We may add more entries
# to it later, so keep it open in the hash.
#-------------------------------------------------------------------------------
sub closeJarFile($$)
{
my($jar_path, $jar_hash) = @_;
# print "Closing jar file $jar_path\n";
if ($main::options{chrome_jars})
{
}
else
{
# installing files.
# nothing to do
}
}
#-------------------------------------------------------------------------------
# WriteOutJarFiles
#
# Now we dump out the jars
#-------------------------------------------------------------------------------
sub WriteOutJarFiles($$)
{
my($chrome_dir, $jars) = @_;
unless ($main::options{chrome_jars}) { return; }
my($full_chrome_path) = full_path_to($chrome_dir);
my($key);
foreach $key (keys %$jars)
{
my($zip) = $jars->{$key};
my($rel_path) = $key;
$rel_path =~ s/\//:/g;
my($output_path) = $full_chrome_path.":".$rel_path;
print "Writing zip file $key to $output_path\n";
# ensure the target dirs exist
my($path) = $output_path;
$path =~ s/[^:]+$//;
mkpath($path);
# unlink $output_path; # remove any existing jar
safeSaveJarFile($zip, $output_path);
# $zip is invalid after this operation, so nuke it here
$jars->{$key} = 0;
}
}
#-------------------------------------------------------------------------------
# registerChromePackage
#
# Enter a chrome package into the installed-chrome.txt file
#-------------------------------------------------------------------------------
sub registerChromePackage($$$$$$)
{
my($jar_file, $file_path, $chrome_dir, $jar_hash, $chrome_type, $pkg_name) = @_;
my($manifest_subdir) = $jar_file;
$manifest_subdir =~ s/:/\//g;
my($chrome_entry);
if ($main::options{use_jars}) {
$chrome_entry = "$chrome_type,install,url,jar:resource:/chrome/$manifest_subdir!/$chrome_type/$pkg_name";
} else {
$manifest_subdir =~ s/\.jar$//;
$chrome_entry = "$chrome_type,install,url,resource:/chrome/$manifest_subdir/$chrome_type/$pkg_name";
}
# print "Entering $chrome_entry in installed-chrome.txt\n";
# ensure chrome_dir exists
mkpath($chrome_dir);
my($inst_chrome) = ${chrome_dir}.":installed-chrome.txt";
if (open(CHROMEFILE, "<$inst_chrome")) {
while (<CHROMEFILE>) {
chomp;
if ($_ eq $chrome_entry) {
# $chrome_entry already appears in installed-chrome.txt file
# just update the mod date
my $now = time;
utime($now, $now, $inst_chrome) || die "Error: Couldn't touch $inst_chrome";
print "+++ updating chrome $inst_chrome\n+++\t\t$chrome_entry\n";
close(CHROMEFILE) || die "Error: can't close $inst_chrome: $!";
return 0;
}
}
close(CHROMEFILE) || die "Error: can't close $inst_chrome: $!";
}
open(CHROMEFILE, ">>${inst_chrome}") || die "Error: Failed to open $inst_chrome\n";
print(CHROMEFILE "${chrome_entry}\n");
close(CHROMEFILE) || die "Error: Failed to close $inst_chrome\n";
print "+++ adding chrome $inst_chrome\n+++\t\t$chrome_entry\n";
}
#-------------------------------------------------------------------------------
# Create or add to a jar file from a jar.mn file.
# Both arguments are relative to the mozilla root dir.
#
#
#-------------------------------------------------------------------------------
sub CreateJarFromManifest($$$)
{
my($jar_man_path, $dest_path, $jars) = @_;
if ($main::options{chrome_jars}) {
print "Jarring from $jar_man_path\n";
}
if ($main::options{chrome_files}) {
print "Installing files from $jar_man_path\n";
}
$jar_man_path = full_path_to($jar_man_path);
$dest_path = full_path_to($dest_path);
# if the jars hash is empty, nuke installed-chrome.txt
if (! scalar(%$jars))
{
print "Nuking installed-chrome.txt\n";
my($installed_chrome) = $dest_path.":installed-chrome.txt";
# unlink $installed_chrome;
}
my $jar_man_dir = "";
my $jar_man_file = "";
if ($jar_man_path =~ /(.+):([^:]+)$/)
{
$jar_man_dir = $1; # no trailing :
$jar_man_file = $2;
}
# Keep a hash of jar files, keyed on relative jar path (e.g. "packages/core.jar")
# Entries are open Archive::Zips (if zipping), and installed-chrome entries.
my($jar_id) = ""; # Current foo/bar.jar from jar.mn file
my($jar_file) = ""; # relative path to jar file (from $dest_path), with mac separators
my($full_jar_path);
open(FILE, "<$jar_man_path") || die "Error: could not open \"$jar_man_path\": $!";
while (<FILE>)
{
my($line) = $_;
chomp($line);
# print "$line\n";
if ($line =~ /^\s*\#.*$/) { # skip comments
next;
}
if ($line =~/^([\w\d.\-\_\\\/]+)\:\s*$/) # line start jar file entries
{
$jar_id = $1;
$jar_file = $jar_id;
$jar_file =~ s|/|:|g; # slash to colons
$full_jar_path = $dest_path.":".$jar_file;
setupJarFile($jar_id, $dest_path, $jars);
}
elsif ($line =~ /^(\+?)\s+([\w\d.\-\_\\\/]+)\s*(\([\w\d.\-\_\\\/]+\))?$\s*/) # jar file entry
{
my($override) = ($1 eq "+");
my($file_dest) = $2;
my($file_src) = $3;
if ($file_src) {
$file_src = substr($file_src, 1, -1); #strip the ()
} else {
$file_src = $file_dest;
}
$file_src =~ s|/|:|g;
if ($jar_file ne "") # if jar is open, add to jar
{
if ($file_dest =~ /([\w\d.\-\_]+)\/([\w\d.\-\_\\\/]+)contents.rdf/)
{
my $chrome_type = $1;
my $pkg_name = $2;
registerChromePackage($jar_file, $file_dest, $dest_path, $jars, $chrome_type, $pkg_name);
}
addToJarFile($jar_id, $jar_man_dir, $file_src, $full_jar_path, $file_dest, $override, $jars);
}
else
{
die "Error: bad jar.mn format at $line\n";
}
}
elsif ($line =~ /^\s*$/ ) # blank line
{
if ($jar_file ne "") #if a jar file is open, close it
{
closeJarFile($full_jar_path, $jars);
$jar_file = "";
$full_jar_path = "";
}
}
}
close(FILE);
if ($jar_file ne "") #if a jar file is open, close it
{
closeJarFile($full_jar_path, $jars);
}
}
1;

View File

@@ -1,228 +0,0 @@
#!perl -w
package Moz::MacCVS;
# package Mac::Apps::MacCVS; this should really be the name of the package
# but due to our directory hierarchy in mozilla, I am not doing it
require 5.004;
require Exporter;
use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT);
use Cwd;
use File::Basename;
use Mac::StandardFile;
use Mac::AppleEvents;
use Mac::AppleEvents::Simple;
@ISA = qw(Exporter);
@EXPORT = qw(new describe checkout update);
$VERSION = "1.00";
# If you want to understand the gobbldeygook that's used to build Apple Events,
# you should start by reading the AEGizmos documentation.
# Architecture:
# cvs session object:
# name - session name
# session_file - session file
#
#
my($last_error) = 0;
my($gAppSig) = 'Mcvs'; # MacCVS Pro
#
# utility routines
#
sub _checkForEventError($)
{
my($evt) = @_;
if ($evt->{ERRNO} != 0)
{
print STDERR "Error. Script returned '$evt->{ERROR} (error $evt->{ERRNO})\n";
$last_error = $evt->{ERRNO};
return 0;
}
return 1; # success
}
#
# Session object methods
#
sub new
{
my ( $proto, $session_file) = @_;
my $class = ref($proto) || $proto;
my $self = {};
if ( defined($session_file) && ( -e $session_file) )
{
$self->{"name"} = basename( $session_file );
$self->{"session_file"} = $session_file;
bless $self, $class;
return $self;
}
else
{
print STDERR "MacCVS->new cvs file < $session_file > does not exist\n";
return;
}
}
# makes sure that the session is open
# assertSessionOpen()
# returns 1 on success
sub assertSessionOpen()
{
my ($self) = shift;
$last_error = 0;
my($prm) =
q"'----':obj {form:name, want:type(alis), seld:TEXT(@), from:'null'()}";
my($evt) = do_event(qw/aevt odoc/, $gAppSig, $prm, $self->{session_file});
return _checkForEventError($evt);
}
# prints the cvs object, used mostly for debugging
sub describe
{
my($self) = shift;
$last_error = 0;
print "MacCVS:: name: ", $self->{name}, " session file: ", $self->{session_file}, "\n";
}
# checkout( self, module, revision, date)
# MacCVS checkout command
# returns 1 on success.
sub checkout()
{
my($self, $module, $revision, $date ) = @_;
unless( defined ($module) ) { $module = ""; } # get rid of the pesky undefined warnings
unless( defined ($revision) ) { $revision = ""; }
unless( defined ($date) ) { $date = ""; }
$last_error = 0;
$self->assertSessionOpen() || die "Error: failed to open MacCVS session file at $self->{session_file}\n";
my($revstring) = ($revision ne "") ? $revision : "(none)";
my($datestring) = ($date ne "") ? $date : "(none)";
print "Checking out $module with revision $revstring, date $datestring\n";
my($prm) =
q"'----':obj {form:name, want:type(docu), seld:TEXT(@), from:'null'()}, ".
q"modl:'TEXT'(@), tagr:'TEXT'(@), tagd:'TEXT'(@) ";
my($evt) = do_event(qw/MCvs cout/, $gAppSig, $prm, $self->{name}, $module, $revision, $date);
return _checkForEventError($evt);
}
# update( self, branch tag, list of paths)
# MacCVS udate command
# returns 1 on success.
# NOTE: MacCVS Pro does not correctly support this stuff yet (as of version 2.7d5).
sub update()
{
my($self, $branch, $paths ) = @_;
$last_error = 0;
$self->assertSessionOpen() || die "Error: failed to open MacCVS session file at $self->{session_file}\n";
if ($branch eq "HEAD") {
$branch = "";
}
my($paths_list) = "";
my($path);
foreach $path (@$paths)
{
if ($paths_list ne "") {
$paths_list = $paths_list.", ";
}
$paths_list = $paths_list."Ò".$path."Ó";
}
my($prm) =
q"'----':obj {form:name, want:type(docu), seld:TEXT(@), from:'null'()}, ".
q"tagr:'TEXT'(@), tFls:[";
$prm = $prm.$paths_list."]";
my($evt) = do_event(qw/MCvs updt/, $gAppSig, $prm, $self->{name}, $branch);
return _checkForEventError($evt);
};
sub getLastError()
{
return $last_error;
}
1;
=pod
=head1 NAME
MacCVS - Interface to MacCVS
=head1 SYNOPSIS
use MacCVS;
$session = MacCVS->new( <session_file_path>) || die "cannot create session";
$session->checkout([module] [revision] [date]) || die "Could not check out";
=head1 DESCRIPTION
This is a MacCVS interface for talking to MacCVS Pro client.
MacCVSSession is the class used to manipulate the session
=item new
MacCVS->new( <cvs session file path>);
Creates a new session. Returns undef on failure.
=item checkout( <module> [revision] [date] )
cvs checkout command. Revision and date are optional
returns 0 on failure
=cut
=head1 SEE ALSO
=over
=item MacCVS Home Page
http://www.maccvs.org/
=back
=head1 AUTHORS
Aleks Totic atotic@netscape.com
Simon Fraser sfraser@netscape.com
=cut
__END__

View File

@@ -1,603 +0,0 @@
=head1 NAME
B<Moz> - routines for automating CodeWarrior builds, and some extra-curricular
activities related to building Mozilla
=head1 SYNOPSIS
use Moz;
OpenErrorLog(":::BuildLog");
StopForErrors();
$Moz::QUIET = 1;
InstallFromManifest(":projects:MANIFEST", $dist_dir);
BuildProjectClean(":projects:SomeProject.mcp", "SomeTarget");
MakeAlias(":projects:SomeProject.shlb", $dist_dir);
DontStopForErrors();
BuildProject(":projects:SomeOtherProject.mcp", "SomeTarget");
=head1 DESCRIPTION
B<Moz> comprises the routines needed to slap CodeWarrior around, force it
to build a sequence of projects, report the results, and a few other things.
This module should only contain functions that are generic to any build,
not just the Mozilla build.
=cut
package Moz::Moz;
require Exporter;
use Cwd;
use File::Copy;
use File::Path;
use File::Basename;
use Mac::Types;
use Mac::Events;
use Mac::Processes;
use ExtUtils::Manifest 'maniread';
use Moz::CodeWarriorLib;
@ISA = qw(Exporter);
@EXPORT = qw( LaunchCodeWarrior
GetCodeWarriorRelativePath
current_directory
full_path_to
DoBuildProject
ImportXMLProject
ExportProjectToXML
OpenErrorLog
MakeAlias
GetFileModDate
StopForErrors
DontStopForErrors
InstallFromManifest
InstallResources
RedirectOutputToFile
Delay
ActivateApplication
IsProcessRunning);
@EXPORT_OK = qw(CloseErrorLog QUIET);
sub current_directory()
{
my $current_directory = cwd();
chop($current_directory) if ( $current_directory =~ m/:$/ );
return $current_directory;
}
sub full_path_to($)
{
my ($path) = @_;
if ( $path =~ m/^[^:]+$/ )
{
$path = ":" . $path;
}
if ( $path =~ m/^:/ )
{
$path = current_directory() . $path;
}
return $path;
}
$logging = 0;
$recent_errors_file = "";
$stop_on_1st_error = 1;
$QUIET = 0;
=head2 Logging all the errors and warnings - C<OpenErrorLog($log_file)>, C<CloseErrorLog()>
The warnings and errors generated in the course of building projects can be logged to a file.
Tinderbox uses this facility to show why a remote build failed.
Logging is off by default.
Start logging at any point in your build process with C<OpenErrorLog($log_file)>.
Stop with C<CloseErrorLog()>.
You never need to close the log explicitly, unless you want to just log a couple of projects in the middle of a big list.
C<CloseErrorLog()> is not exported by default.
=cut
sub CloseErrorLog()
{
if ( $logging )
{
close(ERROR_LOG);
$logging = 0;
StopForErrors() if $stop_on_1st_error;
}
}
sub OpenErrorLog($)
{
my ($log_file) = @_;
CloseErrorLog();
if ( $log_file )
{
$log_file = full_path_to($log_file);
open(ERROR_LOG, ">$log_file") || die "Error: Can't open $log_file\n";
MacPerl::SetFileInfo("CWIE", "TEXT", $log_file);
$log_file =~ m/.+:(.+)/;
$recent_errors_file = full_path_to("$1.part");
$logging = 1;
}
}
=head2 Stopping before it's too late - C<StopForErrors()>, C<DontStopForErrors()>
When building a long list of projects, you decide whether to continue building subsequent projects when one fails.
By default, your build script will C<die> after the first project that generates an error while building.
Change this behavior with C<DontStopForErrors()>.
Re-enable it with C<StopForErrors()>.
=cut
sub StopForErrors()
{
$stop_on_1st_error = 1;
# Can't stop for errors unless we notice them.
# Can't notice them unless we are logging.
# If the user didn't explicitly request logging, log to a temporary file.
if ( ! $recent_errors_file )
{
OpenErrorLog("${TMPDIR}BuildResults");
}
}
sub DontStopForErrors()
{
$stop_on_1st_error = 0;
}
sub log_message($)
{
if ( $logging )
{
my ($message) = @_;
print ERROR_LOG $message;
}
}
sub log_message_with_time($)
{
if ( $logging )
{
my ($message) = @_;
my $time_stamp = localtime();
log_message("$message ($time_stamp)\n");
}
}
sub log_recent_errors($)
{
my ($project_name) = @_;
my $found_errors = 0;
if ( $logging )
{
open(RECENT_ERRORS, "<$recent_errors_file");
while( <RECENT_ERRORS> )
{
if ( /^Error/ || /^CouldnÕt find project file/ || /^Link Error/ )
{
# if (!$found_errors)
# print $_;
$found_errors = 1;
}
print ERROR_LOG $_;
}
close(RECENT_ERRORS);
unlink("$recent_errors_file");
}
if ( $stop_on_1st_error && $found_errors )
{
print ERROR_LOG "### Build failed.\n";
die "### Errors encountered building \"$project_name\".\n";
}
}
sub DoBuildProject($$$)
{
my ($project_path, $target_name, $clean_build) = @_;
$project_path = full_path_to($project_path);
# $project_path =~ m/.+:(.+)/;
# my $project_name = $1;
log_message_with_time("### Building \"$project_path\"");
# Check that the given project exists
if (! -e $project_path)
{
print ERROR_LOG "### Build failed.\n";
die "### Can't find project file \"$project_path\".\n";
}
print "Building \"$project_path\[$target_name\]\"\n";
$had_errors = Moz::CodeWarriorLib::build_project(
$project_path, $target_name, $recent_errors_file, $clean_build
);
WaitNextEvent();
# $had_errors =
#MacPerl::DoAppleScript(<<END_OF_APPLESCRIPT);
# tell (load script file "$CodeWarriorLib") to BuildProject("$project_path", "$project_name", "$target_name", "$recent_errors_file", $clean_build)
#END_OF_APPLESCRIPT
# Append any errors to the globally accumulated log file
# if ( $had_errors ) # Removed this test, because we want warnings, too. -- jrm
{
log_recent_errors($project_path);
}
}
sub ImportXMLProject($$)
{
my ($xml_path, $project_path) = @_;
# my ($codewarrior_ide_name) = Moz::CodeWarriorLib::getCodeWarriorIDEName();
# my $ascript = <<EOS;
# tell application "$codewarrior_ide_name"
# make new (project document) as ("$project_path") with data ("$xml_path")
# end tell
#EOS
# print $ascript."\n";
# my($result) = MacPerl::DoAppleScript($ascript);
# unless ($result) { die "Error: ImportXMLProject AppleScript failed $^E $result\n"; }
#
my($import_error) = Moz::CodeWarriorLib::import_project($xml_path, $project_path);
if ($import_error ne "") {
die "Error: ImportXMLProject failed with error $import_error\n";
}
}
sub ExportProjectToXML($$)
{
my ($project_path, $xml_path) = @_;
my (@suffix_list) = (".mcp");
my ($project_name, $project_dir, $suffix) = fileparse($project_path, @suffix_list);
if ($suffix eq "") { die "Project: $project_path doesn't look like a project file.\n"; }
if (-e $xml_path) {
print "$xml_path exists - not exporting $project_path\n";
}
else {
print "Exporting $project_path to $xml_path\n";
my($export_error) = Moz::CodeWarriorLib::export_project($project_path, $xml_path);
if ($export_error ne "") {
die "Error: export_project failed with error '$export_error'\n";
}
if (! -e $xml_path) {
die "Error: XML export to $xml_path failed\n";
}
}
}
=head2 Miscellaneous
C<MakeAlias($old_file, $new_file)> functions like C<symlink()>, except with better argument defaulting and more explicit error messages.
=cut
sub MakeAlias($$)
{
my ($old_file, $new_file) = @_;
# if the directory to hold $new_file doesn't exist, create it
if ( ($new_file =~ m/(.+:)/) && !-d $1 )
{
mkpath($1);
}
# if a leaf name wasn't specified for $new_file, use the leaf from $old_file
if ( ($new_file =~ m/:$/) && ($old_file =~ m/.+:(.+)/) )
{
$new_file .= $1;
}
my $message = "Can't create a Finder alias (at \"$new_file\")\n for \"$old_file\"; because ";
die "Error: $message \"$old_file\" doesn't exist.\n" unless -e $old_file;
die "Error: $message I won't replace an existing (non-alias) file with an alias.\n" if ( -e $new_file && ! -l $new_file );
# now: $old_file exists; $new_file doesn't (or else, is an alias already)
if ( -l $new_file )
{
# ...then see if it already points to $old_file
my $current_target = full_path_to(readlink($new_file));
my $new_target = full_path_to($old_file);
return if ( $current_target eq $new_target );
# if the desired alias already exists and points to the right thing, then we're done
unlink $new_file;
}
symlink($old_file, $new_file) || die "Error: $message symlink returned an unexpected error.\n";
}
=pod
C<InstallFromManifest()>
=cut
sub InstallFromManifest($;$$)
{
my ($manifest_file, $dest_dir, $flat) = @_;
$flat = 0 unless defined($flat); # if $flat, all rel. paths in MANIFEST get aliased to the root of $dest_dir
$dest_dir ||= ":";
$manifest_file =~ m/(.+):/;
my $source_dir = $1;
chop($dest_dir) if $dest_dir =~ m/:$/;
#Mac::Events->import();
WaitNextEvent();
if ($flat)
{
print "Doing manifest on \"$manifest_file\" FLAT\n" unless $QUIET;
}
else
{
print "Doing manifest on \"$manifest_file\"\n" unless $QUIET;
}
my $read = maniread(full_path_to($manifest_file));
foreach $file (keys %$read)
{
next unless $file;
$subdir = ":";
if (!$flat && ($file =~ /:.+:/ ))
{
$subdir = $&;
}
$file = ":$file" unless $file =~ m/^:/;
MakeAlias("$source_dir$file", "$dest_dir$subdir");
}
}
=pod
C<InstallResources()>
=cut
# parameters are path to MANIFEST file, destination dir, true (to make copies) or false (to make aliases)
sub InstallResources($;$;$)
{
my ($manifest_file, $dest_dir, $copy_files) = @_;
$dest_dir ||= ":";
mkpath($dest_dir) if !-d $dest_dir;
$manifest_file =~ m/(.+):/;
my $source_dir = $1;
chop($dest_dir) if $dest_dir =~ m/:$/;
WaitNextEvent();
print "Installing resources from \"$manifest_file\"\n" unless $QUIET;
my $read = maniread(full_path_to($manifest_file));
foreach $file (keys %$read)
{
next unless $file;
if ($copy_files)
{
copy("$source_dir:$file", "$dest_dir:$file");
}
else
{
MakeAlias("$source_dir:$file", "$dest_dir:$file");
}
}
}
#//--------------------------------------------------------------------------------------------------
#// Delay
#//--------------------------------------------------------------------------------------------------
sub Delay($)
{
my ($delay_seconds) = @_;
$now = time;
$exit_time = $now + $delay_seconds;
while ($exit_time > $now) {
$now = time;
}
}
#//--------------------------------------------------------------------------------------------------
#// GetFileModDate
#//--------------------------------------------------------------------------------------------------
sub GetFileModDate($)
{
my($filePath)=@_;
my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat($filePath);
return $mtime;
}
#//--------------------------------------------------------------------------------------------------
#// LaunchCodeWarrior
#//--------------------------------------------------------------------------------------------------
sub LaunchCodeWarrior($)
{
my($idepath_file) = @_; # full path to IDE location file
my($cur_dir) = cwd();
# this both launches and writes the IDE path file
Moz::CodeWarriorLib::activate($idepath_file);
chdir($cur_dir);
}
#//--------------------------------------------------------------------------------------------------
#// GetCodeWarriorRelativePath
#//--------------------------------------------------------------------------------------------------
sub GetCodeWarriorRelativePath($)
{
my($rel_path) = @_;
return Moz::CodeWarriorLib::getCodeWarriorPath($rel_path);
}
#//--------------------------------------------------------------------------------------------------
#// RedirectOutputToFile
#//--------------------------------------------------------------------------------------------------
sub RedirectOutputToFile($)
{
my($log_file) = @_;
# ensure that folders in the path exist
my($logdir) = "";
my($logfile) = $log_file;
if ($log_file =~ /(.+?:)([^:]+)$/) # ? for non-greedy match
{
$logdir = $1;
$logfile = $2;
mkpath($logdir);
}
print "Output is now being redirected to the file '$log_file'\n";
open(STDOUT, "> $log_file") || die "Can't redirect stdout";
open(STDERR, ">&STDOUT") || die "Can't dup stdout";
select(STDERR); $| = 1; # make unbuffered
select(STDOUT); $| = 1; # make unbuffered
MacPerl::SetFileInfo("CWIE", "TEXT", $log_file);
}
#//--------------------------------------------------------------------------------------------------
#// ActivateApplication
#//--------------------------------------------------------------------------------------------------
sub ActivateApplication($)
{
my ($appSignature) = @_;
my ($psi, $found);
my ($appPSN);
$found = 0;
foreach $psi (values(%Process))
{
if ($psi->processSignature() eq $appSignature)
{
$appPSN = $psi->processNumber();
$found = 1;
last;
}
}
if ($found == 0 || SameProcess($appPSN, GetFrontProcess()))
{
return;
}
SetFrontProcess($appPSN);
while (GetFrontProcess() != $appPSN)
{
WaitNextEvent();
}
}
#//--------------------------------------------------------------------------------------------------
#// IsProcessRunning
#//--------------------------------------------------------------------------------------------------
sub IsProcessRunning($)
{
my($processName, $psn, $psi) = @_;
while ( ($psn, $psi) = each(%Process) ) {
if ($psi->processName eq $processName) { return 1; }
}
return 0;
}
1;
=head1 AUTHORS
Scott Collins <scc@netscape.com>, Simon Fraser <sfraser@netscape.com>, Chris Yeh <cyeh@netscape.com>
=head1 SEE ALSO
BuildMozillaDebug.pl (et al), BuildList.pm, CodeWarriorLib (an AppleScript library)
=head1 COPYRIGHT
The contents of this file are subject to the Netscape Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The Original Code is Mozilla Communicator client code, released
March 31, 1998.
The Initial Developer of the Original Code is Netscape
Communications Corporation. Portions created by Netscape are
Copyright (C) 1998-1999 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
=cut

View File

@@ -1,272 +0,0 @@
package Moz::Prefs;
require 5.004;
require Exporter;
# Package that attempts to read a file from the Preferences folder,
# and get build settings out of it
use strict;
use Exporter;
use File::Path;
use Mac::Files;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(ReadMozUserPrefs);
#-------------------------------------------------------------------------------
#
# GetPrefsFolder
#
#-------------------------------------------------------------------------------
sub GetPrefsFolder()
{
my($prefs_folder) = FindFolder(kOnSystemDisk, kPreferencesFolderType, 1);
return $prefs_folder.":Mozilla build prefs";
}
#-------------------------------------------------------------------------------
#
# SetArrayValue
#
#-------------------------------------------------------------------------------
sub SetArrayValue($$$)
{
my($array_ref, $index1, $index2) = @_;
my($index);
foreach $index (@$array_ref)
{
if ($index->[0] eq $index1)
{
$index->[1] = $index2;
return 1;
}
}
return 0;
}
#-------------------------------------------------------------------------------
#
# WriteDefaultPrefsFile
#
#-------------------------------------------------------------------------------
sub WriteDefaultPrefsFile($)
{
my($file_path) = @_;
my($file_contents);
$file_contents = <<'EOS';
% You can use this file to customize the Mozilla build system.
% The following kinds of lines are allowable:
% Comment lines, which start with a '%' in the first column
% Lines which modify the default build settings. For the list of flags,
% see MozBuildFlags.pm. Examples are:
%
% build pull 0 % don't pull
% options mng 1 % turn mng on
%
% Line containing the special 'buildfrom' flag, which specifies
% where to start the build. Example:
%
% buildfrom nglayout % where to start the build
%
% Lines which specify the location of the files used to store paths
% to the CodeWarrior IDE, and the MacCVS Pro session file. Note quoting
% of paths containing whitespace. Examples:
%
% filepath idepath ::codewarrior.txt
% filepath sessionpath ":Some folder:MacCVS session path.txt"
%
% Lines which modify the build settings like %main::DEBUG.
% Any lines which do not match either of the above are assumed
% to set variables on $main::. Examples:
%
% MOZILLA_OFFICIAL 1
%
EOS
$file_contents =~ s/%/#/g;
local(*PREFS_FILE);
open(PREFS_FILE, "> $file_path") || die "Could not write default prefs file\n";
print PREFS_FILE ($file_contents);
close(PREFS_FILE);
MacPerl::SetFileInfo("McPL", "TEXT", $file_path);
}
#-------------------------------------------------------------------------------
#
# HandlePrefSet
#
#-------------------------------------------------------------------------------
sub HandlePrefSet($$$$)
{
my($flags, $name, $value, $desc) = @_;
if (SetArrayValue($flags, $name, $value)) {
print "Prefs set $desc flag '$name' to '$value'\n";
} else {
die "$desc setting '$name' is not a valid option\n";
}
}
#-------------------------------------------------------------------------------
#
# HandleBuildFromPref
#
#-------------------------------------------------------------------------------
sub HandleBuildFromPref($$)
{
my($build_array, $name) = @_;
my($setting) = 0;
my($index);
foreach $index (@$build_array)
{
if ($index->[0] eq $name) {
$setting = 1;
}
$index->[1] = $setting;
}
if ($setting == 1) {
print "Building from $name onwards, as specified by prefs\n";
} else {
printf "Failed to find buildfrom setting '$name'\n";
}
}
#-------------------------------------------------------------------------------
#
# ReadPrefsFile
#
#-------------------------------------------------------------------------------
sub ReadPrefsFile($$$$$)
{
my($file_path, $build_flags, $options_flags, $filepath_flags, $create_if_missing) = @_;
local(*PREFS_FILE);
if (open(PREFS_FILE, "< $file_path"))
{
print "Reading build prefs from '$file_path'\n";
while (<PREFS_FILE>)
{
my($line) = $_;
chomp($line);
if ($line =~ /^\#/ || $line =~ /^\s*$/) { # ignore comments and empty lines
next;
}
if (($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+\"(.+)\"(\s+#.+)?/) ||
($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+\'(.+)\'(\s+#.+)?/) ||
($line =~ /^\s*([^#\s]+)\s+([^#\s]+)\s+([^#\s]+)(\s+#.+)?/))
{
my($array_name) = $1;
my($option_name) = $2;
my($option_value) = $3;
# print "Read '$array_name' '$option_name' '$option_value'\n";
if ($array_name eq "build")
{
HandlePrefSet($build_flags, $option_name, $option_value, "Build");
}
elsif ($array_name eq "options")
{
HandlePrefSet($options_flags, $option_name, $option_value, "Options");
}
elsif ($array_name eq "filepath" && $option_name && $option_value)
{
HandlePrefSet($filepath_flags, $option_name, $option_value, "Filepath");
}
else
{
print "Unknown pref option at $line\n";
}
}
elsif ($line =~ /^\s*buildfrom\s+([^#\s]+)(\s+#.+)?/)
{
my($build_start) = $1;
HandleBuildFromPref($build_flags, $build_start);
}
elsif ($line =~ /^\s*([^#\s]+)\s+([^#\s]+)(\s+#.+)?/)
{
my($build_var) = $1;
my($var_setting) = $2;
print "Setting \$main::$build_var to $var_setting\n";
eval "\$main::$build_var = \"$var_setting\"";
}
else
{
print "Unrecognized input line at $line\n";
}
}
close(PREFS_FILE);
}
elsif ($create_if_missing)
{
print "No prefs file found at $file_path; using defaults\n";
my($folder_path) = $file_path;
$folder_path =~ s/[^:]+$//;
mkpath($folder_path);
WriteDefaultPrefsFile($file_path);
}
}
#-------------------------------------------------------------------------------
#
# ReadMozUserPrefs
#
#-------------------------------------------------------------------------------
sub ReadMozUserPrefs($$$$)
{
my($prefs_file_name, $build_flags, $options_flags, $filepath_flags) = @_;
if ($prefs_file_name eq "") { return; }
# if local prefs exist, just use those. Othewise, look in the prefs folder
if (-e $prefs_file_name)
{
# read local prefs
ReadPrefsFile($prefs_file_name, $build_flags, $options_flags, $filepath_flags, 0);
}
else
{
# first read prefs folder prefs
my($prefs_path) = GetPrefsFolder();
$prefs_path .= ":$prefs_file_name";
ReadPrefsFile($prefs_path, $build_flags, $options_flags, $filepath_flags, 1);
}
}
1;

View File

@@ -1,932 +0,0 @@
#!/usr/bin/perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
package Moz::ProjectXML;
require 5.004;
require Exporter;
use strict;
use Exporter;
use Cwd;
use XML::DOM;
use vars qw(@ISA @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
ParseXMLDocument
DisposeXMLDocument
WriteXMLDocument
CleanupPro5XML
GetTargetsList
CloneTarget
SetAsSharedLibraryTarget
SetAsStaticLibraryTarget
AddTarget
RemoveTarget
GetTargetSetting
SetTargetSetting
getChildElementTextContents
);
#--------------------------------------------------------------------------------------------------
# A module for reading, manipulating, and writing XML-format CodeWarrior project files.
#
# Sample usage:
#
# use ProjectXML;
#
# my $doc = ProjectXML::ParseXMLDocument("Test.mcp.xml");
# ProjectXML::CloneTarget($doc, "Test.shlb", "Test.lib");
# ProjectXML::SetAsStaticLibraryTarget($doc, "Test.lib", "TestOutput.lib");
# ProjectXML::WriteXMLDocument($doc, "Test_out.xml");
# ProjectXML::DisposeXMLDocument($doc);
#
#--------------------------------------------------------------------------------------------------
#//--------------------------------------------------------------------------------------------------
#// ParseXMLDocument
#// Note that the caller must call DisposeXMLDocument on the returned doc
#//--------------------------------------------------------------------------------------------------
sub ParseXMLDocument($)
{
my($doc_path) = @_;
my $parser = new XML::DOM::Parser(ErrorContext => 2);
my $doc = $parser->parsefile($doc_path);
return $doc;
}
#//--------------------------------------------------------------------------------------------------
#// DisposeXMLDocument
#// Needed to avoid memory leaks - cleanup circular references for garbage collection
#//--------------------------------------------------------------------------------------------------
sub DisposeXMLDocument($)
{
my($doc) = @_;
$doc->dispose();
}
#//--------------------------------------------------------------------------------------------------
#// WriteXMLDocument
#//--------------------------------------------------------------------------------------------------
sub _pro5_tag_compression($$)
{
return 1; # Pro 5 is broken and can't import XML with <foo/> style tags
}
sub _pro6plus_tag_compression($$)
{
return 0; # Pro 6 can deal with empty XML tags like <foo/>
}
sub WriteXMLDocument($$$)
{
my($doc, $file_path, $ide_version) = @_;
if ($ide_version eq "4.0")
{
XML::DOM::setTagCompression(\&_pro5_tag_compression);
}
else
{
XML::DOM::setTagCompression(\&_pro6plus_tag_compression);
}
$doc->printToFile($file_path);
}
#//--------------------------------------------------------------------------------------------------
#// CleanupPro5XML
#// XML Projects exported by Pro 5 contain garbage data under the MWMerge_MacOS_skipResources
#// setting. This routine cleans this up, saving the result to a new file
#//--------------------------------------------------------------------------------------------------
sub CleanupPro5XML($$)
{
my($xml_path, $out_path) = @_;
local(*XML_FILE);
open(XML_FILE, "< $xml_path") || die "Error: failed to open file $xml_path\n";
local(*CLEANED_FILE);
open(CLEANED_FILE, "> $out_path") || die "Error: failed to open file $out_path for writing\n";
my $in_skip_resources_settings = 0;
while(<XML_FILE>)
{
my($line) = $_;
if ($line =~ /^<\?codewarrior/) # is processing inst line
{
my $test_line = $line;
chomp($test_line);
my $out_line = $test_line;
if ($test_line =~ /^<\?codewarrior\s+exportversion=\"(.+)\"\s+ideversion=\"(.+)\"\s*\?>$/)
{
my $export_version = $1;
my $ide_version = $2;
$ide_version = "4.0_mozilla"; # pseudo IDE version so we know we touched it
$out_line = "<?codewarrior exportversion=\"".$export_version."\" ideversion=\"".$ide_version."\"?>";
}
print CLEANED_FILE "$out_line\n";
next;
}
if ($line =~ /MWMerge_MacOS_skipResources/)
{
$in_skip_resources_settings = 1;
print CLEANED_FILE "$line";
}
elsif($in_skip_resources_settings && $line =~ /<!-- Settings for/)
{
# leaving bad settings lines. Write closing tag
print CLEANED_FILE " <!-- Corrupted setting entries removed by script -->\n";
print CLEANED_FILE " </SETTING>\n\n";
print CLEANED_FILE "$line";
$in_skip_resources_settings = 0;
}
elsif (!$in_skip_resources_settings)
{
print CLEANED_FILE "$line";
}
}
close(XML_FILE);
close(CLEANED_FILE);
}
#--------------------------------------------------------------------------------------------------
# SniffProjectXMLIDEVersion
#
#--------------------------------------------------------------------------------------------------
sub SniffProjectXMLIDEVersion($)
{
my($xml_path) = @_;
my $found_version = "";
local(*XML_FILE);
open(XML_FILE, "< $xml_path") || die "Error: failed to open file $xml_path\n";
while(<XML_FILE>)
{
my($line) = $_;
chomp($line);
if ($line =~ /^<\?codewarrior/) # is processing inst line
{
unless ($line =~ /^<\?codewarrior\s+exportversion=\"(.+)\"\s+ideversion=\"(.+)\"\s*\?>$/)
{
die "Error: Failed to find ideversion in $xml_path in line $line\n";
}
my $export_version = $1;
my $ide_version = $2;
$found_version = $ide_version;
last;
}
}
close(XML_FILE);
return $found_version;
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetsList
#// Returns an array of target names
#//--------------------------------------------------------------------------------------------------
sub GetTargetsList($)
{
my($doc) = @_;
my $nodes = $doc->getElementsByTagName("TARGET");
my $n = $nodes->getLength;
my @target_names;
for (my $i = 0; $i < $n; $i++)
{
my ($node) = $nodes->item($i);
my($target_name) = getChildElementTextContents($node, "NAME");
push(@target_names, $target_name);
}
return @target_names;
}
#//--------------------------------------------------------------------------------------------------
#// CloneTarget
#// Clone the named target, renaming it to 'new_name'
#//--------------------------------------------------------------------------------------------------
sub CloneTarget($$$)
{
my($doc, $target_name, $new_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
# clone here
my $target_clone = $target_node->cloneNode(1); # deep clone
# -- munge target settings --
# set the target name field
setChildElementTextContents($doc, $target_clone, "NAME", $new_name);
# set the targetname pref
setTargetNodeSetting($doc, $target_clone, "Targetname", $new_name);
# -- insert new target subtree --
my $target_list = $target_node->getParentNode();
$target_list->appendChild($target_clone);
# -- now add to targetorder --
my (@target_order_nodes) = getChildOfDocument($doc, "TARGETORDER");
my $target_order = @target_order_nodes[0];
my $new_order = $doc->createElement("ORDEREDTARGET");
my $order_name = $doc->createElement("NAME");
$new_order->appendChild($order_name);
setChildElementTextContents($doc, $new_order, "NAME", $new_name);
$target_order->appendChild($new_order);
}
#//--------------------------------------------------------------------------------------------------
#// SetAsSharedLibraryTarget
#//
#//--------------------------------------------------------------------------------------------------
sub SetAsSharedLibraryTarget($$$)
{
my($doc, $target_name, $output_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_type", "SharedLibrary");
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_filetype", "1936223330"); #'shlb'
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_outfile", $output_name);
}
#//--------------------------------------------------------------------------------------------------
#// AddFileToTarget
#//
#// Add a file to the specified target(s).
#//
#//--------------------------------------------------------------------------------------------------
sub AddFileToTarget($$$)
{
my($doc, $target_list, $file_name) = @_;
# the file must be added in 3 places:
# 1. in <TARGET><FILELIST><FILE> (with linkage flags if necessary)
# 2. in <TARGET><LINKORDER><FILEREF>
# 3. in <GROUPLIST><GROUP><FILEREF>
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// RemoveFileFromTarget
#//
#// Remove a file from the specified target, removing it from the entire project
#// if no other targets reference it.
#//
#//--------------------------------------------------------------------------------------------------
sub RemoveFileFromTarget($$$)
{
my($doc, $target_node, $file_name) = @_;
# the file must be removed in 3 places:
# 1. in <TARGET><FILELIST><FILE>
# 2. in <TARGET><LINKORDER><FILEREF>
# 3. in <GROUPLIST><GROUP><FILEREF>
# first, remove from <FILELIST>
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my $file_node = getChildNodeByGrandchildContents($doc, $filelist_node, "FILE", "PATH", $file_name);
unless ($file_node) { return; }
$filelist_node->removeChild($file_node);
# next, remove from <LINKORDER>
my $linkorder_node = getFirstChildElement($target_node, "LINKORDER");
unless ($linkorder_node) { die "Error: failed to find LINKORDER node\n"; }
my $fileref_node = getChildNodeByGrandchildContents($doc, $linkorder_node, "FILEREF", "PATH", $file_name);
unless ($fileref_node) { die "Error: link order node for file $file_name not found\n"; }
$linkorder_node->removeChild($fileref_node);
# last, remove from <GROUPLIST>
# <GROUPLIST> is cross-target, so we have to be careful here.
my $grouplist_node = getChildOfDocument($doc, "GROUPLIST");
unless ($grouplist_node) { die "Error: failed to find GROUPLIST node\n"; }
# if the file isn't in any other targets, remove it from the groups
if (!GetFileInUse($doc, $file_name))
{
print "File $file_name is in no other targest. Removing from project\n";
my @group_nodes;
getChildElementsOfType($doc, $grouplist_node, "GROUP", \@group_nodes);
my $group_node;
foreach $group_node (@group_nodes)
{
my @fileref_nodes;
getChildElementsOfType($doc, $group_node, "FILEREF", \@fileref_nodes);
my $fileref_node;
foreach $fileref_node (@fileref_nodes)
{
my $path_name = getChildElementTextContents($fileref_node, "PATH");
if ($path_name eq $file_name)
{
print "Removing $file_name from project group list\n";
$group_node->removeChild($fileref_node);
last;
}
}
# can a file appear in more than one group?
}
}
}
#//--------------------------------------------------------------------------------------------------
#// SetAsStaticLibraryTarget
#//
#//--------------------------------------------------------------------------------------------------
sub SetAsStaticLibraryTarget($$$)
{
my($doc, $target_name, $output_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_type", "Library");
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_filetype", "1061109567"); #'????'
setTargetNodeSetting($doc, $target_node, "MWProject_PPC_outfile", $output_name);
# static targets don't need any library linkage, so we can remove linkage
# with all .shlb and .Lib files.
my(@obsolete_files) = ("NSStdLibStubs", "InterfacesStubs", "InterfaceLib", "InternetConfigLib");
print " Removing libraries etc. from target\n";
# get all files in target
my @target_files = GetTargetFilesList($doc, $target_name);
my $target_file;
foreach $target_file (@target_files)
{
if ($target_file =~ /(\.shlb|\.lib|\.Lib|\.o|\.exp)$/)
{
RemoveFileFromTarget($doc, $target_node, $target_file);
}
}
print " Removing stub libraries from target\n";
# then remove files with known names
my $obs_file;
foreach $obs_file (@obsolete_files)
{
RemoveFileFromTarget($doc, $target_node, $obs_file);
}
}
#//--------------------------------------------------------------------------------------------------
#// AddTarget
#//
#//--------------------------------------------------------------------------------------------------
sub AddTarget($$)
{
my($doc, $target_name) = @_;
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// RemoveTarget
#//
#//--------------------------------------------------------------------------------------------------
sub RemoveTarget($$)
{
my($doc, $target_name) = @_;
die "Write me\n";
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetSetting
#// Get the value for the specified setting in the specified target
#//--------------------------------------------------------------------------------------------------
sub GetTargetSetting($$$)
{
my($doc, $target_name, $setting_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
return getTargetNodeSetting($target_node, "VALUE");
}
#//--------------------------------------------------------------------------------------------------
#// SetTargetSetting
#// Set the value for the specified setting in the specified target
#//--------------------------------------------------------------------------------------------------
sub SetTargetSetting($$$$)
{
my($doc, $target_name, $setting_name, $new_value) = @_;
my $target_node = getTargetNode($doc, $target_name);
setTargetNodeSetting($doc, $target_node, "VALUE", $new_value);
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetFilesList
#// Return an array of the files in the target (in filelist order)
#//--------------------------------------------------------------------------------------------------
sub GetTargetFilesList($$)
{
my($doc, $target_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
my @files_list;
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my @file_nodes;
getChildElementsOfType($doc, $filelist_node, "FILE", \@file_nodes);
my $node;
foreach $node (@file_nodes)
{
my $file_name = getChildElementTextContents($node, "PATH");
push(@files_list, $file_name);
}
return @files_list;
}
#//--------------------------------------------------------------------------------------------------
#// FileIsInTarget
#//
#//--------------------------------------------------------------------------------------------------
sub FileIsInTarget($$$)
{
my($doc, $file_name, $target_name) = @_;
my $target_node = getTargetNode($doc, $target_name);
unless ($target_node) { die "Error: no target found called $target_name\n"; }
my $file_node = GetTargetFileNode($doc, $target_node, $file_name);
if ($file_node) {
return 1;
}
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// GetFileTargetsList
#// Return an array of the targets that a file is in (expensive)
#//--------------------------------------------------------------------------------------------------
sub GetFileTargetsList($$)
{
my ($doc, $file_name) = @_;
my @target_list;
my @targets = GetTargetsList($doc);
my $target;
foreach $target (@targets)
{
if (FileIsInTarget($doc, $file_name, $target))
{
push(@target_list, $target);
}
}
return @target_list;
}
#//--------------------------------------------------------------------------------------------------
#// GetTargetFileNode
#//
#//--------------------------------------------------------------------------------------------------
sub GetTargetFileNode($$$)
{
my($doc, $target_node, $file_name) = @_;
my $filelist_node = getFirstChildElement($target_node, "FILELIST");
unless ($filelist_node) { die "Error: failed to find FILELIST node\n"; }
my $file_node = getChildNodeByGrandchildContents($doc, $filelist_node, "FILE", "PATH", $file_name);
return $file_node;
}
#//--------------------------------------------------------------------------------------------------
#// GetFileInUse
#// Return true if the file is used by any target
#//--------------------------------------------------------------------------------------------------
sub GetFileInUse($$)
{
my($doc, $file_name) = @_;
my $targetlist_node = getChildOfDocument($doc, "TARGETLIST");
my $target_node = $targetlist_node->getFirstChild();
while ($target_node)
{
if ($target_node->getNodeTypeName eq "ELEMENT_NODE" &&
$target_node->getTagName() eq "TARGET")
{
# if this is a target node
my $file_node = GetTargetFileNode($doc, $target_node, $file_name);
if ($file_node) {
return 1; # found it
}
}
$target_node = $target_node->getNextSibling();
}
# not found
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// getChildOfDocument
#//--------------------------------------------------------------------------------------------------
sub getChildOfDocument($$)
{
my($doc, $child_type) = @_;
return getFirstChildElement($doc->getDocumentElement(), $child_type);
}
#//--------------------------------------------------------------------------------------------------
#// getFirstChildElement
#//--------------------------------------------------------------------------------------------------
sub getFirstChildElement($$)
{
my($node, $element_name) = @_;
my $found_node;
unless ($node) { die "getFirstChildElement called with empty node\n"; }
#look for the first "element_name" child
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $element_name)
{
$found_node = $child_node;
last;
}
$child_node = $child_node->getNextSibling();
}
return $found_node;
}
#//--------------------------------------------------------------------------------------------------
#// getChildElementsOfType
#//
#// Return an array of refs to child nodes of the given type
#//--------------------------------------------------------------------------------------------------
sub getChildElementsOfType($$$$)
{
my($doc, $node, $child_type, $array_ref) = @_;
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $child_type)
{
push(@$array_ref, $child_node);
}
$child_node = $child_node->getNextSibling();
}
}
#//--------------------------------------------------------------------------------------------------
#// getChildElementTextContents
#//--------------------------------------------------------------------------------------------------
#
# Given <FOOPY><NERD>Hi!</NERD></FOOPY>, where $node is <FOOPY>,
# returns "Hi!". If > 1 <NERD> node, returns the contents of the first.
#
sub getChildElementTextContents($$)
{
my($node, $tag_name) = @_;
my $first_element = getFirstChildElement($node, $tag_name);
my $text_node = $first_element->getFirstChild();
my $text_contents = "";
# concat adjacent text nodes
while ($text_node)
{
if ($text_node->getNodeTypeName() ne "TEXT_NODE")
{
last;
}
$text_contents = $text_contents.$text_node->getData();
$text_node = $text_node->getNextSibling();
}
return $text_contents;
}
#//--------------------------------------------------------------------------------------------------
#// setChildElementTextContents
#//--------------------------------------------------------------------------------------------------
sub setChildElementTextContents($$$$)
{
my($doc, $node, $tag_name, $contents_text) = @_;
my $first_element = getFirstChildElement($node, $tag_name);
my $new_text_node = $doc->createTextNode($contents_text);
# replace all child elements with a text element
removeAllChildren($first_element);
$first_element->appendChild($new_text_node);
}
#//--------------------------------------------------------------------------------------------------
#// getChildNodeByContents
#//
#// Consider <foo><bar><baz>Foopy</baz></bar><bar><baz>Loopy</baz></bar></foo>
#// This function, when called with getChildNodeByContents($foonode, "bar", "baz", "Loopy")
#// returns the second <bar> node.
#//--------------------------------------------------------------------------------------------------
sub getChildNodeByGrandchildContents($$$$$)
{
my($doc, $node, $child_type, $gc_type, $gc_contents) = @_; # gc = grandchild
my $found_node;
my $child_node = $node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName eq "ELEMENT_NODE" &&
$child_node->getTagName() eq $child_type)
{
# check for a child of this node of type
my $child_contents = getChildElementTextContents($child_node, $gc_type);
if ($child_contents eq $gc_contents)
{
$found_node = $child_node;
last;
}
}
$child_node = $child_node->getNextSibling();
}
return $found_node;
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNode
#//--------------------------------------------------------------------------------------------------
sub getTargetNode($$)
{
my($doc, $target_name) = @_;
my $targetlist_node = getChildOfDocument($doc, "TARGETLIST");
return getChildNodeByGrandchildContents($doc, $targetlist_node, "TARGET", "NAME", $target_name);
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNamedSettingNode
#//--------------------------------------------------------------------------------------------------
sub getTargetNamedSettingNode($$)
{
my($target_node, $setting_name) = @_;
my $setting_node;
my $settinglist_node = getFirstChildElement($target_node, "SETTINGLIST");
my $child_node = $settinglist_node->getFirstChild();
while ($child_node)
{
if ($child_node->getNodeTypeName ne "ELEMENT_NODE")
{
$child_node = $child_node->getNextSibling();
next;
}
if ($child_node->getTagName() eq "SETTING")
{
my $set_name = getChildElementTextContents($child_node, "NAME");
if ($set_name eq $setting_name)
{
$setting_node = $child_node;
last;
}
}
$child_node = $child_node->getNextSibling();
}
return $setting_node;
}
#//--------------------------------------------------------------------------------------------------
#// getTargetNodeSetting
#//--------------------------------------------------------------------------------------------------
sub getTargetNodeSetting($$)
{
my($target_node, $setting_name) = @_;
my $setting_node = getTargetNamedSettingNode($target_node, $setting_name);
return getChildElementTextContents($setting_node, "VALUE");
}
#//--------------------------------------------------------------------------------------------------
#// setTargetNodeSetting
#//--------------------------------------------------------------------------------------------------
sub setTargetNodeSetting($$$$)
{
my($doc, $target_node, $setting_name, $new_value) = @_;
my $setting_node = getTargetNamedSettingNode($target_node, $setting_name);
setChildElementTextContents($doc, $setting_node, "VALUE", $new_value);
}
#//--------------------------------------------------------------------------------------------------
#// elementInArray
#//--------------------------------------------------------------------------------------------------
sub elementInArray($$)
{
my($element, $array) = @_;
my $test;
foreach $test (@$array)
{
if ($test eq $element) {
return 1;
}
}
return 0;
}
#//--------------------------------------------------------------------------------------------------
#// removeAllChildren
#//--------------------------------------------------------------------------------------------------
sub removeAllChildren($)
{
my($node) = @_;
my $child_node = $node->getFirstChild();
while ($child_node)
{
$node->removeChild($child_node);
$child_node = $node->getFirstChild();
}
}
#//--------------------------------------------------------------------------------------------------
#// dumpNodeData
#//--------------------------------------------------------------------------------------------------
sub dumpNodeData($)
{
my($node) = @_;
unless ($node) { die "Null node passed to dumpNodeData\n"; }
print "Dumping node $node\n";
my($node_type) = $node->getNodeTypeName();
if ($node_type eq "ELEMENT_NODE")
{
my($node_name) = $node->getTagName();
print "Element $node_name\n";
}
elsif ($node_type eq "TEXT_NODE")
{
my($node_data) = $node->getData;
# my(@node_vals) = unpack("C*", $node_data);
print "Text '$node_data'\n"; # may contain LF chars
}
else
{
print "Node $node_type\n";
}
}
#//--------------------------------------------------------------------------------------------------
#// dumpNodeTree
#//--------------------------------------------------------------------------------------------------
sub dumpNodeTree($)
{
my($node) = @_;
my($child_node) = $node->getFirstChild();
unless ($child_node) { return; }
# recurse
dumpNodeData($child_node);
# then go through child nodes
while ($child_node)
{
dumpNodeTree($child_node);
$child_node = $child_node->getNextSibling();
}
}
1;

View File

@@ -1,86 +0,0 @@
#-------------------------------------------------------------------------------
# These 3 lists are the 'master lists' to control what gets built.
#
# Ordering in these arrays is important; it has to reflect the order in
# which the build occurs.
#
# Setting containing spaces must be quoted with double quotes.
#-------------------------------------------------------------------------------
build_flags
all 1
pull 0
dist 0
config 0
xpidl 0
idl 0
stubs 0
runtime 0
common 0
imglib 0
libimg2 0
necko 0
security 0
browserutils 0
intl 0
nglayout 0
accessiblity 0
editor 0
embedding 0
viewer 0
xpapp 0
extensions 0
plugins 0
mailnews 0
apprunner 0
resources 0
options_flags
pull_by_date 0
chrome_jars 1
chrome_files 0
use_jars 1
transformiix 1
mathml 0 MOZ_MATHML
svg 0 MOZ_SVG
# svg requires libart, which is an lgpl library. You need to pull it
# explicitly.
libart_lgpl 0
mng 1
ldap 1 MOZ_LDAP_XPCOM
ldap_experimental 0 MOZ_LDAP_XPCOM_EXPERIMENTAL
xmlextras 1
soap 0 MOZ_SOAP
inspector 1
mailextras 1
xptlink 0
psm 0 ENABLE_SMIME
embedding_test 1
carbon 0 TARGET_CARBON
useimg2 1 USE_IMG2
lowmem 0 MOZ_MAC_LOWMEM
accessible 1 ACCESSIBILITY
bidi 1 IBMBIDI
p3p 0
jsd 1
venkman 1
moz_logging 1 MOZ_LOGGING
chatzilla 1
content_packs 1
xml_rpc 1
cview 1
help 1
timeline 0 MOZ_TIMELINE
static_build 0 MOZ_STATIC_COMPONENT_LIBS
string_debug 0 DEBUG_STRING
string_stats 0 DEBUG_STRING_STATS
xpctools 0 XPC_TOOLS_SUPPORT
smime 1
print_preview 1 NS_PRINT_PREVIEW
moz_xul 1 MOZ_XUL
filepath_flags
idepath ":CodeWarrior IDE Path.txt"
sessionpath ":Mozilla session path.txt"
buildlogfilepath ":Build Logs:Mozilla build log.txt" # this is a path
scriptlogfilepath ":Build Logs:Mozilla script log.txt"

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +0,0 @@
# List of modules to check out. Format is
# module, (tag), (date)
# where tag and date are optional (non-trailing commas are required)
#
# Examples:
# mozilla/nsprpub, NSPRPUB_CLIENT_TAG
# mozilla/gc, , 10/25/2000 12:00:00
#
mozilla/nsprpub, NSPRPUB_PRE_4_2_CLIENT_BRANCH
mozilla/security/nss,
mozilla/security/manager,
mozilla/security/manager/ssl/macbuild, NSS_3_4_LANDING_BRANCH
mozilla/accessible,
DirectorySDKSourceC, LDAPCSDK_40_BRANCH
mozilla/lib/mac/Instrumentation
mozilla/gfx2
mozilla/modules/libpr0n
SeaMonkeyAll
## You need this if you want to be able to use SVG
## Note that this library is under the LGPL, not the MPL
#mozilla/other-licenses/libart_lgpl

View File

@@ -1,79 +0,0 @@
#!perl
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Simon Fraser <sfraser@netscape.com>
#
require 5.004;
use strict;
use Cwd;
use Moz::BuildUtils;
use Moz::BuildCore;
#-------------------------------------------------------------
# Where have the build options gone?
#
# The various build flags have been centralized into one place.
# The master list of options is in MozBuildFlags.txt. However,
# you should never need to edit that file, or this one.
#
# To customize what gets built, or where to start the build,
# edit the $prefs_file_name file in
# System Folder:Preferences:Mozilla build prefs:
# Documentation is provided in that file.
#-------------------------------------------------------------
my($prefs_file_name) = "Mozilla pull prefs";
#-------------------------------------------------------------
# hashes to hold build options
#-------------------------------------------------------------
my(%build);
my(%options);
my(%filepaths);
my(%optiondefines);
# Hash of input files for this build. Eventually, there will be
# input files for manifests, and projects too.
my(%inputfiles) = (
"buildflags", "MozillaBuildFlags.txt",
"checkoutdata", "MozillaCheckoutList.txt",
"buildprogress", "",
"buildmodule", "MozillaBuildList.pm",
"checkouttime", "Mozilla last checkout"
);
#-------------------------------------------------------------
# end build hashes
#-------------------------------------------------------------
# set the build root directory, which is the the dir above mozilla
SetupBuildRootDir(":mozilla:build:mac:build_scripts");
# Set up all the flags on $main::, like DEBUG, CARBON etc.
# Override the defaults using the preferences files.
SetupDefaultBuildOptions(0, ":mozilla:dist:viewer:", "");
my($do_checkout) = 1;
my($do_build) = 0;
RunBuild($do_checkout, $do_build, \%inputfiles, $prefs_file_name);

View File

@@ -1,4 +0,0 @@
This directory is merely here to test the project editor server. It will go away after
it is validated. For more information, see http://camelot.
Testing watchers.

Binary file not shown.

Binary file not shown.

View File

@@ -1 +0,0 @@
// test1.cpp

View File

@@ -1 +0,0 @@
// test2.cpp

Binary file not shown.

View File

@@ -1 +0,0 @@
// test2.cpp

Binary file not shown.

Binary file not shown.

View File

@@ -1,4 +0,0 @@
// test2.cpp
as
dfasdf

View File

@@ -1,12 +0,0 @@
#include <stdio.h>
#include <ConditionalMacros.h>
int main(int argc, char* argv[])
{
FILE* file = fopen("BuildSystemInfo.pm", "w");
if (file != NULL) {
fprintf(file, "$UNIVERSAL_INTERFACES_VERSION=0x%04X;\n", UNIVERSAL_INTERFACES_VERSION);
fclose(file);
}
}

View File

@@ -1,30 +0,0 @@
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Brian Ryner <bryner@netscape.com>
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
DIRS = resources src public
include $(topsrcdir)/config/rules.mk

View File

@@ -1,41 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "MacSharedPrefix.h"
#include "PIPNSSCommon.h"

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#define NSS_3_4

View File

@@ -1,41 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.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 NPL, 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 NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "MacSharedPrefix_debug.h"
#include "PIPNSSCommon.h"

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +0,0 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Javier Delgadillo
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
DEPTH=..\..\..
include <$(DEPTH)/config/config.mak>
DIRS = public src resources
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,62 +0,0 @@
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Brian Ryner <bryner@netscape.com>
# Javier Delgadillo <javi@netscape.com>
# Terry Hayes <thayes@netscape.com>
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
MODULE = pipnss
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
XPIDLSRCS = \
nsIBadCertListener.idl \
nsICertSelect.idl \
nsIX509Cert.idl \
nsIX509CertDB.idl \
nsIPKCS11Slot.idl \
nsIPK11TokenDB.idl \
nsINSSDialogs.idl \
nsISSLStatus.idl \
nsICertOutliner.idl \
nsIKeygenThread.idl \
nsICMSSecureMessage.idl \
nsICMS.idl \
nsIUserCertPicker.idl \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,63 +0,0 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Javier Delgadillo
# Terry Hayes <thayes@netscape.com>
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
MODULE = pipnss
DEPTH=..\..\..\..
IGNORE_MANIFEST=1
include <$(DEPTH)/config/config.mak>
XPIDL_INCLUDES=-I$(DEPTH)\dist\idl
XPIDLSRCS= \
.\nsIBadCertListener.idl \
.\nsICertSelect.idl \
.\nsIX509Cert.idl \
.\nsIX509CertDB.idl \
.\nsIPKCS11Slot.idl \
.\nsIPK11TokenDB.idl \
.\nsINSSDialogs.idl \
.\nsISSLStatus.idl \
.\nsICertOutliner.idl \
.\nsIKeygenThread.idl \
.\nsICMSSecureMessage.idl \
.\nsICMS.idl \
.\nsIUserCertPicker.idl \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,61 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
interface nsIX509Cert;
interface nsITransportSecurityInfo;
[scriptable, uuid(86960956-edb0-11d4-998b-00b0d02354a0)]
interface nsIBadCertListener : nsISupports {
const short UNINIT_ADD_FLAG = -1;
const short ADD_TRUSTED_FOR_SESSION =1;
const short ADD_TRUSTED_PERMANENTLY = 2;
boolean unknownIssuer(in nsITransportSecurityInfo socketInfo,
in nsIX509Cert cert,
out short certAddType);
boolean mismatchDomain(in nsITransportSecurityInfo socketInfo,
in wstring targetURL,
in nsIX509Cert cert);
boolean certExpired(in nsITransportSecurityInfo socketInfo,
in nsIX509Cert cert);
void crlNextupdate(in nsITransportSecurityInfo socketInfo,
in wstring targetURL, in nsIX509Cert cert);
};

View File

@@ -1,123 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): David Drinan <ddrinan@netscape.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 ***** */
#include "nsISupports.idl"
interface nsISupportsArray;
interface nsIX509Cert;
%{ C++
typedef void (*NSSCMSContentCallback)(void *arg, const char *buf, unsigned long len);
%}
native NSSCMSContentCallback(NSSCMSContentCallback);
[ptr] native UnsignedCharPtr(unsigned char);
/*
* nsIHash
* Generic hashing interface
*/
[uuid(a31a3028-ae28-11d5-ba4b-00108303b117)]
interface nsIHash : nsISupports
{
const short HASH_AlgNULL = 0;
const short HASH_AlgMD2 = 1;
const short HASH_AlgMD5 = 2;
const short HASH_AlgSHA1 = 3;
const unsigned long MD2_LEN = 16;
const unsigned long MD5_LEN = 16;
const unsigned long SHA1_LEN = 20;
const unsigned long MAX_HASH_LEN = SHA1_LEN;
unsigned long resultLen(in short aAlg);
void create(in short aAlg);
void begin();
void update(in UnsignedCharPtr aBuf, in unsigned long aLen);
void end(in UnsignedCharPtr aHash, out unsigned long aLen, in unsigned long aMaxLen);
};
/**
* nsICMSMessage
* Interface to a CMS Message
*/
[uuid(a4557478-ae16-11d5-ba4b-00108303b117)]
interface nsICMSMessage : nsISupports
{
void contentIsSigned(out boolean aSigned);
void contentIsEncrypted(out boolean aEncrypted);
void getSignerCommonName(out string aName);
void getSignerEmailAddress(out string aEmail);
void verifySignature();
void verifyDetachedSignature(in UnsignedCharPtr aDigestData, in unsigned long aDigestDataLen);
void CreateEncrypted(in nsISupportsArray aRecipientCerts);
void CreateSigned(in nsIX509Cert scert, in nsIX509Cert ecert, in UnsignedCharPtr aDigestData, in unsigned long aDigestDataLen);
};
/**
* nsICMSDecoder
* Interface to decode an CMS message
*/
[uuid(65244a06-a342-11d5-ba47-00108303b117)]
interface nsICMSDecoder : nsISupports
{
void start(in NSSCMSContentCallback cb, in voidPtr arg);
void update(in string aBuf, in long aLen);
void finish(out nsICMSMessage msg);
};
/**
* nsICMSEncoder
* Interface to Encode an CMS message
*/
[uuid(a15789aa-8903-462b-81e9-4aa2cff4d5cb)]
interface nsICMSEncoder : nsISupports
{
void start(in nsICMSMessage aMsg, in NSSCMSContentCallback cb, in voidPtr arg);
void update(in string aBuf, in long aLen);
void finish();
void encode(in nsICMSMessage aMsg);
};
/**
* NS_CMSMESSAGE_CONTRACTID - contract id of a class that
* implements nsICMSMessage
*/
%{C++
#define NS_CMSDECODER_CONTRACTID "@mozilla.org/nsCMSDecoder;1"
#define NS_CMSENCODER_CONTRACTID "@mozilla.org/nsCMSEncoder;1"
#define NS_CMSMESSAGE_CONTRACTID "@mozilla.org/nsCMSMessage;1"
#define NS_HASH_CONTRACTID "@mozilla.org/nsHash;1"
%}

View File

@@ -1,78 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Terry Hayes <thayes@netscape.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 ***** */
#include "nsISupports.idl"
interface nsIX509Cert;
/**
* nsICMSManager (service)
* Interface to access users certificate store
*/
[scriptable, uuid(14b4394a-1dd2-11b2-b4fd-ba4a194fe97e)]
interface nsICMSSecureMessage : nsISupports
{
/**
* getCertByPrefID - a BASE64 string representing a user's
* certificate (or NULL if there isn't one)
*/
string getCertByPrefID(in string certID);
/**
* decodeCert - decode a BASE64 string into an X509Certificate object
*/
nsIX509Cert decodeCert(in string value);
/**
* sendMessage - send a text message to the recipient indicated
* by the base64-encoded cert.
*/
string sendMessage(in string msg, in string cert);
/**
* receiveMessage - recieve an encrypted (enveloped) message
*/
string receiveMessage(in string msg);
};
/**
* NS_CMSMESSAGE_CONTRACTID - contract id of a class that
* implements nsICMSMessage
*/
%{C++
#define NS_CMSSECUREMESSAGE_CONTRACTID "@mozilla.org/nsCMSSecureMessage;1"
%}

View File

@@ -1,57 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
#include "nsIOutlinerView.idl"
#include "nsIX509Cert.idl"
[scriptable, uuid(4ea60761-31d6-491d-9e34-4b53a26c416c)]
interface nsICertOutliner : nsIOutlinerView {
void loadCerts(in unsigned long type);
nsIX509Cert getCert(in unsigned long index);
};
%{C++
#define NS_CERTOUTLINER_CID { 0x4ea60761, 0x31d6, 0x491d, \
{ 0x9e, 0x34, 0x4b, 0x53, 0xa2, 0x6c, 0x41, 0x6c } }
#define NS_CERTOUTLINER_CONTRACTID "@mozilla.org/security/nsCertOutliner;1"
%}

View File

@@ -1,47 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
interface nsIX509Cert;
interface nsIChannelSecurityInfo;
[scriptable, uuid(3cac403c-edb3-11d4-998b-00b0d02354a0)]
interface nsICertSelect : nsISupports {
nsIX509Cert selectClientAuthCert(in nsIChannelSecurityInfo socketInfo,
in PRUint32 count,
[array, size_is(count)] in nsIX509Cert certs);
};

View File

@@ -1,57 +0,0 @@
/*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*/
// make sure to include all the required file headers
#include "nsISupports.idl"
#include "nsIDOMWindowInternal.idl"
/**
* nsIKeygenThread
* This is used to communicate with the thread generating a key pair,
* to be used by the dialog displaying status information.
*/
[scriptable, uuid(195763b8-1dd2-11b2-a843-eb44e44aaa37)]
interface nsIKeygenThread : nsISupports
{
/**
* startKeyGeneration - run the thread
* A user interface implementing this interface needs to
* call this method as soon as the status information
* is displaying. This will trigger key generation.
* To allow the closure of the status information,
* the thread needs a handle to the displayed window.
*/
void startKeyGeneration(in nsIDOMWindowInternal statusDialog);
/**
* userCanceled - notify the thread
* If the user canceled, the thread is no longer allowed to
* close the dialog. However, if the thread already closed
* it, we are not allowed to close it.
*/
void userCanceled(out boolean threadAlreadyClosedDialog);
};
%{ C++
// {195763b8-1dd2-11b2-a843-eb44e44aaa37}
#define NS_KEYGENTHREAD_CID \
{ 0x195763b8, 0x1dd2, 0x11b2, { 0xa8, 0x43, 0xeb, 0x44, 0xe4, 0x4a, 0xaa, 0x37 } }
#define NS_KEYGENTHREAD_CONTRACTID "@mozilla.org/security/keygenthread;1"
%}

View File

@@ -1,189 +0,0 @@
/*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*/
#include "nsISupports.idl"
#include "nsIX509Cert.idl"
#include "nsIX509CertDB.idl"
interface nsIInterfaceRequestor;
interface nsIKeygenThread;
/**
* nsITokenPasswordDialogs
* This is the interface for setting and changing password
* on a PKCS11 token.
*/
[scriptable, uuid(be26b580-1dd1-11b2-9946-c598d0d07727)]
interface nsITokenPasswordDialogs : nsISupports
{
/**
* setPassword - sets the password/PIN on the named token.
* The canceled output value should be set to TRUE when
* the user (or implementation) cancels the operation.
*/
void setPassword(in nsIInterfaceRequestor ctx, in wstring tokenName,
out boolean canceled);
void getPassword(in nsIInterfaceRequestor ctx,
in wstring tokenName,
out wstring password,
out boolean canceled);
};
/**
* nsIGeneratingKeypairInfoDialogs
* This is the interface for giving feedback to the user
* while generating a key pair.
*/
[scriptable, uuid(11bf5cdc-1dd2-11b2-ba6a-c76afb326fa1)]
interface nsIGeneratingKeypairInfoDialogs : nsISupports
{
void displayGeneratingKeypairInfo(in nsIInterfaceRequestor ctx,
in nsIKeygenThread runnable);
};
/**
* nsINSSDialogs - a collection of functions that
* implement activities that may require interaction
* with the user.
*/
[scriptable, uuid(4a8c5584-1dd2-11b2-bfff-f232dbfab27e)]
interface nsINSSDialogs : nsISupports
{
/**
* This is the base class for NSSDialogs. It must support all
* the interfaces for dialogs that it wants to support.
*
* nsITokenPasswordDialogs is one such implementation.
*/
};
/**
* nsICertificateDialogs
* Provides UI for certificate-related dialogs.
*/
[scriptable, uuid(a03ca940-09be-11d5-ac5d-000064657374)]
interface nsICertificateDialogs : nsISupports
{
/**
* downloadCACert
* UI shown when a user is asked to download a new CA cert. Provides
* user with ability to choose trust settings for the cert.
*/
void downloadCACert(in nsIInterfaceRequestor ctx,
in nsIX509Cert cert,
out unsigned long trust,
out boolean canceled);
void cACertExists(in nsIInterfaceRequestor ctx,
out boolean canceled);
void setPKCS12FilePassword(in nsIInterfaceRequestor ctx,
out wstring password,
out boolean canceled);
void getPKCS12FilePassword(in nsIInterfaceRequestor ctx,
out wstring password,
out boolean canceled);
void viewCert(in nsIX509Cert cert);
void crlImportStatusDialog(in nsIInterfaceRequestor ctx,
in nsICrlEntry nameInDB);
};
/**
* nsIClientAuthDialog
* Provides UI for SSL client-auth dialogs.
*/
[scriptable, uuid(fa4c7520-1433-11d5-ba24-00108303b117)]
interface nsIClientAuthDialogs : nsISupports
{
/**
* display
* UI shown when a user is asked to do SSL client auth.
*/
void ChooseCertificate(in nsIInterfaceRequestor ctx,
in wstring cn,
in wstring organization,
in wstring issuer,
[array, size_is(count)] in wstring certNickList,
[array, size_is(count)] in wstring certDetailsList,
in PRUint32 count,
out PRInt32 selectedIndex,
out boolean canceled);
};
/**
* nsICertPicker
* Provides generic UI for choosing a certificate
*/
[scriptable, uuid(51d59b08-1dd2-11b2-ad4a-a51b92f8a184)]
interface nsICertPickDialogs : nsISupports
{
/**
* PickCertificate
* General purpose certificate prompter
*/
void PickCertificate(in nsIInterfaceRequestor ctx,
in wstring title,
in wstring infoPrompt,
[array, size_is(count)] in wstring certNickList,
[array, size_is(count)] in wstring certDetailsList,
in PRUint32 count,
out PRInt32 selectedIndex,
out boolean canceled);
};
[scriptable, uuid(bb4bae9c-39c5-11d5-ba26-00108303b117)]
interface nsITokenDialogs : nsISupports
{
void ChooseToken(in nsIInterfaceRequestor ctx,
[array, size_is(count)] in wstring tokenNameList,
in PRUint32 count,
out wstring tokenName,
out boolean canceled);
};
[scriptable, uuid(1f8fe77e-1dd2-11b2-8dd2-e55f8d3465b8)]
interface nsIDOMCryptoDialogs : nsISupports
{
/**
* This method is used to warn the user the web site is
* trying to escrow the generated private key. This
* method should return true if the user wants to proceed
* and false if the user cancels the action.
*/
boolean ConfirmKeyEscrow(in nsIX509Cert escrowAuthority);
};
/**
* NS_NSSDIALOGS_CONTRACTID - contract id of a service that
* implements nsINSSDialogs (and possibly other interfaces)
* that provide interaction with the user.
*/
%{C++
#define NS_NSSDIALOGS_CONTRACTID "@mozilla.org/nsNSSDialogs;1"
%}

View File

@@ -1,109 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*/
#include "nsISupports.idl"
#include "nsIEnumerator.idl"
/**
* The PK11 Token Database provides access to the PK11 modules
* that are installed, and the tokens that are available.
* Interfaces: nsIPK11TokenDB
* Threading: ??
*/
%{C++
#define NS_PK11TOKENDB_CONTRACTID "@mozilla.org/security/pk11tokendb;1"
%}
[scriptable, uuid(51191434-1dd2-11b2-a17c-e49c4e99a4e3)]
interface nsIPK11Token : nsISupports
{
const long ASK_EVERY_TIME = -1;
const long ASK_FIRST_TIME = 0;
const long ASK_EXPIRE_TIME = 1;
/*
* The name of the token
*/
readonly attribute wstring tokenName;
readonly attribute wstring tokenLabel;
readonly attribute wstring tokenManID;
readonly attribute wstring tokenHWVersion;
readonly attribute wstring tokenFWVersion;
readonly attribute wstring tokenSerialNumber;
/*
* Login information
*/
boolean isLoggedIn();
void login(in boolean force);
void logout();
/*
* Reset password
*/
void reset();
/*
* Password information
*/
readonly attribute long minimumPasswordLength;
readonly attribute boolean needsUserInit;
boolean checkPassword(in wstring password); /* Logs out if check fails */
void initPassword(in wstring initialPassword);
void changePassword(in wstring oldPassword, in wstring newPassword);
long getAskPasswordTimes();
long getAskPasswordTimeout();
void setAskPasswordDefaults([const] in long askTimes, [const] in long timeout);
/*
* Other attributes
*/
boolean isHardwareToken();
boolean needsLogin();
boolean isFriendly();
};
/**
* nsIPK11TokenDB - Manages PK11 Tokens
*/
[scriptable, uuid(4ee28c82-1dd2-11b2-aabf-bb4017abe395)]
interface nsIPK11TokenDB : nsISupports
{
/*
* Get the internal key database token
*/
nsIPK11Token getInternalKeyToken();
/*
* Find a token by name
*/
nsIPK11Token findTokenByName(in wstring tokenName);
/*
* List all tokens
*/
nsIEnumerator listTokens();
};

View File

@@ -1,103 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
#include "nsIEnumerator.idl"
#include "nsIPK11TokenDB.idl"
%{C++
#define NS_PKCS11MODULEDB_CONTRACTID "@mozilla.org/security/pkcs11moduledb;1"
%}
[scriptable, uuid(c2d4f296-ee60-11d4-998b-00b0d02354a0)]
interface nsIPKCS11Slot : nsISupports {
readonly attribute wstring name;
readonly attribute wstring desc;
readonly attribute wstring manID;
readonly attribute wstring HWVersion;
readonly attribute wstring FWVersion;
const unsigned long SLOT_DISABLED = 0;
const unsigned long SLOT_NOT_PRESENT = 1;
const unsigned long SLOT_UNINITIALIZED = 2;
const unsigned long SLOT_NOT_LOGGED_IN = 3;
const unsigned long SLOT_LOGGED_IN = 4;
const unsigned long SLOT_READY = 5;
readonly attribute unsigned long status;
/* This is really a workaround for now. All of the "slot" functions
* (isTokenPresent(), etc.) are in nsIPK11Token. For now, return the
* token and handle those things there.
*/
nsIPK11Token getToken();
/* more fun with workarounds - we're referring to everything by token name */
readonly attribute wstring tokenName;
};
[scriptable, uuid(8a44bdf9-d1a5-4734-bd5a-34ed7fe564c2)]
interface nsIPKCS11Module : nsISupports
{
readonly attribute wstring name;
readonly attribute wstring libName;
nsIPKCS11Slot findSlotByName(in wstring name);
nsIEnumerator listSlots();
};
[scriptable, uuid(ff9fbcd7-9517-4334-b97a-ceed78909974)]
interface nsIPKCS11ModuleDB : nsISupports
{
nsIPKCS11Module getInternal();
nsIPKCS11Module getInternalFIPS();
nsIPKCS11Module findModuleByName(in wstring name);
nsIPKCS11Slot findSlotByName(in wstring name);
nsIEnumerator listModules();
void toggleFIPSMode();
readonly attribute boolean isFIPSEnabled;
};

View File

@@ -1,46 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
interface nsIX509Cert;
[scriptable, uuid(7b2ca1ca-1dd2-11b2-87ec-d217dbe22b85)]
interface nsISSLStatus : nsISupports {
readonly attribute nsIX509Cert serverCert;
readonly attribute string cipherName;
readonly attribute PRUint32 keyLength;
readonly attribute PRUint32 secretKeyLength;
};

View File

@@ -1,57 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Kai Engert <kaie@netscape.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 ***** */
#include "nsISupports.idl"
interface nsIX509Cert;
interface nsIInterfaceRequestor;
[scriptable, uuid(06d018e0-d41b-4629-a4fc-daaa6029888e)]
interface nsIUserCertPicker : nsISupports {
nsIX509Cert pickByUsage(in nsIInterfaceRequestor ctx,
in wstring title,
in wstring infoPrompt,
in PRInt32 certUsage, // as defined by NSS enum SECCertUsage
in boolean allowInvalid,
in boolean allowDuplicateNicknames,
out boolean canceled);
};
%{C++
#define NS_CERT_PICKER_CONTRACTID "@mozilla.org/user_cert_picker;1"
#define NS_CERT_PICKER_CLASSNAME "Cert Picker Object"
%}

View File

@@ -1,198 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
#include "nsISupportsArray.idl"
[scriptable, uuid(e701dfd8-1dd1-11b2-a172-ffa6cc6156ad)]
interface nsIX509CertValidity : nsISupports {
readonly attribute PRTime notBefore;
readonly attribute wstring notBeforeLocalTime;
readonly attribute wstring notBeforeGMT;
readonly attribute PRTime notAfter;
readonly attribute wstring notAfterLocalTime;
readonly attribute wstring notAfterGMT;
};
//
// Overview of how this ASN1 interface is intended to
// work.
//
// First off, the nsIASN1Sequence is any type in ASN1
// that consists of sub-elements (ie SEQUENCE, SET)
// nsIASN1Printable Items are all the other types that
// can be viewed by themselves without interpreting further.
// Examples would include INTEGER, UTF-8 STRING, OID.
// These are not intended to directly reflect the numberous
// types that exist in ASN1, but merely an interface to ease
// producing a tree display the ASN1 structure of any DER
// object.
//
[scriptable, uuid(ba8bf582-1dd1-11b2-898c-f40246bc9a63)]
interface nsIASN1Object : nsISupports {
const unsigned long ASN1_END_CONTENTS = 0;
const unsigned long ASN1_BOOLEAN = 1;
const unsigned long ASN1_INTEGER = 2;
const unsigned long ASN1_BIT_STRING = 3;
const unsigned long ASN1_OCTET_STRING = 4;
const unsigned long ASN1_NULL = 5;
const unsigned long ASN1_OBJECT_ID = 6;
const unsigned long ASN1_ENUMERATED = 10;
const unsigned long ASN1_UTF8_STRING = 12;
const unsigned long ASN1_SEQUENCE = 16;
const unsigned long ASN1_SET = 17;
const unsigned long ASN1_PRINTABLE_STRING = 19;
const unsigned long ASN1_T61_STRING = 20;
const unsigned long ASN1_IA5_STRING = 22;
const unsigned long ASN1_UTC_TIME = 23;
const unsigned long ASN1_GEN_TIME = 24;
const unsigned long ASN1_VISIBLE_STRING = 26;
const unsigned long ASN1_UNIVERSAL_STRING = 28;
const unsigned long ASN1_BMP_STRING = 30;
const unsigned long ASN1_HIGH_TAG_NUMBER = 31;
const unsigned long ASN1_CONTEXT_SPECIFIC = 32;
const unsigned long ASN1_APPLICATION = 33;
const unsigned long ASN1_PRIVATE = 34;
// This will be either one of the const
// values above.
attribute unsigned long type;
attribute unsigned long tag;
attribute wstring displayName;
attribute wstring displayValue;
};
[scriptable, uuid(b6b957e6-1dd1-11b2-89d7-e30624f50b00)]
interface nsIASN1Sequence : nsIASN1Object {
attribute nsISupportsArray ASN1Objects;
attribute boolean processObjects;
attribute boolean showObjects;
};
[scriptable, uuid(114e1142-1dd2-11b2-ac26-b6db19d9184a)]
interface nsIASN1PrintableItem : nsIASN1Object {
[noscript] void setData(in charPtr data, in unsigned long len);
[noscript] void getData(out charPtr data, out unsigned long len);
};
[scriptable, uuid(f0980f60-ee3d-11d4-998b-00b0d02354a0)]
interface nsIX509Cert : nsISupports {
/*
* attributes for certs
*/
readonly attribute wstring nickname;
readonly attribute wstring emailAddress;
readonly attribute wstring commonName;
readonly attribute wstring organization;
readonly attribute wstring organizationalUnit;
readonly attribute wstring subjectName;
readonly attribute wstring issuerName;
readonly attribute wstring serialNumber;
readonly attribute wstring rsaPubModulus;
readonly attribute wstring sha1Fingerprint;
readonly attribute wstring md5Fingerprint;
readonly attribute wstring issuedDate;
readonly attribute wstring expiresDate;
readonly attribute wstring tokenName;
readonly attribute wstring issuerCommonName;
readonly attribute wstring issuerOrganization;
readonly attribute wstring issuerOrganizationUnit;
readonly attribute nsIX509Cert issuer;
readonly attribute nsIX509CertValidity validity;
readonly attribute string dbKey;
readonly attribute string windowTitle;
readonly attribute boolean usesOCSP;
/*
* enums for certs
*/
const unsigned long UNKNOWN_CERT = 0;
const unsigned long CA_CERT = 1 << 0;
const unsigned long USER_CERT = 1 << 1;
const unsigned long EMAIL_CERT = 1 << 2;
const unsigned long SERVER_CERT = 1 << 3;
// errors in verifying certs
const unsigned long VERIFIED_OK = 0;
const unsigned long NOT_VERIFIED_UNKNOWN = 1 << 0;
const unsigned long CERT_REVOKED = 1 << 1;
const unsigned long CERT_EXPIRED = 1 << 2;
const unsigned long CERT_NOT_TRUSTED = 1 << 3;
const unsigned long ISSUER_NOT_TRUSTED = 1 << 4;
const unsigned long ISSUER_UNKNOWN = 1 << 5;
const unsigned long INVALID_CA = 1 << 6;
/*
* accessors for certs
*/
nsISupportsArray getChain();
void getUsages(out PRUint32 verified,
out PRUint32 count,
[array, size_is(count)] out wstring usages);
void getPurposes(out PRUint32 verified, out wstring purposes);
/*
* This method is here to make it easier to view a cert.
* It will get the implemention of the nsICertificateDialogs
* interface and call the viewCert method passing itself
* as a parameter.
*/
void view();
/*
* This is the attribute which describes the ASN1 layout
* of the certificate. This can be used when doing a
* "pretty print" of the certificate's ASN1 structure.
*/
readonly attribute nsIASN1Object ASN1Structure;
[noscript] unsigned long getRawDER(out charPtr result);
};
%{C++
#define NS_X509CERT_CID { 0xf0980f60, 0xee3d, 0x11d4, \
{ 0x99, 0x8b, 0x00, 0xb0, 0xd0, 0x23, 0x54, 0xa0 } }
#define NS_X509CERT_CONTRACTID "@mozilla.org/security/x509cert;1"
%}

View File

@@ -1,298 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsISupports.idl"
interface nsISupportsArray;
interface nsIX509Cert;
interface nsIPK11Token;
interface nsILocalFile;
interface nsIInterfaceRequestor;
interface nsIURI;
%{C++
#define NS_X509CERTDB_CID { /* da48b3c0-1284-11d5-ac67-000064657374 */ \
0xda48b3c0, \
0x1284, \
0x11d5, \
{0xac, 0x67, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74} \
}
#define NS_X509CERTDB_CONTRACTID "@mozilla.org/security/x509certdb;1"
typedef int (*nsCertCompareFunc)(nsIX509Cert *a, nsIX509Cert *b);
%}
native nsCertCompareFunc(nsCertCompareFunc);
native nsAutoString(nsAutoString);
[ref] native nsAutoStringRef(nsAutoString);
[scriptable, uuid(96b2f5ae-4334-11d5-ba27-00108303b117)]
interface nsIOCSPResponder : nsISupports {
readonly attribute wstring responseSigner;
readonly attribute wstring serviceURL;
};
[scriptable, uuid(c185d920-4a3e-11d5-ba27-00108303b117)]
interface nsICrlEntry : nsISupports {
readonly attribute wstring org;
readonly attribute wstring orgUnit;
readonly attribute wstring lastUpdateLocale;
readonly attribute wstring nextUpdateLocale;
readonly attribute wstring nameInDb;
readonly attribute wstring lastFetchURL;
const unsigned long TYPE_AUTOUPDATE_TIME_BASED = 1;
const unsigned long TYPE_AUTOUPDATE_FREQ_BASED = 2;
wstring ComputeNextAutoUpdateTime(in unsigned long autoUpdateType,
in double noOfDays);
};
[scriptable, uuid(da48b3c0-1284-11d5-ac67-000064657374)]
interface nsIX509CertDB : nsISupports {
/* the database is responsible for managing cert trust */
const unsigned long UNTRUSTED = 0;
const unsigned long TRUSTED_SSL = 1 << 0;
const unsigned long TRUSTED_EMAIL = 1 << 1;
const unsigned long TRUSTED_OBJSIGN = 1 << 2;
nsIX509Cert getCertByNickname(in nsIPK11Token aToken,
in wstring aNickname);
/*
* getCertByDBKey
*
* Will find a certificate based on its dbkey
* retrieved by getting the dbKey attribute of
* the certificate.
*/
nsIX509Cert getCertByDBKey(in string aDBkey, in nsIPK11Token aToken);
/*
* getCertNicknames
*
* Obtain a list of certificate nicknames from the database.
* What the name is depends on type:
* user, ca, or server cert - the nickname
* email cert - the email address
*
* aToken - PKCS#11 token to get certs from (null for all tokens)
* aType - type of certificate to obtain (see nsIX509Cert)
* count, certNameList - the returned array of names
*/
void getCertNicknames(in nsIPK11Token aToken,
in unsigned long aType,
out unsigned long count,
[array, size_is(count)] out wstring certNameList);
/*
* getCertsByType
*
* Obtain a list of certs from the database.
*
*/
[notxpcom, noscript] boolean getCertsByType(in unsigned long aType,
in nsCertCompareFunc aCertCmpFn,
out nsISupportsArray certs);
/* Get the user encryption cert */
nsIX509Cert getEmailEncryptionCert(in wstring aNickname);
/* Get the user signing cert */
nsIX509Cert getEmailSigningCert(in wstring aNickname);
/* Get a cert by email address */
nsIX509Cert getCertByEmailAddress(in nsIPK11Token aToken,
in string aEmailAddress);
/*
* importCertificates
* Use this to import a stream sent down as a mime type into
* the default cert db. The stream may consist of one or more
* certificates.
* XXX We may want to add a parameter for a PK11 Token where
* the certs will utlimtately live. Currently, they'll
* be placed in the default token.
*/
[noscript] void importCertificates(in charPtr data,
in unsigned long length,
in unsigned long type,
in nsIInterfaceRequestor ctx);
[noscript] void importEmailCertificate(in charPtr data,
in unsigned long length,
in nsIInterfaceRequestor ctx);
/*
* importCertificate
*
* Import a user certificate into the database.
* XXX This method and the importCertificate should be merged into one.
*/
[noscript] void importUserCertificate(in charPtr data,
in unsigned long length,
in nsIInterfaceRequestor ctx);
/*
* deleteCertificate
*
* Remove a certificate from the database.
*/
void deleteCertificate(in nsIX509Cert aCert);
/*
* setCertTrust
*
* The certificate database is responsible for managing cert trust. This
* function allows clients to set the trust settings for a cert.
*/
void setCertTrust(in nsIX509Cert cert,
in unsigned long type,
in unsigned long trust);
/*
* getCertTrust
*
* Get the trust settings for this certificate.
*
* trustType = TRUSTED_SSL => returns true if cert is trusted SSL cert
* trustType = TRUSTED_EMAIL => returns true if cert is trusted email cert
* trustType = TRUSTED_OBJSIGN => returns true if cert is trusted
* object signing cert
*/
boolean getCertTrust(in nsIX509Cert cert,
in unsigned long certType,
in unsigned long trustType);
/*
* importPKCS12File
*
* Import a PKCS#12 file contain cert(s) and key(s) into the database.
*/
void importPKCS12File(in nsIPK11Token aToken,
in nsILocalFile aFile);
/*
* exportPKCS12File
*
* Export a set of certs and keys from the database to a PKCS#12 file.
*/
void exportPKCS12File(in nsIPK11Token aToken,
in nsILocalFile aFile,
in PRUint32 count,
[array, size_is(count)] in nsIX509Cert aCerts);
//[array, size_is(count)] in wstring aCertNames);
/*
* getOCSPResponders
*
* Export a set of OCSP responders i.e. CA names and (optional) URLs.
*/
nsISupportsArray getOCSPResponders();
/*
* importCrl
*
* Import a CRL into the database.
*/
[noscript] void importCrl(in charPtr data,
in unsigned long length,
in nsIURI uri,
in PRUint32 type,
in PRBool doSilentDownload,
in wstring crlKey);
/*
* update crl from url
* update an existing crl from the last fetched url. Needed for the update
* button in crl manager
*/
boolean updateCRLFromURL(in wstring url, in wstring key);
/*
* getCrls
*
* Get a list of Crl entries in the DB.
*/
nsISupportsArray getCrls();
/*
* deleteCrl
*
* Delete the crl.
*/
void deleteCrl(in PRUint32 crlIndex);
/* This would reschedule the autoupdate of crls with auto update enable.
* Most likely to be called when update prefs are changed, or when a crl
* is deleted, etc. However, this might not be the most relevant place for
* this api, but unless we have a separate crl handler object....
*/
void rescheduleCRLAutoUpdate();
/*
* Query about the status of OCSP
*/
readonly attribute boolean ocspOn;
/*
* Use this to temporarily disable OCSP checking.
* Needed if OCSP checks slow down UI rendering too much.
* A call to this should be followed with a call to
* enableOCSP soon afterwards.
*/
void disableOCSP();
/*
* Sets the OCSP options to correspond with the preferences
* values.
*/
void enableOCSP();
/*
* decode base64 certificate and return a new nsIX509Cert instance
*
*/
nsIX509Cert constructX509FromBase64(in string base64);
};

View File

@@ -1,33 +0,0 @@
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Brian Ryner <bryner@netscape.com>
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/rules.mk
libs::
$(REGCHROME) content pipnss pipnss.jar
$(REGCHROME) locale en-US/pipnss en-US.jar

View File

@@ -1,18 +0,0 @@
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:chrome="http://www.mozilla.org/rdf/chrome#">
<!-- list all the packages being supplied by this jar -->
<RDF:Seq about="urn:mozilla:package:root">
<RDF:li resource="urn:mozilla:package:pipnss"/>
</RDF:Seq>
<!-- package information -->
<RDF:Description about="urn:mozilla:package:pipnss"
chrome:displayName="pipnss"
chrome:author="PSM Team"
chrome:name="pipnss"
chrome:localeVersion="0.9.8">
</RDF:Description>
</RDF:RDF>

View File

@@ -1,6 +0,0 @@
pipnss.jar:
content/pipnss/contents.rdf (content/contents.rdf)
en-US.jar:
locale/en-US/pipnss/contents.rdf (locale/en-US/contents.rdf)
locale/en-US/pipnss/pipnss.properties (locale/en-US/pipnss.properties)

View File

@@ -1,26 +0,0 @@
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:chrome="http://www.mozilla.org/rdf/chrome#">
<!-- list all the locales being supplied by this jar -->
<RDF:Seq about="urn:mozilla:locale:root">
<RDF:li resource="urn:mozilla:locale:en-US"/>
</RDF:Seq>
<!-- locale information -->
<RDF:Description about="urn:mozilla:locale:en-US"
chrome:displayName="English (US)"
chrome:author="PSM Team"
chrome:name="en-US">
<chrome:packages>
<RDF:Seq about="urn:mozilla:locale:en-US:packages">
<RDF:li resource="urn:mozilla:locale:en-US:pipnss"/>
</RDF:Seq>
</chrome:packages>
</RDF:Description>
<!-- Version Information. State that we work only with major version of this
package. -->
<RDF:Description about="urn:mozilla:locale:en-US:pipnss"
chrome:localeVersion="0.9.8"/>
</RDF:RDF>

View File

@@ -1,203 +0,0 @@
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Javier Delgadillo <javi@netscape.com>
# Brian Ryner <bryner@netscape.com>
# Terry Hayes <thayes@netscape.com>
#
SignedBy=Signed by %S
CertPassPrompt=Please enter the master password for the %S.
RootCertModuleName=Builtin Roots Module
ManufacturerID=Mozilla.org
LibraryDescription=PSM Internal Crypto Services
TokenDescription=Generic Crypto Services
PrivateTokenDescription=Software Security Device
SlotDescription=PSM Internal Cryptographic Services
PrivateSlotDescription=PSM Private Keys
FipsSlotDescription=PSM Internal FIPS-140-1 Cryptographic Services
FipsPrivateSlotDescription=PSM FIPS-140-1 User Private Key Services
InternalToken=Software Security Device
VerifySSLClient=SSL Client Certificate
VerifySSLServer=SSL Server Certificate
VerifySSLStepUp=SSL Server with Step-up
VerifySSLCA=SSL Certificate Authority
VerifyEmailSigner=Email Signer Certificate
VerifyEmailRecip=Email Recipient Certificate
VerifyProtectObjSign=Protected Object Signer
VerifyObjSign=Object Signer
VerifyUserImport=User Import Cert
VerifyCAVerifier=CA Verifier
VerifyStatusResponder=Status Responder Certificate
VerifyAnyCA=Any Certificate Authority
HighGrade=2048 (High Grade)
MediumGrade=1024 (Medium Grade)
LowGrade= 512 (Low Grade)
nick_template=%1$s's %2$s ID
nick_template_with_num=%1$s's %2$s ID #%3$d
#These are the strings set for the ASN1 objects in a certificate.
CertDumpCertificate=Certificate
CertDumpVersion=Version
CertDumpVersion1=Version 1
CertDumpVersion2=Version 2
CertDumpVersion3=Version 3
CertDumpSerialNo=Serial Number
CertDumpOID=Object Identifier
CertDumpMD2WithRSA=PKCS #1 MD2 With RSA Encryption
CertDumpMD5WithRSA=PKCS #1 MD5 With RSA Encryption
CertDumpSHA1WithRSA=PKCS #1 SHA-1 With RSA Encryption
CertDumpDefOID=Object Identifier (%S)
CertDumpNULL=NULL
CertDumpIssuer=Issuer
CertDumpSubject=Subject
CertDumpRDN=Relative Distinguished Name
CertDumpATV=Attribute Type and Value
CertDumpAVACountry=C
CertDumpAVAState=ST
CertDumpAVALocality=L
CertDumpAVAOrg=O
CertDumpAVAOU=OU
CertDumpAVACN=CN
CertDumpUserID=UID
CertDumpPK9Email=E
CertDumpAVADN=DN
CertDumpAVADC=DC
CertDumpValidity=Validity
CertDumpNotBefore=Not Before
CertDumpNotAfter=Not After
CertDumpSPKI=Subject Public Key Info
CertDumpSPKIAlg=Subject Public Key Algorithm
CertDumpAlgID=Algorithm Identifier
CertDumpParams=Algorithm Parameters
CertDumpRSAEncr=PKCS #1 RSA Encryption
CertDumpIssuerUniqueID=Issuer Unique ID
CertDumpSubjPubKey=Subject's Public Key
CertDumpSubjectUniqueID=Subject Unique ID
CertDumpExtensions=Extensions
CertDumpCertType=Netscape Certificate Type
CertDumpKeyUsage=Certificate Key Usage
CertDumpAuthKeyID=Certificate Authority Key Identifier
CertDumpCertTypeEmail=Email
CertDumpEmailCA=Email Certificate Authority
CertDumpKUSign=Signing
CertDumpKUNonRep=Non-repudiation
CertDumpKUEnc=Key Encipherment
CertDumpKUDEnc=Data Encipherment
CertDumpKUKA=Key Agreement
CertDumpKUCertSign=Certificate Signer
CertDumpKUCRLSigner=CRL Signer
CertDumpCritical=Critical
CertDumpNonCritical=Not Critical
CertDumpSigAlg=Certificate Signature Algorithm
CertDumpCertSig=Certificate Signature Value
VerifySSLClient_p=Client
VerifySSLServer_p=Server
VerifySSLStepUp_p=Step-up
VerifySSLCA_p=SSL CA
VerifyEmailSigner_p=Sign
VerifyEmailRecip_p=Encrypt
VerifyProtectObjSign_p=Protected Object Signer
VerifyObjSign_p=Object Signer
VerifyUserImport_p=User Import
VerifyCAVerifier_p=CA Verifier
VerifyStatusResponder_p=Status Responder
VerifyAnyCA_p=CA
VerifiedTrue=true
VerifiedFalse=false
PK11BadPassword=The token password entered was incorrect.
SuccessfulP12Backup=Successfully backed up your security certificate(s) and private key(s).
SuccessfulP12Restore=Successfully restored your security certificate(s) and private key(s).
PKCS12PasswordInvalid=Could not decode PKCS #12 file. Perhaps the password you entered was incorrect?
PKCS12DecodeErr=Failed to decode the file. Either it is not in PKCS #12 format, has been corrupted, or the password you entered was incorrect.
PKCS12UnknownErrRestore=Failed to restore the PKCS #12 file for unknown reasons.
PKCS12UnknownErrBackup=Failed to create the PKCS #12 backup file for unknown reasons.
PKCS12UnknownErr=The PKCS #12 operation failed for unknown reasons.
PKCS12InfoNoSmartcardBackup=It is not possible to back up certificates from a hardware security device such as a smart card.
PKCS12DupData=The certificate and private key already exist on the security device.
AddModulePrompt=Are you sure you want to install this security module?
AddModuleName=Module Name: %S
AddModulePath=Path: %S
AddModuleSuccess=A new security module has been installed
AddModuleFailure=Unable to add module
AddModuleDup=Security Module already exists
DelModuleBadName=Invalid module name.
DelModuleWarning=Are you sure you want to delete this security module?
DelModuleError=Unable to delete module
DelModuleIntSuccess=Internal security module successfully deleted
DelModuleExtSuccess=External security module successfully deleted
ForcedBackup1=You should make a password-protected backup copy of your new security certificate and its associated private key.
ForcedBackup2=If you ever lose access to your private key by forgetting your personal security password, or by experiencing file corruption, you can restore this private key and certificate from this backup copy.
ForcedBackup3=To make a copy, click OK. If possible, you should save your backup copy on a floppy disk that you keep in a safe location.
UnknownCertIssuer=(Unknown Issuer)
UnknownCertOrg=(Unknown Organization)
AVATemplate=%S = %S
SSLDisabled=You cannot connect to %S because SSL is disabled.
SSL2Disabled=You cannot connect to %S because SSL version 2 is disabled.
SSLNoMatchingCiphers=%S and %S cannot communicate securely because they have no common encryption algorithms.
UsersCertRevoked=Could not establish an encrypted connection with %S because your certificate has been revoked.
UsersCertExpired=Could not establish an encrypted connection with %S because your certificate is expired.
UsersCertRejected=Could not establish an encrypted connection because your certificate was rejected by %S. Error Code: %S.
BadMac=%S received a message with incorrect Message Authentication Code. If the error occurs frequently, contact the website administrator.
PeerResetConnection=%S has closed the connection. Error Code: %S
HostResetConnection=The current transfer has been cancelled.
BadPassword=An incorrect password was provided.
BadDatabase=There is a problem with your certificate database [Error Code: %S].
BadServer=%S has sent an incorrect or unexpected message. Error Code: %S
BadClient=%S has received an incorrect or unexpected message. Error Code: %S
SSLGenericError=Error establishing an encrypted connection to %S. Error Code: %S.
TimeOut=Connection request timed out.
PeersCertUntrusted=Could not establish an encrypted connection because certificate presented by %S is not trusted.
PeersCertRevoked=Could not establish an encrypted connection because certificate presented by %S has been revoked.
PeersCertExpired=Could not establish an encrypted connection because certificate presented by %S has expired.
PeersCertWrongDomain=Could not establish an encrypted connection because certificate presented by %S is for a different domain.
PeersCertNoGood=Could not establish an encrypted connection because certificate presented by %S is invalid or corrupted. Error Code: %S
CRLExpired=Certificate Revocation List (CRL) from the CA certifying %S is past its Next Update date. Please update the CRL.
CRLNotYetValid=Certificate Revocation List (CRL) from the CA certifying %S is not yet valid. Please check your system clock.
CRLSigNotValid=Certificate Revocation List (CRL) from the CA certifying %S has an invalid digital signature.
CRLSNotValid=Certificate Revocation List (CRL) from the CA certifying %S is not valid.
OCSPMalformedRequest=Error trying to validate certificate from %S using OSCP - malformed request.
OCSPRequestNeedsSig=Error trying to validate certificate from %S using OSCP - request needs signature.
OCSPUnauthorizedReq=Error trying to validate certificate from %S using OSCP - unauthorized request.
OCSPServerError=Error trying to validate certificate from %S using OSCP - server error.
OCSPTryServerLater=Error trying to validate certificate from %S using OSCP - server is busy. Please try again later.
OCSPFutureResponse=Error trying to validate certificate from %S using OSCP - response contains a date which is in the future.
OCSPOldResponse=Error trying to validate certificate from %S using OSCP - old response.
OCSPCorruptedResponse=Error trying to validate certificate from %S using OSCP - corrupted or unknown response. Error Code: %S.
OCSPUnauthorizedResponse=Error trying to validate certificate from %S using OSCP - unauthorized response.
OCSPUnknownCert=Error trying to validate certificate from %S using OSCP - unknown certificate.
OCSPNoDefaultResponder=Error trying to validate certificate from %S using OSCP - no default responder specified.
OCSPDirLookup=Error trying to validate certificate from %S using OSCP - directory lookup error.
CertInfoIssuedFor=Issued to:
CertInfoIssuedBy=Issued by:
CertInfoValid=Valid
CertInfoFrom=from
CertInfoTo=to
CertInfoPurposes=Purposes
P12DefaultNickname=Imported Certificate
CrlImportSuccess=The browser successfully imported the certificate revocation list (CRL).
CrlImportFailure1=The browser cannot import the Certificate Revocation List (CRL).
CrlImportFailureExpired=A more recent version of this CRL is available.
CrlImportFailureBadSignature=CRL has an invalid Signature.
CrlImportFailureInvalid=New CRL has an invalid format.
CrlImportFailureOld=New CRL is older than the current one.
CrlImportFailureNotYetValid=The CRL is not yet valid. You might want to check your system clock.
CrlImportFailureNetworkProblem=Download of the CRL failed due to Network problems.
CrlImportFailureReasonUnknown=Error Importing CRL to local Database. Error Code:
CrlImportFailure2=Please ask your system administrator for assistance.
NSSInitProblem=Could not initialize the browser's security component. The most likely cause is problems with files in your browser's profile directory. Please check that this directory has no read/write restrictions and your hard disk is not full or close to full. It is recommended that you exit the browser and fix the problem. If you continue to use this browser session, you might see incorrect browser behaviour when accessing security features.

View File

@@ -1,42 +0,0 @@
#!nmake
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Javier Delgadillo
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
DEPTH=..\..\..\..
include <$(DEPTH)\config\rules.mak>
chrome::
$(REGCHROME) content pipnss pipnss.jar
$(REGCHROME) locale en-US/pipnss en-US.jar

View File

@@ -1,136 +0,0 @@
#! gmake
#
# 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 Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Javier Delgadillo <javi@netscape.com>
# Terry Hayes <thayes@netscape.com>
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = pipnss
LIBRARY_NAME = pipnss
IS_COMPONENT = 1
MODULE_NAME = NSS
EXPORT_LIBRARY = 1
META_COMPONENT = crypto
EXPORTS = \
$(NULL)
CPPSRCS = \
nsNSSCallbacks.cpp \
nsNSSComponent.cpp \
nsNSSIOLayer.cpp \
nsNSSModule.cpp \
nsSSLSocketProvider.cpp \
nsTLSSocketProvider.cpp \
nsSDR.cpp \
nsPK11TokenDB.cpp \
nsNSSCertificate.cpp \
nsPKCS12Blob.cpp \
nsNSSASN1Object.cpp \
nsCertOutliner.cpp \
nsKeygenHandler.cpp \
nsCrypto.cpp \
nsPKCS11Slot.cpp \
nsKeygenThread.cpp \
nsCMSSecureMessage.cpp \
nsCMS.cpp \
nsCertPicker.cpp \
$(NULL)
REQUIRES = nspr \
xpcom \
string \
necko \
uriloader \
pref \
caps \
dom \
intl \
locale \
profile \
windowwatcher \
js \
widget \
layout \
content \
pippki \
xpconnect \
jar \
unicharutil \
pipboot \
$(NULL)
ifdef NSS_3_4
DEFINES += -DNSS_3_4
NSS3_LIB = $(LIB_PREFIX)nss3$(DLL_SUFFIX)
SMIME3_LIB = $(LIB_PREFIX)smime3$(DLL_SUFFIX)
SSL3_LIB = $(LIB_PREFIX)ssl3$(DLL_SUFFIX)
SOFTOKEN3_LIB = $(LIB_PREFIX)softokn3$(DLL_SUFFIX)
EXTRA_LIBS = \
$(DIST)/lib/$(LIB_PREFIX)crmf.$(LIB_SUFFIX) \
$(DIST)/lib/$(SMIME3_LIB) \
$(DIST)/lib/$(SSL3_LIB) \
$(DIST)/lib/$(NSS3_LIB) \
$(DIST)/lib/$(SOFTOKEN3_LIB) \
$(NULL)
else
EXTRA_LIBS = $(NSS_LIBS)
endif
EXTRA_DEPS = $(EXTRA_LIBS)
ifeq ($(OS_ARCH),WINNT)
DEFINES += -DNSS_USE_STATIC_LIBS
endif
include $(topsrcdir)/config/rules.mk
# Use local includes because they are inserted before INCLUDES
# so that Mozilla's nss.h is used, not glibc's
LOCAL_INCLUDES += -I$(DIST)/public/security \
-I$(DIST)/private/security \
$(NULL)
EXTRA_DSO_LDOPTS += \
$(MOZ_UNICHARUTIL_LIBS) \
$(MOZ_COMPONENT_LIBS) \
$(MOZ_JS_LIBS) \
$(NULL)

View File

@@ -1,154 +0,0 @@
#!nmake
#
# 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 mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Javier Delgadillo
# Terry Hayes <thayes@netscape.com>
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
MODULE = pipnss
DEPTH=..\..\..\..
IGNORE_MANIFEST=1
LIBRARY_NAME = pipnss
PDBFILE = $(LIBRARY_NAME).pdb
MAPFILE = $(LIBRARY_NAME).map
MODULE_NAME = NSS
META_COMPONENT = crypto
REQUIRES = \
xpcom \
string \
necko \
uriloader \
pref \
caps \
dom \
intl \
locale \
profile \
windowwatcher \
js \
docshell \
widget \
layout \
content \
pippki \
xpconnect \
jar \
layout_xul \
gfx \
unicharutil \
pipboot \
$(NULL)
include <$(DEPTH)/config/config.mak>
CFLAGS = $(CFLAGS) -DNSS_USE_STATIC_LIBS
LINCS = $(LINCS) \
-I$(XPDIST)/public/security \
-I$(XPDIST)/private/security \
$(NULL)
!if defined(NSS_3_4)
CFLAGS=$(CFLAGS) -DNSS_3_4
SUB_LIBRARIES = \
$(DIST)/lib/crmf.lib \
$(DIST)/lib/smime3.lib \
$(DIST)/lib/ssl3.lib \
$(DIST)/lib/nss3.lib \
$(DIST)/lib/softokn3.lib \
$(NULL)
!else
SUB_LIBRARIES = \
$(DIST)/lib/smime.lib \
$(DIST)/lib/crmf.lib \
$(DIST)/lib/ssl.lib \
$(DIST)/lib/nss.lib \
$(DIST)/lib/certhi.lib \
$(DIST)/lib/cryptohi.lib \
$(DIST)/lib/pk11wrap.lib \
$(DIST)/lib/certdb.lib \
$(DIST)/lib/softoken.lib \
$(DIST)/lib/pkcs12.lib \
$(DIST)/lib/pkcs7.lib \
$(DIST)/lib/freebl.lib \
$(DIST)/lib/secutil.lib \
$(DIST)/lib/dbm.lib \
$(NULL)
!endif
LLIBS = \
$(LIBNSPR) \
$(DIST)\lib\unicharutil_s.lib \
$(DIST)\lib\xpcom.lib \
$(DIST)\lib\js3250.lib \
$(NULL)
EXPORTS = \
$(NULL)
OBJS = \
.\$(OBJDIR)\nsNSSCallbacks.obj \
.\$(OBJDIR)\nsNSSComponent.obj \
.\$(OBJDIR)\nsNSSIOLayer.obj \
.\$(OBJDIR)\nsNSSModule.obj \
.\$(OBJDIR)\nsSSLSocketProvider.obj \
.\$(OBJDIR)\nsTLSSocketProvider.obj \
.\$(OBJDIR)\nsSDR.obj \
.\$(OBJDIR)\nsPK11TokenDB.obj \
.\$(OBJDIR)\nsNSSCertificate.obj \
.\$(OBJDIR)\nsPKCS12Blob.obj \
.\$(OBJDIR)\nsKeygenHandler.obj \
.\$(OBJDIR)\nsCertOutliner.obj \
.\$(OBJDIR)\nsNSSASN1Object.obj \
.\$(OBJDIR)\nsCrypto.obj \
.\$(OBJDIR)\nsPKCS11Slot.obj \
.\$(OBJDIR)\nsKeygenThread.obj \
.\$(OBJDIR)\nsCMSSecureMessage.obj \
.\$(OBJDIR)\nsCMS.obj \
.\$(OBJDIR)\nsCertPicker.obj \
$(NULL)
include <$(DEPTH)\config\rules.mak>
libs:: $(DLL)
$(MAKE_INSTALL) $(DIST)\lib\nssckbi.dll $(DIST)\bin
!if defined(NSS_3_4)
$(MAKE_INSTALL) $(DIST)\lib\softokn3.dll $(DIST)\bin
$(MAKE_INSTALL) $(DIST)\lib\nss3.dll $(DIST)\bin
$(MAKE_INSTALL) $(DIST)\lib\smime3.dll $(DIST)\bin
$(MAKE_INSTALL) $(DIST)\lib\ssl3.dll $(DIST)\bin
!endif

View File

@@ -1,515 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): David Drinan <ddrinan@netscape.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 ***** */
#include "nsISupports.h"
#include "nsCMS.h"
#include "nsNSSHelper.h"
#include "nsNSSCertificate.h"
#include "smime.h"
#include "cms.h"
#include "prlog.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
NS_IMPL_THREADSAFE_ISUPPORTS1(nsHash, nsIHash)
nsHash::nsHash() : m_ctxt(nsnull)
{
NS_INIT_ISUPPORTS();
}
nsHash::~nsHash()
{
if (m_ctxt) {
HASH_Destroy(m_ctxt);
}
}
NS_IMETHODIMP nsHash::ResultLen(PRInt16 aAlg, PRUint32 * aLen)
{
*aLen = HASH_ResultLen((HASH_HashType)aAlg);
return NS_OK;
}
NS_IMETHODIMP nsHash::Create(PRInt16 aAlg)
{
m_ctxt = HASH_Create((HASH_HashType)aAlg);
if (m_ctxt == nsnull) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP nsHash::Begin()
{
HASH_Begin(m_ctxt);
return NS_OK;
}
NS_IMETHODIMP nsHash::Update(unsigned char* aBuf, PRUint32 aLen)
{
HASH_Update(m_ctxt, (const unsigned char*)aBuf, aLen);
return NS_OK;
}
NS_IMETHODIMP nsHash::End(unsigned char* aBuf, PRUint32* aResultLen, PRUint32 aMaxResultLen)
{
HASH_End(m_ctxt, aBuf, aResultLen, aMaxResultLen);
return NS_OK;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsCMSMessage, nsICMSMessage)
nsCMSMessage::nsCMSMessage()
{
NS_INIT_ISUPPORTS();
m_cmsMsg = nsnull;
}
nsCMSMessage::nsCMSMessage(NSSCMSMessage *aCMSMsg)
{
NS_INIT_ISUPPORTS();
m_cmsMsg = aCMSMsg;
}
nsCMSMessage::~nsCMSMessage()
{
if (m_cmsMsg) {
NSS_CMSMessage_Destroy(m_cmsMsg);
}
}
NS_IMETHODIMP nsCMSMessage::VerifySignature()
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifySignature\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCMSMessage::GetSignerEmailAddress(char * * aEmail)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::GetSignerEmailAddress\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCMSMessage::GetSignerCommonName(char ** aName)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::GetSignerCommonName\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCMSMessage::ContentIsEncrypted(int *)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::ContentIsEncrypted\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCMSMessage::ContentIsSigned(int *)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::ContentIsSigned\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCMSMessage::VerifyDetachedSignature(unsigned char* aDigestData, PRUint32 aDigestDataLen)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature\n"));
NSSCMSContentInfo *cinfo = nsnull;
NSSCMSSignedData *sigd = nsnull;
NSSCMSSignerInfo *si;
SECItem digest;
PRInt32 nsigners;
nsresult rv = NS_ERROR_FAILURE;
digest.data = aDigestData;
digest.len = aDigestDataLen;
if (NSS_CMSMessage_IsSigned(m_cmsMsg) == PR_FALSE) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - not signed\n"));
return NS_ERROR_FAILURE;
}
cinfo = NSS_CMSMessage_ContentLevel(m_cmsMsg, 0);
sigd = (NSSCMSSignedData*)NSS_CMSContentInfo_GetContent(cinfo);
if (sigd == nsnull) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - no content info\n"));
goto loser;
}
if (NSS_CMSSignedData_SetDigestValue(sigd, SEC_OID_SHA1, &digest)) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - can't set digest value\n"));
goto loser;
}
// Import certs //
if (NSS_CMSSignedData_ImportCerts(sigd, CERT_GetDefaultCertDB(), certUsageEmailSigner, PR_TRUE) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - can not import certs\n"));
goto loser;
}
nsigners = NSS_CMSSignedData_SignerInfoCount(sigd);
PR_ASSERT(nsigners > 0);
si = NSS_CMSSignedData_GetSignerInfo(sigd, 0);
// We verify the first signer info, only //
if (NSS_CMSSignedData_VerifySignerInfo(sigd, 0, CERT_GetDefaultCertDB(), certUsageEmailSigner) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - unable to verify signature\n"));
#ifdef DEBUG
if (NSSCMSVS_SigningCertNotFound == si->verificationStatus) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - signing cert not found\n"));
}
else if(NSSCMSVS_SigningCertNotTrusted == si->verificationStatus) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - signing cert not trusted\n"));
}
#endif
goto loser;
}
// Save the profile //
if (NSS_SMIMESignerInfo_SaveSMIMEProfile(si) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::VerifyDetachedSignature - unable to save smime profile\n"));
goto loser;
}
rv = NS_OK;
loser:
return rv;
}
NS_IMETHODIMP nsCMSMessage::CreateEncrypted(nsISupportsArray * aRecipientCerts)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted\n"));
NSSCMSContentInfo *cinfo;
NSSCMSEnvelopedData *envd;
NSSCMSRecipientInfo *recipientInfo;
CERTCertificate **recipientCerts;
PLArenaPool *tmpPoolp = nsnull;
SECOidTag bulkAlgTag;
int keySize, i;
nsNSSCertificate *nssRecipientCert;
// Check the recipient certificates //
PRUint32 recipientCertCount;
aRecipientCerts->Count(&recipientCertCount);
PR_ASSERT(recipientCertCount > 0);
if ((tmpPoolp = PORT_NewArena(1024)) == nsnull) {
goto loser;
}
if ((recipientCerts = (CERTCertificate**)PORT_ArenaZAlloc(tmpPoolp,
(recipientCertCount+1)*sizeof(CERTCertificate*)))
== nsnull) {
goto loser;
}
for (i=0; i<recipientCertCount; i++) {
nssRecipientCert = NS_STATIC_CAST(nsNSSCertificate*, aRecipientCerts->ElementAt(i));
recipientCerts[i] = nssRecipientCert->GetCert();
}
recipientCerts[i] = nsnull;
// Find a bulk key algorithm //
if (NSS_SMIMEUtil_FindBulkAlgForRecipients(recipientCerts, &bulkAlgTag,
&keySize) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't find bulk alg for recipients\n"));
goto loser;
}
m_cmsMsg = NSS_CMSMessage_Create(NULL);
if (m_cmsMsg == nsnull) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create new cms message\n"));
goto loser;
}
if ((envd = NSS_CMSEnvelopedData_Create(m_cmsMsg, bulkAlgTag, keySize)) == nsnull) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create enveloped data\n"));
goto loser;
}
cinfo = NSS_CMSMessage_GetContentInfo(m_cmsMsg);
if (NSS_CMSContentInfo_SetContent_EnvelopedData(m_cmsMsg, cinfo, envd) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't set content enveloped data\n"));
goto loser;
}
cinfo = NSS_CMSEnvelopedData_GetContentInfo(envd);
if (NSS_CMSContentInfo_SetContent_Data(m_cmsMsg, cinfo, nsnull, PR_FALSE) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't set content data\n"));
goto loser;
}
// Create and attach recipient information //
for (i=0; recipientCerts[i] != nsnull; i++) {
if ((recipientInfo = NSS_CMSRecipientInfo_Create(m_cmsMsg, recipientCerts[i])) == nsnull) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create recipient info\n"));
goto loser;
}
if (NSS_CMSEnvelopedData_AddRecipient(envd, recipientInfo) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't add recipient info\n"));
goto loser;
}
}
if (tmpPoolp) {
PORT_FreeArena(tmpPoolp, PR_FALSE);
}
return NS_OK;
loser:
if (m_cmsMsg) {
NSS_CMSMessage_Destroy(m_cmsMsg);
m_cmsMsg = nsnull;
}
if (tmpPoolp) {
PORT_FreeArena(tmpPoolp, PR_FALSE);
}
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP nsCMSMessage::CreateSigned(nsIX509Cert* aSigningCert, nsIX509Cert* aEncryptCert, unsigned char* aDigestData, PRUint32 aDigestDataLen)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned\n"));
NSSCMSContentInfo *cinfo;
NSSCMSSignedData *sigd;
NSSCMSSignerInfo *signerinfo;
CERTCertificate *scert, *ecert;
/* Get the certs */
scert = NS_STATIC_CAST(nsNSSCertificate*, aSigningCert)->GetCert();
ecert = NS_STATIC_CAST(nsNSSCertificate*, aEncryptCert)->GetCert();
/*
* create the message object
*/
m_cmsMsg = NSS_CMSMessage_Create(NULL); /* create a message on its own pool */
if (m_cmsMsg == NULL) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create new message\n"));
goto loser;
}
/*
* build chain of objects: message->signedData->data
*/
if ((sigd = NSS_CMSSignedData_Create(m_cmsMsg)) == NULL) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signed data\n"));
goto loser;
}
cinfo = NSS_CMSMessage_GetContentInfo(m_cmsMsg);
if (NSS_CMSContentInfo_SetContent_SignedData(m_cmsMsg, cinfo, sigd)
!= SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't set content signed data\n"));
goto loser;
}
cinfo = NSS_CMSSignedData_GetContentInfo(sigd);
/* we're always passing data in and detaching optionally */
if (NSS_CMSContentInfo_SetContent_Data(m_cmsMsg, cinfo, nsnull, PR_TRUE)
!= SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't set content data\n"));
goto loser;
}
/*
* create & attach signer information
*/
if ((signerinfo = NSS_CMSSignerInfo_Create(m_cmsMsg, scert, SEC_OID_SHA1))
== NULL) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signer info\n"));
goto loser;
}
/* we want the cert chain included for this one */
if (NSS_CMSSignerInfo_IncludeCerts(signerinfo, NSSCMSCM_CertChain,
certUsageEmailSigner)
!= SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't include signer cert chain\n"));
goto loser;
}
if (NSS_CMSSignerInfo_AddSigningTime(signerinfo, PR_Now())
!= SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add signing time\n"));
goto loser;
}
if (NSS_CMSSignerInfo_AddSMIMECaps(signerinfo) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add smime caps\n"));
goto loser;
}
if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, ecert,
CERT_GetDefaultCertDB())
!= SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add smime enc key prefs\n"));
goto loser;
}
if (NSS_CMSSignedData_AddCertificate(sigd, ecert) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add own encryption certificate\n"));
goto loser;
}
if (NSS_CMSSignedData_AddSignerInfo(sigd, signerinfo) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add signer info\n"));
goto loser;
}
// Finally, add the pre-computed digest if passed in
if (aDigestData) {
SECItem digest;
digest.data = aDigestData;
digest.len = aDigestDataLen;
if (NSS_CMSSignedData_SetDigestValue(sigd, SEC_OID_SHA1, &digest)) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't set digest value\n"));
goto loser;
}
}
return NS_OK;
loser:
if (m_cmsMsg) {
NSS_CMSMessage_Destroy(m_cmsMsg);
m_cmsMsg = nsnull;
}
return NS_ERROR_FAILURE;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsCMSDecoder, nsICMSDecoder)
nsCMSDecoder::nsCMSDecoder()
{
NS_INIT_ISUPPORTS();
}
nsCMSDecoder::~nsCMSDecoder()
{
}
/* void start (in NSSCMSContentCallback cb, in voidPtr arg); */
NS_IMETHODIMP nsCMSDecoder::Start(NSSCMSContentCallback cb, void * arg)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSDecoder::Start\n"));
m_ctx = new PipUIContext();
m_dcx = NSS_CMSDecoder_Start(0, cb, arg, 0, m_ctx, 0, 0);
if (!m_dcx) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSDecoder::Start - can't start decoder\n"));
return NS_ERROR_FAILURE;
}
return NS_OK;
}
/* void update (in string bug, in long len); */
NS_IMETHODIMP nsCMSDecoder::Update(const char *buf, PRInt32 len)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSDecoder::Update\n"));
NSS_CMSDecoder_Update(m_dcx, (char *)buf, len);
return NS_OK;
}
/* void finish (); */
NS_IMETHODIMP nsCMSDecoder::Finish(nsICMSMessage ** aCMSMsg)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSDecoder::Finish\n"));
NSSCMSMessage *cmsMsg;
cmsMsg = NSS_CMSDecoder_Finish(m_dcx);
if (cmsMsg) {
nsCOMPtr<nsICMSMessage> msg = new nsCMSMessage(cmsMsg);
*aCMSMsg = msg;
NS_ADDREF(*aCMSMsg);
}
return NS_OK;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsCMSEncoder, nsICMSEncoder)
nsCMSEncoder::nsCMSEncoder()
{
NS_INIT_ISUPPORTS();
}
nsCMSEncoder::~nsCMSEncoder()
{
}
/* void start (); */
NS_IMETHODIMP nsCMSEncoder::Start(nsICMSMessage *aMsg, NSSCMSContentCallback cb, void * arg)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Start\n"));
nsCMSMessage *cmsMsg = NS_STATIC_CAST(nsCMSMessage*, aMsg);
m_ctx = new PipUIContext();
m_ecx = NSS_CMSEncoder_Start(cmsMsg->getCMS(), cb, arg, 0, 0, 0, m_ctx, 0, 0, 0, 0);
if (m_ecx == nsnull) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Start - can't start encoder\n"));
return NS_ERROR_FAILURE;
}
return NS_OK;
}
/* void update (in string aBuf, in long aLen); */
NS_IMETHODIMP nsCMSEncoder::Update(const char *aBuf, PRInt32 aLen)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Update\n"));
if (NSS_CMSEncoder_Update(m_ecx, aBuf, aLen) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Update - can't update encoder\n"));
return NS_ERROR_FAILURE;
}
return NS_OK;
}
/* void finish (); */
NS_IMETHODIMP nsCMSEncoder::Finish()
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Finish\n"));
if (NSS_CMSEncoder_Finish(m_ecx) != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Finish - can't finish encoder\n"));
return NS_ERROR_FAILURE;
}
return NS_OK;
}
/* void encode (in nsICMSMessage aMsg); */
NS_IMETHODIMP nsCMSEncoder::Encode(nsICMSMessage *aMsg)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSEncoder::Encode\n"));
return NS_ERROR_NOT_IMPLEMENTED;
}

View File

@@ -1,128 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): David Drinan <ddrinan@netscape.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 ***** */
#ifndef __NS_CMS_H__
#define __NS_CMS_H__
#include "nsISupports.h"
#include "nsCOMPtr.h"
#include "nsIInterfaceRequestor.h"
#include "nsICMS.h"
#include "sechash.h"
#include "cms.h"
#define NS_HASH_CLASSNAME "Hash Object"
#define NS_HASH_CID \
{ 0xa31a3028, 0xae28, 0x11d5, { 0xba, 0x4b, 0x00, 0x10, 0x83, 0x03, 0xb1, 0x17 } }
class nsHash : public nsIHash
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIHASH
nsHash();
virtual ~nsHash();
private:
HASHContext * m_ctxt;
};
#define NS_CMSMESSAGE_CLASSNAME "CMS Message Object"
#define NS_CMSMESSAGE_CID \
{ 0xa4557478, 0xae16, 0x11d5, { 0xba,0x4b,0x00,0x10,0x83,0x03,0xb1,0x17 } }
class nsCMSMessage : public nsICMSMessage
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICMSMESSAGE
nsCMSMessage();
nsCMSMessage(NSSCMSMessage* aCMSMsg);
virtual ~nsCMSMessage();
NSSCMSMessage* getCMS() {return m_cmsMsg;};
private:
NSSCMSMessage * m_cmsMsg;
};
// ===============================================
// nsCMSDecoder - implementation of nsICMSDecoder
// ===============================================
#define NS_CMSDECODER_CLASSNAME "CMS Decoder Object"
#define NS_CMSDECODER_CID \
{ 0x9dcef3a4, 0xa3bc, 0x11d5, { 0xba, 0x47, 0x00, 0x10, 0x83, 0x03, 0xb1, 0x17 } }
class nsCMSDecoder : public nsICMSDecoder
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICMSDECODER
nsCMSDecoder();
virtual ~nsCMSDecoder();
private:
nsCOMPtr<nsIInterfaceRequestor> m_ctx;
NSSCMSDecoderContext *m_dcx;
};
// ===============================================
// nsCMSEncoder - implementation of nsICMSEncoder
// ===============================================
#define NS_CMSENCODER_CLASSNAME "CMS Decoder Object"
#define NS_CMSENCODER_CID \
{ 0xa15789aa, 0x8903, 0x462b, { 0x81, 0xe9, 0x4a, 0xa2, 0xcf, 0xf4, 0xd5, 0xcb } }
class nsCMSEncoder : public nsICMSEncoder
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICMSENCODER
nsCMSEncoder();
virtual ~nsCMSEncoder();
private:
nsCOMPtr<nsIInterfaceRequestor> m_ctx;
NSSCMSEncoderContext *m_ecx;
};
#endif

View File

@@ -1,375 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Terry Hayes <thayes@netscape.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 ***** */
#include "nsMemory.h"
#include "nsXPIDLString.h"
#include "nsCOMPtr.h"
#include "nsISupports.h"
#include "nsIInterfaceRequestor.h"
#include "nsICMSSecureMessage.h"
#include "nsCMSSecureMessage.h"
#include "nsNSSCertificate.h"
#include "nsNSSHelper.h"
#include <string.h>
#include "plbase64.h"
#include "cert.h"
#include "cms.h"
#include "nsIServiceManager.h"
#include "nsIPref.h"
#include "prlog.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
// Standard ISupports implementation
// NOTE: Should these be the thread-safe versions?
/*****
* nsCMSSecureMessage
*****/
// Standard ISupports implementation
NS_IMPL_ISUPPORTS1(nsCMSSecureMessage, nsICMSSecureMessage)
// nsCMSSecureMessage constructor
nsCMSSecureMessage::nsCMSSecureMessage()
{
// initialize superclass
NS_INIT_ISUPPORTS();
}
// nsCMSMessage destructor
nsCMSSecureMessage::~nsCMSSecureMessage()
{
}
/* string getCertByPrefID (in string certID); */
NS_IMETHODIMP nsCMSSecureMessage::
GetCertByPrefID(const char *certID, char **_retval)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::GetCertByPrefID\n"));
nsresult rv = NS_OK;
CERTCertificate *cert = 0;
nsXPIDLCString nickname;
nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
*_retval = 0;
static NS_DEFINE_CID(kPrefCID, NS_PREF_CID);
nsCOMPtr<nsIPref> prefs = do_GetService(kPrefCID, &rv);
if (NS_FAILED(rv)) {
goto done;
}
rv = prefs->GetCharPref(certID,
getter_Copies(nickname));
if (NS_FAILED(rv)) goto done;
/* Find a good cert in the user's database */
cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), (char*)nickname.get(),
certUsageEmailRecipient, PR_TRUE, ctx);
if (!cert) {
/* Success, but no value */
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::GetCertByPrefID - can't find user cert\n"));
goto done;
}
/* Convert the DER to a BASE64 String */
encode(cert->derCert.data, cert->derCert.len, _retval);
done:
if (cert) CERT_DestroyCertificate(cert);
return rv;
}
// nsCMSSecureMessage::DecodeCert
nsresult nsCMSSecureMessage::
DecodeCert(const char *value, nsIX509Cert ** _retval)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::DecodeCert\n"));
nsresult rv = NS_OK;
PRInt32 length;
unsigned char *data = 0;
*_retval = 0;
if (!value) { return NS_ERROR_FAILURE; }
rv = decode(value, &data, &length);
if (NS_FAILED(rv)) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::DecodeCert - can't decode cert\n"));
return rv;
}
nsCOMPtr<nsIX509Cert> cert = new nsNSSCertificate((char *)data, length);
*_retval = cert;
NS_IF_ADDREF(*_retval);
nsCRT::free((char*)data);
return rv;
}
// nsCMSSecureMessage::SendMessage
nsresult nsCMSSecureMessage::
SendMessage(const char *msg, const char *base64Cert, char ** _retval)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage\n"));
nsresult rv = NS_OK;
CERTCertificate *cert = 0;
NSSCMSMessage *cmsMsg = 0;
unsigned char *certDER = 0;
PRInt32 derLen;
NSSCMSEnvelopedData *env;
NSSCMSContentInfo *cinfo;
NSSCMSRecipientInfo *rcpt;
SECItem item;
SECItem output;
PLArenaPool *arena = PORT_NewArena(1024);
SECStatus s;
/* Step 0. Create a CMS Message */
cmsMsg = NSS_CMSMessage_Create(NULL);
if (!cmsMsg) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't create NSSCMSMessage\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
/* Step 1. Import the certificate into NSS */
rv = decode(base64Cert, &certDER, &derLen);
if (NS_FAILED(rv)) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't decode / import cert into NSS\n"));
goto done;
}
cert = CERT_DecodeCertFromPackage((char *)certDER, derLen);
if (!cert) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't decode cert from package\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
#if 0
cert->dbhandle = CERT_GetDefaultCertDB(); /* work-around */
#endif
/* Step 2. Get a signature cert */
/* Step 3. Build inner (signature) content */
/* Step 4. Build outer (enveloped) content */
env = NSS_CMSEnvelopedData_Create(cmsMsg, SEC_OID_DES_EDE3_CBC, 0);
if (!env) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't create envelope data\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
cinfo = NSS_CMSEnvelopedData_GetContentInfo(env);
item.data = (unsigned char *)msg;
item.len = strlen(msg); /* XPCOM equiv?? */
s = NSS_CMSContentInfo_SetContent_Data(cmsMsg, cinfo, 0, PR_FALSE);
if (s != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't set content data\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
rcpt = NSS_CMSRecipientInfo_Create(cmsMsg, cert);
if (!rcpt) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't create recipient info\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
s = NSS_CMSEnvelopedData_AddRecipient(env, rcpt);
if (s != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't add recipient\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
/* Step 5. Add content to message */
cinfo = NSS_CMSMessage_GetContentInfo(cmsMsg);
s = NSS_CMSContentInfo_SetContent_EnvelopedData(cmsMsg, cinfo, env);
if (s != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't set content enveloped data\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
/* Step 6. Encode */
NSSCMSEncoderContext *ecx;
output.data = 0; output.len = 0;
ecx = NSS_CMSEncoder_Start(cmsMsg, 0, 0, &output, arena,
0, 0, 0, 0, 0, 0);
if (!ecx) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't start cms encoder\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
s = NSS_CMSEncoder_Update(ecx, msg, strlen(msg));
if (s != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't update encoder\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
s = NSS_CMSEncoder_Finish(ecx);
if (s != SECSuccess) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::SendMessage - can't finish encoder\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
/* Step 7. Base64 encode and return the result */
rv = encode(output.data, output.len, _retval);
done:
if (certDER) nsCRT::free((char *)certDER);
if (cert) CERT_DestroyCertificate(cert);
if (cmsMsg) NSS_CMSMessage_Destroy(cmsMsg);
if (arena) PORT_FreeArena(arena, PR_FALSE); /* PR_FALSE? */
return rv;
}
/*
* nsCMSSecureMessage::ReceiveMessage
*/
nsresult nsCMSSecureMessage::
ReceiveMessage(const char *msg, char **_retval)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::ReceiveMessage\n"));
nsresult rv = NS_OK;
NSSCMSDecoderContext *dcx;
unsigned char *der = 0;
PRInt32 derLen;
NSSCMSMessage *cmsMsg = 0;
SECItem *content;
nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
/* Step 1. Decode the base64 wrapper */
rv = decode(msg, &der, &derLen);
if (NS_FAILED(rv)) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::ReceiveMessage - can't base64 decode\n"));
goto done;
}
dcx = NSS_CMSDecoder_Start(0, 0, 0, /* pw */ 0, ctx, /* key */ 0, 0);
if (!dcx) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::ReceiveMessage - can't start decoder\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
(void)NSS_CMSDecoder_Update(dcx, (char *)der, derLen);
cmsMsg = NSS_CMSDecoder_Finish(dcx);
if (!cmsMsg) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::ReceiveMessage - can't finish decoder\n"));
rv = NS_ERROR_FAILURE;
/* Memory leak on dcx?? */
goto done;
}
content = NSS_CMSMessage_GetContent(cmsMsg);
if (!content) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::ReceiveMessage - can't get content\n"));
rv = NS_ERROR_FAILURE;
goto done;
}
/* Copy the data */
*_retval = (char*)malloc(content->len+1);
memcpy(*_retval, content->data, content->len);
(*_retval)[content->len] = 0;
done:
if (der) free(der);
if (cmsMsg) NSS_CMSMessage_Destroy(cmsMsg);
return rv;
}
nsresult nsCMSSecureMessage::
encode(const unsigned char *data, PRInt32 dataLen, char **_retval)
{
nsresult rv = NS_OK;
*_retval = PL_Base64Encode((const char *)data, dataLen, NULL);
if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
loser:
return rv;
}
nsresult nsCMSSecureMessage::
decode(const char *data, unsigned char **result, PRInt32 * _retval)
{
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::decode\n"));
nsresult rv = NS_OK;
PRUint32 len = PL_strlen(data);
int adjust = 0;
/* Compute length adjustment */
if (data[len-1] == '=') {
adjust++;
if (data[len-2] == '=') adjust++;
}
*result = (unsigned char *)PL_Base64Decode(data, len, NULL);
if (!*result) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSSecureMessage::decode - error decoding base64\n"));
rv = NS_ERROR_ILLEGAL_VALUE;
goto loser;
}
*_retval = (len*3)/4 - adjust;
loser:
return rv;
}

View File

@@ -1,69 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Terry Hayes <thayes@netscape.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 ***** */
#ifndef _NSCMSSECUREMESSAGE_H_
#define _NSCMSSECUREMESSAGE_H_
#include "nsICMSSecureMessage.h"
#include "cms.h"
// ===============================================
// nsCMSManager - implementation of nsICMSManager
// ===============================================
#define NS_CMSSECUREMESSAGE_CLASSNAME "CMS Secure Message"
#define NS_CMSSECUREMESSAGE_CID \
{ 0x5fb907e0, 0x1dd2, 0x11b2, { 0xa7, 0xc0, 0xf1, 0x4c, 0x41, 0x6a, 0x62, 0xa1 } }
class nsCMSSecureMessage
: public nsICMSSecureMessage
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICMSSECUREMESSAGE
nsCMSSecureMessage();
virtual ~nsCMSSecureMessage();
private:
NS_METHOD encode(const unsigned char *data, PRInt32 dataLen, char **_retval);
NS_METHOD decode(const char *data, unsigned char **result, PRInt32 * _retval);
};
#endif /* _NSCMSMESSAGE_H_ */

View File

@@ -1,727 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
*/
#include "nsNSSComponent.h" // for PIPNSS string bundle calls.
#include "nsCertOutliner.h"
#include "nsIX509Cert.h"
#include "nsIX509CertDB.h"
#include "nsXPIDLString.h"
#include "nsReadableUtils.h"
#include "prlog.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
// outlinerArrayElStr
//
// structure used to hold map of outliner. Each thread (an organization
// field from a cert) has an element in the array. The numChildren field
// stores the number of certs corresponding to that thread.
struct outlinerArrayElStr {
PRUnichar *orgName; /* heading for thread */
PRBool open; /* toggle open state for thread */
PRInt32 certIndex; /* index into cert array for 1st cert */
PRInt32 numChildren; /* number of chidren (certs) for thread */
};
NS_IMPL_ISUPPORTS2(nsCertOutliner, nsICertOutliner, nsIOutlinerView)
nsCertOutliner::nsCertOutliner() : mOutlinerArray(NULL)
{
NS_INIT_ISUPPORTS();
}
nsCertOutliner::~nsCertOutliner()
{
if (mOutlinerArray)
nsMemory::Free(mOutlinerArray);
}
void
nsCertOutliner::FreeCertArray()
{
if (mCertArray) {
PRUint32 count;
nsresult rv = mCertArray->Count(&count);
NS_ASSERTION(NS_SUCCEEDED(rv), "Count failed");
PRInt32 i;
for (i = count - 1; i >= 0; i--)
mCertArray->RemoveElementAt(i);
}
mCertArray = nsnull;
}
// CmpByToken
//
// Compare two certificate by their token name. Returns -1, 0, 1 as
// in strcmp. No token name (null) is treated as <.
PRInt32
nsCertOutliner::CmpByToken(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp1;
nsXPIDLString aTok, bTok;
a->GetTokenName(getter_Copies(aTok));
b->GetTokenName(getter_Copies(bTok));
if (aTok != nsnull && bTok != nsnull) {
nsAutoString aStr(aTok);
cmp1 = aStr.CompareWithConversion(bTok);
} else {
cmp1 = (aTok == nsnull) ? -1 : 1;
}
return cmp1;
}
// CmpByIssuerOrg
//
// Compare two certificates by their O= field. Returns -1, 0, 1 as
// in strcmp. No organization (null) is treated as <.
PRInt32
nsCertOutliner::CmpByIssuerOrg(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp1;
nsXPIDLString aOrg, bOrg;
a->GetIssuerOrganization(getter_Copies(aOrg));
b->GetIssuerOrganization(getter_Copies(bOrg));
if (aOrg != nsnull && bOrg != nsnull) {
nsAutoString aStr(aOrg);
cmp1 = aStr.CompareWithConversion(bOrg);
} else {
cmp1 = (aOrg == nsnull) ? -1 : 1;
}
return cmp1;
}
// CmpByName
//
// Compare two certificates by their CN= field. Returns -1, 0, 1 as
// in strcmp. No common name (null) is treated as <.
PRInt32
nsCertOutliner::CmpByName(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp1;
nsXPIDLString aName, bName;
a->GetOrganization(getter_Copies(aName));
b->GetOrganization(getter_Copies(bName));
if (aName != nsnull && bName != nsnull) {
nsAutoString aStr(aName);
cmp1 = aStr.CompareWithConversion(bName);
} else {
cmp1 = (aName == nsnull) ? -1 : 1;
}
return cmp1;
}
// CmpByTok_IssuerOrg_Name
//
// Compare two certificates by token name, issuer organization,
// and common name, in that order. Used to sort cert list.
PRInt32
nsCertOutliner::CmpByTok_IssuerOrg_Name(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp;
cmp = CmpByToken(a, b);
if (cmp != 0) return cmp;
cmp = CmpByIssuerOrg(a, b);
if (cmp != 0) return cmp;
return CmpByName(a, b);
}
// CountOrganizations
//
// Count the number of different organizations encountered in the cert
// list. Note that the same organization of a different token is counted
// seperately.
PRInt32
nsCertOutliner::CountOrganizations()
{
PRUint32 i, certCount;
nsresult rv = mCertArray->Count(&certCount);
if (NS_FAILED(rv)) return -1;
if (certCount == 0) return 0;
nsCOMPtr<nsISupports> isupport = dont_AddRef(mCertArray->ElementAt(0));
nsCOMPtr<nsIX509Cert> orgCert = do_QueryInterface(isupport);
nsCOMPtr<nsIX509Cert> nextCert = nsnull;
PRInt32 orgCount = 1;
for (i=1; i<certCount; i++) {
isupport = dont_AddRef(mCertArray->ElementAt(i));
nextCert = do_QueryInterface(isupport);
if (!(CmpByToken(orgCert, nextCert) == 0 &&
CmpByIssuerOrg(orgCert, nextCert) == 0)) {
orgCert = nextCert;
orgCount++;
}
}
return orgCount;
}
// GetThreadDescAtIndex
//
// If the row at index is an organization thread, return the collection
// associated with that thread. Otherwise, return null.
outlinerArrayEl *
nsCertOutliner::GetThreadDescAtIndex(PRInt32 index)
{
int i, idx=0;
if (index < 0) return nsnull;
for (i=0; i<mNumOrgs; i++) {
if (index == idx) {
return &mOutlinerArray[i];
}
if (mOutlinerArray[i].open == PR_FALSE) {
idx++;
} else {
idx += mOutlinerArray[i].numChildren + 1;
}
if (idx > index) break;
}
return nsnull;
}
// GetCertAtIndex
//
// If the row at index is a cert, return that cert. Otherwise, return null.
nsIX509Cert *
nsCertOutliner::GetCertAtIndex(PRInt32 index)
{
int i, idx = 0, cIndex = 0, nc;
nsIX509Cert *rawPtr = nsnull;
if (index < 0) return nsnull;
// Loop over the threads
for (i=0; i<mNumOrgs; i++) {
if (index == idx) return nsnull; // index is for thread
idx++; // get past the thread
nc = (mOutlinerArray[i].open) ? mOutlinerArray[i].numChildren : 0;
if (index < idx + nc) { // cert is within range of this thread
PRInt32 certIndex = cIndex + index - idx;
nsCOMPtr<nsISupports> isupport =
dont_AddRef(mCertArray->ElementAt(certIndex));
nsCOMPtr<nsIX509Cert> cert = do_QueryInterface(isupport);
rawPtr = cert;
NS_IF_ADDREF(rawPtr);
break;
}
if (mOutlinerArray[i].open)
idx += mOutlinerArray[i].numChildren;
cIndex += mOutlinerArray[i].numChildren;
if (idx > index) break;
}
return rawPtr;
}
// LoadCerts
//
// Load all of the certificates in the DB for this type. Sort them
// by token, organization, then common name.
NS_IMETHODIMP
nsCertOutliner::LoadCerts(PRUint32 aType)
{
nsresult rv;
PRBool rowsChanged = PR_FALSE;
PRInt32 numChanged = 0;
if (mOutlinerArray) {
FreeCertArray();
nsMemory::Free(mOutlinerArray);
mOutlinerArray = NULL;
rowsChanged = PR_TRUE;
numChanged = mNumRows;
mNumRows = 0;
}
nsCOMPtr<nsIX509CertDB> certdb = do_GetService(NS_X509CERTDB_CONTRACTID);
if (certdb == nsnull) return NS_ERROR_FAILURE;
rv = certdb->GetCertsByType(aType,
CmpByTok_IssuerOrg_Name,
getter_AddRefs(mCertArray));
if (NS_FAILED(rv)) return rv;
PRUint32 count;
rv = mCertArray->Count(&count);
if (NS_FAILED(rv)) return rv;
mNumOrgs = CountOrganizations();
mOutlinerArray = (outlinerArrayEl *)nsMemory::Alloc(
sizeof(outlinerArrayEl) * mNumOrgs);
PRUint32 j = 0;
nsCOMPtr<nsISupports> isupport = dont_AddRef(mCertArray->ElementAt(j));
nsCOMPtr<nsIX509Cert> orgCert = do_QueryInterface(isupport);
for (PRInt32 i=0; i<mNumOrgs; i++) {
orgCert->GetIssuerOrganization(&mOutlinerArray[i].orgName);
mOutlinerArray[i].open = PR_TRUE;
mOutlinerArray[i].certIndex = j;
mOutlinerArray[i].numChildren = 1;
if (++j >= count) break;
isupport = dont_AddRef(mCertArray->ElementAt(j));
nsCOMPtr<nsIX509Cert> nextCert = do_QueryInterface(isupport);
while (CmpByIssuerOrg(orgCert, nextCert) == 0) {
mOutlinerArray[i].numChildren++;
if (++j >= count) break;
isupport = dont_AddRef(mCertArray->ElementAt(j));
nextCert = do_QueryInterface(isupport);
}
orgCert = nextCert;
}
mNumRows = count + mNumOrgs;
if (rowsChanged) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("[%d,%d]", mNumRows, numChanged));
numChanged = mNumRows - numChanged;
if (mOutliner) mOutliner->RowCountChanged(0, numChanged);
}
return NS_OK;
}
//////////////////////////////////////////////////////////////////////////////
//
// Begin nsIOutlinerView methods
//
/////////////////////////////////////////////////////////////////////////////
/* nsIX509Cert getCert(in unsigned long index); */
NS_IMETHODIMP
nsCertOutliner::GetCert(PRUint32 aIndex, nsIX509Cert **_cert)
{
NS_ENSURE_ARG(_cert);
*_cert = GetCertAtIndex(aIndex);
//nsCOMPtr<nsIX509Cert> cert = GetCertAtIndex(aIndex);
//if (cert) {
//*_cert = cert;
//NS_ADDREF(*_cert);
//}
return NS_OK;
}
/* readonly attribute long rowCount; */
NS_IMETHODIMP
nsCertOutliner::GetRowCount(PRInt32 *aRowCount)
{
PRUint32 count = 0;
for (PRInt32 i=0; i<mNumOrgs; i++) {
if (mOutlinerArray[i].open == PR_TRUE) {
count += mOutlinerArray[i].numChildren + 1;
} else {
count++;
}
}
*aRowCount = count;
return NS_OK;
}
/* attribute nsIOutlinerSelection selection; */
NS_IMETHODIMP
nsCertOutliner::GetSelection(nsIOutlinerSelection * *aSelection)
{
*aSelection = mSelection;
NS_IF_ADDREF(*aSelection);
return NS_OK;
}
NS_IMETHODIMP
nsCertOutliner::SetSelection(nsIOutlinerSelection * aSelection)
{
mSelection = aSelection;
return NS_OK;
}
/* void getRowProperties (in long index, in nsISupportsArray properties); */
NS_IMETHODIMP
nsCertOutliner::GetRowProperties(PRInt32 index, nsISupportsArray *properties)
{
return NS_OK;
}
/* void getCellProperties (in long row, in wstring colID,
* in nsISupportsArray properties);
*/
NS_IMETHODIMP
nsCertOutliner::GetCellProperties(PRInt32 row, const PRUnichar *colID,
nsISupportsArray *properties)
{
return NS_OK;
}
/* void getColumnProperties (in wstring colID,
* in nsIDOMElement colElt,
* in nsISupportsArray properties);
*/
NS_IMETHODIMP
nsCertOutliner::GetColumnProperties(const PRUnichar *colID,
nsIDOMElement *colElt,
nsISupportsArray *properties)
{
return NS_OK;
}
/* boolean isContainer (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsContainer(PRInt32 index, PRBool *_retval)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el) {
*_retval = PR_TRUE;
} else {
*_retval = PR_FALSE;
}
return NS_OK;
}
/* boolean isContainerOpen (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsContainerOpen(PRInt32 index, PRBool *_retval)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el && el->open == PR_TRUE) {
*_retval = PR_TRUE;
} else {
*_retval = PR_FALSE;
}
return NS_OK;
}
/* boolean isContainerEmpty (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsContainerEmpty(PRInt32 index, PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* boolean isSeparator (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsSeparator(PRInt32 index, PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* long getParentIndex (in long rowIndex); */
NS_IMETHODIMP
nsCertOutliner::GetParentIndex(PRInt32 rowIndex, PRInt32 *_retval)
{
int i, idx = 0;
for (i=0; i<mNumOrgs; i++) {
if (rowIndex == idx) break; // index is for thread
if (rowIndex < idx + mOutlinerArray[i].numChildren + 1) {
*_retval = idx;
return NS_OK;
}
idx += mOutlinerArray[i].numChildren + 1;
if (idx > rowIndex) break;
}
*_retval = -1;
return NS_OK;
}
/* boolean hasNextSibling (in long rowIndex, in long afterIndex); */
NS_IMETHODIMP
nsCertOutliner::HasNextSibling(PRInt32 rowIndex, PRInt32 afterIndex,
PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* long getLevel (in long index); */
NS_IMETHODIMP
nsCertOutliner::GetLevel(PRInt32 index, PRInt32 *_retval)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el) {
*_retval = 0;
} else {
*_retval = 1;
}
return NS_OK;
}
/* wstring getCellText (in long row, in wstring colID); */
NS_IMETHODIMP
nsCertOutliner::GetCellText(PRInt32 row, const PRUnichar *colID,
nsAString& _retval)
{
nsresult rv;
NS_ConvertUCS2toUTF8 aUtf8ColID(colID);
const char *col = aUtf8ColID.get();
outlinerArrayEl *el = GetThreadDescAtIndex(row);
if (el != nsnull) {
if (strcmp(col, "certcol") == 0)
_retval.Assign(el->orgName);
else
_retval.SetCapacity(0);
return NS_OK;
}
nsCOMPtr<nsIX509Cert> cert = GetCertAtIndex(row);
if (cert == nsnull) return NS_ERROR_FAILURE;
char *str = NULL;
PRUnichar *wstr = NULL;
if (strcmp(col, "certcol") == 0) {
rv = cert->GetCommonName(&wstr);
if (NS_FAILED(rv) || !wstr) {
// can this be fixed to not do copying?
PRUnichar *tmp = nsnull;
rv = cert->GetNickname(&tmp);
nsAutoString nick(tmp);
char *tmps = ToNewCString(nick);
char *mark = strchr(tmps, ':');
if (mark) {
str = PL_strdup(mark + 1);
} else {
wstr = ToNewUnicode(nick);
}
nsMemory::Free(tmp);
nsMemory::Free(tmps);
}
} else if (strcmp(col, "tokencol") == 0) {
rv = cert->GetTokenName(&wstr);
} else if (strcmp(col, "emailcol") == 0) {
rv = cert->GetEmailAddress(&wstr);
} else if (strcmp(col, "verifiedcol") == 0) {
PRUint32 verified;
nsCOMPtr<nsINSSComponent> nssComponent(
do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv)) return rv;
PRBool ocspEnabled;
cert->GetUsesOCSP(&ocspEnabled);
if (ocspEnabled) {
nssComponent->DisableOCSP();
}
rv = cert->GetPurposes(&verified, NULL);
if (verified == nsIX509Cert::VERIFIED_OK) {
nsAutoString vfy;
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("VerifiedTrue").get(), vfy);
if (NS_SUCCEEDED(rv))
wstr = ToNewUnicode(vfy);
} else {
nsAutoString vfy;
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("VerifiedFalse").get(), vfy);
if (NS_SUCCEEDED(rv))
wstr = ToNewUnicode(vfy);
}
if (ocspEnabled) {
nssComponent->EnableOCSP();
}
} else if (strcmp(col, "purposecol") == 0) {
PRUint32 verified;
PRBool ocspEnabled;
nsCOMPtr<nsINSSComponent> nssComponent(
do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv)) return rv;
cert->GetUsesOCSP(&ocspEnabled);
if (ocspEnabled) {
nssComponent->DisableOCSP();
}
rv = cert->GetPurposes(&verified, &wstr);
if (ocspEnabled) {
nssComponent->EnableOCSP();
}
} else if (strcmp(col, "issuedcol") == 0) {
rv = cert->GetIssuedDate(&wstr);
} else if (strcmp(col, "expiredcol") == 0) {
rv = cert->GetExpiresDate(&wstr);
} else if (strcmp(col, "serialnumcol") == 0) {
rv = cert->GetSerialNumber(&wstr);
/*
} else if (strcmp(col, "certdbkeycol") == 0) {
rv = cert->GetDbKey(&str);
*/
} else {
return NS_ERROR_FAILURE;
}
if (str) {
nsAutoString astr = NS_ConvertASCIItoUCS2(str);
wstr = ToNewUnicode(astr);
}
_retval = wstr;
return rv;
}
/* void setOutliner (in nsIOutlinerBoxObject outliner); */
NS_IMETHODIMP
nsCertOutliner::SetOutliner(nsIOutlinerBoxObject *outliner)
{
mOutliner = outliner;
return NS_OK;
}
/* void toggleOpenState (in long index); */
NS_IMETHODIMP
nsCertOutliner::ToggleOpenState(PRInt32 index)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el) el->open = !el->open;
PRInt32 fac = (el->open) ? 1 : -1;
if (mOutliner) mOutliner->RowCountChanged(index, fac * el->numChildren);
mSelection->Select(index);
return NS_OK;
}
/* void cycleHeader (in wstring colID, in nsIDOMElement elt); */
NS_IMETHODIMP
nsCertOutliner::CycleHeader(const PRUnichar *colID, nsIDOMElement *elt)
{
return NS_OK;
}
/* void selectionChanged (); */
NS_IMETHODIMP
nsCertOutliner::SelectionChanged()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void cycleCell (in long row, in wstring colID); */
NS_IMETHODIMP
nsCertOutliner::CycleCell(PRInt32 row, const PRUnichar *colID)
{
return NS_OK;
}
/* boolean isEditable (in long row, in wstring colID); */
NS_IMETHODIMP
nsCertOutliner::IsEditable(PRInt32 row, const PRUnichar *colID, PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* void setCellText (in long row, in wstring colID, in wstring value); */
NS_IMETHODIMP
nsCertOutliner::SetCellText(PRInt32 row, const PRUnichar *colID,
const PRUnichar *value)
{
return NS_OK;
}
/* void performAction (in wstring action); */
NS_IMETHODIMP
nsCertOutliner::PerformAction(const PRUnichar *action)
{
return NS_OK;
}
/* void performActionOnRow (in wstring action, in long row); */
NS_IMETHODIMP
nsCertOutliner::PerformActionOnRow(const PRUnichar *action, PRInt32 row)
{
return NS_OK;
}
/* void performActionOnCell (in wstring action, in long row,
* in wstring colID);
*/
NS_IMETHODIMP
nsCertOutliner::PerformActionOnCell(const PRUnichar *action, PRInt32 row,
const PRUnichar *colID)
{
return NS_OK;
}
#ifdef DEBUG_CERT_OUTLINER
void
nsCertOutliner::dumpMap()
{
for (int i=0; i<mNumOrgs; i++) {
nsAutoString org(mOutlinerArray[i].orgName);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("ORG[%s]", NS_LossyConvertUCS2toASCII(org).get()));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("OPEN[%d]", mOutlinerArray[i].open));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("INDEX[%d]", mOutlinerArray[i].certIndex));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("NCHILD[%d]", mOutlinerArray[i].numChildren));
}
for (int i=0; i<mNumRows; i++) {
outlinerArrayEl *el = GetThreadDescAtIndex(i);
if (el != nsnull) {
nsAutoString td(el->orgName);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("thread desc[%d]: %s", i, NS_LossyConvertUCS2toASCII(td).get()));
}
nsCOMPtr<nsIX509Cert> ct = GetCertAtIndex(i);
if (ct != nsnull) {
PRUnichar *goo;
ct->GetCommonName(&goo);
nsAutoString doo(goo);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("cert [%d]: %s", i, NS_LossyConvertUCS2toASCII(doo).get()));
}
}
}
#endif
//
// CanDropOn
//
// Can't drop on the thread pane.
//
NS_IMETHODIMP nsCertOutliner::CanDropOn(PRInt32 index, PRBool *_retval)
{
NS_ENSURE_ARG_POINTER(_retval);
*_retval = PR_FALSE;
return NS_OK;
}
//
// CanDropBeforeAfter
//
// Can't drop on the thread pane.
//
NS_IMETHODIMP nsCertOutliner::CanDropBeforeAfter(PRInt32 index, PRBool before, PRBool *_retval)
{
NS_ENSURE_ARG_POINTER(_retval);
*_retval = PR_FALSE;
return NS_OK;
}
//
// Drop
//
// Can't drop on the thread pane.
//
NS_IMETHODIMP nsCertOutliner::Drop(PRInt32 row, PRInt32 orient)
{
return NS_OK;
}
//
// IsSorted
//
// ...
//
NS_IMETHODIMP nsCertOutliner::IsSorted(PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}

View File

@@ -1,86 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
*/
#ifndef _NS_CERTOUTLINER_H_
#define _NS_CERTOUTLINER_H_
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsICertOutliner.h"
#include "nsIOutlinerView.h"
#include "nsIOutlinerBoxObject.h"
#include "nsIOutlinerSelection.h"
#include "nsISupportsArray.h"
typedef struct outlinerArrayElStr outlinerArrayEl;
class nsCertOutliner : public nsICertOutliner
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICERTOUTLINER
NS_DECL_NSIOUTLINERVIEW
nsCertOutliner();
virtual ~nsCertOutliner();
protected:
static PRInt32 CmpByToken(nsIX509Cert *a, nsIX509Cert *b);
static PRInt32 CmpByIssuerOrg(nsIX509Cert *a, nsIX509Cert *b);
static PRInt32 CmpByName(nsIX509Cert *a, nsIX509Cert *b);
static PRInt32 CmpByTok_IssuerOrg_Name(nsIX509Cert *a, nsIX509Cert *b);
PRInt32 CountOrganizations();
private:
nsCOMPtr<nsISupportsArray> mCertArray;
nsCOMPtr<nsIOutlinerBoxObject> mOutliner;
nsCOMPtr<nsIOutlinerSelection> mSelection;
outlinerArrayEl *mOutlinerArray;
PRInt32 mNumOrgs;
PRInt32 mNumRows;
outlinerArrayEl *GetThreadDescAtIndex(PRInt32 _index);
nsIX509Cert *GetCertAtIndex(PRInt32 _index);
void FreeCertArray();
#ifdef DEBUG_CERT_OUTLINER
/* for debugging purposes */
void dumpMap();
#endif
};
#endif /* _NS_CERTOUTLINER_H_ */

View File

@@ -1,201 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Kai Engert <kaie@netscape.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 ***** */
#include "nsCertPicker.h"
#include "nsMemory.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsIServiceManager.h"
#include "nsNSSComponent.h"
#include "nsNSSCertificate.h"
#include "nsINSSDialogs.h"
#include "nsReadableUtils.h"
#include "cert.h"
/* strings for marking invalid user cert nicknames */
#define NICKNAME_EXPIRED_STRING " (expired)"
#define NICKNAME_NOT_YET_VALID_STRING " (not yet valid)"
NS_IMPL_ISUPPORTS1(nsCertPicker, nsIUserCertPicker)
nsCertPicker::nsCertPicker()
{
NS_INIT_ISUPPORTS();
}
nsCertPicker::~nsCertPicker()
{
}
/* nsIX509Cert pick (in nsIInterfaceRequestor ctx, in wstring title, in wstring infoPrompt, in PRInt32 certUsage, in boolean allowInvalid, in boolean allowDuplicateNicknames, out boolean canceled); */
NS_IMETHODIMP nsCertPicker::PickByUsage(nsIInterfaceRequestor *ctx, const PRUnichar *title, const PRUnichar *infoPrompt, PRInt32 certUsage, PRBool allowInvalid, PRBool allowDuplicateNicknames, PRBool *canceled, nsIX509Cert **_retval)
{
PRInt32 selectedIndex = -1;
PRUnichar **certNicknameList = nsnull;
PRUnichar **certDetailsList = nsnull;
CERTCertListNode* node = nsnull;
CERTCertificate* cert = nsnull;
nsresult rv;
{
// Iterate over all certs. This assures that user is logged in to all hardware tokens.
CERTCertList *allcerts = nsnull;
nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
allcerts = PK11_ListCerts(PK11CertListUnique, ctx);
CERT_DestroyCertList(allcerts);
}
/* find all user certs that are valid and for SSL */
/* note that we are allowing expired certs in this list */
CERTCertList *certList =
CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(),
(SECCertUsage)certUsage,
!allowDuplicateNicknames,
!allowInvalid,
ctx);
if (!certList) {
return NS_ERROR_NOT_AVAILABLE;
}
rv = NS_OK;
CERTCertNicknames *nicknames =
CERT_NicknameStringsFromCertList(certList,
NICKNAME_EXPIRED_STRING,
NICKNAME_NOT_YET_VALID_STRING);
if (!nicknames) {
rv = NS_ERROR_NOT_AVAILABLE;
}
else {
certNicknameList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames);
certDetailsList = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *) * nicknames->numnicknames);
PRInt32 CertsToUse;
for (CertsToUse = 0, node = CERT_LIST_HEAD(certList);
!CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames;
node = CERT_LIST_NEXT(node)
)
{
nsNSSCertificate *tempCert = new nsNSSCertificate(node->cert);
if (tempCert) {
// XXX we really should be using an nsCOMPtr instead of manually add-refing,
// but nsNSSCertificate does not have a default constructor.
NS_ADDREF(tempCert);
nsAutoString i_nickname(NS_ConvertUTF8toUCS2(nicknames->nicknames[CertsToUse]));
nsAutoString nickWithSerial;
nsAutoString details;
if (NS_SUCCEEDED(tempCert->FormatUIStrings(i_nickname, nickWithSerial, details))) {
certNicknameList[CertsToUse] = ToNewUnicode(nickWithSerial);
certDetailsList[CertsToUse] = ToNewUnicode(details);
}
else {
certNicknameList[CertsToUse] = nsnull;
certDetailsList[CertsToUse] = nsnull;
}
NS_RELEASE(tempCert);
++CertsToUse;
}
}
PRInt32 i = 0;
nsICertPickDialogs *dialogs = nsnull;
rv = getNSSDialogs((void**)&dialogs, NS_GET_IID(nsICertPickDialogs));
if (NS_SUCCEEDED(rv)) {
/* Throw up the cert picker dialog and get back the index of the selected cert */
rv = dialogs->PickCertificate(ctx, title, infoPrompt,
(const PRUnichar**)certNicknameList, (const PRUnichar**)certDetailsList,
CertsToUse, &selectedIndex, canceled);
for (i = 0; i < CertsToUse; ++i) {
nsMemory::Free(certNicknameList[i]);
nsMemory::Free(certDetailsList[i]);
}
nsMemory::Free(certNicknameList);
nsMemory::Free(certDetailsList);
NS_RELEASE(dialogs);
}
if (NS_SUCCEEDED(rv) && !*canceled) {
for (i = 0, node = CERT_LIST_HEAD(certList);
!CERT_LIST_END(node, certList);
++i, node = CERT_LIST_NEXT(node)) {
if (i == selectedIndex) {
nsNSSCertificate *cert = new nsNSSCertificate(node->cert);
if (!cert) {
rv = NS_ERROR_OUT_OF_MEMORY;
break;
}
nsIX509Cert *x509 = 0;
nsresult rv = cert->QueryInterface(NS_GET_IID(nsIX509Cert), (void**)&x509);
if (NS_FAILED(rv)) {
break;
}
NS_ADDREF(x509);
*_retval = x509;
NS_RELEASE(cert);
break;
}
}
}
CERT_FreeNicknames(nicknames);
}
if (certList) {
CERT_DestroyCertList(certList);
}
return rv;
}

View File

@@ -1,58 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 Mozilla Communicator.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp..
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Kai Engert <kaie@netscape.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 ***** */
#ifndef _NSCERTPICKER_H_
#define _NSCERTPICKER_H_
#include "nsIUserCertPicker.h"
#define NS_CERT_PICKER_CID \
{ 0x735959a1, 0xaf01, 0x447e, { 0xb0, 0x2d, 0x56, 0xe9, 0x68, 0xfa, 0x52, 0xb4 } }
class nsCertPicker : public nsIUserCertPicker
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIUSERCERTPICKER
nsCertPicker();
virtual ~nsCertPicker();
private:
};
#endif //_NSCERTPICKER_H_

View File

@@ -1,727 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
*/
#include "nsNSSComponent.h" // for PIPNSS string bundle calls.
#include "nsCertOutliner.h"
#include "nsIX509Cert.h"
#include "nsIX509CertDB.h"
#include "nsXPIDLString.h"
#include "nsReadableUtils.h"
#include "prlog.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
// outlinerArrayElStr
//
// structure used to hold map of outliner. Each thread (an organization
// field from a cert) has an element in the array. The numChildren field
// stores the number of certs corresponding to that thread.
struct outlinerArrayElStr {
PRUnichar *orgName; /* heading for thread */
PRBool open; /* toggle open state for thread */
PRInt32 certIndex; /* index into cert array for 1st cert */
PRInt32 numChildren; /* number of chidren (certs) for thread */
};
NS_IMPL_ISUPPORTS2(nsCertOutliner, nsICertOutliner, nsIOutlinerView)
nsCertOutliner::nsCertOutliner() : mOutlinerArray(NULL)
{
NS_INIT_ISUPPORTS();
}
nsCertOutliner::~nsCertOutliner()
{
if (mOutlinerArray)
nsMemory::Free(mOutlinerArray);
}
void
nsCertOutliner::FreeCertArray()
{
if (mCertArray) {
PRUint32 count;
nsresult rv = mCertArray->Count(&count);
NS_ASSERTION(NS_SUCCEEDED(rv), "Count failed");
PRInt32 i;
for (i = count - 1; i >= 0; i--)
mCertArray->RemoveElementAt(i);
}
mCertArray = nsnull;
}
// CmpByToken
//
// Compare two certificate by their token name. Returns -1, 0, 1 as
// in strcmp. No token name (null) is treated as <.
PRInt32
nsCertOutliner::CmpByToken(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp1;
nsXPIDLString aTok, bTok;
a->GetTokenName(getter_Copies(aTok));
b->GetTokenName(getter_Copies(bTok));
if (aTok != nsnull && bTok != nsnull) {
nsAutoString aStr(aTok);
cmp1 = aStr.CompareWithConversion(bTok);
} else {
cmp1 = (aTok == nsnull) ? -1 : 1;
}
return cmp1;
}
// CmpByIssuerOrg
//
// Compare two certificates by their O= field. Returns -1, 0, 1 as
// in strcmp. No organization (null) is treated as <.
PRInt32
nsCertOutliner::CmpByIssuerOrg(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp1;
nsXPIDLString aOrg, bOrg;
a->GetIssuerOrganization(getter_Copies(aOrg));
b->GetIssuerOrganization(getter_Copies(bOrg));
if (aOrg != nsnull && bOrg != nsnull) {
nsAutoString aStr(aOrg);
cmp1 = aStr.CompareWithConversion(bOrg);
} else {
cmp1 = (aOrg == nsnull) ? -1 : 1;
}
return cmp1;
}
// CmpByName
//
// Compare two certificates by their CN= field. Returns -1, 0, 1 as
// in strcmp. No common name (null) is treated as <.
PRInt32
nsCertOutliner::CmpByName(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp1;
nsXPIDLString aName, bName;
a->GetOrganization(getter_Copies(aName));
b->GetOrganization(getter_Copies(bName));
if (aName != nsnull && bName != nsnull) {
nsAutoString aStr(aName);
cmp1 = aStr.CompareWithConversion(bName);
} else {
cmp1 = (aName == nsnull) ? -1 : 1;
}
return cmp1;
}
// CmpByTok_IssuerOrg_Name
//
// Compare two certificates by token name, issuer organization,
// and common name, in that order. Used to sort cert list.
PRInt32
nsCertOutliner::CmpByTok_IssuerOrg_Name(nsIX509Cert *a, nsIX509Cert *b)
{
PRInt32 cmp;
cmp = CmpByToken(a, b);
if (cmp != 0) return cmp;
cmp = CmpByIssuerOrg(a, b);
if (cmp != 0) return cmp;
return CmpByName(a, b);
}
// CountOrganizations
//
// Count the number of different organizations encountered in the cert
// list. Note that the same organization of a different token is counted
// seperately.
PRInt32
nsCertOutliner::CountOrganizations()
{
PRUint32 i, certCount;
nsresult rv = mCertArray->Count(&certCount);
if (NS_FAILED(rv)) return -1;
if (certCount == 0) return 0;
nsCOMPtr<nsISupports> isupport = dont_AddRef(mCertArray->ElementAt(0));
nsCOMPtr<nsIX509Cert> orgCert = do_QueryInterface(isupport);
nsCOMPtr<nsIX509Cert> nextCert = nsnull;
PRInt32 orgCount = 1;
for (i=1; i<certCount; i++) {
isupport = dont_AddRef(mCertArray->ElementAt(i));
nextCert = do_QueryInterface(isupport);
if (!(CmpByToken(orgCert, nextCert) == 0 &&
CmpByIssuerOrg(orgCert, nextCert) == 0)) {
orgCert = nextCert;
orgCount++;
}
}
return orgCount;
}
// GetThreadDescAtIndex
//
// If the row at index is an organization thread, return the collection
// associated with that thread. Otherwise, return null.
outlinerArrayEl *
nsCertOutliner::GetThreadDescAtIndex(PRInt32 index)
{
int i, idx=0;
if (index < 0) return nsnull;
for (i=0; i<mNumOrgs; i++) {
if (index == idx) {
return &mOutlinerArray[i];
}
if (mOutlinerArray[i].open == PR_FALSE) {
idx++;
} else {
idx += mOutlinerArray[i].numChildren + 1;
}
if (idx > index) break;
}
return nsnull;
}
// GetCertAtIndex
//
// If the row at index is a cert, return that cert. Otherwise, return null.
nsIX509Cert *
nsCertOutliner::GetCertAtIndex(PRInt32 index)
{
int i, idx = 0, cIndex = 0, nc;
nsIX509Cert *rawPtr = nsnull;
if (index < 0) return nsnull;
// Loop over the threads
for (i=0; i<mNumOrgs; i++) {
if (index == idx) return nsnull; // index is for thread
idx++; // get past the thread
nc = (mOutlinerArray[i].open) ? mOutlinerArray[i].numChildren : 0;
if (index < idx + nc) { // cert is within range of this thread
PRInt32 certIndex = cIndex + index - idx;
nsCOMPtr<nsISupports> isupport =
dont_AddRef(mCertArray->ElementAt(certIndex));
nsCOMPtr<nsIX509Cert> cert = do_QueryInterface(isupport);
rawPtr = cert;
NS_IF_ADDREF(rawPtr);
break;
}
if (mOutlinerArray[i].open)
idx += mOutlinerArray[i].numChildren;
cIndex += mOutlinerArray[i].numChildren;
if (idx > index) break;
}
return rawPtr;
}
// LoadCerts
//
// Load all of the certificates in the DB for this type. Sort them
// by token, organization, then common name.
NS_IMETHODIMP
nsCertOutliner::LoadCerts(PRUint32 aType)
{
nsresult rv;
PRBool rowsChanged = PR_FALSE;
PRInt32 numChanged = 0;
if (mOutlinerArray) {
FreeCertArray();
nsMemory::Free(mOutlinerArray);
mOutlinerArray = NULL;
rowsChanged = PR_TRUE;
numChanged = mNumRows;
mNumRows = 0;
}
nsCOMPtr<nsIX509CertDB> certdb = do_GetService(NS_X509CERTDB_CONTRACTID);
if (certdb == nsnull) return NS_ERROR_FAILURE;
rv = certdb->GetCertsByType(aType,
CmpByTok_IssuerOrg_Name,
getter_AddRefs(mCertArray));
if (NS_FAILED(rv)) return rv;
PRUint32 count;
rv = mCertArray->Count(&count);
if (NS_FAILED(rv)) return rv;
mNumOrgs = CountOrganizations();
mOutlinerArray = (outlinerArrayEl *)nsMemory::Alloc(
sizeof(outlinerArrayEl) * mNumOrgs);
PRUint32 j = 0;
nsCOMPtr<nsISupports> isupport = dont_AddRef(mCertArray->ElementAt(j));
nsCOMPtr<nsIX509Cert> orgCert = do_QueryInterface(isupport);
for (PRInt32 i=0; i<mNumOrgs; i++) {
orgCert->GetIssuerOrganization(&mOutlinerArray[i].orgName);
mOutlinerArray[i].open = PR_TRUE;
mOutlinerArray[i].certIndex = j;
mOutlinerArray[i].numChildren = 1;
if (++j >= count) break;
isupport = dont_AddRef(mCertArray->ElementAt(j));
nsCOMPtr<nsIX509Cert> nextCert = do_QueryInterface(isupport);
while (CmpByIssuerOrg(orgCert, nextCert) == 0) {
mOutlinerArray[i].numChildren++;
if (++j >= count) break;
isupport = dont_AddRef(mCertArray->ElementAt(j));
nextCert = do_QueryInterface(isupport);
}
orgCert = nextCert;
}
mNumRows = count + mNumOrgs;
if (rowsChanged) {
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("[%d,%d]", mNumRows, numChanged));
numChanged = mNumRows - numChanged;
if (mOutliner) mOutliner->RowCountChanged(0, numChanged);
}
return NS_OK;
}
//////////////////////////////////////////////////////////////////////////////
//
// Begin nsIOutlinerView methods
//
/////////////////////////////////////////////////////////////////////////////
/* nsIX509Cert getCert(in unsigned long index); */
NS_IMETHODIMP
nsCertOutliner::GetCert(PRUint32 aIndex, nsIX509Cert **_cert)
{
NS_ENSURE_ARG(_cert);
*_cert = GetCertAtIndex(aIndex);
//nsCOMPtr<nsIX509Cert> cert = GetCertAtIndex(aIndex);
//if (cert) {
//*_cert = cert;
//NS_ADDREF(*_cert);
//}
return NS_OK;
}
/* readonly attribute long rowCount; */
NS_IMETHODIMP
nsCertOutliner::GetRowCount(PRInt32 *aRowCount)
{
PRUint32 count = 0;
for (PRInt32 i=0; i<mNumOrgs; i++) {
if (mOutlinerArray[i].open == PR_TRUE) {
count += mOutlinerArray[i].numChildren + 1;
} else {
count++;
}
}
*aRowCount = count;
return NS_OK;
}
/* attribute nsIOutlinerSelection selection; */
NS_IMETHODIMP
nsCertOutliner::GetSelection(nsIOutlinerSelection * *aSelection)
{
*aSelection = mSelection;
NS_IF_ADDREF(*aSelection);
return NS_OK;
}
NS_IMETHODIMP
nsCertOutliner::SetSelection(nsIOutlinerSelection * aSelection)
{
mSelection = aSelection;
return NS_OK;
}
/* void getRowProperties (in long index, in nsISupportsArray properties); */
NS_IMETHODIMP
nsCertOutliner::GetRowProperties(PRInt32 index, nsISupportsArray *properties)
{
return NS_OK;
}
/* void getCellProperties (in long row, in wstring colID,
* in nsISupportsArray properties);
*/
NS_IMETHODIMP
nsCertOutliner::GetCellProperties(PRInt32 row, const PRUnichar *colID,
nsISupportsArray *properties)
{
return NS_OK;
}
/* void getColumnProperties (in wstring colID,
* in nsIDOMElement colElt,
* in nsISupportsArray properties);
*/
NS_IMETHODIMP
nsCertOutliner::GetColumnProperties(const PRUnichar *colID,
nsIDOMElement *colElt,
nsISupportsArray *properties)
{
return NS_OK;
}
/* boolean isContainer (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsContainer(PRInt32 index, PRBool *_retval)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el) {
*_retval = PR_TRUE;
} else {
*_retval = PR_FALSE;
}
return NS_OK;
}
/* boolean isContainerOpen (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsContainerOpen(PRInt32 index, PRBool *_retval)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el && el->open == PR_TRUE) {
*_retval = PR_TRUE;
} else {
*_retval = PR_FALSE;
}
return NS_OK;
}
/* boolean isContainerEmpty (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsContainerEmpty(PRInt32 index, PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* boolean isSeparator (in long index); */
NS_IMETHODIMP
nsCertOutliner::IsSeparator(PRInt32 index, PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* long getParentIndex (in long rowIndex); */
NS_IMETHODIMP
nsCertOutliner::GetParentIndex(PRInt32 rowIndex, PRInt32 *_retval)
{
int i, idx = 0;
for (i=0; i<mNumOrgs; i++) {
if (rowIndex == idx) break; // index is for thread
if (rowIndex < idx + mOutlinerArray[i].numChildren + 1) {
*_retval = idx;
return NS_OK;
}
idx += mOutlinerArray[i].numChildren + 1;
if (idx > rowIndex) break;
}
*_retval = -1;
return NS_OK;
}
/* boolean hasNextSibling (in long rowIndex, in long afterIndex); */
NS_IMETHODIMP
nsCertOutliner::HasNextSibling(PRInt32 rowIndex, PRInt32 afterIndex,
PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* long getLevel (in long index); */
NS_IMETHODIMP
nsCertOutliner::GetLevel(PRInt32 index, PRInt32 *_retval)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el) {
*_retval = 0;
} else {
*_retval = 1;
}
return NS_OK;
}
/* wstring getCellText (in long row, in wstring colID); */
NS_IMETHODIMP
nsCertOutliner::GetCellText(PRInt32 row, const PRUnichar *colID,
nsAString& _retval)
{
nsresult rv;
NS_ConvertUCS2toUTF8 aUtf8ColID(colID);
const char *col = aUtf8ColID.get();
outlinerArrayEl *el = GetThreadDescAtIndex(row);
if (el != nsnull) {
if (strcmp(col, "certcol") == 0)
_retval.Assign(el->orgName);
else
_retval.SetCapacity(0);
return NS_OK;
}
nsCOMPtr<nsIX509Cert> cert = GetCertAtIndex(row);
if (cert == nsnull) return NS_ERROR_FAILURE;
char *str = NULL;
PRUnichar *wstr = NULL;
if (strcmp(col, "certcol") == 0) {
rv = cert->GetCommonName(&wstr);
if (NS_FAILED(rv) || !wstr) {
// can this be fixed to not do copying?
PRUnichar *tmp = nsnull;
rv = cert->GetNickname(&tmp);
nsAutoString nick(tmp);
char *tmps = ToNewCString(nick);
char *mark = strchr(tmps, ':');
if (mark) {
str = PL_strdup(mark + 1);
} else {
wstr = ToNewUnicode(nick);
}
nsMemory::Free(tmp);
nsMemory::Free(tmps);
}
} else if (strcmp(col, "tokencol") == 0) {
rv = cert->GetTokenName(&wstr);
} else if (strcmp(col, "emailcol") == 0) {
rv = cert->GetEmailAddress(&wstr);
} else if (strcmp(col, "verifiedcol") == 0) {
PRUint32 verified;
nsCOMPtr<nsINSSComponent> nssComponent(
do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv)) return rv;
PRBool ocspEnabled;
cert->GetUsesOCSP(&ocspEnabled);
if (ocspEnabled) {
nssComponent->DisableOCSP();
}
rv = cert->GetPurposes(&verified, NULL);
if (verified == nsIX509Cert::VERIFIED_OK) {
nsAutoString vfy;
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("VerifiedTrue").get(), vfy);
if (NS_SUCCEEDED(rv))
wstr = ToNewUnicode(vfy);
} else {
nsAutoString vfy;
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("VerifiedFalse").get(), vfy);
if (NS_SUCCEEDED(rv))
wstr = ToNewUnicode(vfy);
}
if (ocspEnabled) {
nssComponent->EnableOCSP();
}
} else if (strcmp(col, "purposecol") == 0) {
PRUint32 verified;
PRBool ocspEnabled;
nsCOMPtr<nsINSSComponent> nssComponent(
do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv)) return rv;
cert->GetUsesOCSP(&ocspEnabled);
if (ocspEnabled) {
nssComponent->DisableOCSP();
}
rv = cert->GetPurposes(&verified, &wstr);
if (ocspEnabled) {
nssComponent->EnableOCSP();
}
} else if (strcmp(col, "issuedcol") == 0) {
rv = cert->GetIssuedDate(&wstr);
} else if (strcmp(col, "expiredcol") == 0) {
rv = cert->GetExpiresDate(&wstr);
} else if (strcmp(col, "serialnumcol") == 0) {
rv = cert->GetSerialNumber(&wstr);
/*
} else if (strcmp(col, "certdbkeycol") == 0) {
rv = cert->GetDbKey(&str);
*/
} else {
return NS_ERROR_FAILURE;
}
if (str) {
nsAutoString astr = NS_ConvertASCIItoUCS2(str);
wstr = ToNewUnicode(astr);
}
_retval = wstr;
return rv;
}
/* void setOutliner (in nsIOutlinerBoxObject outliner); */
NS_IMETHODIMP
nsCertOutliner::SetOutliner(nsIOutlinerBoxObject *outliner)
{
mOutliner = outliner;
return NS_OK;
}
/* void toggleOpenState (in long index); */
NS_IMETHODIMP
nsCertOutliner::ToggleOpenState(PRInt32 index)
{
outlinerArrayEl *el = GetThreadDescAtIndex(index);
if (el) el->open = !el->open;
PRInt32 fac = (el->open) ? 1 : -1;
if (mOutliner) mOutliner->RowCountChanged(index, fac * el->numChildren);
mSelection->Select(index);
return NS_OK;
}
/* void cycleHeader (in wstring colID, in nsIDOMElement elt); */
NS_IMETHODIMP
nsCertOutliner::CycleHeader(const PRUnichar *colID, nsIDOMElement *elt)
{
return NS_OK;
}
/* void selectionChanged (); */
NS_IMETHODIMP
nsCertOutliner::SelectionChanged()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void cycleCell (in long row, in wstring colID); */
NS_IMETHODIMP
nsCertOutliner::CycleCell(PRInt32 row, const PRUnichar *colID)
{
return NS_OK;
}
/* boolean isEditable (in long row, in wstring colID); */
NS_IMETHODIMP
nsCertOutliner::IsEditable(PRInt32 row, const PRUnichar *colID, PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}
/* void setCellText (in long row, in wstring colID, in wstring value); */
NS_IMETHODIMP
nsCertOutliner::SetCellText(PRInt32 row, const PRUnichar *colID,
const PRUnichar *value)
{
return NS_OK;
}
/* void performAction (in wstring action); */
NS_IMETHODIMP
nsCertOutliner::PerformAction(const PRUnichar *action)
{
return NS_OK;
}
/* void performActionOnRow (in wstring action, in long row); */
NS_IMETHODIMP
nsCertOutliner::PerformActionOnRow(const PRUnichar *action, PRInt32 row)
{
return NS_OK;
}
/* void performActionOnCell (in wstring action, in long row,
* in wstring colID);
*/
NS_IMETHODIMP
nsCertOutliner::PerformActionOnCell(const PRUnichar *action, PRInt32 row,
const PRUnichar *colID)
{
return NS_OK;
}
#ifdef DEBUG_CERT_OUTLINER
void
nsCertOutliner::dumpMap()
{
for (int i=0; i<mNumOrgs; i++) {
nsAutoString org(mOutlinerArray[i].orgName);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("ORG[%s]", NS_LossyConvertUCS2toASCII(org).get()));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("OPEN[%d]", mOutlinerArray[i].open));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("INDEX[%d]", mOutlinerArray[i].certIndex));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("NCHILD[%d]", mOutlinerArray[i].numChildren));
}
for (int i=0; i<mNumRows; i++) {
outlinerArrayEl *el = GetThreadDescAtIndex(i);
if (el != nsnull) {
nsAutoString td(el->orgName);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("thread desc[%d]: %s", i, NS_LossyConvertUCS2toASCII(td).get()));
}
nsCOMPtr<nsIX509Cert> ct = GetCertAtIndex(i);
if (ct != nsnull) {
PRUnichar *goo;
ct->GetCommonName(&goo);
nsAutoString doo(goo);
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("cert [%d]: %s", i, NS_LossyConvertUCS2toASCII(doo).get()));
}
}
}
#endif
//
// CanDropOn
//
// Can't drop on the thread pane.
//
NS_IMETHODIMP nsCertOutliner::CanDropOn(PRInt32 index, PRBool *_retval)
{
NS_ENSURE_ARG_POINTER(_retval);
*_retval = PR_FALSE;
return NS_OK;
}
//
// CanDropBeforeAfter
//
// Can't drop on the thread pane.
//
NS_IMETHODIMP nsCertOutliner::CanDropBeforeAfter(PRInt32 index, PRBool before, PRBool *_retval)
{
NS_ENSURE_ARG_POINTER(_retval);
*_retval = PR_FALSE;
return NS_OK;
}
//
// Drop
//
// Can't drop on the thread pane.
//
NS_IMETHODIMP nsCertOutliner::Drop(PRInt32 row, PRInt32 orient)
{
return NS_OK;
}
//
// IsSorted
//
// ...
//
NS_IMETHODIMP nsCertOutliner::IsSorted(PRBool *_retval)
{
*_retval = PR_FALSE;
return NS_OK;
}

View File

@@ -1,86 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
*/
#ifndef _NS_CERTOUTLINER_H_
#define _NS_CERTOUTLINER_H_
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsICertOutliner.h"
#include "nsIOutlinerView.h"
#include "nsIOutlinerBoxObject.h"
#include "nsIOutlinerSelection.h"
#include "nsISupportsArray.h"
typedef struct outlinerArrayElStr outlinerArrayEl;
class nsCertOutliner : public nsICertOutliner
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICERTOUTLINER
NS_DECL_NSIOUTLINERVIEW
nsCertOutliner();
virtual ~nsCertOutliner();
protected:
static PRInt32 CmpByToken(nsIX509Cert *a, nsIX509Cert *b);
static PRInt32 CmpByIssuerOrg(nsIX509Cert *a, nsIX509Cert *b);
static PRInt32 CmpByName(nsIX509Cert *a, nsIX509Cert *b);
static PRInt32 CmpByTok_IssuerOrg_Name(nsIX509Cert *a, nsIX509Cert *b);
PRInt32 CountOrganizations();
private:
nsCOMPtr<nsISupportsArray> mCertArray;
nsCOMPtr<nsIOutlinerBoxObject> mOutliner;
nsCOMPtr<nsIOutlinerSelection> mSelection;
outlinerArrayEl *mOutlinerArray;
PRInt32 mNumOrgs;
PRInt32 mNumRows;
outlinerArrayEl *GetThreadDescAtIndex(PRInt32 _index);
nsIX509Cert *GetCertAtIndex(PRInt32 _index);
void FreeCertArray();
#ifdef DEBUG_CERT_OUTLINER
/* for debugging purposes */
void dumpMap();
#endif
};
#endif /* _NS_CERTOUTLINER_H_ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,95 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*/
#ifndef _nsCrypto_h_
#define _nsCrypto_h_
#include "nsCOMPtr.h"
#include "nsIDOMCRMFObject.h"
#include "nsIDOMCrypto.h"
#include "nsIDOMPkcs11.h"
#include "nsString.h"
#include "jsapi.h"
#include "nsIPrincipal.h"
#define NS_CRYPTO_CLASSNAME "Crypto JavaScript Class"
#define NS_CRYPTO_CID \
{0x929d9320, 0x251e, 0x11d4, { 0x8a, 0x7c, 0x00, 0x60, 0x08, 0xc8, 0x44, 0xc3} }
#define NS_PKCS11_CLASSNAME "Pkcs11 JavaScript Class"
#define NS_PKCS11_CID \
{0x74b7a390, 0x3b41, 0x11d4, { 0x8a, 0x80, 0x00, 0x60, 0x08, 0xc8, 0x44, 0xc3} }
#define PSM_VERSION_STRING "2.2"
class nsIPSMComponent;
class nsIDOMScriptObjectFactory;
class nsIEventQueue;
class nsCRMFObject : public nsIDOMCRMFObject
{
public:
nsCRMFObject();
virtual ~nsCRMFObject();
NS_DECL_NSIDOMCRMFOBJECT
NS_DECL_ISUPPORTS
nsresult init();
nsresult SetCRMFRequest(char *inRequest);
private:
nsString mBase64Request;
};
class nsCrypto: public nsIDOMCrypto
{
public:
nsCrypto();
virtual ~nsCrypto();
nsresult init();
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMCRYPTO
static nsIPrincipal* GetScriptPrincipal(JSContext *cx);
static nsIEventQueue* GetUIEventQueue();
};
class nsPkcs11 : public nsIDOMPkcs11
{
public:
nsPkcs11();
virtual ~nsPkcs11();
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMPKCS11
};
#endif //_nsCrypto_h_

View File

@@ -1,640 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
extern "C" {
#include "secdert.h"
#ifndef NSS_3_4
#include "keydbt.h"
#endif
}
#include "nspr.h"
#include "nsNSSComponent.h" // for PIPNSS string bundle calls.
#include "keyhi.h"
#include "secder.h"
#include "cryptohi.h"
#include "base64.h"
#include "secasn1.h"
#ifdef NSS_3_4
extern "C" {
#include "pk11pqg.h"
}
#endif
#include "nsProxiedService.h"
#include "nsKeygenHandler.h"
#include "nsVoidArray.h"
#include "nsIServiceManager.h"
#include "nsIDOMHTMLSelectElement.h"
#include "nsIContent.h"
#include "nsINSSDialogs.h"
#include "nsKeygenThread.h"
#include "nsReadableUtils.h"
#include "nsUnicharUtils.h"
//These defines are taken from the PKCS#11 spec
#define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000
#define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020
#define CKM_DSA_KEY_PAIR_GEN 0x00000010
//All possible key size choices.
static SECKeySizeChoiceInfo SECKeySizeChoiceList[] = {
{ nsnull, 2048 },
{ nsnull, 1024 },
{ nsnull, 512 },
{ nsnull, 0 },
};
DERTemplate CERTSubjectPublicKeyInfoTemplate[] = {
{ DER_SEQUENCE,
0, nsnull, sizeof(CERTSubjectPublicKeyInfo) },
{ DER_INLINE,
offsetof(CERTSubjectPublicKeyInfo,algorithm),
SECAlgorithmIDTemplate, },
{ DER_BIT_STRING,
offsetof(CERTSubjectPublicKeyInfo,subjectPublicKey), },
{ 0, }
};
DERTemplate CERTPublicKeyAndChallengeTemplate[] =
{
{ DER_SEQUENCE, 0, nsnull, sizeof(CERTPublicKeyAndChallenge) },
{ DER_ANY, offsetof(CERTPublicKeyAndChallenge,spki), },
{ DER_IA5_STRING, offsetof(CERTPublicKeyAndChallenge,challenge), },
{ 0, }
};
#ifdef NSS_3_4
DERTemplate SECAlgorithmIDTemplate[] = {
{ DER_SEQUENCE,
0, NULL, sizeof(SECAlgorithmID) },
{ DER_OBJECT_ID,
offsetof(SECAlgorithmID,algorithm), },
{ DER_OPTIONAL | DER_ANY,
offsetof(SECAlgorithmID,parameters), },
{ 0, }
};
const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = {
{ SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) },
{ SEC_ASN1_INTEGER, offsetof(PQGParams,prime) },
{ SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) },
{ SEC_ASN1_INTEGER, offsetof(PQGParams,base) },
{ 0, }
};
#endif
static NS_DEFINE_IID(kFormProcessorIID, NS_IFORMPROCESSOR_IID);
static NS_DEFINE_IID(kIDOMHTMLSelectElementIID, NS_IDOMHTMLSELECTELEMENT_IID);
static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
static const char *mozKeyGen = "-mozilla-keygen";
static PQGParams *
decode_pqg_params(char *aStr)
{
unsigned char *buf;
unsigned int len;
PRArenaPool *arena;
PQGParams *params;
SECStatus status;
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (!arena)
return nsnull;
params = NS_STATIC_CAST(PQGParams*, PORT_ArenaZAlloc(arena, sizeof(PQGParams)));
if (!params)
goto loser;
params->arena = arena;
buf = ATOB_AsciiToData(aStr, &len);
if ((!buf) || (len == 0))
goto loser;
status = SEC_ASN1Decode(arena, params, SECKEY_PQGParamsTemplate, (const char*)buf, len);
if (status != SECSuccess)
goto loser;
return params;
loser:
if (arena) {
PORT_FreeArena(arena, PR_FALSE);
}
if (buf) {
PR_Free(buf);
}
return nsnull;
}
static int
pqg_prime_bits(char *str)
{
PQGParams *params = nsnull;
int primeBits = 0, i;
params = decode_pqg_params(str);
if (!params)
goto done; /* lose */
for (i = 0; params->prime.data[i] == 0; i++)
/* empty */;
primeBits = (params->prime.len - i) * 8;
done:
if (params)
#ifdef NSS_3_4
PK11_PQG_DestroyParams(params);
#else
PQG_DestroyParams(params);
#endif
return primeBits;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsKeygenFormProcessor, nsIFormProcessor);
MOZ_DECL_CTOR_COUNTER(nsKeygenFormProcessor)
nsKeygenFormProcessor::nsKeygenFormProcessor()
{
NS_INIT_REFCNT();
MOZ_COUNT_CTOR(nsKeygenFormProcessor);
m_ctx = new PipUIContext();
}
nsKeygenFormProcessor::~nsKeygenFormProcessor()
{
MOZ_COUNT_DTOR(nsKeygenFormProcessor);
}
NS_METHOD
nsKeygenFormProcessor::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult)
{
nsresult rv;
NS_ENSURE_NO_AGGREGATION(aOuter);
nsKeygenFormProcessor* formProc = new nsKeygenFormProcessor();
if (!formProc)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsISupports> stabilize = formProc;
rv = formProc->Init();
if (NS_SUCCEEDED(rv)) {
rv = formProc->QueryInterface(aIID, aResult);
}
return rv;
}
nsresult
nsKeygenFormProcessor::Init()
{
nsresult rv;
nsAutoString str;
// Get the key strings //
nsCOMPtr<nsINSSComponent> nssComponent;
nssComponent = do_GetService(kNSSComponentCID, &rv);
if (NS_FAILED(rv))
return rv;
nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("HighGrade").get(),
str);
SECKeySizeChoiceList[0].name = ToNewUnicode(str);
nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("MediumGrade").get(),
str);
SECKeySizeChoiceList[1].name = ToNewUnicode(str);
nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("LowGrade").get(),
str);
SECKeySizeChoiceList[2].name = ToNewUnicode(str);
return NS_OK;
}
nsresult
nsKeygenFormProcessor::GetSlot(PRUint32 aMechanism, PK11SlotInfo** aSlot)
{
return GetSlotWithMechanism(aMechanism,m_ctx,aSlot);
}
PRUint32 MapGenMechToAlgoMech(PRUint32 mechanism)
{
PRUint32 searchMech;
/* We are interested in slots based on the ability to perform
a given algorithm, not on their ability to generate keys usable
by that algorithm. Therefore, map keygen-specific mechanism tags
to tags for the corresponding crypto algorthm. */
switch(mechanism)
{
case CKM_RSA_PKCS_KEY_PAIR_GEN:
searchMech = CKM_RSA_PKCS;
break;
case CKM_DSA_KEY_PAIR_GEN:
searchMech = CKM_DSA;
break;
case CKM_RC4_KEY_GEN:
searchMech = CKM_RC4;
break;
case CKM_DH_PKCS_KEY_PAIR_GEN:
searchMech = CKM_DH_PKCS_DERIVE; /* ### mwelch is this right? */
break;
case CKM_DES_KEY_GEN:
/* What do we do about DES keygen? Right now, we're just using
DES_KEY_GEN to look for tokens, because otherwise we'll have
to search the token list three times. */
default:
searchMech = mechanism;
break;
}
return searchMech;
}
nsresult
GetSlotWithMechanism(PRUint32 aMechanism,
nsIInterfaceRequestor *m_ctx,
PK11SlotInfo** aSlot)
{
PK11SlotList * slotList = nsnull;
PRUnichar** tokenNameList = nsnull;
nsITokenDialogs * dialogs;
PRUnichar *unicodeTokenChosen;
PK11SlotListElement *slotElement, *tmpSlot;
PRUint32 numSlots = 0, i = 0;
PRBool canceled;
nsresult rv = NS_OK;
*aSlot = nsnull;
// Get the slot
slotList = PK11_GetAllTokens(MapGenMechToAlgoMech(aMechanism),
PR_TRUE, PR_TRUE, m_ctx);
if (!slotList || !slotList->head) {
rv = NS_ERROR_FAILURE;
goto loser;
}
if (!slotList->head->next) {
/* only one slot available, just return it */
*aSlot = slotList->head->slot;
} else {
// Gerenate a list of slots and ask the user to choose //
tmpSlot = slotList->head;
while (tmpSlot) {
numSlots++;
tmpSlot = tmpSlot->next;
}
// Allocate the slot name buffer //
tokenNameList = NS_STATIC_CAST(PRUnichar**, nsMemory::Alloc(sizeof(PRUnichar *) * numSlots));
i = 0;
slotElement = PK11_GetFirstSafe(slotList);
while (slotElement) {
tokenNameList[i] = ToNewUnicode(NS_ConvertUTF8toUCS2(PK11_GetTokenName(slotElement->slot)));
slotElement = PK11_GetNextSafe(slotList, slotElement, PR_FALSE);
i++;
}
/* Throw up the token list dialog and get back the token */
rv = getNSSDialogs((void**)&dialogs,
NS_GET_IID(nsITokenDialogs));
if (NS_FAILED(rv)) goto loser;
rv = dialogs->ChooseToken(nsnull, (const PRUnichar**)tokenNameList, numSlots, &unicodeTokenChosen, &canceled);
NS_RELEASE(dialogs);
if (NS_FAILED(rv)) goto loser;
if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
// Get the slot //
slotElement = PK11_GetFirstSafe(slotList);
nsAutoString tokenStr(unicodeTokenChosen);
while (slotElement) {
if (tokenStr.Equals(NS_ConvertUTF8toUCS2(PK11_GetTokenName(slotElement->slot)))) {
*aSlot = slotElement->slot;
break;
}
slotElement = PK11_GetNextSafe(slotList, slotElement, PR_FALSE);
}
if(!(*aSlot)) {
rv = NS_ERROR_FAILURE;
goto loser;
}
}
// Get a reference to the slot //
PK11_ReferenceSlot(*aSlot);
loser:
if (slotList) {
PK11_FreeSlotList(slotList);
}
if (tokenNameList) {
nsMemory::Free(tokenNameList);
}
return rv;
}
nsresult
nsKeygenFormProcessor::GetPublicKey(nsString& aValue, nsString& aChallenge,
nsString& aKeyType,
nsString& aOutPublicKey, nsString& aPqg)
{
nsresult rv = NS_ERROR_FAILURE;
char *keystring = nsnull;
char *pqgString = nsnull, *str = nsnull;
nsAutoString rsaStr;
nsAutoString dsaStr;
KeyType type;
PRUint32 keyGenMechanism;
PRInt32 primeBits;
PQGParams *pqgParams;
PK11SlotInfo *slot = nsnull;
PK11RSAGenParams rsaParams;
SECOidTag algTag;
int keysize = 0;
void *params;
SECKEYPrivateKey *privateKey = nsnull;
SECKEYPublicKey *publicKey = nsnull;
CERTSubjectPublicKeyInfo *spkInfo = nsnull;
PRArenaPool *arena = nsnull;
SECStatus sec_rv = SECFailure;
SECItem spkiItem;
SECItem pkacItem;
SECItem signedItem;
CERTPublicKeyAndChallenge pkac;
SECKeySizeChoiceInfo *choice = SECKeySizeChoiceList;
nsIGeneratingKeypairInfoDialogs * dialogs;
nsKeygenThread *KeygenRunnable = 0;
nsCOMPtr<nsIKeygenThread> runnable;
// Get the key size //
while (choice) {
if (aValue.Equals(choice->name)) {
keysize = choice->size;
break;
}
choice++;
}
if (!choice) {
goto loser;
}
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (!arena) {
goto loser;
}
// Set the keygen mechanism
rsaStr.Assign(NS_LITERAL_STRING("rsa"));
dsaStr.Assign(NS_LITERAL_STRING("dsa"));
if (aKeyType.IsEmpty() || aKeyType.Equals(rsaStr)) {
type = rsaKey;
keyGenMechanism = CKM_RSA_PKCS_KEY_PAIR_GEN;
} else if (aKeyType.Equals(dsaStr)) {
char * end;
pqgString = ToNewCString(aPqg);
type = dsaKey;
keyGenMechanism = CKM_DSA_KEY_PAIR_GEN;
if (strcmp(pqgString, "null") == 0)
goto loser;
str = pqgString;
do {
end = strchr(str, ',');
if (end != nsnull)
*end = '\0';
primeBits = pqg_prime_bits(str);
if (choice->size == primeBits)
goto found_match;
str = end + 1;
} while (end != nsnull);
goto loser;
found_match:
pqgParams = decode_pqg_params(str);
} else {
goto loser;
}
// Get the slot
rv = GetSlot(keyGenMechanism, &slot);
if (NS_FAILED(rv)) {
goto loser;
}
switch (keyGenMechanism) {
case CKM_RSA_PKCS_KEY_PAIR_GEN:
rsaParams.keySizeInBits = keysize;
rsaParams.pe = DEFAULT_RSA_KEYGEN_PE;
algTag = DEFAULT_RSA_KEYGEN_ALG;
params = &rsaParams;
break;
case CKM_DSA_KEY_PAIR_GEN:
// XXX Fix this! XXX //
goto loser;
default:
goto loser;
}
/* Make sure token is initialized. */
rv = setPassword(slot, m_ctx);
if (NS_FAILED(rv))
goto loser;
sec_rv = PK11_Authenticate(slot, PR_TRUE, m_ctx);
if (sec_rv != SECSuccess) {
goto loser;
}
rv = getNSSDialogs((void**)&dialogs,
NS_GET_IID(nsIGeneratingKeypairInfoDialogs));
if (NS_SUCCEEDED(rv)) {
KeygenRunnable = new nsKeygenThread();
if (KeygenRunnable) {
NS_ADDREF(KeygenRunnable);
}
}
if (NS_FAILED(rv) || !KeygenRunnable) {
rv = NS_OK;
privateKey = PK11_GenerateKeyPair(slot, keyGenMechanism, params,
&publicKey, PR_TRUE, PR_TRUE, nsnull);
} else {
KeygenRunnable->SetParams( slot, keyGenMechanism, params, PR_TRUE, PR_TRUE, nsnull );
runnable = do_QueryInterface(KeygenRunnable);
if (runnable) {
rv = dialogs->DisplayGeneratingKeypairInfo(m_ctx, runnable);
// We call join on the thread,
// so we can be sure that no simultaneous access to the passed parameters will happen.
KeygenRunnable->Join();
NS_RELEASE(dialogs);
if (NS_SUCCEEDED(rv)) {
rv = KeygenRunnable->GetParams(&privateKey, &publicKey);
}
}
}
if (NS_FAILED(rv) || !privateKey) {
goto loser;
}
// just in case we'll need to authenticate to the db -jp //
privateKey->wincx = m_ctx;
/*
* Create a subject public key info from the public key.
*/
spkInfo = SECKEY_CreateSubjectPublicKeyInfo(publicKey);
if ( !spkInfo ) {
goto loser;
}
/*
* Now DER encode the whole subjectPublicKeyInfo.
*/
sec_rv=DER_Encode(arena, &spkiItem, CERTSubjectPublicKeyInfoTemplate, spkInfo);
if (sec_rv != SECSuccess) {
goto loser;
}
/*
* set up the PublicKeyAndChallenge data structure, then DER encode it
*/
pkac.spki = spkiItem;
pkac.challenge.len = aChallenge.Length();
pkac.challenge.data = (unsigned char *)ToNewCString(aChallenge);
sec_rv = DER_Encode(arena, &pkacItem, CERTPublicKeyAndChallengeTemplate, &pkac);
if ( sec_rv != SECSuccess ) {
goto loser;
}
/*
* now sign the DER encoded PublicKeyAndChallenge
*/
sec_rv = SEC_DerSignData(arena, &signedItem, pkacItem.data, pkacItem.len,
privateKey, algTag);
if ( sec_rv != SECSuccess ) {
goto loser;
}
/*
* Convert the signed public key and challenge into base64/ascii.
*/
keystring = BTOA_DataToAscii(signedItem.data, signedItem.len);
aOutPublicKey.AssignWithConversion(keystring);
nsCRT::free(keystring);
rv = NS_OK;
loser:
if ( sec_rv != SECSuccess ) {
if ( privateKey ) {
PK11_DestroyTokenObject(privateKey->pkcs11Slot,privateKey->pkcs11ID);
SECKEY_DestroyPrivateKey(privateKey);
}
if ( publicKey ) {
PK11_DestroyTokenObject(publicKey->pkcs11Slot,publicKey->pkcs11ID);
}
}
if ( spkInfo ) {
SECKEY_DestroySubjectPublicKeyInfo(spkInfo);
}
if ( publicKey ) {
SECKEY_DestroyPublicKey(publicKey);
}
if ( arena ) {
PORT_FreeArena(arena, PR_TRUE);
}
if (slot != nsnull) {
PK11_FreeSlot(slot);
}
if (KeygenRunnable) {
NS_RELEASE(KeygenRunnable);
}
return rv;
}
NS_METHOD
nsKeygenFormProcessor::ProcessValue(nsIDOMHTMLElement *aElement,
const nsString& aName,
nsString& aValue)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIDOMHTMLSelectElement>selectElement;
nsresult res = aElement->QueryInterface(kIDOMHTMLSelectElementIID,
getter_AddRefs(selectElement));
if (NS_SUCCEEDED(res)) {
nsAutoString keygenvalue;
nsAutoString challengeValue;
nsAutoString keyTypeValue;
nsAutoString pqgValue;
nsString publicKey;
res = selectElement->GetAttribute(NS_LITERAL_STRING("_moz-type"), keygenvalue);
if (NS_CONTENT_ATTR_HAS_VALUE == res && keygenvalue.Equals(NS_LITERAL_STRING("-mozilla-keygen"))) {
res = selectElement->GetAttribute(NS_LITERAL_STRING("pqg"), pqgValue);
res = selectElement->GetAttribute(NS_LITERAL_STRING("keytype"), keyTypeValue);
if (NS_FAILED(res) || keyTypeValue.IsEmpty()) {
// If this field is not present, we default to rsa.
keyTypeValue.Assign(NS_LITERAL_STRING("rsa"));
}
res = selectElement->GetAttribute(NS_LITERAL_STRING("challenge"), challengeValue);
rv = GetPublicKey(aValue, challengeValue, keyTypeValue,
publicKey, pqgValue);
aValue = publicKey;
}
}
return rv;
}
NS_METHOD nsKeygenFormProcessor::ProvideContent(const nsString& aFormType,
nsVoidArray& aContent,
nsString& aAttribute)
{
nsString selectKey;
SECKeySizeChoiceInfo *choice = SECKeySizeChoiceList;
selectKey.Assign(NS_LITERAL_STRING("SELECT"));
if (Compare(aFormType, NS_LITERAL_STRING("SELECT"),
nsCaseInsensitiveStringComparator()) == 0) {
for (SECKeySizeChoiceInfo* choice = SECKeySizeChoiceList; choice && choice->name; ++choice) {
nsString *str = new nsString(choice->name);
aContent.AppendElement(str);
}
aAttribute.AssignWithConversion(mozKeyGen);
}
return NS_OK;
}

View File

@@ -1,70 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Drinan. (ddrinan@netscape.com)
*
*/
#ifndef _NSKEYGENHANDLER_H_
#define _NSKEYGENHANDLER_H_
// Form Processor
#include "nsIFormProcessor.h"
typedef struct SECKeySizeChoiceInfoStr {
PRUnichar *name;
int size;
} SECKeySizeChoiceInfo;
nsresult GetSlotWithMechanism(PRUint32 mechanism,
nsIInterfaceRequestor *ctx,
PK11SlotInfo **retSlot);
#define DEFAULT_RSA_KEYGEN_PE 65537L
#define DEFAULT_RSA_KEYGEN_ALG SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION
class nsKeygenFormProcessor : public nsIFormProcessor {
public:
nsKeygenFormProcessor();
virtual ~nsKeygenFormProcessor();
nsresult Init();
NS_IMETHOD ProcessValue(nsIDOMHTMLElement *aElement,
const nsString& aName,
nsString& aValue);
NS_IMETHOD ProvideContent(const nsString& aFormType,
nsVoidArray& aContent,
nsString& aAttribute);
NS_DECL_ISUPPORTS
static NS_METHOD Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
protected:
nsresult GetPublicKey(nsString& aValue, nsString& aChallenge,
nsString& akeyType, nsString& aOutPublicKey,
nsString& aPqg);
nsresult GetSlot(PRUint32 aMechanism, PK11SlotInfo** aSlot);
private:
nsCOMPtr<nsIInterfaceRequestor> m_ctx;
};
#endif //_NSKEYGENHANDLER_H_

View File

@@ -1,257 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*/
#include "pk11func.h"
#include "nsCOMPtr.h"
#include "nsProxiedService.h"
#include "nsKeygenThread.h"
NS_IMPL_THREADSAFE_ISUPPORTS1(nsKeygenThread, nsIKeygenThread)
nsKeygenThread::nsKeygenThread()
:mutex(nsnull),
statusDialogPtr(nsnull),
iAmRunning(PR_FALSE),
keygenReady(PR_FALSE),
statusDialogClosed(PR_FALSE),
alreadyReceivedParams(PR_FALSE),
privateKey(nsnull),
publicKey(nsnull),
slot(nsnull),
keyGenMechanism(0),
params(nsnull),
isPerm(PR_FALSE),
isSensitive(PR_FALSE),
wincx(nsnull),
threadHandle(nsnull)
{
NS_INIT_ISUPPORTS();
mutex = PR_NewLock();
}
nsKeygenThread::~nsKeygenThread()
{
if (mutex) {
PR_DestroyLock(mutex);
}
if (statusDialogPtr) {
NS_RELEASE(statusDialogPtr);
}
}
void nsKeygenThread::SetParams(
PK11SlotInfo *a_slot,
PRUint32 a_keyGenMechanism,
void *a_params,
PRBool a_isPerm,
PRBool a_isSensitive,
void *a_wincx )
{
PR_Lock(mutex);
if (!alreadyReceivedParams) {
alreadyReceivedParams = PR_TRUE;
if (a_slot) {
slot = PK11_ReferenceSlot(a_slot);
}
else {
slot = nsnull;
}
keyGenMechanism = a_keyGenMechanism;
params = a_params;
isPerm = a_isPerm;
isSensitive = a_isSensitive;
wincx = a_wincx;
}
PR_Unlock(mutex);
}
nsresult nsKeygenThread::GetParams(
SECKEYPrivateKey **a_privateKey,
SECKEYPublicKey **a_publicKey)
{
if (!a_privateKey || !a_publicKey) {
return NS_ERROR_FAILURE;
}
nsresult rv;
PR_Lock(mutex);
// GetParams must not be called until thread creator called
// Join on this thread.
NS_ASSERTION(keygenReady, "logic error in nsKeygenThread::GetParams");
if (keygenReady) {
*a_privateKey = privateKey;
*a_publicKey = publicKey;
privateKey = 0;
publicKey = 0;
rv = NS_OK;
}
else {
rv = NS_ERROR_FAILURE;
}
PR_Unlock(mutex);
return rv;
}
static void PR_CALLBACK nsKeygenThreadRunner(void *arg)
{
nsKeygenThread *self = NS_STATIC_CAST(nsKeygenThread *, arg);
self->Run();
}
nsresult nsKeygenThread::StartKeyGeneration(nsIDOMWindowInternal *statusDialog)
{
if (!mutex)
return NS_OK;
if (!statusDialog )
return NS_OK;
nsCOMPtr<nsIProxyObjectManager> proxyman(do_GetService(NS_XPCOMPROXY_CONTRACTID));
if (!proxyman)
return NS_OK;
nsCOMPtr<nsIDOMWindowInternal> wi;
proxyman->GetProxyForObject( NS_UI_THREAD_EVENTQ,
nsIDOMWindowInternal::GetIID(),
statusDialog,
PROXY_SYNC | PROXY_ALWAYS,
getter_AddRefs(wi));
PR_Lock(mutex);
if (iAmRunning || keygenReady) {
PR_Unlock(mutex);
return NS_OK;
}
statusDialogPtr = wi;
NS_ADDREF(statusDialogPtr);
wi = 0;
iAmRunning = PR_TRUE;
threadHandle = PR_CreateThread(PR_USER_THREAD, nsKeygenThreadRunner, NS_STATIC_CAST(void*, this),
PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0);
// bool thread_started_ok = (threadHandle != nsnull);
// we might want to return "thread started ok" to caller in the future
NS_ASSERTION(threadHandle, "Could not create nsKeygenThreadRunner thread\n");
PR_Unlock(mutex);
return NS_OK;
}
nsresult nsKeygenThread::UserCanceled(PRBool *threadAlreadyClosedDialog)
{
threadAlreadyClosedDialog = PR_FALSE;
if (!mutex)
return NS_OK;
PR_Lock(mutex);
if (keygenReady)
*threadAlreadyClosedDialog = statusDialogClosed;
// User somehow closed the dialog, but we will not cancel.
// Bad luck, we told him not do, and user still has to wait.
// However, we remember that it's closed and will not close
// it again to avoid problems.
statusDialogClosed = PR_TRUE;
PR_Unlock(mutex);
return NS_OK;
}
void nsKeygenThread::Run(void)
{
PRBool canGenerate = PR_FALSE;
PR_Lock(mutex);
if (alreadyReceivedParams) {
canGenerate = PR_TRUE;
keygenReady = PR_FALSE;
}
PR_Unlock(mutex);
if (canGenerate)
privateKey = PK11_GenerateKeyPair(slot, keyGenMechanism,
params, &publicKey,
isPerm, isSensitive, wincx);
// This call gave us ownership over privateKey and publicKey.
// But as the params structure is owner by our caller,
// we effectively transferred ownership to the caller.
// As long as key generation can't be canceled, we don't need
// to care for cleaning this up.
nsIDOMWindowInternal *windowToClose = 0;
PR_Lock(mutex);
keygenReady = PR_TRUE;
iAmRunning = PR_FALSE;
// forget our parameters
if (slot) {
PK11_FreeSlot(slot);
slot = 0;
}
keyGenMechanism = 0;
params = 0;
wincx = 0;
if (!statusDialogClosed)
windowToClose = statusDialogPtr;
statusDialogPtr = 0;
statusDialogClosed = PR_TRUE;
PR_Unlock(mutex);
if (windowToClose)
windowToClose->Close();
}
void nsKeygenThread::Join()
{
if (!threadHandle)
return;
PR_JoinThread(threadHandle);
threadHandle = nsnull;
return;
}

View File

@@ -1,76 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*/
#ifndef _NSKEYGENTHREAD_H_
#define _NSKEYGENTHREAD_H_
#include "keyhi.h"
#include "nspr.h"
#include "nsIKeygenThread.h"
class nsKeygenThread : public nsIKeygenThread
{
private:
PRLock *mutex;
nsIDOMWindowInternal* statusDialogPtr;
PRBool iAmRunning;
PRBool keygenReady;
PRBool statusDialogClosed;
PRBool alreadyReceivedParams;
SECKEYPrivateKey *privateKey;
SECKEYPublicKey *publicKey;
PK11SlotInfo *slot;
PRUint32 keyGenMechanism;
void *params;
PRBool isPerm;
PRBool isSensitive;
void *wincx;
PRThread *threadHandle;
public:
nsKeygenThread();
virtual ~nsKeygenThread();
NS_DECL_NSIKEYGENTHREAD
NS_DECL_ISUPPORTS
void SetParams(
PK11SlotInfo *a_slot,
PRUint32 a_keyGenMechanism,
void *a_params,
PRBool a_isPerm,
PRBool a_isSensitive,
void *a_wincx );
nsresult GetParams(
SECKEYPrivateKey **a_privateKey,
SECKEYPublicKey **a_publicKey);
void Join(void);
void Run(void);
};
#endif //_NSKEYGENTHREAD_H_

View File

@@ -1,475 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "nsNSSASN1Object.h"
#include "nsIComponentManager.h"
#include "secasn1.h"
#include "nsReadableUtils.h"
NS_IMPL_THREADSAFE_ISUPPORTS2(nsNSSASN1Sequence, nsIASN1Sequence,
nsIASN1Object);
NS_IMPL_THREADSAFE_ISUPPORTS2(nsNSSASN1PrintableItem, nsIASN1PrintableItem,
nsIASN1Object);
// This function is used to interpret an integer that
// was encoded in a DER buffer. This function is used
// when converting a DER buffer into a nsIASN1Object
// structure. This interprets the buffer in data
// as defined by the DER (Distinguised Encoding Rules) of
// ASN1.
static int
getInteger256(unsigned char *data, unsigned int nb)
{
int val;
switch (nb) {
case 1:
val = data[0];
break;
case 2:
val = (data[0] << 8) | data[1];
break;
case 3:
val = (data[0] << 16) | (data[1] << 8) | data[2];
break;
case 4:
val = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
break;
default:
return -1;
}
return val;
}
// This function is used to retrieve the lenght of a DER encoded
// item. It looks to see if this a multibyte length and then
// interprets the buffer accordingly to get the actual length value.
// This funciton is used mostly while parsing the DER headers.
//
// A DER encoded item has the following structure:
//
// <tag><length<data consisting of lenght bytes>
static PRInt32
getDERItemLength(unsigned char *data, unsigned char *end,
unsigned long *bytesUsed, PRBool *indefinite)
{
unsigned char lbyte = *data++;
PRInt32 length = -1;
*indefinite = PR_FALSE;
if (lbyte >= 0x80) {
// Multibyte length
unsigned nb = (unsigned) (lbyte & 0x7f);
if (nb > 4) {
return -1;
}
if (nb > 0) {
if ((data+nb) > end) {
return -1;
}
length = getInteger256(data, nb);
if (length < 0)
return -1;
} else {
*indefinite = PR_TRUE;
length = 0;
}
*bytesUsed = nb+1;
} else {
length = lbyte;
*bytesUsed = 1;
}
return length;
}
static nsresult
buildASN1ObjectFromDER(unsigned char *data,
unsigned char *end,
nsIASN1Sequence *parent)
{
nsresult rv;
nsCOMPtr<nsIASN1Sequence> sequence;
nsCOMPtr<nsIASN1PrintableItem> printableItem;
nsCOMPtr<nsIASN1Object> asn1Obj;
nsCOMPtr<nsISupportsArray> parentObjects;
NS_ENSURE_ARG_POINTER(parent);
if (data >= end)
return NS_OK;
unsigned char code, tagnum;
// A DER item has the form of |tag|len|data
// tag is one byte and describes the type of elment
// we are dealing with.
// len is a DER encoded int telling us how long the data is
// data is a buffer that is len bytes long and has to be
// interpreted according to its type.
unsigned long bytesUsed;
PRBool indefinite;
PRInt32 len;
PRUint32 type;
if (parent == nsnull) {
parent = new nsNSSASN1Sequence();
NS_IF_ADDREF(parent);
}
if (parent == nsnull)
return NS_ERROR_FAILURE;
rv = parent->GetASN1Objects(getter_AddRefs(parentObjects));
if (NS_FAILED(rv) || parentObjects == nsnull)
return NS_ERROR_FAILURE;
while (data < end) {
code = *data;
tagnum = code & SEC_ASN1_TAGNUM_MASK;
/*
* NOTE: This code does not (yet) handle the high-tag-number form!
*/
if (tagnum == SEC_ASN1_HIGH_TAG_NUMBER) {
return NS_ERROR_FAILURE;
}
data++;
len = getDERItemLength(data, end, &bytesUsed, &indefinite);
data += bytesUsed;
if ((len < 0) || ((data+len) > end))
return NS_ERROR_FAILURE;
if (code & SEC_ASN1_CONSTRUCTED) {
if (len > 0 || indefinite) {
sequence = new nsNSSASN1Sequence();
switch (code & SEC_ASN1_CLASS_MASK) {
case SEC_ASN1_UNIVERSAL:
type = tagnum;
break;
case SEC_ASN1_APPLICATION:
type = nsIASN1Object::ASN1_APPLICATION;
break;
case SEC_ASN1_CONTEXT_SPECIFIC:
type = nsIASN1Object::ASN1_CONTEXT_SPECIFIC;
break;
case SEC_ASN1_PRIVATE:
type = nsIASN1Object::ASN1_PRIVATE;
break;
default:
NS_ASSERTION(0,"Bad DER");
return NS_ERROR_FAILURE;
}
sequence->SetTag(tagnum);
sequence->SetType(type);
rv = buildASN1ObjectFromDER(data, (len == 0) ? end : data + len,
sequence);
asn1Obj = sequence;
}
} else {
printableItem = new nsNSSASN1PrintableItem();
asn1Obj = printableItem;
asn1Obj->SetType(tagnum);
asn1Obj->SetTag(tagnum);
printableItem->SetData((char*)data, len);
}
data += len;
parentObjects->AppendElement(asn1Obj);
}
return NS_OK;
}
nsresult
CreateFromDER(unsigned char *data,
unsigned int len,
nsIASN1Object **retval)
{
nsCOMPtr<nsIASN1Sequence> sequence = new nsNSSASN1Sequence;
*retval = nsnull;
nsresult rv = buildASN1ObjectFromDER(data, data+len, sequence);
if (NS_SUCCEEDED(rv)) {
// The actual object will be the first element inserted
// into the sequence of the sequence variable we created.
nsCOMPtr<nsISupportsArray> elements;
sequence->GetASN1Objects(getter_AddRefs(elements));
nsCOMPtr<nsISupports> isupports = dont_AddRef(elements->ElementAt(0));
nsCOMPtr<nsIASN1Object> asn1Obj(do_QueryInterface(isupports));
*retval = asn1Obj;
if (*retval == nsnull)
return NS_ERROR_FAILURE;
NS_ADDREF(*retval);
}
return rv;
}
nsNSSASN1Sequence::nsNSSASN1Sequence() : mProcessObjects(PR_TRUE),
mShowObjects(PR_TRUE)
{
NS_INIT_ISUPPORTS();
/* member initializers and constructor code */
}
nsNSSASN1Sequence::~nsNSSASN1Sequence()
{
/* destructor code */
}
/* attribute nsISupportsArray ASN1Objects; */
NS_IMETHODIMP
nsNSSASN1Sequence::GetASN1Objects(nsISupportsArray * *aASN1Objects)
{
if (mASN1Objects == nsnull) {
mASN1Objects = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID);
}
*aASN1Objects = mASN1Objects;
NS_IF_ADDREF(*aASN1Objects);
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetASN1Objects(nsISupportsArray * aASN1Objects)
{
mASN1Objects = aASN1Objects;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::GetTag(PRUint32 *aTag)
{
*aTag = mTag;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetTag(PRUint32 aTag)
{
mTag = aTag;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::GetType(PRUint32 *aType)
{
*aType = mType;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetType(PRUint32 aType)
{
mType = aType;
return NS_OK;
}
/* attribute wstring displayName; */
NS_IMETHODIMP
nsNSSASN1Sequence::GetDisplayName(PRUnichar * *aDisplayName)
{
NS_ENSURE_ARG_POINTER(aDisplayName);
*aDisplayName = ToNewUnicode(mDisplayName);
return (*aDisplayName) ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetDisplayName(const PRUnichar * aDisplayName)
{
mDisplayName.Assign(aDisplayName);
return NS_OK;
}
/* attribute wstring displayValue; */
NS_IMETHODIMP
nsNSSASN1Sequence::GetDisplayValue(PRUnichar * *aDisplayValue)
{
NS_ENSURE_ARG_POINTER(aDisplayValue);
*aDisplayValue = ToNewUnicode(mDisplayValue);
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetDisplayValue(const PRUnichar * aDisplayValue)
{
mDisplayValue.Assign(aDisplayValue);
return NS_OK;
}
/* attribute boolean processObjects; */
NS_IMETHODIMP
nsNSSASN1Sequence::GetProcessObjects(PRBool *aProcessObjects)
{
NS_ENSURE_ARG_POINTER(aProcessObjects);
*aProcessObjects = mProcessObjects;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetProcessObjects(PRBool aProcessObjects)
{
mProcessObjects = aProcessObjects;
SetShowObjects(mProcessObjects);
return NS_OK;
}
/* attribute boolean showObjects; */
NS_IMETHODIMP
nsNSSASN1Sequence::GetShowObjects(PRBool *aShowObjects)
{
NS_ENSURE_ARG_POINTER(aShowObjects);
*aShowObjects = mShowObjects;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1Sequence::SetShowObjects(PRBool aShowObjects)
{
mShowObjects = aShowObjects;
return NS_OK;
}
nsNSSASN1PrintableItem::nsNSSASN1PrintableItem() : mData(nsnull),
mLen(0)
{
NS_INIT_ISUPPORTS();
/* member initializers and constructor code */
}
nsNSSASN1PrintableItem::~nsNSSASN1PrintableItem()
{
/* destructor code */
if (mData)
nsMemory::Free(mData);
}
/* readonly attribute wstring value; */
NS_IMETHODIMP
nsNSSASN1PrintableItem::GetDisplayValue(PRUnichar * *aValue)
{
*aValue = ToNewUnicode(mValue);
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::SetDisplayValue(const PRUnichar * aValue)
{
mValue.Assign(aValue);
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::GetTag(PRUint32 *aTag)
{
*aTag = mTag;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::SetTag(PRUint32 aTag)
{
mTag = aTag;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::GetType(PRUint32 *aType)
{
*aType = mType;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::SetType(PRUint32 aType)
{
mType = aType;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::SetData(char *data, PRUint32 len)
{
if (len > 0) {
if (mData) {
if (mLen < len)
nsMemory::Realloc(mData, len);
} else {
mData = (unsigned char*)nsMemory::Alloc(len);
}
if (mData == nsnull)
return NS_ERROR_FAILURE;
memcpy(mData, data, len);
} else if (len == 0) {
if (mData) {
nsMemory::Free(mData);
mData = nsnull;
}
} else {
NS_ASSERTION(0,"Passed in invalid buffer length to SetData");
return NS_ERROR_FAILURE;
}
mLen = len;
return NS_OK;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::GetData(char **outData, PRUint32 *outLen)
{
NS_ENSURE_ARG_POINTER(outData);
NS_ENSURE_ARG_POINTER(outLen);
*outData = (char*)mData;
*outLen = mLen;
return NS_OK;
}
/* attribute wstring displayName; */
NS_IMETHODIMP
nsNSSASN1PrintableItem::GetDisplayName(PRUnichar * *aDisplayName)
{
NS_ENSURE_ARG_POINTER(aDisplayName);
*aDisplayName = ToNewUnicode(mDisplayName);
return (*aDisplayName) ? NS_OK : NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsNSSASN1PrintableItem::SetDisplayName(const PRUnichar * aDisplayName)
{
mDisplayName.Assign(aDisplayName);
return NS_OK;
}

View File

@@ -1,92 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef _NSSASN_H_
#define _NSSASN_H_
#include "nscore.h"
#include "nsIX509Cert.h"
#include "nsIASN1Outliner.h"
#include "nsIOutlinerView.h"
#include "nsIOutlinerSelection.h"
#include "nsCOMPtr.h"
#include "nsString.h"
//
// Read comments in nsIX509Cert.idl for a description of the desired
// purpose for this ASN1 interface implementation.
//
class nsNSSASN1Sequence : public nsIASN1Sequence
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIASN1SEQUENCE
NS_DECL_NSIASN1OBJECT
nsNSSASN1Sequence();
virtual ~nsNSSASN1Sequence();
/* additional members */
private:
nsCOMPtr<nsISupportsArray> mASN1Objects;
nsString mDisplayName;
nsString mDisplayValue;
PRUint32 mType;
PRUint32 mTag;
PRBool mProcessObjects;
PRBool mShowObjects;
};
class nsNSSASN1PrintableItem : public nsIASN1PrintableItem
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIASN1PRINTABLEITEM
NS_DECL_NSIASN1OBJECT
nsNSSASN1PrintableItem();
virtual ~nsNSSASN1PrintableItem();
/* additional members */
private:
nsString mDisplayName;
nsString mValue;
PRUint32 mType;
PRUint32 mTag;
unsigned char *mData;
PRUint32 mLen;
};
nsresult CreateFromDER(unsigned char *data,
unsigned int len,
nsIASN1Object **retval);
#endif //_NSSASN_H_

View File

@@ -1,318 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
* Terry Hayes <thayes@netscape.com>
*/
#include "nsNSSComponent.h" // for PIPNSS string bundle calls.
#include "nsNSSCallbacks.h"
#include "nsNSSCertificate.h"
#include "nsISSLStatus.h"
#include "nsNSSIOLayer.h" // for nsNSSSocketInfo
#include "nsIWebProgressListener.h"
#include "nsIStringBundle.h"
#include "nsXPIDLString.h"
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsReadableUtils.h"
#include "nsIPrompt.h"
#include "nsProxiedService.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "ssl.h"
#include "cert.h"
static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
/* Implementation of nsISSLStatus */
class nsSSLStatus
: public nsISSLStatus
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISSLSTATUS
nsSSLStatus();
virtual ~nsSSLStatus();
/* public for initilization in this file */
nsCOMPtr<nsIX509Cert> mServerCert;
PRUint32 mKeyLength;
PRUint32 mSecretKeyLength;
nsXPIDLCString mCipherName;
};
NS_IMETHODIMP
nsSSLStatus::GetServerCert(nsIX509Cert** _result)
{
NS_ASSERTION(_result, "non-NULL destination required");
*_result = mServerCert;
NS_IF_ADDREF(*_result);
return NS_OK;
}
NS_IMETHODIMP
nsSSLStatus::GetKeyLength(PRUint32* _result)
{
NS_ASSERTION(_result, "non-NULL destination required");
*_result = mKeyLength;
return NS_OK;
}
NS_IMETHODIMP
nsSSLStatus::GetSecretKeyLength(PRUint32* _result)
{
NS_ASSERTION(_result, "non-NULL destination required");
*_result = mSecretKeyLength;
return NS_OK;
}
NS_IMETHODIMP
nsSSLStatus::GetCipherName(char** _result)
{
NS_ASSERTION(_result, "non-NULL destination required");
*_result = PL_strdup(mCipherName.get());
return NS_OK;
}
nsSSLStatus::nsSSLStatus()
: mKeyLength(0), mSecretKeyLength(0)
{
NS_INIT_ISUPPORTS();
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsSSLStatus, nsISSLStatus);
nsSSLStatus::~nsSSLStatus()
{
}
char* PK11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg) {
nsresult rv = NS_OK;
PRUnichar *password = nsnull;
PRBool value = PR_FALSE;
nsIInterfaceRequestor *ir = NS_STATIC_CAST(nsIInterfaceRequestor*, arg);
nsCOMPtr<nsIPrompt> proxyPrompt;
// If no context is provided, no prompt is possible.
if (!ir)
return nsnull;
/* TODO: Retry should generate a different dialog message */
/*
if (retry)
return nsnull;
*/
// The interface requestor object may not be safe, so
// proxy the call to get the nsIPrompt.
nsCOMPtr<nsIProxyObjectManager> proxyman(do_GetService(NS_XPCOMPROXY_CONTRACTID));
if (!proxyman) return nsnull;
nsCOMPtr<nsIInterfaceRequestor> proxiedCallbacks;
proxyman->GetProxyForObject(NS_UI_THREAD_EVENTQ,
NS_GET_IID(nsIInterfaceRequestor),
ir,
PROXY_SYNC,
getter_AddRefs(proxiedCallbacks));
// Get the desired interface
nsCOMPtr<nsIPrompt> prompt(do_GetInterface(proxiedCallbacks));
if (!prompt) {
NS_ASSERTION(PR_FALSE, "callbacks does not implement nsIPrompt");
return nsnull;
}
// Finally, get a proxy for the nsIPrompt
proxyman->GetProxyForObject(NS_UI_THREAD_EVENTQ,
NS_GET_IID(nsIPrompt),
prompt,
PROXY_SYNC,
getter_AddRefs(proxyPrompt));
nsXPIDLString promptString;
nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv))
return nsnull;
const PRUnichar* formatStrings[1] = { ToNewUnicode(nsDependentCString(PK11_GetTokenName(slot))) };
rv = nssComponent->PIPBundleFormatStringFromName(NS_LITERAL_STRING("CertPassPrompt").get(),
formatStrings, 1,
getter_Copies(promptString));
nsMemory::Free(NS_CONST_CAST(PRUnichar*, formatStrings[0]));
if (NS_FAILED(rv))
return nsnull;
rv = proxyPrompt->PromptPassword(nsnull, promptString.get(),
&password, nsnull, nsnull, &value);
if (NS_SUCCEEDED(rv) && value) {
char* str = ToNewCString(nsDependentString(password));
Recycle(password);
return str;
}
return nsnull;
}
void PR_CALLBACK HandshakeCallback(PRFileDesc* fd, void* client_data) {
PRInt32 sslStatus;
char* signer = nsnull;
char* cipherName = nsnull;
PRInt32 keyLength;
nsresult rv;
PRInt32 encryptBits;
if (SECSuccess == SSL_SecurityStatus(fd, &sslStatus, &cipherName, &keyLength,
&encryptBits, &signer, nsnull))
{
PRInt32 secStatus;
if (sslStatus == SSL_SECURITY_STATUS_OFF)
secStatus = nsIWebProgressListener::STATE_IS_BROKEN;
else if (encryptBits >= 90)
secStatus = (nsIWebProgressListener::STATE_IS_SECURE |
nsIWebProgressListener::STATE_SECURE_HIGH);
else
secStatus = (nsIWebProgressListener::STATE_IS_SECURE |
nsIWebProgressListener::STATE_SECURE_LOW);
CERTCertificate *peerCert = SSL_PeerCertificate(fd);
char* caName = CERT_GetOrgName(&peerCert->issuer);
CERT_DestroyCertificate(peerCert);
if (!caName) {
caName = signer;
}
// If the CA name is RSA Data Security, then change the name to the real
// name of the company i.e. VeriSign, Inc.
if (nsCRT::strcmp((const char*)caName, "RSA Data Security, Inc.") == 0) {
// In this case, caName != signer since the logic implies signer
// would be at minimal "O=RSA Data Security, Inc" because caName
// is what comes after to O=. So we're OK just freeing this memory
// without checking to see if it's equal to signer;
NS_ASSERTION(caName != signer, "caName was equal to caName when it shouldn't be");
PR_Free(caName);
caName = PL_strdup("Verisign, Inc.");
}
nsXPIDLString shortDesc;
const PRUnichar* formatStrings[1] = { ToNewUnicode(nsDependentCString(caName)) };
nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv))
return;
rv = nssComponent->PIPBundleFormatStringFromName(NS_LITERAL_STRING("SignedBy").get(),
formatStrings, 1,
getter_Copies(shortDesc));
nsMemory::Free(NS_CONST_CAST(PRUnichar*, formatStrings[0]));
nsNSSSocketInfo* infoObject = (nsNSSSocketInfo*) fd->higher->secret;
infoObject->SetSecurityState(secStatus);
infoObject->SetShortSecurityDescription((const PRUnichar*)shortDesc);
/* Set the SSL Status information */
nsCOMPtr<nsSSLStatus> status = new nsSSLStatus();
CERTCertificate *serverCert = SSL_PeerCertificate(fd);
if (serverCert) status->mServerCert = new nsNSSCertificate(serverCert);
status->mKeyLength = keyLength;
status->mSecretKeyLength = encryptBits;
status->mCipherName.Adopt(cipherName);
infoObject->SetSSLStatus(status);
if (caName != signer)
PR_Free(caName);
PR_Free(signer);
}
}
SECStatus PR_CALLBACK AuthCertificateCallback(void* client_data, PRFileDesc* fd,
PRBool checksig, PRBool isServer) {
// first the default action
SECStatus rv = SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
// We want to remember the CA certs in the temp db, so that the application can find the
// complete chain at any time it might need it.
// But we keep only those CA certs in the temp db, that we didn't already know.
if (SECSuccess == rv) {
CERTCertificate *serverCert = SSL_PeerCertificate(fd);
if (serverCert) {
CERTCertList *certList = CERT_GetCertChainFromCert(serverCert, PR_Now(), certUsageSSLCA);
nsCOMPtr<nsINSSComponent> nssComponent;
for (CERTCertListNode *node = CERT_LIST_HEAD(certList);
!CERT_LIST_END(node, certList);
node = CERT_LIST_NEXT(node)) {
if (node->cert->slot) {
// This cert was found on a token, no need to remember it in the temp db.
continue;
}
if (node->cert->isperm) {
// We don't need to remember certs already stored in perm db.
continue;
}
if (node->cert == serverCert) {
// We don't want to remember the server cert,
// the code that cares for displaying page info does this already.
continue;
}
// We have found a signer cert that we want to remember.
if (!nssComponent) {
// delay getting the service until we really need it
nsresult rv;
nssComponent = do_GetService(kNSSComponentCID, &rv);
}
if (nssComponent) {
nssComponent->RememberCert(node->cert);
}
}
CERT_DestroyCertList(certList);
CERT_DestroyCertificate(serverCert);
}
}
return rv;
}

View File

@@ -1,38 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*/
#ifndef _NSNSSCALLBACKS_H_
#define _NSNSSCALLBACKS_H_
#include "pk11func.h"
#include "nspr.h"
char* PK11PasswordPrompt(PK11SlotInfo *slot, PRBool retry, void* arg);
void PR_CALLBACK HandshakeCallback(PRFileDesc *fd, void *client_data);
SECStatus PR_CALLBACK AuthCertificateCallback(void* client_data, PRFileDesc* fd,
PRBool checksig, PRBool isServer);
#endif // _NSNSSCALLBACKS_H_

File diff suppressed because it is too large Load Diff

View File

@@ -1,158 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
*/
#ifndef _NS_NSSCERTIFICATE_H_
#define _NS_NSSCERTIFICATE_H_
#include "nsIX509Cert.h"
#include "nsIX509CertDB.h"
#ifdef NSS_3_4
/* private NSS defines used by PSM */
/* (must be declated before cert.h) */
#define CERT_NewTempCertificate __CERT_NewTempCertificate
#define CERT_AddTempCertToPerm __CERT_AddTempCertToPerm
#endif
#include "prtypes.h"
#include "cert.h"
#include "secitem.h"
#include "nsString.h"
class nsINSSComponent;
/* Certificate */
class nsNSSCertificate : public nsIX509Cert
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIX509CERT
nsNSSCertificate(char *certDER, int derLen);
nsNSSCertificate(CERTCertificate *cert);
/* from a request? */
virtual ~nsNSSCertificate();
CERTCertificate *GetCert();
nsresult MarkForPermDeletion();
nsresult SetCertType(PRUint32 aCertType);
nsresult GetCertType(PRUint32 *aCertType);
nsresult FormatUIStrings(const nsAutoString &nickname, nsAutoString &nickWithSerial, nsAutoString &details);
private:
CERTCertificate *mCert;
PRBool mPermDelete;
PRUint32 mCertType;
nsCOMPtr<nsIASN1Object> mASN1Structure;
nsresult CreateASN1Struct();
nsresult CreateTBSCertificateASN1Struct(nsIASN1Sequence **retSequence,
nsINSSComponent *nssComponent);
PRBool verifyFailed(PRUint32 *_verified);
nsresult GetUsageArray(char *suffix,
PRUint32 *_verified,
PRUint32 *_count,
PRUnichar **tmpUsages);
};
/* Header file */
#define CRL_AUTOUPDATE_TIMIINGTYPE_PREF "security.crl.autoupdate.timingType"
#define CRL_AUTOUPDATE_TIME_PREF "security.crl.autoupdate.nextInstant"
#define CRL_AUTOUPDATE_URL_PREF "security.crl.autoupdate.url"
#define CRL_AUTOUPDATE_DAYCNT_PREF "security.crl.autoupdate.dayCnt"
#define CRL_AUTOUPDATE_FREQCNT_PREF "security.crl.autoupdate.freqCnt"
#define CRL_AUTOUPDATE_ERRCNT_PREF "security.crl.autoupdate.errCount"
#define CRL_AUTOUPDATE_ERRDETAIL_PREF "security.crl.autoupdate.errDetail"
#define CRL_AUTOUPDATE_ENABLED_PREF "security.crl.autoupdate.enable."
#define CRL_AUTOUPDATE_DEFAULT_DELAY 30000UL
class nsCrlEntry : public nsICrlEntry
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICRLENTRY
nsCrlEntry();
nsCrlEntry(CERTSignedCrl *);
nsCrlEntry(const PRUnichar*, const PRUnichar*, const PRUnichar*, const PRUnichar*, PRTime, PRTime, const PRUnichar*, const PRUnichar*);
virtual ~nsCrlEntry();
/* additional members */
private:
nsString mOrg;
nsString mOrgUnit;
nsString mLastUpdateLocale;
nsString mNextUpdateLocale;
PRTime mLastUpdate;
PRTime mNextUpdate;
nsString mNameInDb;
nsString mLastFetchURL;
nsString mNextAutoUpdateDate;
};
class nsNSSCertificateDB : public nsIX509CertDB
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIX509CERTDB
nsNSSCertificateDB();
virtual ~nsNSSCertificateDB();
static PRUint32 getCertType(CERTCertificate *cert);
private:
void getCertNames(CERTCertList *certList,
PRUint32 type,
PRUint32 *_count,
PRUnichar ***_certNameList);
CERTDERCerts *getCertsFromPackage(PRArenaPool *arena, char *data,
PRUint32 length);
nsresult handleCACertDownload(nsISupportsArray *x509Certs,
nsIInterfaceRequestor *ctx);
};
// Use this function to generate a default nickname for a user
// certificate that is to be imported onto a token.
char *
default_nickname(CERTCertificate *cert, nsIInterfaceRequestor* ctx);
#endif /* _NS_NSSCERTIFICATE_H_ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,221 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Hubbie Shaw
* Doug Turner <dougt@netscape.com>
* Brian Ryner <bryner@netscape.com>
* Kai Engert <kaie@netscape.com>
*/
#ifndef _nsNSSComponent_h_
#define _nsNSSComponent_h_
#include "nsCOMPtr.h"
#include "nsISecurityManagerComponent.h"
#include "nsISignatureVerifier.h"
#include "nsIURIContentListener.h"
#include "nsIStreamListener.h"
#include "nsIEntropyCollector.h"
#include "nsString.h"
#include "nsIStringBundle.h"
#include "nsIPref.h"
#include "nsIObserver.h"
#include "nsIObserverService.h"
#include "nsWeakReference.h"
#include "nsIScriptSecurityManager.h"
#include "nsITimer.h"
#include "nsITimerCallback.h"
#include "nsNetUtil.h"
#include "nsHashtable.h"
#include "prlock.h"
#include "nsNSSHelper.h"
#define NS_NSSCOMPONENT_CID \
{0xa277189c, 0x1dd1, 0x11b2, {0xa8, 0xc9, 0xe4, 0xe8, 0xbf, 0xb1, 0x33, 0x8e}}
//Define an interface that we can use to look up from the
//callbacks passed to NSS.
#define NS_INSSCOMPONENT_IID_STR "d4b49dd6-1dd1-11b2-b6fe-b14cfaf69cbd"
#define NS_INSSCOMPONENT_IID \
{0xd4b49dd6, 0x1dd1, 0x11b2, \
{ 0xb6, 0xfe, 0xb1, 0x4c, 0xfa, 0xf6, 0x9c, 0xbd }}
#define NS_PSMCONTENTLISTEN_CID {0xc94f4a30, 0x64d7, 0x11d4, {0x99, 0x60, 0x00, 0xb0, 0xd0, 0x23, 0x54, 0xa0}}
#define NS_PSMCONTENTLISTEN_CONTRACTID "@mozilla.org/security/psmdownload;1"
//--------------------------------------------
// Now we need a content listener to register
//--------------------------------------------
class PSMContentDownloader : public nsIStreamListener
{
public:
PSMContentDownloader() {NS_ASSERTION(PR_FALSE, "don't use this constructor."); }
PSMContentDownloader(PRUint32 type);
virtual ~PSMContentDownloader();
void setSilentDownload(PRBool flag);
void setCrlAutodownloadKey(nsAutoString key);
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUESTOBSERVER
NS_DECL_NSISTREAMLISTENER
enum {UNKNOWN_TYPE = 0};
enum {X509_CA_CERT = 1};
enum {X509_USER_CERT = 2};
enum {X509_EMAIL_CERT = 3};
enum {X509_SERVER_CERT = 4};
enum {PKCS7_CRL = 5};
protected:
char* mByteData;
PRInt32 mBufferOffset;
PRInt32 mContentLength;
PRUint32 mType;
PRBool mDoSilentDownload;
nsAutoString mCrlAutoDownloadKey;
nsCOMPtr<nsISecurityManagerComponent> mNSS;
nsCOMPtr<nsIURI> mURI;
nsresult handleContentDownloadError(nsresult errCode);
};
class NS_NO_VTABLE nsINSSComponent : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_INSSCOMPONENT_IID)
NS_IMETHOD GetPIPNSSBundleString(const PRUnichar *name,
nsAString &outString) = 0;
NS_IMETHOD GetPIPNSSBundleString(const PRUnichar *name,
PRUnichar **outString) = 0;
NS_IMETHOD PIPBundleFormatStringFromName(const PRUnichar *name,
const PRUnichar **params,
PRUint32 numParams,
PRUnichar **outString) = 0;
// This method will just disable OCSP in NSS, it will not
// alter the respective pref values.
NS_IMETHOD DisableOCSP() = 0;
// This method will set the OCSP value according to the
// values in the preferences.
NS_IMETHOD EnableOCSP() = 0;
NS_IMETHOD RememberCert(CERTCertificate *cert) = 0;
NS_IMETHOD RemoveCrlFromList(nsAutoString) = 0;
NS_IMETHOD DefineNextTimer() = 0;
NS_IMETHOD DownloadCRLDirectly(nsAutoString, nsAutoString) = 0;
};
struct PRLock;
// Implementation of the PSM component interface.
class nsNSSComponent : public nsISecurityManagerComponent,
public nsISignatureVerifier,
public nsIEntropyCollector,
public nsINSSComponent,
public nsIObserver,
public nsSupportsWeakReference,
public nsITimerCallback
{
public:
NS_DEFINE_STATIC_CID_ACCESSOR( NS_NSSCOMPONENT_CID );
nsNSSComponent();
virtual ~nsNSSComponent();
NS_DECL_ISUPPORTS
NS_DECL_NSISECURITYMANAGERCOMPONENT
NS_DECL_NSISIGNATUREVERIFIER
NS_DECL_NSIENTROPYCOLLECTOR
NS_DECL_NSIOBSERVER
NS_METHOD Init();
NS_IMETHOD GetPIPNSSBundleString(const PRUnichar *name,
nsAString &outString);
NS_IMETHOD GetPIPNSSBundleString(const PRUnichar *name,
PRUnichar **outString);
NS_IMETHOD PIPBundleFormatStringFromName(const PRUnichar *name,
const PRUnichar **params,
PRUint32 numParams,
PRUnichar **outString);
NS_IMETHOD DisableOCSP();
NS_IMETHOD EnableOCSP();
nsresult InitializeCRLUpdateTimer();
nsresult StopCRLUpdateTimer();
NS_IMETHOD RemoveCrlFromList(nsAutoString);
NS_IMETHOD DefineNextTimer();
NS_IMETHOD DownloadCRLDirectly(nsAutoString, nsAutoString);
NS_IMETHOD RememberCert(CERTCertificate *cert);
NS_IMETHOD_(void) Notify(nsITimer *timer);
private:
nsresult InitializeNSS();
nsresult ShutdownNSS();
void InstallLoadableRoots();
nsresult InitializePIPNSSBundle();
nsresult ConfigureInternalPKCS11Token();
nsresult RegisterPSMContentListener();
nsresult RegisterObservers();
static int PR_CALLBACK PrefChangedCallback(const char* aPrefName, void* data);
void PrefChanged(const char* aPrefName);
nsresult DownloadCrlSilently();
nsresult PostCRLImportEvent(nsCAutoString *urlString, PSMContentDownloader *psmDownloader);
nsresult getParamsForNextCrlToDownload(nsAutoString *url, PRTime *time, nsAutoString *key);
PRLock *mutex;
nsCOMPtr<nsIScriptSecurityManager> mScriptSecurityManager;
nsCOMPtr<nsIStringBundle> mPIPNSSBundle;
nsCOMPtr<nsIURIContentListener> mPSMContentListener;
nsCOMPtr<nsIPref> mPref;
nsCOMPtr<nsITimer> mTimer;
PRBool mNSSInitialized;
PRBool mObserversRegistered;
PLHashTable *hashTableCerts;
nsAutoString mDownloadURL;
nsAutoString mCrlUpdateKey;
PRLock *mCrlTimerLock;
nsHashtable *crlsScheduledForDownload;
PRBool crlDownloadTimerOn;
PRBool mUpdateTimerInitialized;
static int mInstanceCount;
};
class PSMContentListener : public nsIURIContentListener,
public nsSupportsWeakReference {
public:
PSMContentListener();
virtual ~PSMContentListener();
nsresult init();
NS_DECL_ISUPPORTS
NS_DECL_NSIURICONTENTLISTENER
private:
nsCOMPtr<nsISupports> mLoadCookie;
nsCOMPtr<nsIURIContentListener> mParentContentListener;
};
#endif // _nsNSSComponent_h_

View File

@@ -1,89 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Javier Delgadillo <javi@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef NSS_HELPER_
#define NSS_HELPER_
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "pk11func.h"
//
// Implementation of an nsIInterfaceRequestor for use
// as context for NSS calls
//
class PipUIContext : public nsIInterfaceRequestor
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIINTERFACEREQUESTOR
PipUIContext();
virtual ~PipUIContext();
};
//
// Function to get the implementor for a certain set of NSS
// specific dialogs.
//
nsresult
getNSSDialogs(void **_result, REFNSIID aIID);
extern "C" {
// a "fake" unicode conversion function
PRBool
pip_ucs2_ascii_conversion_fn(PRBool toUnicode,
unsigned char *inBuf,
unsigned int inBufLen,
unsigned char *outBuf,
unsigned int maxOutBufLen,
unsigned int *outBufLen,
PRBool swapBytes);
}
//
// A function that sets the password on an unitialized slot.
//
nsresult
setPassword(PK11SlotInfo *slot, nsIInterfaceRequestor *ctx);
#ifdef XP_MAC
extern OSErr ConvertMacPathToUnixPath(const char *macPath, char **unixPath);
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,119 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*/
#ifndef _NSNSSIOLAYER_H
#define _NSNSSIOLAYER_H
#include "prtypes.h"
#include "prio.h"
#include "certt.h"
#include "nsString.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsITransportSecurityInfo.h"
#include "nsISSLSocketControl.h"
#include "nsISSLStatus.h"
#include "nsISSLStatusProvider.h"
#include "nsXPIDLString.h"
class nsIChannel;
class nsNSSSocketInfo : public nsITransportSecurityInfo,
public nsISSLSocketControl,
public nsIInterfaceRequestor,
public nsISSLStatusProvider
{
public:
nsNSSSocketInfo();
virtual ~nsNSSSocketInfo();
NS_DECL_ISUPPORTS
NS_DECL_NSITRANSPORTSECURITYINFO
NS_DECL_NSISSLSOCKETCONTROL
NS_DECL_NSIINTERFACEREQUESTOR
NS_DECL_NSISSLSTATUSPROVIDER
nsresult SetSecurityState(PRInt32 aState);
nsresult SetShortSecurityDescription(const PRUnichar *aText);
nsresult SetForTLSStepUp(PRBool useTLS);
nsresult GetForTLSStepUp(PRBool *useTLS);
nsresult GetFileDescPtr(PRFileDesc** aFilePtr);
nsresult SetFileDescPtr(PRFileDesc* aFilePtr);
nsresult GetFirstWrite(PRBool *aFirstWrite);
nsresult SetFirstWrite(PRBool aFirstWrite);
nsresult GetHostName(char **aHostName);
nsresult SetHostName(const char *aHostName);
nsresult GetPort(PRInt32 *aPort);
nsresult SetPort(PRInt32 aPort);
nsresult GetTLSIntolerant(PRBool *aTLSIntolerant);
nsresult SetTLSIntolerant(PRBool aTLSIntolerant);
nsresult RememberCAChain(CERTCertList *aCertList);
/* Set SSL Status values */
nsresult SetSSLStatus(nsISSLStatus *aSSLStatus);
protected:
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
PRFileDesc* mFd;
PRInt32 mSecurityState;
nsString mShortDesc;
PRBool mForceHandshake;
PRBool mForTLSStepUp;
PRBool mFirstWrite;
PRBool mTLSIntolerant;
PRInt32 mPort;
nsXPIDLCString mHostName;
CERTCertList *mCAChain;
/* SSL Status */
nsCOMPtr<nsISSLStatus> mSSLStatus;
};
nsresult nsSSLIOLayerNewSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc **fd,
nsISupports **securityInfo,
PRBool forTLSStepUp);
nsresult nsSSLIOLayerAddToSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc *fd,
nsISupports **securityInfo,
PRBool forTLSStepUp);
nsresult nsSSLIOLayerFreeTLSIntolerantSites();
nsresult displayAlert(nsXPIDLString formattedString, nsNSSSocketInfo *infoObject);
nsresult displayUnknownCertErrorAlert(nsNSSSocketInfo *infoObject, int error);
#endif /* _NSNSSIOLAYER_H */

View File

@@ -1,353 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Hubbie Shaw
* Doug Turner <dougt@netscape.com>
* Brian Ryner <bryner@netscape.com>
*/
#include "nsIModule.h"
#include "nsIGenericFactory.h"
#include "nsNSSComponent.h"
#include "nsSSLSocketProvider.h"
#include "nsTLSSocketProvider.h"
#include "nsKeygenHandler.h"
#include "nsSDR.h"
#include "nsPK11TokenDB.h"
#include "nsPKCS11Slot.h"
#include "nsNSSCertificate.h"
#include "nsCertOutliner.h"
#include "nsCrypto.h"
//For the NS_CRYPTO_CONTRACTID define
#include "nsDOMCID.h"
#include "nsCMSSecureMessage.h"
#include "nsCMS.h"
#include "nsCertPicker.h"
#include "nsCURILoader.h"
#include "nsICategoryManager.h"
// We must ensure that the nsNSSComponent has been loaded before
// creating any other components.
static void EnsureNSSInitialized(PRBool triggeredByNSSComponent)
{
static PRBool haveLoaded = PR_FALSE;
if (haveLoaded)
return;
haveLoaded = PR_TRUE;
if (triggeredByNSSComponent) {
// Me must prevent a recursion, as nsNSSComponent creates
// additional instances
return;
}
nsCOMPtr<nsISupports> nssComponent
= do_GetService(PSM_COMPONENT_CONTRACTID);
}
// These two macros are ripped off from nsIGenericFactory.h and slightly
// modified.
#define NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(triggeredByNSSComponent, \
_InstanceClass) \
static NS_IMETHODIMP \
_InstanceClass##Constructor(nsISupports *aOuter, REFNSIID aIID, \
void **aResult) \
{ \
nsresult rv; \
_InstanceClass * inst; \
\
EnsureNSSInitialized(triggeredByNSSComponent); \
\
*aResult = NULL; \
if (NULL != aOuter) { \
rv = NS_ERROR_NO_AGGREGATION; \
return rv; \
} \
\
NS_NEWXPCOM(inst, _InstanceClass); \
if (NULL == inst) { \
rv = NS_ERROR_OUT_OF_MEMORY; \
return rv; \
} \
NS_ADDREF(inst); \
rv = inst->QueryInterface(aIID, aResult); \
NS_RELEASE(inst); \
\
return rv; \
} \
#define NS_NSS_GENERIC_FACTORY_CONSTRUCTOR_INIT(triggeredByNSSComponent, \
_InstanceClass, _InitMethod) \
static NS_IMETHODIMP \
_InstanceClass##Constructor(nsISupports *aOuter, REFNSIID aIID, \
void **aResult) \
{ \
nsresult rv; \
_InstanceClass * inst; \
\
EnsureNSSInitialized(triggeredByNSSComponent); \
\
*aResult = NULL; \
if (NULL != aOuter) { \
rv = NS_ERROR_NO_AGGREGATION; \
return rv; \
} \
\
NS_NEWXPCOM(inst, _InstanceClass); \
if (NULL == inst) { \
rv = NS_ERROR_OUT_OF_MEMORY; \
return rv; \
} \
NS_ADDREF(inst); \
rv = inst->_InitMethod(); \
if(NS_SUCCEEDED(rv)) { \
rv = inst->QueryInterface(aIID, aResult); \
} \
NS_RELEASE(inst); \
\
return rv; \
} \
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR_INIT(PR_TRUE, nsNSSComponent, Init)
// Use the special factory constructor for everything this module implements,
// because all code could potentially require the NSS library.
// Our factory constructor takes an additional boolean parameter.
// Only for the nsNSSComponent, set this to PR_TRUE.
// All other classes must have this set to PR_FALSE.
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsSSLSocketProvider)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsTLSSocketProvider)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsSecretDecoderRing)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsPK11TokenDB)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsPKCS11ModuleDB)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR_INIT(PR_FALSE, PSMContentListener, init)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsNSSCertificateDB)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCertOutliner)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCrypto)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsPkcs11)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCMSSecureMessage)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCMSDecoder)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCMSEncoder)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCMSMessage)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsHash)
NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(PR_FALSE, nsCertPicker)
static NS_METHOD RegisterPSMContentListeners(
nsIComponentManager *aCompMgr,
nsIFile *aPath, const char *registryLocation,
const char *componentType, const nsModuleComponentInfo *info)
{
nsresult rv;
nsCOMPtr<nsICategoryManager> catman =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString previous;
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/x-x509-ca-cert",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/x-x509-server-cert",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/x-x509-user-cert",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/x-x509-email-cert",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/x-pkcs7-crl",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/x-x509-crl",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
catman->AddCategoryEntry(
NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY,
"application/pkix-crl",
info->mContractID, PR_TRUE, PR_TRUE, getter_Copies(previous));
return NS_OK;
}
static nsModuleComponentInfo components[] =
{
{
PSM_COMPONENT_CLASSNAME,
NS_NSSCOMPONENT_CID,
PSM_COMPONENT_CONTRACTID,
nsNSSComponentConstructor
},
{
NS_ISSLSOCKETPROVIDER_CLASSNAME,
NS_SSLSOCKETPROVIDER_CID,
NS_ISSLSOCKETPROVIDER_CONTRACTID,
nsSSLSocketProviderConstructor
},
{
NS_TLSSTEPUPSOCKETPROVIDER_CLASSNAME,
NS_TLSSTEPUPSOCKETPROVIDER_CID,
NS_TLSSTEPUPSOCKETPROVIDER_CONTRACTID,
nsTLSSocketProviderConstructor
},
{
NS_ISSLFHSOCKETPROVIDER_CLASSNAME,
NS_SSLSOCKETPROVIDER_CID,
NS_ISSLFHSOCKETPROVIDER_CONTRACTID,
nsSSLSocketProviderConstructor
},
{
NS_SDR_CLASSNAME,
NS_SDR_CID,
NS_SDR_CONTRACTID,
nsSecretDecoderRingConstructor
},
{
"PK11 Token Database",
NS_PK11TOKENDB_CID,
NS_PK11TOKENDB_CONTRACTID,
nsPK11TokenDBConstructor
},
{
"PKCS11 Module Database",
NS_PKCS11MODULEDB_CID,
NS_PKCS11MODULEDB_CONTRACTID,
nsPKCS11ModuleDBConstructor
},
{
"Generic Certificate Content Handler",
NS_PSMCONTENTLISTEN_CID,
NS_PSMCONTENTLISTEN_CONTRACTID,
PSMContentListenerConstructor
},
{
"X509 Certificate Database",
NS_X509CERTDB_CID,
NS_X509CERTDB_CONTRACTID,
nsNSSCertificateDBConstructor
},
{
"Form Processor",
NS_FORMPROCESSOR_CID,
NS_FORMPROCESSOR_CONTRACTID,
nsKeygenFormProcessor::Create
},
{
"Certificate Outliner",
NS_CERTOUTLINER_CID,
NS_CERTOUTLINER_CONTRACTID,
nsCertOutlinerConstructor
},
{
NS_PKCS11_CLASSNAME,
NS_PKCS11_CID,
NS_PKCS11_CONTRACTID,
nsPkcs11Constructor
},
{
NS_CRYPTO_CLASSNAME,
NS_CRYPTO_CID,
NS_CRYPTO_CONTRACTID,
nsCryptoConstructor
},
{
NS_CMSSECUREMESSAGE_CLASSNAME,
NS_CMSSECUREMESSAGE_CID,
NS_CMSSECUREMESSAGE_CONTRACTID,
nsCMSSecureMessageConstructor
},
{
NS_CMSDECODER_CLASSNAME,
NS_CMSDECODER_CID,
NS_CMSDECODER_CONTRACTID,
nsCMSDecoderConstructor
},
{
NS_CMSENCODER_CLASSNAME,
NS_CMSENCODER_CID,
NS_CMSENCODER_CONTRACTID,
nsCMSEncoderConstructor
},
{
NS_CMSMESSAGE_CLASSNAME,
NS_CMSMESSAGE_CID,
NS_CMSMESSAGE_CONTRACTID,
nsCMSMessageConstructor
},
{
NS_HASH_CLASSNAME,
NS_HASH_CID,
NS_HASH_CONTRACTID,
nsHashConstructor
},
{
NS_CERT_PICKER_CLASSNAME,
NS_CERT_PICKER_CID,
NS_CERT_PICKER_CONTRACTID,
nsCertPickerConstructor
},
{
"PSM Content Listeners",
NS_PSMCONTENTLISTEN_CID,
"@mozilla.org/uriloader/psm-external-content-listener;1",
PSMContentListenerConstructor,
RegisterPSMContentListeners
}
};
NS_IMPL_NSGETMODULE(NSS, components);

View File

@@ -1,385 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*/
#include "nsISupports.h"
#include "nsIPK11TokenDB.h"
#include "prerror.h"
#include "secerr.h"
#include "nsReadableUtils.h"
#include "nsPK11TokenDB.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
NS_IMPL_ISUPPORTS1(nsPK11Token, nsIPK11Token)
nsPK11Token::nsPK11Token(PK11SlotInfo *slot)
{
NS_INIT_ISUPPORTS();
PK11_ReferenceSlot(slot);
mSlot = slot;
mTokenName = NS_ConvertUTF8toUCS2(PK11_GetTokenName(slot));
SECStatus srv;
CK_TOKEN_INFO tok_info;
srv = PK11_GetTokenInfo(mSlot, &tok_info);
if (srv == SECSuccess) {
// Set the Label field
mTokenLabel.AssignWithConversion((char *)tok_info.label,
sizeof(tok_info.label));
mTokenLabel.Trim(" ", PR_FALSE, PR_TRUE);
// Set the Manufacturer field
mTokenManID.AssignWithConversion((char *)tok_info.manufacturerID,
sizeof(tok_info.manufacturerID));
mTokenManID.Trim(" ", PR_FALSE, PR_TRUE);
// Set the Hardware Version field
mTokenHWVersion.AppendInt(tok_info.hardwareVersion.major);
mTokenHWVersion.Append(NS_LITERAL_STRING("."));
mTokenHWVersion.AppendInt(tok_info.hardwareVersion.minor);
// Set the Firmware Version field
mTokenFWVersion.AppendInt(tok_info.firmwareVersion.major);
mTokenFWVersion.Append(NS_LITERAL_STRING("."));
mTokenFWVersion.AppendInt(tok_info.firmwareVersion.minor);
// Set the Serial Number field
mTokenSerialNum.AssignWithConversion((char *)tok_info.serialNumber,
sizeof(tok_info.serialNumber));
mTokenSerialNum.Trim(" ", PR_FALSE, PR_TRUE);
}
mUIContext = new PipUIContext();
}
nsPK11Token::~nsPK11Token()
{
if (mSlot) PK11_FreeSlot(mSlot);
/* destructor code */
}
/* readonly attribute wstring tokenName; */
NS_IMETHODIMP nsPK11Token::GetTokenName(PRUnichar * *aTokenName)
{
*aTokenName = ToNewUnicode(mTokenName);
if (!*aTokenName) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring tokenDesc; */
NS_IMETHODIMP nsPK11Token::GetTokenLabel(PRUnichar **aTokLabel)
{
*aTokLabel = ToNewUnicode(mTokenLabel);
if (!*aTokLabel) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring tokenManID; */
NS_IMETHODIMP nsPK11Token::GetTokenManID(PRUnichar **aTokManID)
{
*aTokManID = ToNewUnicode(mTokenManID);
if (!*aTokManID) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring tokenHWVersion; */
NS_IMETHODIMP nsPK11Token::GetTokenHWVersion(PRUnichar **aTokHWVersion)
{
*aTokHWVersion = ToNewUnicode(mTokenHWVersion);
if (!*aTokHWVersion) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring tokenFWVersion; */
NS_IMETHODIMP nsPK11Token::GetTokenFWVersion(PRUnichar **aTokFWVersion)
{
*aTokFWVersion = ToNewUnicode(mTokenFWVersion);
if (!*aTokFWVersion) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring tokenSerialNumber; */
NS_IMETHODIMP nsPK11Token::GetTokenSerialNumber(PRUnichar **aTokSerialNum)
{
*aTokSerialNum = ToNewUnicode(mTokenSerialNum);
if (!*aTokSerialNum) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* boolean isLoggedIn (); */
NS_IMETHODIMP nsPK11Token::IsLoggedIn(PRBool *_retval)
{
nsresult rv = NS_OK;
*_retval = PK11_IsLoggedIn(mSlot, 0);
return rv;
}
/* void logout (in boolean force); */
NS_IMETHODIMP
nsPK11Token::Login(PRBool force)
{
nsresult rv;
SECStatus srv;
PRBool test;
rv = this->NeedsLogin(&test);
if (NS_FAILED(rv)) return rv;
if (test && force) {
rv = this->Logout();
if (NS_FAILED(rv)) return rv;
}
rv = setPassword(mSlot, mUIContext);
if (NS_FAILED(rv)) return rv;
srv = PK11_Authenticate(mSlot, PR_TRUE, mUIContext);
return (srv == SECSuccess) ? NS_OK : NS_ERROR_FAILURE;
}
/* void logout (); */
NS_IMETHODIMP nsPK11Token::Logout()
{
// PK11_MapError sets CKR_USER_NOT_LOGGED_IN to SEC_ERROR_LIBRARY_FAILURE,
// so not going to learn anything here by a failure. Treat it like void.
PK11_Logout(mSlot);
return NS_OK;
}
/* void reset (); */
NS_IMETHODIMP nsPK11Token::Reset()
{
PK11_ResetToken(mSlot, 0);
return NS_OK;
}
/* readonly attribute long minimumPasswordLength; */
NS_IMETHODIMP nsPK11Token::GetMinimumPasswordLength(PRInt32 *aMinimumPasswordLength)
{
*aMinimumPasswordLength = PK11_GetMinimumPwdLength(mSlot);
return NS_OK;
}
/* readonly attribute boolean needsUserInit; */
NS_IMETHODIMP nsPK11Token::GetNeedsUserInit(PRBool *aNeedsUserInit)
{
*aNeedsUserInit = PK11_NeedUserInit(mSlot);
return NS_OK;
}
/* boolean checkPassword (in wstring password); */
NS_IMETHODIMP nsPK11Token::CheckPassword(const PRUnichar *password, PRBool *_retval)
{
SECStatus srv;
PRInt32 prerr;
NS_ConvertUCS2toUTF8 aUtf8Password(password);
srv = PK11_CheckUserPassword(mSlot,
NS_CONST_CAST(char *, aUtf8Password.get()));
if (srv != SECSuccess) {
*_retval = PR_FALSE;
prerr = PR_GetError();
if (prerr != SEC_ERROR_BAD_PASSWORD) {
/* something really bad happened - throw an exception */
return NS_ERROR_FAILURE;
}
} else {
*_retval = PR_TRUE;
}
return NS_OK;
}
/* void initPassword (in wstring initialPassword); */
NS_IMETHODIMP nsPK11Token::InitPassword(const PRUnichar *initialPassword)
{
nsresult rv = NS_OK;
SECStatus status;
NS_ConvertUCS2toUTF8 aUtf8InitialPassword(initialPassword);
status = PK11_InitPin(mSlot, "", NS_CONST_CAST(char*, aUtf8InitialPassword.get()));
if (status == SECFailure) { rv = NS_ERROR_FAILURE; goto done; }
done:
return rv;
}
/* long getAskPasswordTimes(); */
NS_IMETHODIMP
nsPK11Token::GetAskPasswordTimes(PRInt32 *rvAskTimes)
{
int askTimes, askTimeout;
PK11_GetSlotPWValues(mSlot, &askTimes, &askTimeout);
*rvAskTimes = askTimes;
return NS_OK;
}
/* long getAskPasswordTimeout(); */
NS_IMETHODIMP
nsPK11Token::GetAskPasswordTimeout(PRInt32 *rvAskTimeout)
{
int askTimes, askTimeout;
PK11_GetSlotPWValues(mSlot, &askTimes, &askTimeout);
*rvAskTimeout = askTimeout;
return NS_OK;
}
/* void setAskPasswordDefaults(in unsigned long askTimes,
* in unsigned long timeout);
*/
NS_IMETHODIMP
nsPK11Token::SetAskPasswordDefaults(const PRInt32 askTimes,
const PRInt32 askTimeout)
{
PK11_SetSlotPWValues(mSlot, askTimes, askTimeout);
return NS_OK;
}
/* void changePassword (in wstring oldPassword, in wstring newPassword); */
NS_IMETHODIMP nsPK11Token::ChangePassword(const PRUnichar *oldPassword, const PRUnichar *newPassword)
{
SECStatus rv;
NS_ConvertUCS2toUTF8 aUtf8OldPassword(oldPassword);
NS_ConvertUCS2toUTF8 aUtf8NewPassword(newPassword);
rv = PK11_ChangePW(mSlot,
NS_CONST_CAST(char *, aUtf8OldPassword.get()),
NS_CONST_CAST(char *, aUtf8NewPassword.get()));
return (rv == SECSuccess) ? NS_OK : NS_ERROR_FAILURE;
}
/* boolean isHardwareToken (); */
NS_IMETHODIMP nsPK11Token::IsHardwareToken(PRBool *_retval)
{
nsresult rv = NS_OK;
*_retval = PK11_IsHW(mSlot);
return rv;
}
/* boolean needsLogin (); */
NS_IMETHODIMP nsPK11Token::NeedsLogin(PRBool *_retval)
{
nsresult rv = NS_OK;
*_retval = PK11_NeedLogin(mSlot);
return rv;
}
/* boolean isFriendly (); */
NS_IMETHODIMP nsPK11Token::IsFriendly(PRBool *_retval)
{
nsresult rv = NS_OK;
*_retval = PK11_IsFriendly(mSlot);
return rv;
}
/*=========================================================*/
NS_IMPL_ISUPPORTS1(nsPK11TokenDB, nsIPK11TokenDB)
nsPK11TokenDB::nsPK11TokenDB()
{
NS_INIT_ISUPPORTS();
/* member initializers and constructor code */
}
nsPK11TokenDB::~nsPK11TokenDB()
{
/* destructor code */
}
/* nsIPK11Token getInternalKeyToken (); */
NS_IMETHODIMP nsPK11TokenDB::GetInternalKeyToken(nsIPK11Token **_retval)
{
nsresult rv = NS_OK;
PK11SlotInfo *slot = 0;
nsCOMPtr<nsIPK11Token> token;
slot = PK11_GetInternalKeySlot();
if (!slot) { rv = NS_ERROR_FAILURE; goto done; }
token = new nsPK11Token(slot);
if (!token) { rv = NS_ERROR_OUT_OF_MEMORY; goto done; }
*_retval = token;
NS_ADDREF(*_retval);
done:
if (slot) PK11_FreeSlot(slot);
return rv;
}
/* nsIPK11Token findTokenByName (in wchar tokenName); */
NS_IMETHODIMP nsPK11TokenDB::
FindTokenByName(const PRUnichar* tokenName, nsIPK11Token **_retval)
{
nsresult rv = NS_OK;
PK11SlotInfo *slot = 0;
NS_ConvertUCS2toUTF8 aUtf8TokenName(tokenName);
slot = PK11_FindSlotByName(NS_CONST_CAST(char*, aUtf8TokenName.get()));
if (!slot) { rv = NS_ERROR_FAILURE; goto done; }
*_retval = new nsPK11Token(slot);
if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto done; }
NS_ADDREF(*_retval);
done:
if (slot) PK11_FreeSlot(slot);
return rv;
}
/* nsIEnumerator listTokens (); */
NS_IMETHODIMP nsPK11TokenDB::ListTokens(nsIEnumerator* *_retval)
{
nsresult rv = NS_OK;
nsCOMPtr<nsISupportsArray> array;
PK11SlotList *list = 0;
PK11SlotListElement *le;
rv = NS_NewISupportsArray(getter_AddRefs(array));
if (NS_FAILED(rv)) { goto done; }
/* List all tokens, creating PK11Token objects and putting them
* into the array.
*/
list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, 0);
if (!list) { rv = NS_ERROR_FAILURE; goto done; }
for (le = PK11_GetFirstSafe(list); le; le = PK11_GetNextSafe(list, le, PR_FALSE)) {
nsCOMPtr<nsIPK11Token> token = new nsPK11Token(le->slot);
array->AppendElement(token);
}
rv = array->Enumerate(_retval);
done:
if (list) PK11_FreeSlotList(list);
return rv;
}

View File

@@ -1,70 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*/
#ifndef __NS_PK11TOKENDB_H__
#define __NS_PK11TOKENDB_H__
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsISupports.h"
#include "nsIPK11TokenDB.h"
#include "nsISupportsArray.h"
#include "nsNSSHelper.h"
#include "pk11func.h"
class nsPK11Token : public nsIPK11Token
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPK11TOKEN
nsPK11Token(PK11SlotInfo *slot);
virtual ~nsPK11Token();
/* additional members */
private:
friend class nsPK11TokenDB;
nsString mTokenName;
nsString mTokenLabel, mTokenManID, mTokenHWVersion, mTokenFWVersion;
nsString mTokenSerialNum;
PK11SlotInfo *mSlot;
nsCOMPtr<nsIInterfaceRequestor> mUIContext;
};
class nsPK11TokenDB : public nsIPK11TokenDB
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPK11TOKENDB
nsPK11TokenDB();
virtual ~nsPK11TokenDB();
/* additional members */
};
#define NS_PK11TOKENDB_CID \
{ 0xb084a2ce, 0x1dd1, 0x11b2, \
{ 0xbf, 0x10, 0x83, 0x24, 0xf8, 0xe0, 0x65, 0xcc }}
#endif

View File

@@ -1,405 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
*/
#include "nsPKCS11Slot.h"
#include "nsPK11TokenDB.h"
#include "nsCOMPtr.h"
#include "nsISupportsArray.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "secmod.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
NS_IMPL_ISUPPORTS1(nsPKCS11Slot, nsIPKCS11Slot)
nsPKCS11Slot::nsPKCS11Slot(PK11SlotInfo *slot)
{
NS_INIT_ISUPPORTS();
PK11_ReferenceSlot(slot);
mSlot = slot;
CK_SLOT_INFO slot_info;
if (PK11_GetSlotInfo(mSlot, &slot_info) == SECSuccess) {
// Set the Description field
mSlotDesc.AssignWithConversion((char *)slot_info.slotDescription,
sizeof(slot_info.slotDescription));
mSlotDesc.Trim(" ", PR_FALSE, PR_TRUE);
// Set the Manufacturer field
mSlotManID.AssignWithConversion((char *)slot_info.manufacturerID,
sizeof(slot_info.manufacturerID));
mSlotManID.Trim(" ", PR_FALSE, PR_TRUE);
// Set the Hardware Version field
mSlotHWVersion.AppendInt(slot_info.hardwareVersion.major);
mSlotHWVersion.Append(NS_LITERAL_STRING("."));
mSlotHWVersion.AppendInt(slot_info.hardwareVersion.minor);
// Set the Firmware Version field
mSlotFWVersion.AppendInt(slot_info.firmwareVersion.major);
mSlotFWVersion.Append(NS_LITERAL_STRING("."));
mSlotFWVersion.AppendInt(slot_info.firmwareVersion.minor);
}
}
nsPKCS11Slot::~nsPKCS11Slot()
{
if (mSlot) PK11_FreeSlot(mSlot);
}
/* readonly attribute wstring name; */
NS_IMETHODIMP
nsPKCS11Slot::GetName(PRUnichar **aName)
{
char *csn = PK11_GetSlotName(mSlot);
if (strlen(csn) > 0) {
*aName = ToNewUnicode(NS_ConvertUTF8toUCS2(csn));
} else if (PK11_HasRootCerts(mSlot)) {
// This is a workaround to an NSS bug - the root certs module has
// no slot name. Not bothering to localize, because this is a workaround
// and for now all the slot names returned by NSS are char * anyway.
*aName = ToNewUnicode(NS_LITERAL_STRING("Root Certificates"));
} else {
// same as above, this is a catch-all
*aName = ToNewUnicode(NS_LITERAL_STRING("Unnamed Slot"));
}
if (!*aName) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring desc; */
NS_IMETHODIMP
nsPKCS11Slot::GetDesc(PRUnichar **aDesc)
{
*aDesc = ToNewUnicode(mSlotDesc);
if (!*aDesc) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring manID; */
NS_IMETHODIMP
nsPKCS11Slot::GetManID(PRUnichar **aManID)
{
*aManID = ToNewUnicode(mSlotManID);
if (!*aManID) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring HWVersion; */
NS_IMETHODIMP
nsPKCS11Slot::GetHWVersion(PRUnichar **aHWVersion)
{
*aHWVersion = ToNewUnicode(mSlotHWVersion);
if (!*aHWVersion) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* readonly attribute wstring FWVersion; */
NS_IMETHODIMP
nsPKCS11Slot::GetFWVersion(PRUnichar **aFWVersion)
{
*aFWVersion = ToNewUnicode(mSlotFWVersion);
if (!*aFWVersion) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
/* nsIPK11Token getToken (); */
NS_IMETHODIMP
nsPKCS11Slot::GetToken(nsIPK11Token **_retval)
{
nsCOMPtr<nsIPK11Token> token = new nsPK11Token(mSlot);
if (!token)
return NS_ERROR_OUT_OF_MEMORY;
*_retval = token;
NS_ADDREF(*_retval);
return NS_OK;
}
/* readonly attribute wstring tokenName; */
NS_IMETHODIMP
nsPKCS11Slot::GetTokenName(PRUnichar **aName)
{
*aName = ToNewUnicode(NS_ConvertUTF8toUCS2(PK11_GetTokenName(mSlot)));
if (!*aName) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsPKCS11Slot::GetStatus(PRUint32 *_retval)
{
if (PK11_IsDisabled(mSlot))
*_retval = SLOT_DISABLED;
else if (!PK11_IsPresent(mSlot))
*_retval = SLOT_NOT_PRESENT;
else if (PK11_NeedLogin(mSlot) && PK11_NeedUserInit(mSlot))
*_retval = SLOT_UNINITIALIZED;
else if (PK11_NeedLogin(mSlot) && !PK11_IsLoggedIn(mSlot, NULL))
*_retval = SLOT_NOT_LOGGED_IN;
else if (PK11_NeedLogin(mSlot))
*_retval = SLOT_LOGGED_IN;
else
*_retval = SLOT_READY;
return NS_OK;
}
NS_IMPL_ISUPPORTS1(nsPKCS11Module, nsIPKCS11Module)
nsPKCS11Module::nsPKCS11Module(SECMODModule *module)
{
NS_INIT_ISUPPORTS();
SECMOD_ReferenceModule(module);
mModule = module;
}
nsPKCS11Module::~nsPKCS11Module()
{
SECMOD_DestroyModule(mModule);
}
/* readonly attribute wstring name; */
NS_IMETHODIMP
nsPKCS11Module::GetName(PRUnichar **aName)
{
*aName = ToNewUnicode(NS_ConvertUTF8toUCS2(mModule->commonName));
return NS_OK;
}
/* readonly attribute wstring libName; */
NS_IMETHODIMP
nsPKCS11Module::GetLibName(PRUnichar **aName)
{
*aName = ToNewUnicode(NS_ConvertUTF8toUCS2(mModule->dllName));
return NS_OK;
}
/* nsIPKCS11Slot findSlotByName(in wstring name); */
NS_IMETHODIMP
nsPKCS11Module::FindSlotByName(const PRUnichar *aName,
nsIPKCS11Slot **_retval)
{
char *asciiname = NULL;
asciiname = ToNewUTF8String(nsDependentString(aName));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting \"%s\"\n", asciiname));
PK11SlotInfo *slotinfo = SECMOD_FindSlot(mModule, asciiname);
if (!slotinfo) {
// XXX *sigh* if token is present, SECMOD_FindSlot goes by token
// name (huh?) reimplement it here for the fun of it.
for (int i=0; i<mModule->slotCount; i++) {
if (nsCRT::strcmp(asciiname, PK11_GetSlotName(mModule->slots[i])) == 0) {
slotinfo = PK11_ReferenceSlot(mModule->slots[i]);
}
}
if (!slotinfo) {
// XXX another workaround - the builtin module has no name
if (nsCRT::strcmp(asciiname, "Root Certificates") == 0) {
slotinfo = PK11_ReferenceSlot(mModule->slots[0]);
} else {
// give up
nsMemory::Free(asciiname);
return NS_ERROR_FAILURE;
}
}
}
nsMemory::Free(asciiname);
nsCOMPtr<nsIPKCS11Slot> slot = new nsPKCS11Slot(slotinfo);
if (!slot)
return NS_ERROR_OUT_OF_MEMORY;
*_retval = slot;
NS_ADDREF(*_retval);
return NS_OK;
}
/* nsIEnumerator listSlots (); */
NS_IMETHODIMP
nsPKCS11Module::ListSlots(nsIEnumerator **_retval)
{
nsresult rv = NS_OK;
int i;
/* get isupports array */
nsCOMPtr<nsISupportsArray> array;
rv = NS_NewISupportsArray(getter_AddRefs(array));
if (NS_FAILED(rv)) return rv;
for (i=0; i<mModule->slotCount; i++) {
if (mModule->slots[i]) {
nsCOMPtr<nsIPKCS11Slot> slot = new nsPKCS11Slot(mModule->slots[i]);
array->AppendElement(slot);
}
}
rv = array->Enumerate(_retval);
return rv;
}
NS_IMPL_ISUPPORTS1(nsPKCS11ModuleDB, nsIPKCS11ModuleDB)
nsPKCS11ModuleDB::nsPKCS11ModuleDB()
{
NS_INIT_ISUPPORTS();
}
nsPKCS11ModuleDB::~nsPKCS11ModuleDB()
{
}
/* nsIPKCS11Module getInternal (); */
NS_IMETHODIMP
nsPKCS11ModuleDB::GetInternal(nsIPKCS11Module **_retval)
{
nsCOMPtr<nsIPKCS11Module> module =
#ifdef NSS_3_4
new nsPKCS11Module(SECMOD_CreateModule(NULL,SECMOD_INT_NAME,
NULL,SECMOD_INT_FLAGS));
#else
new nsPKCS11Module(SECMOD_GetInternalModule());
#endif
if (!module)
return NS_ERROR_OUT_OF_MEMORY;
*_retval = module;
NS_ADDREF(*_retval);
return NS_OK;
}
/* nsIPKCS11Module getInternalFIPS (); */
NS_IMETHODIMP
nsPKCS11ModuleDB::GetInternalFIPS(nsIPKCS11Module **_retval)
{
nsCOMPtr<nsIPKCS11Module> module =
#ifdef NSS_3_4
new nsPKCS11Module(SECMOD_CreateModule(NULL, SECMOD_FIPS_NAME, NULL,
SECMOD_FIPS_FLAGS));
#else
new nsPKCS11Module(SECMOD_GetFIPSInternal());
#endif
if (!module)
return NS_ERROR_OUT_OF_MEMORY;
*_retval = module;
NS_ADDREF(*_retval);
return NS_OK;
}
/* nsIPKCS11Module findModuleByName(in wstring name); */
NS_IMETHODIMP
nsPKCS11ModuleDB::FindModuleByName(const PRUnichar *aName,
nsIPKCS11Module **_retval)
{
NS_ConvertUCS2toUTF8 aUtf8Name(aName);
SECMODModule *mod =
SECMOD_FindModule(NS_CONST_CAST(char *, aUtf8Name.get()));
if (!mod)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIPKCS11Module> module = new nsPKCS11Module(mod);
if (!module)
return NS_ERROR_OUT_OF_MEMORY;
*_retval = module;
NS_ADDREF(*_retval);
return NS_OK;
}
/* This is essentially the same as nsIPK11Token::findTokenByName, except
* that it returns an nsIPKCS11Slot, which may be desired.
*/
/* nsIPKCS11Module findSlotByName(in wstring name); */
NS_IMETHODIMP
nsPKCS11ModuleDB::FindSlotByName(const PRUnichar *aName,
nsIPKCS11Slot **_retval)
{
NS_ConvertUCS2toUTF8 aUtf8Name(aName);
PK11SlotInfo *slotinfo =
PK11_FindSlotByName(NS_CONST_CAST(char*, aUtf8Name.get()));
if (!slotinfo)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIPKCS11Slot> slot = new nsPKCS11Slot(slotinfo);
if (!slot)
return NS_ERROR_OUT_OF_MEMORY;
*_retval = slot;
NS_ADDREF(*_retval);
return NS_OK;
}
/* nsIEnumerator listModules (); */
NS_IMETHODIMP
nsPKCS11ModuleDB::ListModules(nsIEnumerator **_retval)
{
nsresult rv = NS_OK;
/* get isupports array */
nsCOMPtr<nsISupportsArray> array;
rv = NS_NewISupportsArray(getter_AddRefs(array));
if (NS_FAILED(rv)) return rv;
/* get the default list of modules */
SECMODModuleList *list = SECMOD_GetDefaultModuleList();
/* lock down the list for reading */
SECMODListLock *lock = SECMOD_GetDefaultModuleListLock();
SECMOD_GetReadLock(lock);
while (list) {
nsCOMPtr<nsIPKCS11Module> module = new nsPKCS11Module(list->module);
array->AppendElement(module);
list = list->next;
}
SECMOD_ReleaseReadLock(lock);
rv = array->Enumerate(_retval);
return rv;
}
/* void toggleFIPSMode (); */
NS_IMETHODIMP nsPKCS11ModuleDB::ToggleFIPSMode()
{
// The way to toggle FIPS mode in NSS is extremely obscure.
// Basically, we delete the internal module, and voila it
// gets replaced with the opposite module, ie if it was
// FIPS before, then it becomes non-FIPS next.
SECMODModule *internal;
// This function returns us a pointer to a local copy of
// the internal module stashed in NSS. We don't want to
// delete it since it will cause much pain in NSS.
internal = SECMOD_GetInternalModule();
if (!internal)
return NS_ERROR_FAILURE;
SECStatus srv = SECMOD_DeleteInternalModule(internal->commonName);
if (srv != SECSuccess)
return NS_ERROR_FAILURE;
return NS_OK;
}
/* readonly attribute boolean isFIPSEnabled; */
NS_IMETHODIMP nsPKCS11ModuleDB::GetIsFIPSEnabled(PRBool *aIsFIPSEnabled)
{
*aIsFIPSEnabled = PK11_IsFIPS();
return NS_OK;
}

View File

@@ -1,75 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*/
#ifndef __NS_PKCS11SLOT_H__
#define __NS_PKCS11SLOT_H__
#include "nsISupports.h"
#include "nsIPKCS11Slot.h"
#include "nsString.h"
#include "pk11func.h"
class nsPKCS11Slot : public nsIPKCS11Slot
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPKCS11SLOT
nsPKCS11Slot(PK11SlotInfo *slot);
virtual ~nsPKCS11Slot();
private:
PK11SlotInfo *mSlot;
nsString mSlotDesc, mSlotManID, mSlotHWVersion, mSlotFWVersion;
};
class nsPKCS11Module : public nsIPKCS11Module
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPKCS11MODULE
nsPKCS11Module(SECMODModule *module);
virtual ~nsPKCS11Module();
private:
SECMODModule *mModule;
};
class nsPKCS11ModuleDB : public nsIPKCS11ModuleDB
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPKCS11MODULEDB
nsPKCS11ModuleDB();
virtual ~nsPKCS11ModuleDB();
/* additional members */
};
#define NS_PKCS11MODULEDB_CID \
{ 0xff9fbcd7, 0x9517, 0x4334, \
{ 0xb9, 0x7a, 0xce, 0xed, 0x78, 0x90, 0x99, 0x74 }}
#endif

View File

@@ -1,823 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
* $Id: nsPKCS12Blob.cpp,v 1.22.4.1 2002-01-31 19:29:56 javi%netscape.com Exp $
*/
#include "prmem.h"
#include "prprf.h"
#include "nsISupportsArray.h"
#include "nsIFileSpec.h"
#include "nsINSSDialogs.h"
#include "nsIDirectoryService.h"
#include "nsIWindowWatcher.h"
#include "nsIPrompt.h"
#include "nsProxiedService.h"
#include "nsNSSComponent.h"
#include "nsNSSHelper.h"
#include "nsPKCS12Blob.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "nsFileStream.h"
#include "nsXPIDLString.h"
#include "nsDirectoryServiceDefs.h"
#include "nsNSSHelper.h"
#include "nsNSSCertificate.h"
#include "nsKeygenHandler.h" //For GetSlotWithMechanism
#include "nsPK11TokenDB.h"
#include "pk11func.h"
#include "secerr.h"
#ifdef PR_LOGGING
extern PRLogModuleInfo* gPIPNSSLog;
#endif
static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
#define PIP_PKCS12_TMPFILENAME ".pip_p12tmp"
#define PIP_PKCS12_BUFFER_SIZE 2048
#define PIP_PKCS12_RESTORE_OK 1
#define PIP_PKCS12_BACKUP_OK 2
#define PIP_PKCS12_USER_CANCELED 3
#define PIP_PKCS12_NOSMARTCARD_EXPORT 4
#define PIP_PKCS12_RESTORE_FAILED 5
#define PIP_PKCS12_BACKUP_FAILED 6
#define PIP_PKCS12_NSS_ERROR 7
// constructor
nsPKCS12Blob::nsPKCS12Blob():mCertArray(0),
mTmpFile(nsnull),
mTmpFilePath(nsnull),
mTokenSet(PR_FALSE)
{
mUIContext = new PipUIContext();
}
// destructor
nsPKCS12Blob::~nsPKCS12Blob()
{
}
// nsPKCS12Blob::SetToken
//
// Set the token to use for import/export
void
nsPKCS12Blob::SetToken(nsIPK11Token *token)
{
if (token) {
mToken = token;
} else {
PK11SlotInfo *slot;
nsresult rv = GetSlotWithMechanism(CKM_RSA_PKCS, mUIContext,&slot);
if (NS_FAILED(rv)) {
mToken = 0;
} else {
mToken = new nsPK11Token(slot);
}
}
mTokenSet = PR_TRUE;
}
// nsPKCS12Blob::ImportFromFile
//
// Given a file handle, read a PKCS#12 blob from that file, decode it,
// and import the results into the token.
nsresult
nsPKCS12Blob::ImportFromFile(nsILocalFile *file)
{
nsresult rv;
SECStatus srv = SECSuccess;
SEC_PKCS12DecoderContext *dcx = NULL;
SECItem unicodePw;
PK11SlotInfo *slot=nsnull;
nsXPIDLString tokenName;
nsXPIDLCString tokenNameCString;
const char *tokNameRef;
if (!mToken && !mTokenSet) {
SetToken(NULL); // Ask the user to pick a slot
} else if (!mToken && mTokenSet) {
// Someone tried setting the token before, but that failed.
// Probably because the user canceled.
handleError(PIP_PKCS12_USER_CANCELED);
return NS_OK;
}
// init slot
rv = mToken->Login(PR_TRUE);
if (NS_FAILED(rv)) goto finish;
// get file password (unicode)
unicodePw.data = NULL;
rv = getPKCS12FilePassword(&unicodePw);
if (NS_FAILED(rv)) goto finish;
if (unicodePw.data == NULL) {
handleError(PIP_PKCS12_USER_CANCELED);
return NS_OK;
}
mToken->GetTokenName(getter_Copies(tokenName));
tokenNameCString.Adopt(ToNewUTF8String(tokenName));
tokNameRef = tokenNameCString; //I do this here so that the
//NS_CONST_CAST below doesn't
//break the build on Win32
slot = PK11_FindSlotByName(NS_CONST_CAST(char*,tokNameRef));
if (!slot) {
srv = SECFailure;
goto finish;
}
// initialize the decoder
dcx = SEC_PKCS12DecoderStart(&unicodePw, slot, NULL,
digest_open, digest_close,
digest_read, digest_write,
this);
if (!dcx) {
srv = SECFailure;
goto finish;
}
// read input file and feed it to the decoder
rv = inputToDecoder(dcx, file);
if (NS_FAILED(rv)) goto finish;
// verify the blob
srv = SEC_PKCS12DecoderVerify(dcx);
if (srv) goto finish;
// validate bags
srv = SEC_PKCS12DecoderValidateBags(dcx, nickname_collision);
if (srv) goto finish;
// import cert and key
srv = SEC_PKCS12DecoderImportBags(dcx);
if (srv) goto finish;
// Later - check to see if this should become default email cert
handleError(PIP_PKCS12_RESTORE_OK);
finish:
// If srv != SECSuccess, NSS probably set a specific error code.
// We should use that error code instead of inventing a new one
// for every error possible.
if (srv != SECSuccess) {
handleError(PIP_PKCS12_NSS_ERROR);
} else if (NS_FAILED(rv)) {
handleError(PIP_PKCS12_RESTORE_FAILED);
}
// finish the decoder
if (dcx)
SEC_PKCS12DecoderFinish(dcx);
return NS_OK;
}
#if 0
// nsPKCS12Blob::LoadCerts
//
// Given an array of certificate nicknames, load the corresponding
// certificates into a local array.
nsresult
nsPKCS12Blob::LoadCerts(const PRUnichar **certNames, int numCerts)
{
nsresult rv;
char namecpy[256];
/* Create the local array if needed */
if (!mCertArray) {
rv = NS_NewISupportsArray(getter_AddRefs(mCertArray));
if (NS_FAILED(rv)) {
if (!handleError())
return NS_ERROR_OUT_OF_MEMORY;
}
}
/* Add the certs */
for (int i=0; i<numCerts; i++) {
strcpy(namecpy, NS_ConvertUCS2toUTF8(certNames[i]));
CERTCertificate *nssCert = PK11_FindCertFromNickname(namecpy, NULL);
if (!nssCert) {
if (!handleError())
return NS_ERROR_FAILURE;
else continue; /* user may request to keep going */
}
nsCOMPtr<nsIX509Cert> cert = new nsNSSCertificate(nssCert);
if (!cert) {
if (!handleError())
return NS_ERROR_OUT_OF_MEMORY;
} else {
mCertArray->AppendElement(cert);
}
CERT_DestroyCertificate(nssCert);
}
return NS_OK;
}
#endif
// nsPKCS12Blob::ExportToFile
//
// Having already loaded the certs, form them into a blob (loading the keys
// also), encode the blob, and stuff it into the file.
//
// TODO: handle slots correctly
// mirror "slotToUse" behavior from PSM 1.x
// verify the cert array to start off with?
// open output file as nsIFileStream object?
// set appropriate error codes
nsresult
nsPKCS12Blob::ExportToFile(nsILocalFile *file,
nsIX509Cert **certs, int numCerts)
{
nsresult rv;
SECStatus srv = SECSuccess;
SEC_PKCS12ExportContext *ecx = NULL;
SEC_PKCS12SafeInfo *certSafe = NULL, *keySafe = NULL;
SECItem unicodePw;
nsXPIDLCString xpidlFilePath;
nsAutoString filePath;
int i;
nsCOMPtr<nsILocalFile> localFileRef;
NS_ASSERTION(mToken, "Need to set the token before exporting");
// init slot
PRBool InformedUserNoSmartcardBackup = PR_FALSE;
int numCertsExported = 0;
rv = mToken->Login(PR_TRUE);
if (NS_FAILED(rv)) goto finish;
// get file password (unicode)
unicodePw.data = NULL;
rv = newPKCS12FilePassword(&unicodePw);
if (NS_FAILED(rv)) goto finish;
if (unicodePw.data == NULL) {
handleError(PIP_PKCS12_USER_CANCELED);
return NS_OK;
}
// what about slotToUse in psm 1.x ???
// create export context
ecx = SEC_PKCS12CreateExportContext(NULL, NULL, NULL /*slot*/, NULL);
if (!ecx) {
srv = SECFailure;
goto finish;
}
// add password integrity
srv = SEC_PKCS12AddPasswordIntegrity(ecx, &unicodePw, SEC_OID_SHA1);
if (srv) goto finish;
#if 0
// count the number of certs to export
nrv = mCertArray->Count(&numCerts);
if (NS_FAILED(nrv)) goto finish;
// loop over the certs
for (i=0; i<numCerts; i++) {
nsCOMPtr<nsIX509Cert> cert;
nrv = mCertArray->GetElementAt(i, getter_AddRefs(cert));
if (NS_FAILED(nrv)) goto finish;
#endif
for (i=0; i<numCerts; i++) {
// nsNSSCertificate *cert = NS_REINTREPRET_POINTER_CAST(nsNSSCertificate *,
// certs[i]);
nsNSSCertificate *cert = (nsNSSCertificate *)certs[i];
// get it as a CERTCertificate XXX
CERTCertificate *nssCert = NULL;
nssCert = cert->GetCert();
if (!nssCert) {
rv = NS_ERROR_FAILURE;
goto finish;
}
// We can only successfully export certs that are on
// internal token. Most, if not all, smart card vendors
// won't let you extract the private key (in any way
// shape or form) from the card. So let's punt if
// the cert is not in the internal db.
if (nssCert->slot && !PK11_IsInternal(nssCert->slot)) {
CERT_DestroyCertificate(nssCert);
if (!InformedUserNoSmartcardBackup) {
InformedUserNoSmartcardBackup = PR_TRUE;
handleError(PIP_PKCS12_NOSMARTCARD_EXPORT);
}
continue;
}
// XXX this is why, to verify the slot is the same
// PK11_FindObjectForCert(nssCert, NULL, slot);
// create the cert and key safes
keySafe = SEC_PKCS12CreateUnencryptedSafe(ecx);
if (!SEC_PKCS12IsEncryptionAllowed() || PK11_IsFIPS()) {
certSafe = keySafe;
} else {
certSafe = SEC_PKCS12CreatePasswordPrivSafe(ecx, &unicodePw,
SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC);
}
if (!certSafe || !keySafe) {
rv = NS_ERROR_FAILURE;
goto finish;
}
// add the cert and key to the blob
srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, NULL, nssCert,
CERT_GetDefaultCertDB(), // XXX
keySafe, NULL, PR_TRUE, &unicodePw,
SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC);
if (srv) goto finish;
// cert was dup'ed, so release it
CERT_DestroyCertificate(nssCert);
++numCertsExported;
}
if (!numCertsExported) goto finish;
// prepare the instance to write to an export file
this->mTmpFile = NULL;
file->GetPath(getter_Copies(xpidlFilePath));
filePath.AssignWithConversion(xpidlFilePath);
// Use the nsCOMPtr var localFileRef so that
// the reference to the nsILocalFile we create gets released as soon as
// we're out of scope, ie when this function exits.
if (filePath.RFind(".p12", PR_TRUE, -1, 4) < 0) {
// We're going to add the .p12 extension to the file name just like
// Communicator used to. We create a new nsILocalFile and initialize
// it with the new patch.
filePath.Append(NS_LITERAL_STRING(".p12"));
localFileRef = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
if (NS_FAILED(rv)) goto finish;
localFileRef->InitWithUnicodePath(filePath.get());
file = localFileRef;
}
rv = file->OpenNSPRFileDesc(PR_RDWR|PR_CREATE_FILE|PR_TRUNCATE, 0664,
&mTmpFile);
if (NS_FAILED(rv) || !this->mTmpFile) goto finish;
// encode and write
srv = SEC_PKCS12Encode(ecx, write_export_file, this);
if (srv) goto finish;
handleError(PIP_PKCS12_BACKUP_OK);
finish:
if (NS_FAILED(rv) || srv != SECSuccess) {
handleError(PIP_PKCS12_BACKUP_FAILED);
}
if (ecx)
SEC_PKCS12DestroyExportContext(ecx);
if (this->mTmpFile) {
PR_Close(this->mTmpFile);
this->mTmpFile = NULL;
}
return rv;
}
///////////////////////////////////////////////////////////////////////
//
// private members
//
///////////////////////////////////////////////////////////////////////
// unicodeToItem
//
// For the NSS PKCS#12 library, must convert PRUnichars (shorts) to
// a buffer of octets. Must handle byte order correctly.
// TODO: Is there a mozilla way to do this? In the string lib?
void
nsPKCS12Blob::unicodeToItem(PRUnichar *uni, SECItem *item)
{
int len = 0;
int i = 0;
while (uni[len++] != 0);
SECITEM_AllocItem(NULL, item, sizeof(PRUnichar) * len);
#ifdef IS_LITTLE_ENDIAN
for (i=0; i<len; i++) {
item->data[2*i ] = (unsigned char )(uni[i] << 8);
item->data[2*i+1] = (unsigned char )(uni[i]);
}
#else
memcpy(item->data, uni, item->len);
#endif
}
// newPKCS12FilePassword
//
// Launch a dialog requesting the user for a new PKCS#12 file passowrd.
// Handle user canceled by returning null password (caller must catch).
nsresult
nsPKCS12Blob::newPKCS12FilePassword(SECItem *unicodePw)
{
nsresult rv = NS_OK;
PRUnichar *password;
PRBool canceled;
nsCOMPtr<nsICertificateDialogs> certDialogs;
rv = ::getNSSDialogs(getter_AddRefs(certDialogs),
NS_GET_IID(nsICertificateDialogs));
if (NS_FAILED(rv)) return rv;
rv = certDialogs->SetPKCS12FilePassword(mUIContext, &password, &canceled);
if (NS_FAILED(rv) || canceled) return rv;
unicodeToItem(password, unicodePw);
return NS_OK;
}
// getPKCS12FilePassword
//
// Launch a dialog requesting the user for the password to a PKCS#12 file.
// Handle user canceled by returning null password (caller must catch).
nsresult
nsPKCS12Blob::getPKCS12FilePassword(SECItem *unicodePw)
{
nsresult rv = NS_OK;
PRUnichar *password;
PRBool canceled;
nsCOMPtr<nsICertificateDialogs> certDialogs;
rv = ::getNSSDialogs(getter_AddRefs(certDialogs),
NS_GET_IID(nsICertificateDialogs));
if (NS_FAILED(rv)) return rv;
rv = certDialogs->GetPKCS12FilePassword(mUIContext, &password, &canceled);
if (NS_FAILED(rv) || canceled) return rv;
unicodeToItem(password, unicodePw);
return NS_OK;
}
// inputToDecoder
//
// Given a decoder, read bytes from file and input them to the decoder.
nsresult
nsPKCS12Blob::inputToDecoder(SEC_PKCS12DecoderContext *dcx, nsILocalFile *file)
{
nsresult rv;
SECStatus srv;
PRUint32 amount;
unsigned char buf[PIP_PKCS12_BUFFER_SIZE];
// everybody else is doin' it
nsCOMPtr<nsIFileSpec> tempSpec;
{
nsXPIDLCString pathBuf;
file->GetPath(getter_Copies(pathBuf));
rv = NS_NewFileSpec(getter_AddRefs(tempSpec));
if (NS_FAILED(rv)) return rv;
rv = tempSpec->SetNativePath(pathBuf);
if (NS_FAILED(rv)) return rv;
}
nsInputFileStream fileStream(tempSpec);
while (PR_TRUE) {
amount = fileStream.read(buf, PIP_PKCS12_BUFFER_SIZE);
if (amount < 0) {
fileStream.close();
return NS_ERROR_FAILURE;
}
// feed the file data into the decoder
srv = SEC_PKCS12DecoderUpdate(dcx, buf, amount);
if (srv) {
fileStream.close();
return NS_ERROR_FAILURE;
}
if (amount < PIP_PKCS12_BUFFER_SIZE)
break;
}
fileStream.close();
return NS_OK;
}
#ifdef XP_MAC
OSErr ConvertMacPathToUnixPath(const char *macPath, char **unixPath)
{
PRIntn len;
char *cursor;
len = PL_strlen(macPath);
cursor = (char*)PR_Malloc(len+2);
if (!cursor)
return memFullErr;
memcpy(cursor+1, macPath, len+1);
*unixPath = cursor;
*cursor = '/';
while ((cursor = PL_strchr(cursor, ':')) != NULL) {
*cursor = '/';
cursor++;
}
return noErr;
}
#endif
//
// C callback methods
//
// digest_open
// open a temporary file for reading/writing digests
SECStatus PR_CALLBACK
nsPKCS12Blob::digest_open(void *arg, PRBool reading)
{
nsPKCS12Blob *cx = (nsPKCS12Blob *)arg;
nsresult rv;
// use DirectoryService to find the system temp directory
nsCOMPtr<nsILocalFile> tmpFile;
nsCOMPtr<nsIProperties> directoryService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return SECFailure;
directoryService->Get(NS_OS_TEMP_DIR,
NS_GET_IID(nsIFile),
getter_AddRefs(tmpFile));
if (tmpFile) {
tmpFile->Append(PIP_PKCS12_TMPFILENAME);
nsXPIDLCString pathBuf;
tmpFile->GetPath(getter_Copies(pathBuf));
cx->mTmpFilePath = PL_strdup(pathBuf.get());
#ifdef XP_MAC
char *unixPath = nsnull;
ConvertMacPathToUnixPath(cx->mTmpFilePath, &unixPath);
nsMemory::Free(cx->mTmpFilePath);
cx->mTmpFilePath = unixPath;
#endif
}
// Open the file using NSPR
if (reading) {
cx->mTmpFile = PR_Open(cx->mTmpFilePath, PR_RDONLY, 0400);
} else {
cx->mTmpFile = PR_Open(cx->mTmpFilePath,
PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE, 0600);
}
return (cx->mTmpFile != NULL) ? SECSuccess : SECFailure;
}
// digest_close
// close the temp file opened above
SECStatus PR_CALLBACK
nsPKCS12Blob::digest_close(void *arg, PRBool remove_it)
{
nsPKCS12Blob *cx = (nsPKCS12Blob *)arg;
PR_Close(cx->mTmpFile);
if (remove_it) {
PR_Delete(cx->mTmpFilePath);
PR_Free(cx->mTmpFilePath);
cx->mTmpFilePath = NULL;
}
cx->mTmpFile = NULL;
return SECSuccess;
}
// digest_read
// read bytes from the temp digest file
int PR_CALLBACK
nsPKCS12Blob::digest_read(void *arg, unsigned char *buf, unsigned long len)
{
nsPKCS12Blob *cx = (nsPKCS12Blob *)arg;
return PR_Read(cx->mTmpFile, buf, len);
}
// digest_write
// write bytes to the temp digest file
int PR_CALLBACK
nsPKCS12Blob::digest_write(void *arg, unsigned char *buf, unsigned long len)
{
nsPKCS12Blob *cx = (nsPKCS12Blob *)arg;
return PR_Write(cx->mTmpFile, buf, len);
}
// nickname_collision
// what to do when the nickname collides with one already in the db.
// TODO: not handled, throw a dialog allowing the nick to be changed?
SECItem * PR_CALLBACK
nsPKCS12Blob::nickname_collision(SECItem *oldNick, PRBool *cancel, void *wincx)
{
*cancel = PR_FALSE;
nsresult rv;
nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv)) return nsnull;
int count = 1;
nsXPIDLCString nickname;
nsString nickFromProp;
nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("P12DefaultNickname").get(),
nickFromProp);
nsXPIDLCString nickFromPropC;
nickFromPropC.Adopt(ToNewUTF8String(nickFromProp));
// The user is trying to import a PKCS#12 file that doesn't have the
// attribute we use to set the nickname. So in order to reduce the
// number of interactions we require with the user, we'll build a nickname
// for the user. The nickname isn't prominently displayed in the UI,
// so it's OK if we generate one on our own here.
// XXX If the NSS API were smarter and actually passed a pointer to
// the CERTCertificate* we're importing we could actually just
// call default_nickname (which is what the issuance code path
// does) and come up with a reasonable nickname. Alas, the NSS
// API limits our ability to produce a useful nickname without
// bugging the user. :(
while (1) {
// If we've gotten this far, that means there isn't a certificate
// in the database that has the same subject name as the cert we're
// trying to import. So we need to come up with a "nickname" to
// satisfy the NSS requirement or fail in trying to import.
// Basically we use a default nickname from a properties file and
// see if a certificate exists with that nickname. If there isn't, then
// create update the count by one and append the string '#1' Or
// whatever the count currently is, and look for a cert with
// that nickname. Keep updating the count until we find a nickname
// without a corresponding cert.
// XXX If a user imports *many* certs without the 'friendly name'
// attribute, then this may take a long time. :(
if (count > 1) {
nickname.Adopt(PR_smprintf("%s #%d", nickFromPropC.get(), count));
} else {
nickname = nickFromPropC;
}
CERTCertificate *cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(),
NS_CONST_CAST(char*,nickname.get()));
if (!cert) {
break;
}
CERT_DestroyCertificate(cert);
count++;
}
SECItem *newNick = new SECItem;
if (!newNick)
return nsnull;
newNick->type = siAsciiString;
newNick->data = (unsigned char*) nsCRT::strdup(nickname);
newNick->len = nsCRT::strlen((char*)newNick->data);
return newNick;
}
// write_export_file
// write bytes to the exported PKCS#12 file
void PR_CALLBACK
nsPKCS12Blob::write_export_file(void *arg, const char *buf, unsigned long len)
{
nsPKCS12Blob *cx = (nsPKCS12Blob *)arg;
PR_Write(cx->mTmpFile, buf, len);
}
// pip_ucs2_ascii_conversion_fn
// required to be set by NSS (to do PKCS#12), but since we've already got
// unicode make this a no-op.
PRBool
pip_ucs2_ascii_conversion_fn(PRBool toUnicode,
unsigned char *inBuf,
unsigned int inBufLen,
unsigned char *outBuf,
unsigned int maxOutBufLen,
unsigned int *outBufLen,
PRBool swapBytes)
{
// do a no-op, since I've already got unicode. Hah!
*outBufLen = inBufLen;
memcpy(outBuf, inBuf, inBufLen);
return PR_TRUE;
}
#define kWindowWatcherCID "@mozilla.org/embedcomp/window-watcher;1"
PRBool
nsPKCS12Blob::handleError(int myerr)
{
nsresult rv;
PRBool keepGoing = PR_FALSE;
int prerr = PORT_GetError();
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("PKCS12: NSS/NSPR error(%d)", prerr));
PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("PKCS12: I called(%d)", myerr));
nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
if (NS_FAILED(rv)) return PR_FALSE;
nsCOMPtr<nsIProxyObjectManager> proxyman(
do_GetService(NS_XPCOMPROXY_CONTRACTID));
if (!proxyman) return PR_FALSE;
nsCOMPtr<nsIPrompt> errPrompt;
nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(kWindowWatcherCID));
if (wwatch) {
wwatch->GetNewPrompter(0, getter_AddRefs(errPrompt));
if (errPrompt) {
nsCOMPtr<nsIPrompt> proxyPrompt;
proxyman->GetProxyForObject(NS_UI_THREAD_EVENTQ, NS_GET_IID(nsIPrompt),
errPrompt, PROXY_SYNC,
getter_AddRefs(proxyPrompt));
if (!proxyPrompt) return PR_FALSE;
} else {
return PR_FALSE;
}
} else {
return PR_FALSE;
}
nsAutoString errorMsg;
switch (myerr) {
case PIP_PKCS12_RESTORE_OK:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("SuccessfulP12Restore").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
return PR_TRUE;
case PIP_PKCS12_BACKUP_OK:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("SuccessfulP12Backup").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
return PR_TRUE;
case PIP_PKCS12_USER_CANCELED:
return PR_TRUE; /* Just ignore it for now */
case PIP_PKCS12_NOSMARTCARD_EXPORT:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12InfoNoSmartcardBackup").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
return PR_TRUE;
case PIP_PKCS12_RESTORE_FAILED:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12UnknownErrRestore").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
return PR_TRUE;
case PIP_PKCS12_BACKUP_FAILED:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12UnknownErrBackup").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
return PR_TRUE;
case PIP_PKCS12_NSS_ERROR:
switch (prerr) {
// The following errors have the potential to be "handled", by asking
// the user (via a dialog) whether s/he wishes to continue
case 0: break;
case SEC_ERROR_PKCS12_CERT_COLLISION:
/* pop a dialog saying the cert is already in the database */
/* ask to keep going? what happens if one collision but others ok? */
// The following errors cannot be "handled", notify the user (via an alert)
// that the operation failed.
#if 0
// XXX a boy can dream...
// but the PKCS12 lib never throws this error
// but then again, how would it? anyway, convey the info below
case SEC_ERROR_PKCS12_PRIVACY_PASSWORD_INCORRECT:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12PasswordInvalid").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
break;
#endif
case SEC_ERROR_BAD_PASSWORD:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PK11BadPassword").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
break;
case SEC_ERROR_BAD_DER:
case SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE:
case SEC_ERROR_PKCS12_INVALID_MAC:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12DecodeErr").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
break;
case SEC_ERROR_PKCS12_DUPLICATE_DATA:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12DupData").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
break;
default:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12UnknownErr").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
}
break;
case 0:
default:
rv = nssComponent->GetPIPNSSBundleString(
NS_LITERAL_STRING("PKCS12UnknownErr").get(),
errorMsg);
if (NS_FAILED(rv)) return rv;
errPrompt->Alert(nsnull, errorMsg.get());
break;
}
if (NS_FAILED(rv)) return rv;
return keepGoing;
}

View File

@@ -1,105 +0,0 @@
/*
* 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 Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ian McGreer <mcgreer@netscape.com>
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*
* $Id: nsPKCS12Blob.h,v 1.6 2001-06-19 05:29:54 javi%netscape.com Exp $
*/
#ifndef _NS_PKCS12BLOB_H_
#define _NS_PKCS12BLOB_H_
#include "nsCOMPtr.h"
#include "nsILocalFile.h"
#include "nsIPK11TokenDB.h"
#include "nsNSSHelper.h"
#include "nss.h"
extern "C" {
#include "pkcs12.h"
#include "p12plcy.h"
}
//
// nsPKCS12Blob
//
// Class for importing/exporting PKCS#12 blobs
//
class nsPKCS12Blob
{
public:
nsPKCS12Blob();
virtual ~nsPKCS12Blob();
// Set the token to use (default is internal)
void SetToken(nsIPK11Token *token);
// PKCS#12 Import
nsresult ImportFromFile(nsILocalFile *file);
// PKCS#12 Export
#if 0
//nsresult LoadCerts(const PRUnichar **certNames, int numCerts);
nsresult LoadCerts(nsIX509Cert **certs, int numCerts);
#endif
nsresult ExportToFile(nsILocalFile *file, nsIX509Cert **certs, int numCerts);
private:
nsCOMPtr<nsIPK11Token> mToken;
nsCOMPtr<nsISupportsArray> mCertArray;
nsCOMPtr<nsIInterfaceRequestor> mUIContext;
// local helper functions
nsresult getPKCS12FilePassword(SECItem *);
nsresult newPKCS12FilePassword(SECItem *);
nsresult inputToDecoder(SEC_PKCS12DecoderContext *, nsILocalFile *);
void unicodeToItem(PRUnichar *, SECItem *);
PRBool handleError(int myerr = 0);
// NSPR file I/O for temporary digest file
PRFileDesc *mTmpFile;
char *mTmpFilePath;
PRBool mTokenSet;
// C-style callback functions for the NSS PKCS#12 library
static SECStatus PR_CALLBACK digest_open(void *, PRBool);
static SECStatus PR_CALLBACK digest_close(void *, PRBool);
static int PR_CALLBACK digest_read(void *, unsigned char *, unsigned long);
static int PR_CALLBACK digest_write(void *, unsigned char *, unsigned long);
static SECItem * PR_CALLBACK nickname_collision(SECItem *, PRBool *, void *);
static void PR_CALLBACK write_export_file(void *arg, const char *buf, unsigned long len);
};
#endif /* _NS_PKCS12BLOB_H_ */

View File

@@ -1,348 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*/
#include "stdlib.h"
#include "plstr.h"
#include "plbase64.h"
#include "nsMemory.h"
#include "nsString.h"
#include "nsCOMPtr.h"
#include "nsISupports.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIServiceManager.h"
#include "nsISecurityManagerComponent.h"
#include "nsIWindowWatcher.h"
#include "nsIPrompt.h"
#include "nsProxiedService.h"
#include "nsINSSDialogs.h"
#include "nsISecretDecoderRing.h"
#include "nsSDR.h"
#include "nsNSSComponent.h"
#include "pk11func.h"
#include "pk11sdr.h" // For PK11SDR_Encrypt, PK11SDR_Decrypt
//
// Implementation of an nsIInterfaceRequestor for use
// as context for NSS calls
//
class nsSDRContext : public nsIInterfaceRequestor
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIINTERFACEREQUESTOR
nsSDRContext();
virtual ~nsSDRContext();
};
NS_IMPL_ISUPPORTS1(nsSDRContext, nsIInterfaceRequestor)
nsSDRContext::nsSDRContext()
{
NS_INIT_ISUPPORTS();
}
nsSDRContext::~nsSDRContext()
{
}
/* void getInterface (in nsIIDRef uuid, [iid_is (uuid), retval] out nsQIResult result); */
NS_IMETHODIMP nsSDRContext::GetInterface(const nsIID & uuid, void * *result)
{
if (uuid.Equals(NS_GET_IID(nsIPrompt))) {
nsCOMPtr<nsIProxyObjectManager> proxyman(do_GetService(NS_XPCOMPROXY_CONTRACTID));
if (!proxyman) return NS_ERROR_FAILURE;
nsCOMPtr<nsIPrompt> prompter;
nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService("@mozilla.org/embedcomp/window-watcher;1"));
if (wwatch) {
wwatch->GetNewPrompter(0, getter_AddRefs(prompter));
if (prompter) {
nsCOMPtr<nsIPrompt> proxyPrompt;
proxyman->GetProxyForObject(NS_UI_THREAD_EVENTQ, NS_GET_IID(nsIPrompt),
prompter, PROXY_SYNC, getter_AddRefs(proxyPrompt));
if (!proxyPrompt) return NS_ERROR_FAILURE;
*result = proxyPrompt;
NS_ADDREF((nsIPrompt*)*result);
}
}
} else {
return NS_ERROR_NO_INTERFACE;
}
return NS_OK;
}
// Standard ISupports implementation
// NOTE: Should these be the thread-safe versions?
NS_IMPL_ISUPPORTS2(nsSecretDecoderRing, nsISecretDecoderRing, nsISecretDecoderRingConfig)
// nsSecretDecoderRing constructor
nsSecretDecoderRing::nsSecretDecoderRing()
{
// initialize superclass
NS_INIT_ISUPPORTS();
// (Possibly) create the Security Manager component to get things
// initialized
nsCOMPtr<nsISecurityManagerComponent> nss = do_GetService(PSM_COMPONENT_CONTRACTID);
}
// nsSecretDecoderRing destructor
nsSecretDecoderRing::~nsSecretDecoderRing()
{
}
/* [noscript] long encrypt (in buffer data, in long dataLen, out buffer result); */
NS_IMETHODIMP nsSecretDecoderRing::
Encrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval)
{
nsresult rv = NS_OK;
PK11SlotInfo *slot = 0;
SECItem keyid;
SECItem request;
SECItem reply;
SECStatus s;
nsCOMPtr<nsIInterfaceRequestor> ctx = new nsSDRContext();
slot = PK11_GetInternalKeySlot();
if (!slot) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
/* Make sure token is initialized. */
rv = setPassword(slot, ctx);
if (NS_FAILED(rv))
goto loser;
s = PK11_Authenticate(slot, PR_TRUE, ctx);
if (s != SECSuccess) { rv = NS_ERROR_FAILURE; goto loser; }
/* Use default key id */
keyid.data = 0;
keyid.len = 0;
request.data = data;
request.len = dataLen;
reply.data = 0;
reply.len = 0;
s= PK11SDR_Encrypt(&keyid, &request, &reply, ctx);
if (s != SECSuccess) { rv = NS_ERROR_FAILURE; goto loser; }
*result = reply.data;
*_retval = reply.len;
loser:
if (slot) PK11_FreeSlot(slot);
return rv;
}
/* [noscript] long decrypt (in buffer data, in long dataLen, out buffer result); */
NS_IMETHODIMP nsSecretDecoderRing::
Decrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval)
{
nsresult rv = NS_OK;
PK11SlotInfo *slot = 0;
SECStatus s;
SECItem request;
SECItem reply;
nsCOMPtr<nsIInterfaceRequestor> ctx = new nsSDRContext();
*result = 0;
*_retval = 0;
/* Find token with SDR key */
slot = PK11_GetInternalKeySlot();
if (!slot) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
/* Force authentication */
if (PK11_Authenticate(slot, PR_TRUE, ctx) != SECSuccess)
{
rv = NS_ERROR_NOT_AVAILABLE;
goto loser;
}
request.data = data;
request.len = dataLen;
reply.data = 0;
reply.len = 0;
s = PK11SDR_Decrypt(&request, &reply, ctx);
if (s != SECSuccess) { rv = NS_ERROR_FAILURE; goto loser; }
*result = reply.data;
*_retval = reply.len;
loser:
if (slot) PK11_FreeSlot(slot);
return rv;
}
/* string encryptString (in string text); */
NS_IMETHODIMP nsSecretDecoderRing::
EncryptString(const char *text, char **_retval)
{
nsresult rv = NS_OK;
unsigned char *encrypted = 0;
PRInt32 eLen;
if (text == nsnull || _retval == nsnull) {
rv = NS_ERROR_INVALID_POINTER;
goto loser;
}
rv = Encrypt((unsigned char *)text, PL_strlen(text), &encrypted, &eLen);
if (rv != NS_OK) { goto loser; }
rv = encode(encrypted, eLen, _retval);
loser:
if (encrypted) nsMemory::Free(encrypted);
return rv;
}
/* string decryptString (in string crypt); */
NS_IMETHODIMP nsSecretDecoderRing::
DecryptString(const char *crypt, char **_retval)
{
nsresult rv = NS_OK;
char *r = 0;
unsigned char *decoded = 0;
PRInt32 decodedLen;
unsigned char *decrypted = 0;
PRInt32 decryptedLen;
if (crypt == nsnull || _retval == nsnull) {
rv = NS_ERROR_INVALID_POINTER;
goto loser;
}
rv = decode(crypt, &decoded, &decodedLen);
if (rv != NS_OK) goto loser;
rv = Decrypt(decoded, decodedLen, &decrypted, &decryptedLen);
if (rv != NS_OK) goto loser;
// Convert to NUL-terminated string
r = (char *)nsMemory::Alloc(decryptedLen+1);
if (!r) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
memcpy(r, decrypted, decryptedLen);
r[decryptedLen] = 0;
*_retval = r;
r = 0;
loser:
if (r) nsMemory::Free(r);
if (decrypted) nsMemory::Free(decrypted);
if (decoded) nsMemory::Free(decoded);
return rv;
}
/* void changePassword(); */
NS_IMETHODIMP nsSecretDecoderRing::
ChangePassword()
{
nsresult rv;
PK11SlotInfo *slot;
slot = PK11_GetInternalKeySlot();
if (!slot) return NS_ERROR_NOT_AVAILABLE;
/* Convert UTF8 token name to UCS2 */
NS_ConvertUTF8toUCS2 tokenName(PK11_GetTokenName(slot));
PK11_FreeSlot(slot);
/* Get the set password dialog handler imlementation */
nsCOMPtr<nsITokenPasswordDialogs> dialogs;
rv = getNSSDialogs(getter_AddRefs(dialogs),
NS_GET_IID(nsITokenPasswordDialogs));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIInterfaceRequestor> ctx = new nsSDRContext();
PRBool canceled;
rv = dialogs->SetPassword(ctx, tokenName.get(), &canceled);
/* canceled is ignored */
return rv;
}
/* void logout(); */
NS_IMETHODIMP nsSecretDecoderRing::
Logout()
{
PK11_LogoutAll();
return NS_OK;
}
/* void setWindow(in nsISupports w); */
nsresult nsSecretDecoderRing::
SetWindow(nsISupports *w)
{
return NS_OK;
}
// Support routines
nsresult nsSecretDecoderRing::
encode(const unsigned char *data, PRInt32 dataLen, char **_retval)
{
nsresult rv = NS_OK;
*_retval = PL_Base64Encode((const char *)data, dataLen, NULL);
if (!*_retval) { rv = NS_ERROR_OUT_OF_MEMORY; goto loser; }
loser:
return rv;
}
nsresult nsSecretDecoderRing::
decode(const char *data, unsigned char **result, PRInt32 * _retval)
{
nsresult rv = NS_OK;
PRUint32 len = PL_strlen(data);
int adjust = 0;
/* Compute length adjustment */
if (data[len-1] == '=') {
adjust++;
if (data[len-2] == '=') adjust++;
}
*result = (unsigned char *)PL_Base64Decode(data, len, NULL);
if (!*result) { rv = NS_ERROR_ILLEGAL_VALUE; goto loser; }
*_retval = (len*3)/4 - adjust;
loser:
return rv;
}

View File

@@ -1,76 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Terry Hayes <thayes@netscape.com>
*/
#ifndef _NSSDR_H_
#define _NSSDR_H_
#include "nsISecretDecoderRing.h"
class nsINSSDialogs;
/**
* NS_SDR_CONTRACTID - contract id for SDR services.
* Implements nsISecretDecoderRing.
* Should eventually implement an interface to set window
* context and other information. (nsISecretDecoderRingConfig)
*
* NOTE: This definition should move to base code. It
* is conditionally defined here until it is moved.
* Delete this after defining in the new location.
*/
#ifndef NS_SDR_CONTRACTID
#define NS_SDR_CONTRACTID "@mozilla.org/security/sdr;1"
#endif
// ===============================================
// nsSecretDecoderRing - implementation of nsISecretDecoderRing
// ===============================================
#define NS_SDR_CLASSNAME "PIPNSS Secret Decoder Ring"
#define NS_SDR_CID \
{ 0x0c4f1ddc, 0x1dd2, 0x11b2, { 0x9d, 0x95, 0xf2, 0xfd, 0xf1, 0x13, 0x04, 0x4b } }
class nsSecretDecoderRing
: public nsISecretDecoderRing,
public nsISecretDecoderRingConfig
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISECRETDECODERRING
NS_DECL_NSISECRETDECODERRINGCONFIG
nsSecretDecoderRing();
virtual ~nsSecretDecoderRing();
private:
/**
* encode - encodes binary into BASE64 string.
* decode - decode BASE64 string into binary.
*/
nsresult encode(const unsigned char *data, PRInt32 dataLen, char **_retval);
nsresult decode(const char *data, unsigned char **result, PRInt32 * _retval);
};
#endif /* _NSSDR_H_ */

View File

@@ -1,75 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*/
#include "nsSSLSocketProvider.h"
#include "nsNSSIOLayer.h"
nsSSLSocketProvider::nsSSLSocketProvider()
{
NS_INIT_ISUPPORTS();
}
nsSSLSocketProvider::~nsSSLSocketProvider()
{
}
NS_IMPL_THREADSAFE_ISUPPORTS2(nsSSLSocketProvider, nsISocketProvider,
nsISSLSocketProvider);
NS_IMETHODIMP
nsSSLSocketProvider::NewSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc **_result,
nsISupports **securityInfo)
{
nsresult rv = nsSSLIOLayerNewSocket(host,
port,
proxyHost,
proxyPort,
_result,
securityInfo,
PR_FALSE);
return (NS_FAILED(rv)) ? NS_ERROR_SOCKET_CREATE_FAILED : NS_OK;
}
// Add the SSL IO layer to an existing socket
NS_IMETHODIMP
nsSSLSocketProvider::AddToSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc *aSocket,
nsISupports **securityInfo)
{
nsresult rv = nsSSLIOLayerAddToSocket(host,
port,
proxyHost,
proxyPort,
aSocket,
securityInfo,
PR_FALSE);
return (NS_FAILED(rv)) ? NS_ERROR_SOCKET_CREATE_FAILED : NS_OK;
}

View File

@@ -1,46 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*/
#ifndef _NSSSLSOCKETPROVIDER_H_
#define _NSSSLSOCKETPROVIDER_H_
#include "nsISSLSocketProvider.h"
/* 217d014a-1dd2-11b2-999c-b0c4df79b324 */
#define NS_SSLSOCKETPROVIDER_CID \
{ 0x217d014a, 0x1dd2, 0x11b2, {0x99, 0x9c, 0xb0, 0xc4, 0xdf, 0x79, 0xb3, 0x24}}
class nsSSLSocketProvider : public nsISSLSocketProvider
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISOCKETPROVIDER
NS_DECL_NSISSLSOCKETPROVIDER
// nsSSLSocketProvider methods:
nsSSLSocketProvider();
virtual ~nsSSLSocketProvider();
};
#endif /* _NSSSLSOCKETPROVIDER_H_ */

View File

@@ -1,76 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 mozilla.org code.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*/
#include "nsTLSSocketProvider.h"
#include "nsNSSIOLayer.h"
nsTLSSocketProvider::nsTLSSocketProvider()
{
NS_INIT_ISUPPORTS();
}
nsTLSSocketProvider::~nsTLSSocketProvider()
{
}
NS_IMPL_THREADSAFE_ISUPPORTS2(nsTLSSocketProvider, nsISocketProvider,
nsISSLSocketProvider);
NS_IMETHODIMP
nsTLSSocketProvider::NewSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc **_result,
nsISupports **securityInfo)
{
nsresult rv = nsSSLIOLayerNewSocket(host,
port,
proxyHost,
proxyPort,
_result,
securityInfo,
PR_TRUE);
return (NS_FAILED(rv)) ? NS_ERROR_SOCKET_CREATE_FAILED : NS_OK;
}
// Add the SSL IO layer to an existing socket
NS_IMETHODIMP
nsTLSSocketProvider::AddToSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc *aSocket,
nsISupports **securityInfo)
{
nsresult rv = nsSSLIOLayerAddToSocket(host,
port,
proxyHost,
proxyPort,
aSocket,
securityInfo,
PR_TRUE);
return (NS_FAILED(rv)) ? NS_ERROR_SOCKET_CREATE_FAILED : NS_OK;
}

Some files were not shown because too many files have changed in this diff Show More