Compare commits

..

5 Commits

Author SHA1 Message Date
thayes%netscape.com
4127f7ed92 Initialize reply message structure.
git-svn-id: svn://10.0.0.236/branches/sdr_1@70179 18797224-902f-48f8-a5cc-f745e15eee43
2000-05-16 23:43:20 +00:00
thayes%netscape.com
fc8cd8ebd2 Add ctx argumeent to SDR calls. This value will be returned (eventually) to
applications on password requests.


git-svn-id: svn://10.0.0.236/branches/sdr_1@70175 18797224-902f-48f8-a5cc-f745e15eee43
2000-05-16 23:34:47 +00:00
thayes%netscape.com
26ed09faf4 Change protocol for SDR to include ctx pointer
git-svn-id: svn://10.0.0.236/branches/sdr_1@70157 18797224-902f-48f8-a5cc-f745e15eee43
2000-05-16 23:07:21 +00:00
thayes%netscape.com
14e542e142 Add change-password protocol and client function
git-svn-id: svn://10.0.0.236/branches/sdr_1@70001 18797224-902f-48f8-a5cc-f745e15eee43
2000-05-16 05:51:56 +00:00
(no author)
fe9b32e930 This commit was manufactured by cvs2svn to create branch 'sdr_1'.
git-svn-id: svn://10.0.0.236/branches/sdr_1@69858 18797224-902f-48f8-a5cc-f745e15eee43
2000-05-15 20:56:32 +00:00
335 changed files with 17675 additions and 104241 deletions

View File

@@ -0,0 +1,74 @@
#! 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):
#
# 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.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View File

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

View File

@@ -0,0 +1,3 @@
cmtclist.h
cmtcmn.h
cmtjs.h

View File

@@ -0,0 +1,74 @@
#! 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):
#
# 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.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
include config.mk
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View File

@@ -1,4 +1,4 @@
# -*- Mode: perl; indent-tabs-mode: nil -*-
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
@@ -10,14 +10,14 @@
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code are the Bugzilla Tests.
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Zach Lipton
# Portions created by Zach Lipton are
# Copyright (C) 2001 Zach Lipton. All
# 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): Zach Lipton <zach@zachlipton.com>
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
@@ -32,36 +32,39 @@
# GPL.
#
package Support::Files;
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
@additional_files = ('syncshadowdb','processmail');
@exclude_files = ('importxml.pl');
include $(DEPTH)/config/autoconf.mk
$file = '*';
@files = glob($file);
LIBRARY_NAME = cmt
sub isTestingFile {
my ($file) = @_;
my $exclude;
foreach $exclude (@exclude_files) {
if ($file eq $exclude) { return undef; } # get rid of excluded files.
}
EXPORTS = \
cmtcmn.h \
cmtjs.h \
cmtclist.h \
$(NULL)
if ($file =~ /\.cgi$|\.pl$|\.pm$/) {
return 1;
}
my $additional;
foreach $additional (@additional_files) {
if ($file eq $additional) { return 1; }
}
return undef;
}
MODULE = security
foreach $currentfile (@files) {
if (isTestingFile($currentfile)) {
push(@testitems,$currentfile);
}
}
CSRCS = cmtinit.c \
cmtssl.c \
cmtutils.c \
cmtcert.c \
cmthash.c \
cmtpkcs7.c \
cmtres.c \
cmtjs.c \
cmtevent.c \
cmtpasswd.c \
cmtadvisor.c \
cmtrng.c \
cmtsdr.c \
$(NULL)
EXTRA_DSO_LDOPTS += -L$(DIST)/bin -lprotocol
include $(topsrcdir)/config/rules.mk
1;

View File

@@ -0,0 +1,99 @@
/*
* 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):
*
* 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 "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#ifdef XP_MAC
#include "cmtmac.h"
#endif
CMTStatus CMT_SecurityAdvisor(PCMT_CONTROL control, CMTSecurityAdvisorData* data, CMUint32 *resID)
{
CMTItem message = {0, NULL, 0};
SecurityAdvisorRequest request;
SingleNumMessage reply;
if (!control) {
return CMTFailure;
}
if (!data) {
return CMTFailure;
}
request.infoContext = data->infoContext;
request.resID = data->resID;
request.hostname = data->hostname;
request.senderAddr = data->senderAddr;
request.encryptedP7CInfo = data->encryptedP7CInfo;
request.signedP7CInfo = data->signedP7CInfo;
request.decodeError = data->decodeError;
request.verifyError = data->verifyError;
request.encryptthis = data->encryptthis;
request.signthis = data->signthis;
request.numRecipients = data->numRecipients;
request.recipients = data->recipients;
message.type = SSM_REQUEST_MESSAGE | SSM_SECURITY_ADVISOR;
if (CMT_EncodeMessage(SecurityAdvisorRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_SECURITY_ADVISOR)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*resID = reply.value;
return CMTSuccess;
loser:
if (message.data) {
free(message.data);
}
return CMTFailure;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,111 @@
/*
* 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):
*
* 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 cmtclist_h___
#define cmtclist_h___
typedef struct CMTCListStr CMTCList;
/*
** Circular linked list
*/
struct CMTCListStr {
CMTCList *next;
CMTCList *prev;
};
/*
** Insert element "_e" into the list, before "_l".
*/
#define CMT_INSERT_BEFORE(_e,_l) \
(_e)->next = (_l); \
(_e)->prev = (_l)->prev; \
(_l)->prev->next = (_e); \
(_l)->prev = (_e); \
/*
** Insert element "_e" into the list, after "_l".
*/
#define CMT_INSERT_AFTER(_e,_l) \
(_e)->next = (_l)->next; \
(_e)->prev = (_l); \
(_l)->next->prev = (_e); \
(_l)->next = (_e); \
/*
** Append an element "_e" to the end of the list "_l"
*/
#define CMT_APPEND_LINK(_e,_l) CMT_INSERT_BEFORE(_e,_l)
/*
** Insert an element "_e" at the head of the list "_l"
*/
#define CMT_INSERT_LINK(_e,_l) CMT_INSERT_AFTER(_e,_l)
/* Return the head/tail of the list */
#define CMT_LIST_HEAD(_l) (_l)->next
#define CMT_LIST_TAIL(_l) (_l)->prev
/*
** Remove the element "_e" from it's circular list.
*/
#define CMT_REMOVE_LINK(_e) \
(_e)->prev->next = (_e)->next; \
(_e)->next->prev = (_e)->prev; \
/*
** Remove the element "_e" from it's circular list. Also initializes the
** linkage.
*/
#define CMT_REMOVE_AND_INIT_LINK(_e) \
(_e)->prev->next = (_e)->next; \
(_e)->next->prev = (_e)->prev; \
(_e)->next = (_e); \
(_e)->prev = (_e); \
/*
** Return non-zero if the given circular list "_l" is empty, zero if the
** circular list is not empty
*/
#define CMT_CLIST_IS_EMPTY(_l) \
((_l)->next == (_l))
/*
** Initialize a circular list
*/
#define CMT_INIT_CLIST(_l) \
(_l)->next = (_l); \
(_l)->prev = (_l); \
#define CMT_INIT_STATIC_CLIST(_l) \
{(_l), (_l)}
#endif /* cmtclist_h___ */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,480 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include <string.h>
#ifdef XP_UNIX
#include <sys/time.h>
#endif
/* Typedefs */
typedef void (*taskcompleted_handler_fn)(CMUint32 resourceID, CMUint32 numReqProcessed, CMUint32 resultCode, void* data);
CMTStatus CMT_SetUIHandlerCallback(PCMT_CONTROL control,
uiHandlerCallback_fn f, void *data)
{
return CMT_RegisterEventHandler(control, SSM_UI_EVENT, 0,
(void_fun)f, data);
}
void CMT_SetFilePathPromptCallback(PCMT_CONTROL control,
filePathPromptCallback_fn f, void* arg)
{
control->userFuncs.promptFilePath = f;
control->userFuncs.filePromptArg = arg;
}
void CMT_SetPromptCallback(PCMT_CONTROL control,
promptCallback_fn f, void *arg)
{
control->userFuncs.promptCallback = f;
control->userFuncs.promptArg = arg;
}
void CMT_SetSavePrefsCallback(PCMT_CONTROL control, savePrefsCallback_fn f)
{
control->userFuncs.savePrefs = f;
}
CMTStatus CMT_RegisterEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID, void_fun handler,
void* data)
{
PCMT_EVENT ptr;
/* This is the first connection */
if (control->cmtEventHandlers == NULL) {
control->cmtEventHandlers = ptr =
(PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (!ptr) {
goto loser;
}
} else {
/* Look for another event handler of the same type. Make sure the
event handler with a rsrcid of 0 is farther down the list so
that it doesn't get chosen when there's an event handler for
a specific rsrcid.
*/
for (ptr=control->cmtEventHandlers; ptr != NULL; ptr = ptr->next) {
if (ptr->type == type && resourceID != 0) {
/* So we've got an event handler that wants to over-ride
an existing event handler. We'll put it before the one
that's already here.
*/
if (ptr->previous == NULL) {
/* We're going to insert at the front of the list*/
control->cmtEventHandlers = ptr->previous =
(PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (ptr->previous == NULL) {
goto loser;
}
ptr->previous->next = ptr;
ptr = control->cmtEventHandlers;
} else {
/* We want to insert in the middle of the list */
PCMT_EVENT tmpEvent;
tmpEvent = (PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (tmpEvent == NULL) {
goto loser;
}
tmpEvent->previous = ptr->previous;
ptr->previous->next = tmpEvent;
tmpEvent->next = ptr;
ptr->previous = tmpEvent;
ptr = tmpEvent;
}
break;
}
if (ptr->next == NULL) break;
}
if (ptr == NULL) {
goto loser;
}
if (ptr->next == NULL) {
/* We're adding the event handler at the end of the list. */
ptr->next = (PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (!ptr->next) {
goto loser;
}
/* Fix up the pointers */
ptr->next->previous = ptr;
ptr = ptr->next;
}
}
/* Fill in the data */
ptr->type = type;
ptr->resourceID = resourceID;
ptr->handler = handler;
ptr->data = data;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_UnregisterEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID)
{
PCMT_EVENT ptr, pptr = NULL;
for (ptr = control->cmtEventHandlers; ptr != NULL;
pptr = ptr, ptr = ptr->next) {
if ((ptr->type == type) && (ptr->resourceID == resourceID)) {
if (pptr == NULL) {
/* node is at head */
control->cmtEventHandlers = ptr->next;
if (control->cmtEventHandlers != NULL) {
control->cmtEventHandlers->previous = NULL;
}
free(ptr);
return CMTSuccess;
}
/* node is elsewhere */
pptr->next = ptr->next;
if (ptr->next != NULL) {
ptr->next->previous = pptr;
}
free(ptr);
return CMTSuccess;
}
}
return CMTFailure;
}
PCMT_EVENT CMT_GetEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID)
{
PCMT_EVENT ptr;
for (ptr = control->cmtEventHandlers; ptr != NULL; ptr = ptr->next) {
if ((ptr->type == type) && ((ptr->resourceID == resourceID) ||
!ptr->resourceID)) {
return ptr;
}
}
return NULL;
}
PCMT_EVENT CMT_GetFirstEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID)
{
PCMT_EVENT ptr;
for (ptr = control->cmtEventHandlers; ptr != NULL; ptr = ptr->next) {
if ((ptr->type == type) && ((ptr->resourceID == resourceID) ||
!ptr->resourceID)) {
return ptr;
}
}
return NULL;
}
PCMT_EVENT CMT_GetNextEventHandler(PCMT_CONTROL control, PCMT_EVENT e)
{
PCMT_EVENT ptr;
for (ptr = control->cmtEventHandlers; ptr != NULL || ptr == e;
ptr = ptr->next) {
}
for (; ptr != NULL; ptr = ptr->next) {
if ((ptr->type == e->type) && ((ptr->resourceID == e->resourceID) ||
!ptr->resourceID)) {
return ptr;
}
}
return NULL;
}
void CMT_ProcessEvent(PCMT_CONTROL cm_control)
{
CMTSocket sock;
CMTItem eventData={ 0, NULL, 0 };
/* Get the control socket */
sock = cm_control->sock;
/* Acquire a lock on the control connection */
CMT_LOCK(cm_control->mutex);
/* Do another select here to be sure
that the socket is readable */
if (cm_control->sockFuncs.select(&sock, 1, 1) != sock) {
/* There's no event. */
goto done;
}
/* Read the event */
if (CMT_ReceiveMessage(cm_control, &eventData) == CMTFailure) {
goto done;
}
CMT_UNLOCK(cm_control->mutex);
/* Dispatch the event */
CMT_DispatchEvent(cm_control, &eventData);
return;
done:
/* Release the lock on the control connection */
CMT_UNLOCK(cm_control->mutex);
}
void CMT_EventLoop(PCMT_CONTROL cm_control)
{
CMTSocket sock;
/* Get the control socket */
sock = cm_control->sock;
CMT_ReferenceControlConnection(cm_control);
/* Select on the control socket to see if it's readable */
while(cm_control->sockFuncs.select(&sock, 1, 0)) {
CMT_ProcessEvent(cm_control);
}
CMT_CloseControlConnection(cm_control);
return;
}
void
CMT_PromptUser(PCMT_CONTROL cm_control, CMTItem *eventData)
{
char *promptReply = NULL;
CMTItem response={ 0, NULL, 0 };
PromptRequest request;
PromptReply reply;
void * clientContext;
/* Decode the message */
if (CMT_DecodeMessage(PromptRequestTemplate, &request, eventData) != CMTSuccess) {
goto loser;
}
/* Copy the client context to a pointer */
clientContext = CMT_CopyItemToPtr(request.clientContext);
if (cm_control->userFuncs.promptCallback == NULL) {
goto loser;
}
promptReply =
cm_control->userFuncs.promptCallback(cm_control->userFuncs.promptArg,
request.prompt, clientContext, 1);
response.type = SSM_EVENT_MESSAGE | SSM_PROMPT_EVENT;
if (!promptReply) {
/* the user canceled the prompt or other errors occurred */
reply.cancel = CM_TRUE;
}
else {
/* note that this includes an empty string (zero length) password */
reply.cancel = CM_FALSE;
}
reply.resID = request.resID;
reply.promptReply = promptReply;
/* Encode the message */
if (CMT_EncodeMessage(PromptReplyTemplate, &response, &reply) != CMTSuccess) {
goto loser;
}
CMT_TransmitMessage(cm_control, &response);
loser:
if (promptReply != NULL) {
cm_control->userFuncs.userFree(promptReply);
}
return;
}
void CMT_GetFilePath(PCMT_CONTROL cm_control, CMTItem * eventData)
{
char *fileName=NULL;
CMTItem response = { 0, NULL, 0 };
FilePathRequest request;
FilePathReply reply;
/* Decode the request */
if (CMT_DecodeMessage(FilePathRequestTemplate, &request, eventData) != CMTSuccess) {
goto loser;
}
if (cm_control->userFuncs.promptFilePath == NULL) {
goto loser;
}
fileName =
cm_control->userFuncs.promptFilePath(cm_control->userFuncs.filePromptArg,
request.prompt, request.fileRegEx,
request.getExistingFile);
response.type = SSM_EVENT_MESSAGE | SSM_FILE_PATH_EVENT;
reply.resID = request.resID;
reply.filePath = fileName;
/* Encode the reply */
if (CMT_EncodeMessage(FilePathReplyTemplate, &response, &reply) != CMTSuccess) {
goto loser;
}
CMT_TransmitMessage(cm_control, &response);
cm_control->userFuncs.userFree(fileName);
loser:
return;
}
void CMT_SavePrefs(PCMT_CONTROL cm_control, CMTItem* eventData)
{
SetPrefListMessage request;
int i;
/* decode the request */
if (CMT_DecodeMessage(SetPrefListMessageTemplate, &request, eventData) !=
CMTSuccess) {
return;
}
if (cm_control->userFuncs.savePrefs == NULL) {
/* callback was not registered: bail */
return;
}
cm_control->userFuncs.savePrefs(request.length,
(CMTSetPrefElement*)request.list);
for (i = 0; i < request.length; i++) {
if (request.list[i].key != NULL) {
free(request.list[i].key);
}
if (request.list[i].value != NULL) {
free(request.list[i].value);
}
}
return;
}
void CMT_DispatchEvent(PCMT_CONTROL cm_control, CMTItem * eventData)
{
CMUint32 eventType;
CMTItem msgCopy;
/* Init the msgCopy */
msgCopy.data = 0;
/* Get the event type */
if ((eventData->type & SSM_CATEGORY_MASK) != SSM_EVENT_MESSAGE) {
/* Somehow there was a message on the socket that was not
* an event message. Dropping it on the floor.
*/
goto loser;
}
eventType = (eventData->type & SSM_TYPE_MASK);
/* We must now dispatch the event based on it's type */
switch (eventType) {
case SSM_UI_EVENT:
{
PCMT_EVENT p;
UIEvent event;
void * clientContext = NULL;
/* Copy the message to allow a second try with the old format */
msgCopy.len = eventData->len;
msgCopy.data = calloc(msgCopy.len, 1);
if (msgCopy.data) {
memcpy(msgCopy.data, eventData->data, eventData->len);
}
/* Get the event data first */
if (CMT_DecodeMessage(UIEventTemplate, &event, eventData) != CMTSuccess) {
/* Attempt to decode using the old format. Modal is True */
if (!msgCopy.data ||
CMT_DecodeMessage(OldUIEventTemplate, &event, &msgCopy) != CMTSuccess) {
goto loser;
}
/* Set default modal value */
event.isModal = CM_TRUE;
}
/* Convert the client context to a pointer */
clientContext = CMT_CopyItemToPtr(event.clientContext);
/* Call any handlers for this event */
p = CMT_GetEventHandler(cm_control, eventType, event.resourceID);
if (!p) {
goto loser;
}
(*(uiHandlerCallback_fn)(p->handler))(event.resourceID,
clientContext, event.width,
event.height, event.isModal, event.url,
p->data);
break;
}
case SSM_TASK_COMPLETED_EVENT:
{
PCMT_EVENT p;
TaskCompletedEvent event;
/* Get the event data */
if (CMT_DecodeMessage(TaskCompletedEventTemplate, &event, eventData) != CMTSuccess) {
goto loser;
}
/* Call handler for this event */
p = CMT_GetEventHandler(cm_control, eventType, event.resourceID);
if (!p) {
goto loser;
}
(*(taskcompleted_handler_fn)(p->handler))(event.resourceID,
event.numTasks,
event.result, p->data);
break;
}
case SSM_AUTH_EVENT:
CMT_ServicePasswordRequest(cm_control, eventData);
break;
case SSM_FILE_PATH_EVENT:
CMT_GetFilePath(cm_control, eventData);
break;
case SSM_PROMPT_EVENT:
CMT_PromptUser(cm_control, eventData);
break;
case SSM_SAVE_PREF_EVENT:
CMT_SavePrefs(cm_control, eventData);
break;
default:
break;
}
loser:
free(eventData->data);
free(msgCopy.data);
return;
}

View File

@@ -0,0 +1,216 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#include "string.h"
#else
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
CMTStatus CMT_HashCreate(PCMT_CONTROL control, CMUint32 algID,
CMUint32 * connID)
{
CMTItem message;
SingleNumMessage request;
DataConnectionReply reply;
/* Check passed in parameters */
if (!control) {
goto loser;
}
/* Set up the request */
request.value = algID;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_HASH_STREAM;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the response */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_HASH_STREAM)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
CMTSocket sock;
sock = control->sockFuncs.socket(0);
if(sock == NULL) {
goto loser;
}
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
/* Send the hello message */
control->sockFuncs.send(sock, control->nonce.data, control->nonce.len);
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
/* Set the connection ID */
*connID = reply.connID;
return CMTSuccess;
}
loser:
*connID = 0;
return CMTFailure;
}
CMTStatus CMT_HASH_Destroy(PCMT_CONTROL control, CMUint32 connectionID)
{
if (!control) {
goto loser;
}
/* Get the cotext implementation data */
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_HASH_Begin(PCMT_CONTROL control, CMUint32 connectionID)
{
return CMTSuccess;
}
CMTStatus CMT_HASH_Update(PCMT_CONTROL control, CMUint32 connectionID, const unsigned char * buf, CMUint32 len)
{
CMTSocket sock;
CMUint32 sent;
/* Do some parameter checking */
if (!control || !buf) {
goto loser;
}
/* Get the data socket */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
/* Write the data to the socket */
sent = CMT_WriteThisMany(control, sock, (void*)buf, len);
if (sent != len) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_HASH_End(PCMT_CONTROL control, CMUint32 connectionID,
unsigned char * result, CMUint32 * resultlen,
CMUint32 maxLen)
{
CMTItem hash = { 0, NULL, 0 };
/* Do some parameter checking */
if (!control || !result || !resultlen) {
goto loser;
}
/* Close the connection */
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
/* Get the context info */
if (CMT_GetStringAttribute(control, connectionID, SSM_FID_HASHCONN_RESULT,
&hash) == CMTFailure) {
goto loser;
}
if (!hash.data) {
goto loser;
}
*resultlen = hash.len;
if (hash.len > maxLen) {
memcpy(result, hash.data, maxLen);
} else {
memcpy(result, hash.data, hash.len);
}
if (hash.data) {
free(hash.data);
}
return CMTSuccess;
loser:
if (hash.data) {
free(hash.data);
}
return CMTFailure;
}

View File

@@ -0,0 +1,56 @@
/*
* 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):
*
* 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 __CMTIMPL_H_
#define __CMTIMPL_H_
typedef unsigned long CMT_HANDLE;
struct _CMTControl {
CMT_HANDLE channelID;
int socketID;
CMTStatus (* cmtEventCallback)(struct _CMTControl * control,
CMTItem * event, void * arg);
void * cmtEventCallbackArg;
struct _CMTData * cmtDataConnection;
} _CMTControl;
struct _CMTData {
CMT_HANDLE channelID;
int socketID;
struct _CMTData * next;
struct _CMTData * previous;
};
#endif /*__CMTIMPL_H_*/

View File

@@ -0,0 +1,484 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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.
*/
#ifdef XP_UNIX
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <netinet/tcp.h>
#else
#ifdef XP_MAC
#include <Events.h> // for WaitNextEvent
#else /* Windows */
#include <windows.h>
#include <winsock.h>
#include <direct.h>
#include <sys/stat.h>
#endif
#endif
#include "messages.h"
#include "cmtcmn.h"
#include "cmtutils.h"
#include <string.h>
#ifdef XP_UNIX
#define DIRECTORY_SEPARATOR '/'
#elif defined WIN32
#define DIRECTORY_SEPARATOR '\\'
#elif defined XP_MAC
#define DIRECTORY_SEPARATOR ':'
#endif
/* Local defines */
#define CARTMAN_PORT 11111
#define MAX_PATH_LEN 256
/* write to the cmnav.log */
#if 0
#define LOG(x); do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, x); fclose(f); } } while(0);
#define LOG_S(x); do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, "%s", x); fclose(f); } } while(0);
#define ASSERT(x); if (!(x)) { LOG("ASSERT:"); LOG(#x); LOG("\n"); exit(-1); }
#else
#define LOG(x); ;
#define LOG_S(x); ;
#define ASSERT(x); ;
#endif
static char*
getCurrWorkDir(char *buf, int maxLen)
{
#if defined WIN32
return _getcwd(buf, maxLen);
#elif defined XP_UNIX
return getcwd(buf, maxLen);
#else
return NULL;
#endif
}
static void
setWorkingDir(char *path)
{
#if defined WIN32
_chdir(path);
#elif defined XP_UNIX
chdir(path);
#else
return;
#endif
}
static CMTStatus
launch_psm(char *executable)
{
char command[MAX_PATH_LEN];
#ifdef WIN32
STARTUPINFO sui;
PROCESS_INFORMATION pi;
UNALIGNED long *posfhnd;
int i;
char *posfile;
sprintf(command,"%s > psmlog", executable);
ZeroMemory( &sui, sizeof(sui) );
sui.cb = sizeof(sui);
sui.cbReserved2 = (WORD)(sizeof( int ) + (3 * (sizeof( char ) +
sizeof( long ))));
sui.lpReserved2 = calloc( sui.cbReserved2, 1 );
*((UNALIGNED int *)(sui.lpReserved2)) = 3;
posfile = (char *)(sui.lpReserved2 + sizeof( int ));
posfhnd = (UNALIGNED long *)(sui.lpReserved2 + sizeof( int ) +
(3 * sizeof( char )));
for ( i = 0, posfile = (char *)(sui.lpReserved2 + sizeof( int )),
posfhnd = (UNALIGNED long *)(sui.lpReserved2 + sizeof( int ) + (3 * sizeof( char ))) ;
i < 3 ; i++, posfile++, posfhnd++ ) {
*posfile = 0;
*posfhnd = (long)INVALID_HANDLE_VALUE;
}
/* Now, fire up PSM */
if (!CreateProcess(NULL, command, NULL, NULL, TRUE, DETACHED_PROCESS,
NULL, NULL, &sui, &pi)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
#elif defined XP_UNIX
sprintf(command,"./%s &", executable);
if (system(command) == -1) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
#else
return CMTFailure;
#endif
}
PCMT_CONTROL CMT_EstablishControlConnection(char *inPath,
CMT_SocketFuncs *sockFuncs,
CMT_MUTEX *mutex)
{
PCMT_CONTROL control;
char *executable;
char *newWorkingDir;
char oldWorkingDir[MAX_PATH_LEN];
int i;
char *path = NULL;
size_t stringLen;
/* On the Mac, we do special magic in the Seamonkey PSM component, so
if PSM isn't launched by the time we reach this point, we're not doing well. */
#ifndef XP_MAC
struct stat stbuf;
/*
* Create our own copy of path.
* I'd like to do a straight strdup here, but that caused problems
* for https.
*/
stringLen = strlen(inPath);
path = (char*) malloc(stringLen+1);
memcpy(path, inPath, stringLen);
path[stringLen] = '\0';
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL) {
return control;
}
/*
* We have to try to launch it now, so it better be a valid
* path.
*/
if (stat(path, &stbuf) == -1) {
goto loser;
}
/*
* Now we have to parse the path and launch the psm server.
*/
executable = strrchr(path, DIRECTORY_SEPARATOR);
if (executable != NULL) {
*executable = '\0';
executable ++;
newWorkingDir = path;
} else {
executable = path;
newWorkingDir = NULL;
}
if (getCurrWorkDir(oldWorkingDir, MAX_PATH_LEN) == NULL) {
goto loser;
}
setWorkingDir(newWorkingDir);
if (launch_psm(executable) != CMTSuccess) {
goto loser;
}
setWorkingDir(oldWorkingDir);
#endif
/*
* Now try to connect to the psm server. We will try to connect
* a maximum of 30 times and then give up.
*/
#ifdef WIN32
for (i=0; i<30; i++) {
Sleep(1000);
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL) {
break;
}
}
#elif defined XP_UNIX
i = 0;
while (i<1000) {
i += sleep(10);
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL) {
break;
}
}
#elif defined(XP_MAC)
for (i=0; i<30; i++)
{
EventRecord theEvent;
WaitNextEvent(0, &theEvent, 30, NULL);
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL)
break;
}
#else
/*
* Figure out how to sleep for a while first
*/
for (i=0; i<30; i++) {
control = CMT_ControlConnect(mutex, sockFuncs);
if (control!= NULL) {
break;
}
}
#endif
if (control == NULL) {
goto loser;
}
if (path) {
free (path);
}
return control;
loser:
if (control != NULL) {
CMT_CloseControlConnection(control);
}
if (path) {
free(path);
}
return NULL;
}
PCMT_CONTROL CMT_ControlConnect(CMT_MUTEX *mutex, CMT_SocketFuncs *sockFuncs)
{
PCMT_CONTROL control = NULL;
CMTSocket sock=NULL;
#ifdef XP_UNIX
int unixSock = 1;
char path[20];
#else
int unixSock = 0;
char *path=NULL;
#endif
if (sockFuncs == NULL) {
return NULL;
}
#ifdef XP_UNIX
sprintf(path, "/tmp/.nsmc-%d", (int)geteuid());
#endif
sock = sockFuncs->socket(unixSock);
if (sock == NULL) {
LOG("Could not create a socket to connect to Control Connection.\n");
goto loser;
}
/* Connect to the psm process */
if (sockFuncs->connect(sock, CARTMAN_PORT, path)) {
LOG("Could not connect to Cartman\n");
goto loser;
}
#ifdef XP_UNIX
if (sockFuncs->verify(sock) != CMTSuccess) {
goto loser;
}
#endif
LOG("Connected to Cartman\n");
/* fill in the CMTControl struct */
control = (PCMT_CONTROL)calloc(sizeof(CMT_CONTROL), 1);
if (control == NULL ) {
goto loser;
}
control->sock = sock;
if (mutex != NULL) {
control->mutex = (CMT_MUTEX*)calloc(sizeof(CMT_MUTEX),1);
if (control->mutex == NULL) {
goto loser;
}
*control->mutex = *mutex;
}
memcpy(&control->sockFuncs, sockFuncs, sizeof(CMT_SocketFuncs));
control->refCount = 1;
goto done;
loser:
if (control != NULL) {
free(control);
}
if (sock != NULL) {
sockFuncs->close(sock);
}
control = NULL;
done:
return control;
}
CMTStatus CMT_CloseControlConnection(PCMT_CONTROL control)
{
/* XXX Don't know what to do here yet */
if (control != NULL) {
CMInt32 refCount;
CMT_LOCK(control->mutex);
control->refCount--;
refCount = control->refCount;
CMT_UNLOCK(control->mutex);
if (refCount <= 0) {
if (control->mutex != NULL) {
free (control->mutex);
}
control->sockFuncs.close(control->sock);
free(control);
}
}
return CMTSuccess;
}
CMTStatus CMT_Hello(PCMT_CONTROL control, CMUint32 version, char* profile,
char* profileDir)
{
CMTItem message;
PCMT_EVENT eventHandler;
CMBool doesUI;
HelloRequest request;
HelloReply reply;
/* Check the passed parameters */
if (!control) {
return CMTFailure;
}
if (!profile) {
return CMTFailure;
}
if (!profileDir) {
return CMTFailure;
}
/* Create the hello message */
eventHandler = CMT_GetEventHandler(control, SSM_UI_EVENT, 0);
doesUI = (eventHandler == NULL) ? CM_FALSE : CM_TRUE;
/* Setup the request struct */
request.version = version;
request.policy = 0; /* no more policy */
request.doesUI = doesUI;
request.profile = profile;
request.profileDir = profileDir;
message.type = SSM_REQUEST_MESSAGE | SSM_HELLO_MESSAGE;
if (CMT_EncodeMessage(HelloRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_HELLO_MESSAGE)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(HelloReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Successful response */
if (reply.result == 0) {
/* Save the nonce value */
control->sessionID = reply.sessionID;
control->protocolVersion = reply.version;
control->port = reply.httpPort;
control->nonce = reply.nonce;
control->policy = reply.policy;
control->serverStringVersion = reply.stringVersion;
/* XXX Free the messages */
return CMTSuccess;
}
loser:
/* XXX Free the messages */
return CMTFailure;
}
CMTStatus CMT_PassAllPrefs(PCMT_CONTROL control, int num,
CMTSetPrefElement* list)
{
SetPrefListMessage request;
SingleNumMessage reply;
CMTItem message;
if ((control == NULL) || (list == NULL)) {
return CMTFailure;
}
/* pack the request */
request.length = num;
request.list = (SetPrefElement*)list;
if (CMT_EncodeMessage(SetPrefListMessageTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_PREF_ACTION;
/* send the message */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PREF_ACTION)) {
goto loser;
}
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
/* don't really need to check the return value */
return CMTSuccess;
loser:
return CMTFailure;
}
char* CMT_GetServerStringVersion(PCMT_CONTROL control)
{
if (control == NULL) {
return NULL;
}
return control->serverStringVersion;
}

View File

@@ -0,0 +1,556 @@
/*
* 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):
*
* 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 "cmtutils.h"
#include "cmtjs.h"
#include "messages.h"
CMTStatus
CMT_GenerateKeyPair(PCMT_CONTROL control, CMUint32 keyGenContext,
CMUint32 mechType, CMTItem *param, CMUint32 keySize,
CMUint32 *keyPairId)
{
CMTItem message;
CMTStatus rv;
KeyPairGenRequest request = {0, 0, 0, {0, NULL, 0}};
SingleNumMessage reply;
if (!control) {
return CMTFailure;
}
request.keyGenCtxtID = keyGenContext;
request.genMechanism = mechType;
if (param) {
request.params = *param;
}
request.keySize = keySize;
/* Encode the message */
if (CMT_EncodeMessage(KeyPairGenRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_CREATE_KEY_PAIR;
/* Send the message and get the response */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_CREATE_KEY_PAIR)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*keyPairId = reply.value;
return CMTSuccess;
loser:
*keyPairId = 0;
return CMTFailure;
}
CMTStatus
CMT_CreateNewCRMFRequest(PCMT_CONTROL control, CMUint32 keyPairID,
SSMKeyGenType keyGenType, CMUint32 *reqID)
{
CMTItem message;
CMTStatus rv;
SingleNumMessage request;
SingleNumMessage reply;
if (!control) {
return CMTFailure;
}
request.value = keyPairID;
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION |
SSM_CREATE_CRMF_REQ;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_CREATE_CRMF_REQ)) {
goto loser;
}
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*reqID = reply.value;
rv = CMT_SetNumericAttribute(control, *reqID, SSM_FID_CRMFREQ_KEY_TYPE,
keyGenType);
if (rv != CMTSuccess) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_EncodeCRMFRequest(PCMT_CONTROL control, CMUint32 *crmfReqID,
CMUint32 numRequests, char ** der)
{
CMTItem message;
CMTStatus rv;
EncodeCRMFReqRequest request;
SingleItemMessage reply;
if (!control) {
return CMTFailure;
}
request.numRequests = numRequests;
request.reqIDs = (long *) crmfReqID;
/* Encode the request */
if (CMT_EncodeMessage(EncodeCRMFReqRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION | SSM_DER_ENCODE_REQ;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_DER_ENCODE_REQ)) {
goto loser;
}
/* XXX Should this be a string? Decode the message */
if (CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*der = (char *) reply.item.data;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_ProcessCMMFResponse(PCMT_CONTROL control, char *nickname,
char *certRepString, CMBool doBackup,
void *clientContext)
{
CMTItem message;
CMTStatus rv;
CMMFCertResponseRequest request;
if(!control) {
return CMTFailure;
}
request.nickname = nickname;
request.base64Der = certRepString;
request.doBackup = doBackup;
request.clientContext = CMT_CopyPtrToItem(clientContext);
/* Encode the request */
if (CMT_EncodeMessage(CMMFCertResponseRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION | SSM_PROCESS_CMMF_RESP;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_PROCESS_CMMF_RESP)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_CreateResource(PCMT_CONTROL control, SSMResourceType resType,
CMTItem *params, CMUint32 *rsrcId, CMUint32 *errorCode)
{
CMTItem message;
CMTStatus rv;
CreateResourceRequest request = {0, {0, NULL, 0}};
CreateResourceReply reply;
request.type = resType;
if (params) {
request.params = *params;
}
/* Encode the request */
if (CMT_EncodeMessage(CreateResourceRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_CREATE_RESOURCE;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_CREATE_RESOURCE)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(CreateResourceReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*rsrcId = reply.resID;
*errorCode = reply.result;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_SignText(PCMT_CONTROL control, CMUint32 resID, char* stringToSign, char* hostName, char* caOption, CMInt32 numCAs, char** caNames)
{
CMTItem message;
SignTextRequest request;
/* So some basic parameter checking */
if (!control || !stringToSign) {
goto loser;
}
/* Set up the request */
request.resID = resID;
request.stringToSign = stringToSign;
request.hostName = hostName;
request.caOption = caOption;
request.numCAs = numCAs;
request.caNames = caNames;
/* Encode the message */
if (CMT_EncodeMessage(SignTextRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_FORMSIGN_ACTION | SSM_SIGN_TEXT;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_FORMSIGN_ACTION | SSM_SIGN_TEXT)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_ProcessChallengeResponse(PCMT_CONTROL control, char *challengeString,
char **responseString)
{
CMTItem message;
CMTStatus rv;
SingleStringMessage request;
SingleStringMessage reply;
/* Set the request */
request.string = challengeString;
/* Encode the request */
if (CMT_EncodeMessage(SingleStringMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION | SSM_CHALLENGE;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_CHALLENGE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleStringMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*responseString = reply.string;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_FinishGeneratingKeys(PCMT_CONTROL control, CMUint32 keyGenContext)
{
CMTItem message;
CMTStatus rv;
SingleNumMessage request;
/* Set up the request */
request.value = keyGenContext;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_FINISH_KEY_GEN;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the reply */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_FINISH_KEY_GEN)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_GetLocalizedString(PCMT_CONTROL control,
SSMLocalizedString whichString,
char **localizedString)
{
CMTItem message;
CMTStatus rv;
SingleNumMessage request;
GetLocalizedTextReply reply;
/* Set up the request */
request.value = whichString;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_LOCALIZED_TEXT;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_LOCALIZED_TEXT)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(GetLocalizedTextReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
if (reply.whichString != whichString) {
goto loser;
}
*localizedString = reply.localizedString;
return CMTSuccess;
loser:
*localizedString = NULL;
return rv;
}
CMTStatus
CMT_AddNewModule(PCMT_CONTROL control,
char *moduleName,
char *libraryPath,
unsigned long pubMechFlags,
unsigned long pubCipherFlags)
{
CMTItem message;
CMTStatus rv;
AddNewSecurityModuleRequest request;
SingleNumMessage reply;
/* Set up the request */
request.moduleName = moduleName;
request.libraryPath = libraryPath;
request.pubMechFlags = pubMechFlags;
request.pubCipherFlags = pubCipherFlags;
/* Encode the request */
if (CMT_EncodeMessage(AddNewSecurityModuleRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_ADD_NEW_MODULE;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_ADD_NEW_MODULE)) {
goto loser;
}
/* Decode the response */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
return (CMTStatus) reply.value;
loser:
return CMTFailure;
}
CMTStatus
CMT_DeleteModule(PCMT_CONTROL control,
char *moduleName,
int *moduleType)
{
CMTItem message;
CMTStatus rv;
SingleStringMessage request;
SingleNumMessage reply;
/* Set up the request */
request.string = moduleName;
/* Encode the request */
if (CMT_EncodeMessage(SingleStringMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_DEL_MODULE;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_DEL_MODULE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*moduleType = reply.value;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_LogoutAllTokens(PCMT_CONTROL control)
{
CMTItem message;
CMTStatus rv;
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_LOGOUT_ALL;
message.data = NULL;
message.len = 0;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
return rv;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION |
SSM_LOGOUT_ALL)) {
return CMTFailure;
}
return CMTSuccess;
}
CMTStatus CMT_GetSSLCapabilities(PCMT_CONTROL control, CMInt32 *capabilites)
{
SingleNumMessage reply;
CMTItem message;
CMTStatus rv;
message.type = (SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION |
SSM_ENABLED_CIPHERS);
message.data = NULL;
message.len = 0;
rv = CMT_SendMessage(control, &message);
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION |
SSM_ENABLED_CIPHERS)) {
goto loser;
}
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply,
&message) != CMTSuccess) {
goto loser;
}
*capabilites = reply.value;
return CMTSuccess;
loser:
return CMTFailure;
}

View File

@@ -0,0 +1,555 @@
/*
* 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):
*
* 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 _CMTJS_H_
#define _CMTJS_H_
#include "cmtcmn.h"
#include "ssmdefs.h"
#include "rsrcids.h"
/*
* Define some constants.
*/
/*
* These defines are used in conjuction with the function
* CMT_AddNewModule.
*/
#define PUBLIC_MECH_RSA_FLAG 0x00000001ul
#define PUBLIC_MECH_DSA_FLAG 0x00000002ul
#define PUBLIC_MECH_RC2_FLAG 0x00000004ul
#define PUBLIC_MECH_RC4_FLAG 0x00000008ul
#define PUBLIC_MECH_DES_FLAG 0x00000010ul
#define PUBLIC_MECH_DH_FLAG 0x00000020ul
#define PUBLIC_MECH_FORTEZZA_FLAG 0x00000040ul
#define PUBLIC_MECH_RC5_FLAG 0x00000080ul
#define PUBLIC_MECH_SHA1_FLAG 0x00000100ul
#define PUBLIC_MECH_MD5_FLAG 0x00000200ul
#define PUBLIC_MECH_MD2_FLAG 0x00000400ul
#define PUBLIC_MECH_RANDOM_FLAG 0x08000000ul
#define PUBLIC_MECH_FRIENDLY_FLAG 0x10000000ul
#define PUBLIC_OWN_PW_DEFAULTS 0X20000000ul
#define PUBLIC_DISABLE_FLAG 0x40000000ul
/*
* This is the lone supported constant for the Cipher flag
* for CMT_AddNewModule
*/
#define PUBLIC_CIPHER_FORTEZZA_FLAG 0x00000001ul
CMT_BEGIN_EXTERN_C
/*
* FUNCTION: CMT_GenerateKeyPair
* -----------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* keyGenContext
* The Resource ID of a key gen context to use for creating the
* key pair.
* mechType
* A PKCS11 mechanism used to generate the key pair. Valid values are:
* CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000
* CKM_DSA_KEY_PAIR_GEN 0x00000010
* The definition of these values can be found at
* http://www.rsa.com/rsalabs/pubs/pkcs11.html
* The psm module currently supports v2.01 of PKCS11
* params
* This parameter will be used to pass parameters to the Key Pair
* generation process. Currently this feature is not supported, so
* pass in NULL for this parameter.
* keySize
* The size (in bits) of the key to generate.
* keyPairId
* A pointer to pre-allocated memory where the function can place
* the value of the resource ID of the key pair that gets created.
*
* NOTES:
* This function will send a message to the psm server requesting that
* a public/private key pair be generated. The key gen context will queue
* the request. You can send as many key gen requests as you want with a
* given key gen context. After sending all the key gen requests, the user
* must call CMT_FinishGeneratingKeys so that the key gen context actually
* generates the keys.
*
* RETURN:
* A return value of CMTSuccess indicates the request for key generation
* was queued successfully and the corresponding resource ID can be found
* at *keyPairId. Any other return value indicates an error and the value
* at *keyPairId should be ignored.
*/
CMTStatus
CMT_GenerateKeyPair(PCMT_CONTROL control, CMUint32 keyGenContext,
CMUint32 mechType, CMTItem *params, CMUint32 keySize,
CMUint32 *keyPairId);
/*
* FUNCTION: CMT_FinishGeneratingKeys
* ----------------------------------
* INPUTS
* control
* The Control Connection that has already established a connection
* with the psm server.
* keyGenContext
* The resource ID of the key gen context which should finish
* generating its key pairs.
* NOTES
* This function will send a message to the psm server notifying the key
* gen context with the resource ID of keyGenContext to finish generating
* all of the key gen requests it has queued up. After each key gen has
* finished, the psm server will send a SSM_TASK_COMPLETED_EVENT. So in order
* to detect when all of the key gens are done, the user should register
* an event handler. See comments for CMT_RegisterEventHandler for information
* on how to successfully register event handler callbacks. You must register
* the event handler with keyGenContext as the target resource ID for this
* to work correctly.
*
* RETURN:
* A return value of CMTSuccess indicates the key gen context has started to
* generate the key pairs in its queue. Any other return value indicates an
* error and the key pairs will not be generated.
*/
CMTStatus
CMT_FinishGeneratingKeys(PCMT_CONTROL control, CMUint32 keyGenContext);
/*
* FUNCTION: CMT_CreateNewCRMFRequest
* ----------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* keyPairID
* The resource ID of the key pair that should be associated with
* the CRMF request created. At the time this function is called,
* key pair should have already been created.
* keyGenType
* An enumeration that explains how the key pair will be used.
* Look at the definition of SSMKeyGenType in ssmdefs.h for valid
* values and their affects on the request.
* reqID
* A pointer to a pre-allocatd chunk of memory where the library
* can place the resource ID of the new CRMF request.
* NOTES:
* This function sends a message to the psm server requesting that a new
* CRMF resource object be created. Each CRMF request must be associated with
* a public/private key pair, that is why the keyPairID parameter exists.
* The keyGenType parameter is used to initialize the request, eg set the
* correct keyUsage extension.
*
* Before encoding a CRMF request, the user will want to set the appropriate
* attributes to build up the request. The supported attributes are:
*
* Attribute Enumeration Attribute Type What value means
* --------------------- -------------- ----------------
* SSM_FID_CRMFREQ_REGTOKEN String The value to encode as
* the registration token
* value for the request.
*
* SSM_FID_CRMFREQ_AUTHENTICATOR String The value to encode as
* authenticator control
* in the request.
*
* SSM_FID_DN String The RFC1485 formatted
* DN to include in the
* CRMF request.
*
* For information on how to properly set the attribute of a resource, refer
* to the comments for the functions CMT_SetNumericAttribute and
* CMT_SetStringAttribute.
*
* RETURN:
* A return value of CMTSuccess indicates a new CRMF resource was created by
* the psm server and has the resource ID placed at *reqID. Any other return
* value indicates an error and the value at *reqID should be ignored.
*/
CMTStatus
CMT_CreateNewCRMFRequest(PCMT_CONTROL control, CMUint32 keyPairID,
SSMKeyGenType keyGenType, CMUint32 *reqID);
/*
* FUNCTION: CMT_EncodeCRMFRequest
* ------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* crmfReqID
* An array of resource ID's for CRMF objects to be encoded.
* numRequests
* The length of the array crmfReqID that is passed in.
* der
* A pointer to a pre-allocated pointer for a char* where the library
* can place the final DER-encoding of the requests.
* NOTES
* This function will send a message to the psm server requesting that
* a number of CRMF requests be encoded into their appropriate DER
* representation. The DER that is sent back will be of the type
* CertReqMessages as define in the internet draft for CRMF. To look at the
* draft, visit the following URL:
* http://search.ietf.org/internet-drafts/internet-draft-ietf-pkix-crmf-01.txt
*
* RETURN:
* A return value of CMTSuccess indicates psm successfully encoded the requests
* and placed the base64 DER encoded request at *der. Any other return value
* indicates an error and the value at *der should be ignored.
*/
CMTStatus
CMT_EncodeCRMFRequest(PCMT_CONTROL control, CMUint32 *crmfReqID,
CMUint32 numRequests, char ** der);
/*
* FUNCTION: CMT_ProcessCMMFResponse
* ---------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* nickname
* The nickname that should be associated with the certificate
* contained in the CMMF Response.
* certRepString
* This is the base 64 encoded CertRepContent that issues a certificate.
* The psm server will decode the base 64 data and then parse the
* CertRepContent.
* doBackup
* A boolean value indicating whether or not psm should initiate the
* process of backing up the newly issued certificate into a PKCS-12
* file.
* clientContext
* Client supplied data pointer that is returned to the client during
* a UI event.
* NOTES:
* This function takes a CertRepContent as defined in the CMMF internet draft
* (http://search.ietf.org/internet-drafts/draft-ietf-pkix-cmmf-02.txt) and
* imports the certificate into the user's database. The certificate will have
* the string value of nickanme as it's nickname when added to the database
* unless another certificate with that same Distinguished Name (DN) already
* exists in the database, in which case the nickname of the certificate that
* already exists will be used. If the value passed in for doBackup is
* non-zero, then the psm server will initiate the process of backing up the
* certificate(s) that were just imported.
*
* RETURN:
* A return value of CMTSuccess indicates the certificate(s) were successfully
* added to the database. Any other return value means the certificate(s) could
* not be successfully added to the database.
*/
CMTStatus
CMT_ProcessCMMFResponse(PCMT_CONTROL control, char *nickname,
char *certRepString, CMBool doBackup,
void *clientContext);
/*
* FUNCTION: CMT_CreateResource
* ----------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* resType
* The enumeration representing the resource type to create.
* params
* A resource dependent binary string that will be sent to the psm
* server. Each resource will expect a binary string it defines.
* rsrcId
* A pointer to a pre-allocated chunk of memory where the library
* can place the resource ID of the newly created resource.
* errorCode
* A pointer to a pre-allocated chunk of memory where the library
* can place the errorCode returned by the psm server after creating
* the resource.
* NOTES:
* This function sends a message to the psm server requesting that a new
* resource be created. The params parameter depends on the type of resource
* being created. Below is a table detailing the format of the params for
* a given resource type. Only the resource types listed below can be created
* by calling this function.
*
* Resource Type constant Value for params
* ------------------------------ ----------------
* SSM_RESTYPE_KEYGEN_CONTEXT NULL
* SSM_RESTYPE_SECADVISOR_CONTEXT NULL
* SSM_RESTYPE_SIGNTEXT NULL
*
* RETURN
* A return value of CMTSuccess means the psm server received the request and
* processed the create resource create. If the value at *errorCode is zero,
* then the value at *rsrcId is the resource ID of the newly created resource.
* Otherwise, creating the new resource failed and *errorCode contains the
* error code returned by the psm server. ???What are the return values and
* what do they mean. Any other return value indicates there was an error
* in the communication with the psm server and the values at *rsrcId and
* *errorCode should be ignored.
*/
CMTStatus
CMT_CreateResource(PCMT_CONTROL control, SSMResourceType resType,
CMTItem *params, CMUint32 *rsrcId, CMUint32 *errorCode);
/*
* FUNCTION: CMT_SignText
* ----------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* resID
* The resource ID of an SSMSignTextResource.
* stringToSign
* The string that the psm server should sign.
* hostName
* The host name of the site that is requesting a string to be
* signed. This is used for displaying the UI that tells the user
* a web site has requested the use sign some text.
* caOption
* If the value is "auto" then psm will select the certificate
* to use for signing automatically.
* If the value is "ask" then psm will display a list of
* certificates for signing.
* numCAs
* The number of CA names included in the array caNames passed in as
* the last parameter to this function.
* caNames
* An array of CA Names to use for filtering the user certs to use
* for signing the text.
* NOTES
* This function will sign the text passed via the parameter stringToSign.
* The function will also cause the psm server to send some UI notifying the
* user that a site has requested the user sign some text. The hostName
* parameter is used in the UI to inform the user which site is requesting
* the signed text. The caOption is used to determine if the psm server
* should automatically select which personal cert to use in signing the
* text. The caNames array is ussed to narrow down the field of personal
* certs to use when signing the text. In other words, only personal certs
* trusted by the CA's passed in will be used.
*
* RETURN
* If the function returns CMTSuccess, that indicates the psm server
* successfully signed the text. The signed text can be retrieved by
* calling CMT_GetStringResource and passing in SSM_FID_SIGNTEXT_RESULT
* as the field ID. Any other return value indicates an error meaning the
* string was not signed successfully.
*/
CMTStatus
CMT_SignText(PCMT_CONTROL control, CMUint32 resID, char* stringToSign,
char* hostName, char *caOption, CMInt32 numCAs, char** caNames);
/*
* FUNCTION: CMT_ProcessChallengeResponse
* --------------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* challengeString
* The base64 encoded Challenge string received as the
* Proof-Of-Possession Challenge in response to CRMF request that
* specified Challenge-Reponse as the method for Proof-Of-Possession.
* responseString
* A pointer to pre-allocated char* where the library can place a
* copy of the bas64 encoded response to the challenge presented.
* NOTES
* This function takes the a challenge--that is encrypted with the public key
* of a certificate we created--and decrypts it with the private key we
* generated. The format of the challenge is as follows:
*
* Challenge ::= SEQUENCE {
* owf AlgorithmIdentifier OPTIONAL,
* -- MUST be present in the first Challenge; MAY be omitted in any
* -- subsequent Challenge in POPODecKeyChallContent (if omitted,
* -- then the owf used in the immediately preceding Challenge is
* -- to be used).
* witness OCTET STRING,
* -- the result of applying the one-way function (owf) to a
* -- randomly-generated INTEGER, A. [Note that a different
* -- INTEGER MUST be used for each Challenge.]
* sender GeneralName,
* -- the name of the sender.
* key OCTET STRING,
* -- the public key used to encrypt the challenge. This will allow
* -- the client to find the appropriate key to do the decryption.
* challenge OCTET STRING
* -- the encryption (under the public key for which the cert.
* -- request is being made) of Rand, where Rand is specified as
* -- Rand ::= SEQUENCE {
* -- int INTEGER,
* -- - the randomly-generated INTEGER A (above)
* -- senderHash OCTET STRING
* -- - the result of applying the one-way function (owf) to
* -- - the sender's general name
* -- }
* -- the size of "int" must be small enough such that "Rand" can be
* -- contained within a single PKCS #1 encryption block.
* }
* This challenge is based on the Challenge initially defined in the CMMF
* internet draft, but differs in that this structure includes the sender
* as part of the challenge along with the public key and includes a has
* of the sender in the encrypted Rand structure. The reason for including
* the key is to facilitate looking up the key that should be used to
* decipher the challenge. Including the hash of the sender in the encrypted
* Rand structure makes the challenge smaller and allows it to fit in
* one RSA block.
*
* The response is of the type POPODecKeyRespContent as defined in the CMMF
* internet draft.
*
* RETURN
* A return value of CMTSuccess indicates psm successfully parsed and processed
* the challenge and created a response. The base64 encoded response to the
* challenge is placed at *responseString. Any other return value indicates
* an error and the value at *responseString should be ignored.
*/
CMTStatus
CMT_ProcessChallengeResponse(PCMT_CONTROL control, char *challengeString,
char **responseString);
/*
* FUNCTION: CMT_GetLocalizedString
* --------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* whichString
* The enumerated value corresponding to the localized string to
* retrieve from the psm server
* localizedString
* A pointer to a pre-allocated char* where the library can place
* copy of the localized string retrieved from the psm server.
* NOTES
* This function retrieves a localized string from the psm server. These
* strings are useful for strings that aren't localized in the client
* making use of the psm server, but need to be displayed by the user. Look
* in protocol.h for the enumerations of the localized strings that can
* be fetched from psm via this method.
*
* RETURN
* A return value of CMTSuccess indicates the localized string was retrieved
* successfully and the localized value is located at *localizedString. Any
* other return value indicates an error and the value at *localizedString
* should be ignored.
*/
CMTStatus
CMT_GetLocalizedString(PCMT_CONTROL control,
SSMLocalizedString whichString,
char **localizedString);
/*
* FUNCTION: CMT_DeleteModule
* --------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* moduleName
* The name of the PKCS11 module to delete.
* moduleType
* A pointer to a pre-allocated integer where the library can place
* a value that tells what the type of module was deleted.
* NOTES
* This function will send a message to the psm server requesting the server
* delete a PKCS-11 module stored in psm's security module database. moduleName
* is the value passed in as moduleName when the module was added to the
* security module database of psm.
* The values that may be returned by psm for moduleType are:
*
* 0 The module was an external module developped by a third party
* that was added to the psm security module.
*
* 1 The module deleted was the internal PKCS-11 module that comes
* built in with the psm server.
*
* 2 The module that was deleted was the FIPS internal module.
*
* RETURN
* A return value of CMTSuccess indicates the security module was successfully
* delete from the psm security module database and the value at *moduleType
* will tell what type of module was deleted.
* Any other return value indicates an error and the value at *moduleType
* should be ignored.
*/
CMTStatus
CMT_DeleteModule(PCMT_CONTROL control,
char *moduleName,
int *moduleType);
/*
* FUNCTION: CMT_AddNewModule
* --------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* moduleName
* The name to be associated with the module once it is added to
* the psm security module database.
* libraryPath
* The path to the library to be loaded. The library should be
* loadable at run-time.
* pubMechFlags
* A bit vector indicating all cryptographic mechanisms that should
* be turned on by default. This module will become the default
* handler for the mechanisms that are set by this bit vector.
* pubCipherFlags
* A bit vector indicating all SSL or S/MIME cipher functions
* supported by the module. Most modules will pas in 0x0 for this
* parameter.
* NOTES:
* This function sends a message to the psm server and requests the .so
* file on UNIX or .dll file on Windows be loaded as a PKCS11 module and
* be stored in the psm security module database. The module will be stored
* with the name moduleName that is passed in and will always expect the
* library to live at the path passed in via the parameter libraryPath.
* The pubMechFlags tell the psm server how this module should be used.
* Valid values are the #define constants defined at the beginning of
* this file.
*
* RETURN
* A return value of CMTSuccess indicates the module was successfully loaded
* and placed in the security module database of psm. Any other return value
* indicates an error and means the module was not loaded successfully and
* not stored in the psm server's security module database.
*/
CMTStatus
CMT_AddNewModule(PCMT_CONTROL control,
char *moduleName,
char *libraryPath,
unsigned long pubMechFlags,
unsigned long pubCipherFlags);
CMT_END_EXTERN_C
#endif /*_CMTJS_H_*/

View File

@@ -0,0 +1,75 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 "cmtmac.h"
#include "macsocket.h"
#include "stdlib.h"
#ifndef XP_MAC
#error Link with the builtin strdup() on your platform.
#endif
static void
my_strcpy(char *dest, const char *source)
{
char *i = dest;
const char *j = source;
while(*j)
*i++ = *j++;
*i = '\0';
}
static int
my_strlen(const char *str)
{
const char *c = str;
int i = 0;
while(*c++ != '\0')
i++;
return i;
}
char * strdup(const char *oldstr)
{
/* used to keep the mac client library from referring to strdup elsewhere */
char *newstr;
newstr = (char *) malloc(my_strlen(oldstr)+1);
if (newstr)
my_strcpy(newstr, oldstr);
return newstr;
}

View File

@@ -0,0 +1,40 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 __CMTMAC_H__
#define __CMTMAC_H__
char * strdup(const char *str);
#endif

View File

@@ -0,0 +1,119 @@
/*
* 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):
*
* 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.
*/
/************************************************************************
* Code to handle password requests from the the PSM module.
*
************************************************************************
*/
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
void CMT_SetAppFreeCallback(PCMT_CONTROL control,
applicationFreeCallback_fn f)
{
control->userFuncs.userFree = f;
}
void CMT_ServicePasswordRequest(PCMT_CONTROL cm_control, CMTItem * requestData)
{
CMTItem response = {0, NULL, 0};
PasswordRequest request;
PasswordReply reply;
void * clientContext;
/********************************************
* What we trying to do here:
* 1) Throw up a dialog box and request a password.
* 2) Create a message and send it to the PSM module.
********************************************
*/
/* Decode the request */
if (CMT_DecodeMessage(PasswordRequestTemplate, &request, requestData) != CMTSuccess) {
goto loser;
}
/* Copy the client context to a pointer */
clientContext = CMT_CopyItemToPtr(request.clientContext);
if (cm_control->userFuncs.promptCallback == NULL) {
goto loser;
}
reply.passwd =
cm_control->userFuncs.promptCallback(cm_control->userFuncs.promptArg,
request.prompt, clientContext, 1);
reply.tokenID = request.tokenKey;
if (!reply.passwd) {
/* the user cancelled the prompt or other errors occurred */
reply.result = -1;
}
else {
/* note that this includes an empty string (zero length password) */
reply.result = 0;
}
/* Encode the reply */
if (CMT_EncodeMessage(PasswordReplyTemplate, &response, &reply) != CMTSuccess) {
goto loser;
}
/* Set the message response type */
response.type = SSM_EVENT_MESSAGE | SSM_AUTH_EVENT;
CMT_TransmitMessage(cm_control, &response);
goto done;
loser:
/* something has gone wrong */
done:
/*clean up anyway */
/* We can't just free up memory allocated by the host
application because the versions of free may not match up.
When you run the plug-in with an optimized older browser,
you'll see tons of Asserts (why they still have asserts in an
optimized build is a different question, but without them
I wouldn't have figured out this problem) about a pointer not
being a valid heap pointer and eventually crash. This was
the offending free line.
So we need to call a function within the browser that
calls the free linked in with it. js_free is
such a function. But this is extremely ugly.
*/
if (reply.passwd)
cm_control->userFuncs.userFree(reply.passwd);
if (request.prompt)
free(request.prompt);
return;
}

View File

@@ -0,0 +1,636 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#else /* Windows */
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
typedef struct _CMTP7Private {
CMTPrivate priv;
CMTP7ContentCallback cb;
void *cb_arg;
} CMTP7Private;
CMTStatus CMT_PKCS7DecoderStart(PCMT_CONTROL control, void* clientContext, CMUint32 * connectionID, CMInt32 * result,
CMTP7ContentCallback cb, void *cb_arg)
{
CMTItem message;
CMTStatus rv;
CMTP7Private *priv=NULL;
SingleItemMessage request;
DataConnectionReply reply;
/* Check passed in parameters */
if (!control) {
goto loser;
}
request.item = CMT_CopyPtrToItem(clientContext);
/* Encode message */
if (CMT_EncodeMessage(SingleItemMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7DECODE_STREAM;
/* Send the message. */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7DECODE_STREAM)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
CMTSocket sock;
priv = (CMTP7Private *)malloc(sizeof(CMTP7Private));
if (priv == NULL)
goto loser;
priv->priv.dest = (CMTReclaimFunc) free;
priv->cb = cb;
priv->cb_arg = cb_arg;
sock = control->sockFuncs.socket(0);
if (sock == NULL) {
goto loser;
}
if (control->sockFuncs.connect(sock, (short)reply.port,
NULL) != CMTSuccess) {
goto loser;
}
if (control->sockFuncs.send(sock, control->nonce.data,
control->nonce.len) != control->nonce.len){
goto loser;
}
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
*connectionID = reply.connID;
rv = CMT_SetPrivate(control, reply.connID, &priv->priv);
if (rv != CMTSuccess)
goto loser;
return CMTSuccess;
}
loser:
if (priv) {
free(priv);
}
*result = reply.result;
return CMTFailure;
}
CMTStatus CMT_PKCS7DecoderUpdate(PCMT_CONTROL control, CMUint32 connectionID, const char * buf, CMUint32 len)
{
CMUint32 sent;
CMTP7Private *priv;
unsigned long nbytes;
char read_buf[128];
CMTSocket sock, ctrlsock, selSock, sockArr[2];
/* Do some parameter checking */
if (!control || !buf) {
goto loser;
}
/* Get the data socket */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
/* Write the data to the socket */
sent = CMT_WriteThisMany(control, sock, (void*)buf, len);
if (sent != len) {
goto loser;
}
ctrlsock = control->sock;
sockArr[0] = ctrlsock;
sockArr[1] = sock;
while ((selSock = control->sockFuncs.select(sockArr,2,1)))
{
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else {
nbytes = control->sockFuncs.recv(sock, read_buf, sizeof(read_buf));
if (nbytes == -1) {
goto loser;
}
if (nbytes == 0) {
break;
}
priv->cb(priv->cb_arg, read_buf, nbytes);
}
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7DecoderFinish(PCMT_CONTROL control, CMUint32 connectionID,
CMUint32 * resourceID)
{
CMTP7Private *priv;
long nbytes;
char buf[128];
CMTSocket sock, ctrlsock, selSock, sockArr[2];
/* Do some parameter checking */
if (!control) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
ctrlsock = control->sock;
/* drain socket before we close it */
control->sockFuncs.shutdown(sock);
sockArr[0] = sock;
sockArr[1] = ctrlsock;
/* Let's see if doing a poll first gets rid of a weird bug where we
* lock up the client.
*/
#ifndef XP_MAC
if (control->sockFuncs.select(sockArr,2,1) != NULL)
#endif
{
while (1) {
selSock = control->sockFuncs.select(sockArr,2,0);
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else if (selSock == sock) {
nbytes = control->sockFuncs.recv(sock, buf, sizeof(buf));
if (nbytes < 0) {
goto loser;
} else if (nbytes == 0) {
break;
}
priv->cb(priv->cb_arg, buf, nbytes);
}
}
}
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
/* Get the PKCS7 content info */
if (CMT_GetRIDAttribute(control, connectionID, SSM_FID_P7CONN_CONTENT_INFO,
resourceID) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
if (control) {
CMT_CloseDataConnection(control, connectionID);
}
return CMTFailure;
}
CMTStatus CMT_PKCS7DestroyContentInfo(PCMT_CONTROL control, CMUint32 resourceID)
{
if (!control) {
goto loser;
}
/* Delete the resource */
if (CMT_DestroyResource(control, resourceID, SSM_FID_P7CONN_CONTENT_INFO) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7VerifyDetachedSignature(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 certUsage, CMUint32 hashAlgID, CMUint32 keepCerts, CMTItem* digest, CMInt32 * result)
{
CMTItem message;
VerifyDetachedSigRequest request;
SingleNumMessage reply;
/* Do some parameter checking */
if (!control || !digest || !result) {
goto loser;
}
/* Set the request */
request.pkcs7ContentID = resourceID;
request.certUsage = certUsage;
request.hashAlgID = hashAlgID;
request.keepCert = (CMBool) keepCerts;
request.hash = *digest;
/* Encode the request */
if (CMT_EncodeMessage(VerifyDetachedSigRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_OBJECT_SIGNING | SSM_VERIFY_DETACHED_SIG;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_OBJECT_SIGNING |SSM_VERIFY_DETACHED_SIG)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*result = reply.value;
return CMTSuccess;
loser:
*result = reply.value;
return CMTFailure;
}
CMTStatus CMT_PKCS7VerifySignature(PCMT_CONTROL control, CMUint32 pubKeyAlgID,
CMTItem *pubKeyParams, CMTItem *signerPubKey,
CMTItem *computedHash, CMTItem *signature,
CMInt32 *result)
{
return CMTFailure;
}
CMTStatus CMT_CreateSigned(PCMT_CONTROL control, CMUint32 scertRID,
CMUint32 ecertRID, CMUint32 dig_alg,
CMTItem *digest, CMUint32 *ciRID, CMInt32 *errCode)
{
CMTItem message;
CreateSignedRequest request;
CreateContentInfoReply reply;
/* Do some parameter checking */
if (!control || !scertRID || !ecertRID || !digest || !ciRID) {
goto loser;
}
/* Set the request */
request.scertRID = scertRID;
request.ecertRID = ecertRID;
request.dig_alg = dig_alg;
request.digest = *digest;
/* Encode the request */
if (CMT_EncodeMessage(CreateSignedRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_SIGNED;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_SIGNED)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(CreateContentInfoReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*ciRID = reply.ciRID;
if (reply.result == 0) {
return CMTSuccess;
}
loser:
if (CMT_DecodeMessage(CreateContentInfoReplyTemplate, &reply, &message) == CMTSuccess) {
*errCode = reply.errorCode;
} else {
*errCode = 0;
}
return CMTFailure;
}
CMTStatus CMT_CreateEncrypted(PCMT_CONTROL control, CMUint32 scertRID,
CMUint32 *rcertRIDs, CMUint32 *ciRID)
{
CMTItem message;
CMInt32 nrcerts;
CreateEncryptedRequest request;
CreateContentInfoReply reply;
/* Do some parameter checking */
if (!control || !scertRID || !rcertRIDs || !ciRID) {
goto loser;
}
/* Calculate the number of certs */
for (nrcerts =0; rcertRIDs[nrcerts] != 0; nrcerts++) {
/* Nothing */
;
}
/* Set up the request */
request.scertRID = scertRID;
request.nrcerts = nrcerts;
request.rcertRIDs = (long *) rcertRIDs;
/* Encode the request */
if (CMT_EncodeMessage(CreateEncryptedRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_ENCRYPTED;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message response type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_ENCRYPTED)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(CreateContentInfoReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*ciRID = reply.ciRID;
if (reply.result == 0) {
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7EncoderStart(PCMT_CONTROL control, CMUint32 ciRID,
CMUint32 *connectionID, CMTP7ContentCallback cb,
void *cb_arg)
{
CMTItem message;
CMTStatus rv;
CMTP7Private *priv;
PKCS7DataConnectionRequest request;
DataConnectionReply reply;
/* Check passed in parameters */
if (!control || !ciRID) {
goto loser;
}
/* Set up the request */
request.resID = ciRID;
request.clientContext.len = 0;
request.clientContext.data = NULL;
/* Encode the request */
if (CMT_EncodeMessage(PKCS7DataConnectionRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7ENCODE_STREAM;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7ENCODE_STREAM)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
CMTSocket sock;
priv = (CMTP7Private *)malloc(sizeof(CMTP7Private));
if (priv == NULL)
goto loser;
priv->priv.dest = (CMTReclaimFunc) free;
priv->cb = cb;
priv->cb_arg = cb_arg;
sock = control->sockFuncs.socket(0);
if (sock == NULL) {
goto loser;
}
if (control->sockFuncs.connect(sock, (short)reply.port,
NULL) != CMTSuccess) {
goto loser;
}
if (control->sockFuncs.send(sock, control->nonce.data,
control->nonce.len) != control->nonce.len) {
goto loser;
}
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
*connectionID = reply.connID;
rv = CMT_SetPrivate(control, reply.connID, &priv->priv);
if (rv != CMTSuccess)
goto loser;
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7EncoderUpdate(PCMT_CONTROL control, CMUint32 connectionID,
const char *buf, CMUint32 len)
{
CMUint32 sent;
CMTP7Private *priv;
unsigned long nbytes;
char read_buf[128];
CMTSocket sock, ctrlsock, sockArr[2], selSock;
/* Do some parameter checking */
if (!control || !connectionID || !buf) {
goto loser;
}
/* Get the data socket */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
/* Write the data to the socket */
sent = CMT_WriteThisMany(control, sock, (void*)buf, len);
if (sent != len) {
goto loser;
}
ctrlsock = control->sock;
sockArr[0] = ctrlsock;
sockArr[1] = sock;
while ((selSock = control->sockFuncs.select(sockArr, 2, 1)) != NULL)
{
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else {
nbytes = control->sockFuncs.recv(sock, read_buf, sizeof(read_buf));
if (nbytes == -1) {
goto loser;
} else if (nbytes == 0) {
break;
} else {
priv->cb(priv->cb_arg, read_buf, nbytes);
}
}
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7EncoderFinish(PCMT_CONTROL control, CMUint32 connectionID)
{
CMTP7Private *priv;
unsigned long nbytes;
char buf[128];
CMTSocket sock, ctrlsock, sockArr[2], selSock;
/* Do some parameter checking */
if (!control) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
ctrlsock = control->sock;
sockArr[0] = ctrlsock;
sockArr[1] = sock;
control->sockFuncs.shutdown(sock);
while (1) {
selSock = control->sockFuncs.select(sockArr, 2, 0);
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else if (selSock == sock) {
nbytes = control->sockFuncs.recv(sock, buf, sizeof(buf));
if (nbytes < 0) {
goto loser;
} else if (nbytes == 0) {
break;
} else {
priv->cb(priv->cb_arg, buf, nbytes);
}
}
}
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
if (control) {
CMT_CloseDataConnection(control, connectionID);
}
return CMTFailure;
}

View File

@@ -0,0 +1,479 @@
/* -*- mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#else
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include <string.h>
CMTStatus CMT_GetNumericAttribute(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 fieldID, CMInt32 *value)
{
CMTItem message;
GetAttribRequest request;
GetAttribReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.fieldID = fieldID;
/* Encode the request */
if (CMT_EncodeMessage(GetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(GetAttribReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*value = reply.value.u.numeric;
/* Success */
if (reply.result == 0) {
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_SetNumericAttribute(PCMT_CONTROL control, CMUint32 resourceID,
CMUint32 fieldID, CMInt32 value)
{
CMTItem message;
SetAttribRequest request;
if (!control) {
goto loser;
}
/* Set the request */
request.resID = resourceID;
request.fieldID = fieldID;
request.value.type = SSM_NUMERIC_ATTRIBUTE;
request.value.u.numeric = value;
/* Encode the message */
if (CMT_EncodeMessage(SetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE;
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_PadStringValue(CMTItem *dest, CMTItem src)
{
dest->data = NewArray(unsigned char, src.len+1);
if (dest->data == NULL) {
return CMTFailure;
}
memcpy(dest->data, src.data, src.len);
dest->data[src.len] = '\0';
dest->len = src.len;
free(src.data);
return CMTSuccess;
}
CMTStatus CMT_GetStringAttribute(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 fieldID, CMTItem *value)
{
CMTItem message;
GetAttribRequest request;
GetAttribReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.fieldID = fieldID;
/* Encode the request */
if (CMT_EncodeMessage(GetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_STRING_ATTRIBUTE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_STRING_ATTRIBUTE)) {
goto loser;
}
/* Decode the response */
if (CMT_DecodeMessage(GetAttribReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
return CMT_PadStringValue(value, reply.value.u.string);
}
loser:
return CMTFailure;
}
CMTStatus
CMT_SetStringAttribute(PCMT_CONTROL control, CMUint32 resourceID,
CMUint32 fieldID, CMTItem *value)
{
CMTItem message;
SetAttribRequest request;
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.fieldID = fieldID;
request.value.type = SSM_STRING_ATTRIBUTE;
request.value.u.string = *value;
/* Encode the request */
if (CMT_EncodeMessage(SetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_STRING_ATTRIBUTE;
/* Send the message */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
/* Validate the message request type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_STRING_ATTRIBUTE)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_DuplicateResource(PCMT_CONTROL control, CMUint32 resourceID,
CMUint32 *newResID)
{
CMTItem message;
SingleNumMessage request;
DupResourceReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.value = resourceID;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_DUPLICATE_RESOURCE;
/* Send the mesage */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_DUPLICATE_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DupResourceReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*newResID = reply.resID;
return CMTSuccess;
}
loser:
*newResID = 0;
return CMTFailure;
}
CMTStatus CMT_DestroyResource(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 resourceType)
{
CMTItem message;
DestroyResourceRequest request;
SingleNumMessage reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.resType = resourceType;
/* Encode the message */
if (CMT_EncodeMessage(DestroyResourceRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_DESTROY_RESOURCE;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_DESTROY_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.value == 0) {
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_PickleResource(PCMT_CONTROL control, CMUint32 resourceID, CMTItem * pickledResource)
{
CMTItem message;
SingleNumMessage request;
PickleResourceReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.value = resourceID;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_PICKLE_RESOURCE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_PICKLE_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(PickleResourceReplyTemplate, &reply,&message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*pickledResource = reply.blob;
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_UnpickleResource(PCMT_CONTROL control, CMUint32 resourceType, CMTItem pickledResource, CMUint32 * resourceID)
{
CMTItem message;
UnpickleResourceRequest request;
UnpickleResourceReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resourceType = resourceType;
request.resourceData = pickledResource;
/* Encode the request */
if (CMT_EncodeMessage(UnpickleResourceRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_UNPICKLE_RESOURCE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_UNPICKLE_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(UnpickleResourceReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*resourceID = reply.resID;
return CMTSuccess;
}
loser:
*resourceID = 0;
return CMTFailure;
}
CMTStatus CMT_GetRIDAttribute(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 fieldID, CMUint32 *value)
{
CMTItem message;
GetAttribRequest request;
GetAttribReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set the request */
request.resID = resourceID;
request.fieldID = fieldID;
/* Encode the message */
if (CMT_EncodeMessage(GetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_RID_ATTRIBUTE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message response type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_RID_ATTRIBUTE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(GetAttribReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*value = reply.value.u.rid;
return CMTSuccess;
}
loser:
return CMTFailure;
}

View File

@@ -0,0 +1,270 @@
/*
* 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):
*
* 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.
*/
/*
cmtrng.c -- Support for PSM random number generator and the seeding
thereof with data from the client.
Created by mwelch 1999 Oct 21
*/
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
#include <string.h>
CMTStatus
CMT_EnsureInitializedRNGBuf(PCMT_CONTROL control)
{
if (control->rng.outBuf == NULL)
{
control->rng.outBuf = (char *) calloc(RNG_OUT_BUFFER_LEN, sizeof(char));
if (control->rng.outBuf == NULL)
goto loser;
control->rng.validOutBytes = 0;
control->rng.out_cur = control->rng.outBuf;
control->rng.out_end = control->rng.out_cur + RNG_OUT_BUFFER_LEN;
control->rng.inBuf = (char *) calloc(RNG_IN_BUFFER_LEN, sizeof(char));
if (control->rng.outBuf == NULL)
goto loser;
}
return CMTSuccess;
loser:
if (control->rng.outBuf != NULL)
{
free(control->rng.outBuf);
control->rng.outBuf = NULL;
}
if (control->rng.inBuf != NULL)
{
free(control->rng.inBuf);
control->rng.inBuf = NULL;
}
return CMTFailure;
}
size_t
CMT_RequestPSMRandomData(PCMT_CONTROL control,
void *buf, CMUint32 maxbytes)
{
SingleNumMessage req;
SingleItemMessage reply;
CMTItem message;
size_t rv = 0;
/* Parameter checking */
if (!control || !buf || (maxbytes == 0))
goto loser;
/* Initialization. */
memset(&reply, 0, sizeof(SingleItemMessage));
/* Ask PSM for the data. */
req.value = maxbytes;
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &req) != CMTSuccess)
goto loser;
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_MISC_ACTION | SSM_MISC_GET_RNG_DATA;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure)
goto loser;
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_MISC_ACTION | SSM_MISC_GET_RNG_DATA))
goto loser;
/* Decode message */
if (CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message) != CMTSuccess)
goto loser;
/* Success - fill the return buf with what we got */
if (reply.item.len > maxbytes)
reply.item.len = maxbytes;
memcpy(buf, reply.item.data, reply.item.len);
rv = reply.item.len;
loser:
if (reply.item.data)
free(reply.item.data);
if (message.data)
free(message.data);
return rv;
}
size_t
CMT_GenerateRandomBytes(PCMT_CONTROL control,
void *buf, CMUint32 maxbytes)
{
CMUint32 remaining = maxbytes;
CMT_RNGState *rng = &(control->rng);
char *walk = (char *) buf;
/* Is there already enough in the incoming cache? */
while(remaining > rng->validInBytes)
{
/* Get what we have on hand. */
memcpy(walk, rng->in_cur, rng->validInBytes);
walk += rng->validInBytes;
remaining -= rng->validInBytes;
/* Request a buffer from PSM. */
rng->validInBytes = CMT_RequestPSMRandomData(control,
rng->inBuf,
RNG_IN_BUFFER_LEN);
if (rng->validInBytes == 0)
return (maxbytes - remaining); /* call failed */
rng->in_cur = rng->inBuf;
}
if (remaining > 0)
{
memcpy(walk, rng->in_cur, remaining);
rng->in_cur += remaining;
rng->validInBytes -= remaining;
}
return maxbytes;
}
void
cmt_rng_xor(void *dstBuf, void *srcBuf, int len)
{
unsigned char *s = (unsigned char*) srcBuf;
unsigned char *d = (unsigned char*) dstBuf;
unsigned char tmp;
int i;
for(i=0; i<len; i++, s++, d++)
{
tmp = *d;
/* I wish C had circular shift operators. So do others on the team. */
tmp = ((tmp << 1) | (tmp >> 7));
*d = tmp ^ *s;
}
}
CMTStatus
CMT_RandomUpdate(PCMT_CONTROL control, void *data, size_t numbytes)
{
size_t dataLeft = numbytes, cacheLeft;
char *walk = (char *) data;
if (CMT_EnsureInitializedRNGBuf(control) != CMTSuccess)
goto loser;
/* If we have more than what the buffer can handle, wrap around. */
cacheLeft = (control->rng.out_end - control->rng.out_cur);
while (dataLeft >= cacheLeft)
{
cmt_rng_xor(control->rng.out_cur, walk, cacheLeft);
walk += cacheLeft;
dataLeft -= cacheLeft;
control->rng.out_cur = control->rng.outBuf;
/* Max out used space */
control->rng.validOutBytes = cacheLeft = RNG_OUT_BUFFER_LEN;
}
/*
We now have less seed data available than we do space in the buf.
Write what we have and update validOutBytes if we're not looping already.
*/
cmt_rng_xor(control->rng.out_cur, walk, dataLeft);
control->rng.out_cur += dataLeft;
if (control->rng.validOutBytes < RNG_OUT_BUFFER_LEN)
control->rng.validOutBytes += dataLeft;
return CMTSuccess;
loser:
return CMTFailure;
}
size_t
CMT_GetNoise(PCMT_CONTROL control, void *buf, CMUint32 maxbytes)
{
/* ### mwelch - GetNoise and GenerateRandomBytes can be the
same function now, because presumably the RNG is being
seeded with environmental noise on the PSM end before we
make any of these requests */
return CMT_GenerateRandomBytes(control, buf, maxbytes);
}
CMTStatus
CMT_FlushPendingRandomData(PCMT_CONTROL control)
{
CMTItem message;
memset(&message, 0, sizeof(CMTItem));
if (CMT_EnsureInitializedRNGBuf(control) != CMTSuccess)
return CMTFailure; /* couldn't initialize RNG buffer */
if (control->rng.validOutBytes == 0)
return CMTSuccess; /* no random data available == we're flushed */
/* We have random data available. Send this to PSM.
We're sending an event, so no reply is needed. */
message.type = SSM_EVENT_MESSAGE
| SSM_MISC_ACTION
| SSM_MISC_PUT_RNG_DATA;
message.len = control->rng.validOutBytes;
message.data = (unsigned char *) calloc(message.len, sizeof(char));
if (!message.data)
goto loser;
memcpy(message.data, control->rng.outBuf, message.len);
if (CMT_TransmitMessage(control, &message) == CMTFailure)
goto loser;
/* Clear the RNG ring buffer, we've used that data */
control->rng.out_cur = control->rng.outBuf;
control->rng.validOutBytes = 0;
/* zero the buffer, because we XOR in new data */
memset(control->rng.outBuf, 0, RNG_OUT_BUFFER_LEN);
goto done;
loser:
if (message.data)
free(message.data);
return CMTFailure;
done:
return CMTSuccess;
}

View File

@@ -0,0 +1,237 @@
/*
* 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):
*
* 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.
*/
/*
cmtsdr.c -- Support for the Secret Decoder Ring, which provides
encryption and decryption using stored keys.
Created by thayes 18 April 2000
*/
#include "stddef.h"
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "protocolshr.h"
#include "rsrcids.h"
#include <string.h>
#undef PROCESS_LOCALLY
/* Encryption result - contains the key id and the resulting data */
/* An empty key id indicates that NO encryption was performed */
typedef struct EncryptionResult
{
CMTItem keyid;
CMTItem data;
} EncryptionResult;
/* Constants for testing */
static const char *kPrefix = "Encrypted:";
static CMTItem
CMT_CopyDataToItem(const unsigned char *data, CMUint32 len)
{
CMTItem item;
item.data = (unsigned char*) calloc(len, 1);
item.len = len;
memcpy(item.data, data, len);
return item;
}
static CMTStatus
tmp_SendMessage(PCMT_CONTROL control, CMTItem *message)
{
#ifndef PROCESS_LOCALLY
return CMT_SendMessage(control, message);
#else
if (message->type == SSM_SDR_ENCRYPT_REQUEST)
return CMT_DoEncryptionRequest(message);
else if (message->type == SSM_SDR_DECRYPT_REQUEST)
return CMT_DoDecryptionRequest(message);
return CMTFailure;
#endif
}
/* End test code */
CMTStatus
CMT_SDREncrypt(PCMT_CONTROL control, void *ctx,
const unsigned char *key, CMUint32 keyLen,
const unsigned char *data, CMUint32 dataLen,
unsigned char **result, CMUint32 *resultLen)
{
CMTStatus rv = CMTSuccess;
CMTItem message;
EncryptRequestMessage request;
SingleItemMessage reply;
/* Fill in the request */
request.keyid = CMT_CopyDataToItem(key, keyLen);
request.data = CMT_CopyDataToItem(data, dataLen);
request.ctx = CMT_CopyPtrToItem(ctx);
reply.item.data = 0;
reply.item.len = 0;
message.data = 0;
message.len = 0;
/* Encode */
rv = CMT_EncodeMessage(EncryptRequestTemplate, &message, &request);
if (rv != CMTSuccess) {
goto loser;
}
message.type = SSM_SDR_ENCRYPT_REQUEST;
/* Send */
/* if (CMT_SendMessage(control, &message) != CMTSuccess) goto loser; */
rv = tmp_SendMessage(control, &message);
if (rv != CMTSuccess) goto loser;
if (message.type != SSM_SDR_ENCRYPT_REPLY) { rv = CMTFailure; goto loser; }
rv = CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message);
if (rv != CMTSuccess)
goto loser;
*result = reply.item.data;
*resultLen = reply.item.len;
reply.item.data = 0;
loser:
if (message.data) free(message.data);
if (request.keyid.data) free(request.keyid.data);
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv; /* need return value */
}
CMTStatus
CMT_SDRDecrypt(PCMT_CONTROL control, void *ctx,
const unsigned char *data, CMUint32 dataLen,
unsigned char **result, CMUint32 *resultLen)
{
CMTStatus rv;
CMTItem message;
DecryptRequestMessage request;
SingleItemMessage reply;
/* Fill in the request */
request.data = CMT_CopyDataToItem(data, dataLen);
request.ctx = CMT_CopyPtrToItem(ctx);
reply.item.data = 0;
reply.item.len = 0;
message.data = 0;
message.len = 0;
/* Encode */
rv = CMT_EncodeMessage(DecryptRequestTemplate, &message, &request);
if (rv != CMTSuccess) {
goto loser;
}
message.type = SSM_SDR_DECRYPT_REQUEST;
/* Send */
/* if (CMT_SendMessage(control, &message) != CMTSuccess) goto loser; */
rv = tmp_SendMessage(control, &message);
if (rv != CMTSuccess) goto loser;
if (message.type != SSM_SDR_DECRYPT_REPLY) { rv = CMTFailure; goto loser; }
rv = CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message);
if (rv != CMTSuccess)
goto loser;
*result = reply.item.data;
*resultLen = reply.item.len;
reply.item.data = 0;
loser:
if (message.data) free(message.data);
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv; /* need return value */
}
CMTStatus
CMT_SDRChangePassword(PCMT_CONTROL control, void *ctx)
{
CMTStatus rv = CMTSuccess;
CMTItem message;
SingleItemMessage request;
SingleNumMessage reply;
/* Fill in the request */
request.item = CMT_CopyPtrToItem(ctx);
message.data = 0;
message.len = 0;
/* Encode */
rv = CMT_EncodeMessage(SingleItemMessageTemplate, &message, &request);
if (rv != CMTSuccess) {
goto loser;
}
message.type = (SSM_REQUEST_MESSAGE|SSM_MISC_ACTION|SSM_MISC_UI|SSM_UI_CHANGE_PASSWORD);
/* Send */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) goto loser;
if (message.type !=
(SSM_REPLY_OK_MESSAGE|SSM_MISC_ACTION|SSM_MISC_UI|SSM_UI_CHANGE_PASSWORD)) {
rv = CMTFailure;
goto loser;
}
rv = CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message);
if (rv != CMTSuccess)
goto loser;
loser:
if (request.item.data) free(request.item.data);
if (message.data) free(message.data);
return rv; /* need return value */
}

View File

@@ -0,0 +1,467 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#else /* windows */
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
CMTStatus CMT_OpenSSLConnection(PCMT_CONTROL control, CMTSocket sock,
SSMSSLConnectionRequestType flags,
CMUint32 port, char * hostIP,
char * hostName, CMBool forceHandshake, void* clientContext)
{
CMTItem message;
SSLDataConnectionRequest request;
DataConnectionReply reply;
CMUint32 sent;
/* Do some parameter checking */
if (!control || !hostIP || !hostName) {
goto loser;
}
request.flags = flags;
request.port = port;
request.hostIP = hostIP;
request.hostName = hostName;
request.forceHandshake = forceHandshake;
request.clientContext = CMT_CopyPtrToItem(clientContext);
/* Encode message */
if (CMT_EncodeMessage(SSLDataConnectionRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_SSL_CONNECTION;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_SSL_CONNECTION)) {
goto loser;
}
/* Decode message */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
sent = CMT_WriteThisMany(control, sock, control->nonce.data,
control->nonce.len);
if (sent != control->nonce.len) {
goto loser;
}
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_GetSSLDataErrorCode(PCMT_CONTROL control, CMTSocket sock,
CMInt32* errorCode)
{
CMUint32 connID;
if (!control || !errorCode) {
goto loser;
}
/* get the data connection */
if (CMT_GetDataConnectionID(control, sock, &connID) != CMTSuccess) {
goto loser;
}
/* get the PR error */
if (CMT_GetNumericAttribute(control, connID, SSM_FID_SSLDATA_ERROR_VALUE,
errorCode) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_ReleaseSSLSocketStatus(PCMT_CONTROL control, CMTSocket sock)
{
CMUint32 connectionID;
if (!control || !sock) {
goto loser;
}
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
if (CMT_SetNumericAttribute(control, connectionID,
SSM_FID_SSLDATA_DISCARD_SOCKET_STATUS,
0) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_GetSSLSocketStatus(PCMT_CONTROL control, CMTSocket sock,
CMTItem* pickledStatus, CMInt32* level)
{
CMUint32 connectionID;
SingleNumMessage request;
CMTItem message;
PickleSecurityStatusReply reply;
if (!control || !pickledStatus || !level) {
goto loser;
}
/* get the data connection */
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
/* set up the request */
request.value = connectionID;
/* encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_CONSERVE_RESOURCE | SSM_PICKLE_SECURITY_STATUS;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_CONSERVE_RESOURCE | SSM_PICKLE_SECURITY_STATUS)) {
goto loser;
}
/* decode the reply */
if (CMT_DecodeMessage(PickleSecurityStatusReplyTemplate, &reply, &message)
!= CMTSuccess) {
goto loser;
}
/* success */
if (reply.result == 0) {
*pickledStatus = reply.blob;
*level = reply.securityLevel;
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_OpenTLSConnection(PCMT_CONTROL control, CMTSocket sock,
CMUint32 port, char* hostIP, char* hostName)
{
TLSDataConnectionRequest request;
CMTItem message;
DataConnectionReply reply;
CMUint32 sent;
/* do some parameter checking */
if (!control || !hostIP || !hostName) {
goto loser;
}
request.port = port;
request.hostIP = hostIP;
request.hostName = hostName;
/* encode the message */
if (CMT_EncodeMessage(TLSDataConnectionRequestTemplate, &message, &request)
!= CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION |
SSM_TLS_CONNECTION;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION |
SSM_TLS_CONNECTION)) {
goto loser;
}
/* decode the message */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
/* success */
if (reply.result == 0) {
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
sent = CMT_WriteThisMany(control, sock, control->nonce.data,
control->nonce.len);
if (sent != control->nonce.len) {
goto loser;
}
/* save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_TLSStepUp(PCMT_CONTROL control, CMTSocket sock,
void* clientContext)
{
TLSStepUpRequest request;
SingleNumMessage reply;
CMTItem message;
CMUint32 connectionID;
/* check arguments */
if (!control || !sock) {
goto loser;
}
/* get the data connection ID */
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
/* set up the request */
request.connID = connectionID;
request.clientContext = CMT_CopyPtrToItem(clientContext);
/* encode the request */
if (CMT_EncodeMessage(TLSStepUpRequestTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_TLS_STEPUP;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_TLS_STEPUP)) {
goto loser;
}
/* decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
return (CMTStatus) reply.value;
loser:
return CMTFailure;
}
CMTStatus CMT_OpenSSLProxyConnection(PCMT_CONTROL control, CMTSocket sock,
CMUint32 port, char* hostIP,
char* hostName)
{
TLSDataConnectionRequest request;
CMTItem message;
DataConnectionReply reply;
CMUint32 sent;
/* do some parameter checking */
if (!control || !hostIP || !hostName) {
goto loser;
}
request.port = port;
request.hostIP = hostIP;
request.hostName = hostName;
/* encode the message */
if (CMT_EncodeMessage(TLSDataConnectionRequestTemplate, &message, &request)
!= CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION |
SSM_PROXY_CONNECTION;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION |
SSM_PROXY_CONNECTION)) {
goto loser;
}
/* decode the message */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
/* success */
if (reply.result == 0) {
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
sent = CMT_WriteThisMany(control, sock, control->nonce.data,
control->nonce.len);
if (sent != control->nonce.len) {
goto loser;
}
/* save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_ProxyStepUp(PCMT_CONTROL control, CMTSocket sock,
void* clientContext, char* remoteUrl)
{
ProxyStepUpRequest request;
SingleNumMessage reply;
CMTItem message;
CMUint32 connectionID;
/* check arguments */
if (!control || !sock || !remoteUrl) {
goto loser;
}
/* get the data connection ID */
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
/* set up the request */
request.connID = connectionID;
request.clientContext = CMT_CopyPtrToItem(clientContext);
request.url = remoteUrl;
/* encode the request */
if (CMT_EncodeMessage(ProxyStepUpRequestTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_PROXY_STEPUP;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_PROXY_STEPUP)) {
goto loser;
}
/* decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
return (CMTStatus) reply.value;
loser:
return CMTFailure;
}

View File

@@ -0,0 +1,636 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#else /* Windows */
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include "cmtcmn.h"
#include "cmtutils.h"
#include "newproto.h"
#include <string.h>
/* Local defines */
#if 0
#define PSM_WAIT_BEFORE_SLEEP (CM_TicksPerSecond() * 60)
#define PSM_SPINTIME PSM_WAIT_BEFORE_SLEEP
#define PSM_KEEP_CONNECTION_ALIVE (PSM_WAIT_BEFORE_SLEEP * 900)
#endif
/* If you want to dump the messages sent between the plug-in and the PSM
* server, then remove the comment for the appropriate define.
*/
#if 0
#define PRINT_SEND_MESSAGES
#define PRINT_RECEIVE_MESSAGES
#endif
#ifdef PRINT_SEND_MESSAGES
#ifndef DEBUG_MESSAGES
#define DEBUG_MESSAGES
#endif /*DEBUG_MESSAGES*/
#endif /*PRINT_SEND_MESSAGES*/
#ifdef PRINT_RECEIVE_MESSAGES
#ifndef DEBUG_MESSAGES
#define DEBUG_MESSAGES
#endif /*DEBUG_MESSAGES*/
#endif /*PRINT_RECEIVE_MESSAGES*/
#ifdef DEBUG_MESSAGES
#define LOG(x) do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, x); fclose(f); } } while(0);
#define LOG_S(x) do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, "%s", x); fclose(f); } } while(0);
#define ASSERT(x) if (!(x)) { LOG("ASSERT:"); LOG(#x); LOG("\n"); exit(-1); }
#else
#define LOG(x)
#define LOG_S(x)
#define ASSERT(x)
#endif
CMUint32
cmt_Strlen(char *str)
{
CMUint32 len = strlen(str);
return sizeof(CMInt32) + (((len + 3)/4)*4);
}
CMUint32
cmt_Bloblen(CMTItem *blob)
{
return sizeof(CMInt32) + (((blob->len +3)/4)*4);
}
char *
cmt_PackString(char *buf, char *str)
{
CMUint32 len = strlen(str);
CMUint32 networkLen = htonl(len);
CMUint32 padlen = ((len + 3)/4)*4;
memcpy(buf, &networkLen, sizeof(CMUint32));
memcpy(buf + sizeof(CMUint32), str, len);
memset(buf + sizeof(CMUint32) + len, 0, padlen - len);
return buf+sizeof(CMUint32)+padlen;
}
char *
cmt_PackBlob(char *buf, CMTItem *blob)
{
CMUint32 len = blob->len;
CMUint32 networkLen = htonl(len);
CMUint32 padlen = (((blob->len + 3)/4)*4);
*((CMUint32*)buf) = networkLen;
memcpy(buf + sizeof(CMUint32), blob->data, len);
memset(buf + sizeof(CMUint32) + len, 0, padlen - len);
return buf + sizeof(CMUint32) + padlen;
}
char *
cmt_UnpackString(char *buf, char **str)
{
char *p = NULL;
CMUint32 len, padlen;
/* Get the string length */
len = ntohl(*(CMUint32*)buf);
/* Get the padded length */
padlen = ((len + 3)/4)*4;
/* Allocate the string and copy the data */
p = (char *) malloc(len + 1);
if (!p) {
goto loser;
}
/* Copy the data and NULL terminate */
memcpy(p, buf+sizeof(CMUint32), len);
p[len] = 0;
*str = p;
return buf+sizeof(CMUint32)+padlen;
loser:
*str = NULL;
if (p) {
free(p);
}
return buf+sizeof(CMUint32)+padlen;
}
char *
cmt_UnpackBlob(char *buf, CMTItem **blob)
{
CMTItem *p = NULL;
CMUint32 len, padlen;
/* Get the blob length */
len = ntohl(*(CMUint32*)buf);
/* Get the padded length */
padlen = ((len + 3)/4)*4;
/* Allocate the CMTItem for the blob */
p = (CMTItem*)malloc(sizeof(CMTItem));
if (!p) {
goto loser;
}
p->len = len;
p->data = (unsigned char *) malloc(len);
if (!p->data) {
goto loser;
}
/* Copy that data across */
memcpy(p->data, buf+sizeof(CMUint32), len);
*blob = p;
return buf+sizeof(CMUint32)+padlen;
loser:
*blob = NULL;
CMT_FreeMessage(p);
return buf+sizeof(CMUint32)+padlen;
}
#ifdef DEBUG_MESSAGES
void prettyPrintMessage(CMTItem *msg)
{
int numLines = ((msg->len+7)/8);
char curBuffer[9], *cursor, string[2], hexVal[8];
char hexArray[25];
int i, j, numToCopy;
/*Try printing out 8 bytes at a time. */
LOG("\n**********************************************************\n");
LOG("About to pretty Print Message\n\n");
curBuffer[9] = '\0';
hexArray[24] = '\0';
hexVal[2] = '\0';
string[1] = '\0';
LOG("Header Info\n");
LOG("Message Type: ");
sprintf(hexArray, "%lx\n", msg->type);
LOG(hexArray);
LOG("Message Length: ");
sprintf (hexArray, "%ld\n\n", msg->len);
LOG(hexArray);
LOG("Body of Message\n");
for (i=0, cursor=msg->data; i<numLines; i++, cursor+=8) {
/* First copy over the buffer to our local array */
numToCopy = ((msg->len - (unsigned int)((unsigned long)cursor-(unsigned long)msg->data)) < 8) ?
msg->len - (unsigned int)((unsigned long)cursor-(unsigned long)msg->data) : 8;
memcpy(curBuffer, cursor, 8);
for (j=0;j<numToCopy;j++) {
string[0] = curBuffer[j];
if (isprint(curBuffer[j])) {
string[0] = curBuffer[j];
} else {
string[0] = ' ';
}
LOG(string);
}
string[0] = ' ';
for (;j<8;j++) {
LOG(string);
}
LOG("\t");
for (j=0; j<numToCopy; j++) {
sprintf (hexVal,"%.2x", 0x0ff & (unsigned short)curBuffer[j]);
LOG(hexVal);
LOG(" ");
}
LOG("\n");
}
LOG("Done Pretty Printing Message\n");
LOG("**********************************************************\n\n");
}
#endif
CMTStatus CMT_SendMessage(PCMT_CONTROL control, CMTItem* message)
{
CMTStatus status;
CMUint32 msgCategory;
CMBool done = CM_FALSE;
#ifdef PRINT_SEND_MESSAGES
LOG("About to print message sent to PSM\n");
prettyPrintMessage(message);
#endif
/* Acquire lock on the control connection */
CMT_LOCK(control->mutex);
/* Try to send pending random data */
if (message->type != (SSM_REQUEST_MESSAGE | SSM_HELLO_MESSAGE))
{
/* If we've already said hello, then flush random data
just before sending the request. */
status = CMT_FlushPendingRandomData(control);
if (status != CMTSuccess)
goto loser;
}
status = CMT_TransmitMessage(control, message);
if (status != CMTSuccess) {
goto loser;
}
/* We have to deal with other types of data on the socket and */
/* handle them accordingly */
while (!done) {
status = CMT_ReceiveMessage(control, message);
if (status != CMTSuccess) {
goto loser;
}
msgCategory = (message->type & SSM_CATEGORY_MASK);
switch (msgCategory) {
case SSM_REPLY_OK_MESSAGE:
done = CM_TRUE;
break;
case SSM_REPLY_ERR_MESSAGE:
done = CM_TRUE;
break;
case SSM_EVENT_MESSAGE:
CMT_DispatchEvent(control, message);
break;
/* XXX FIX THIS!!! For the moment I'm ignoring all other types */
default:
break;
}
}
/* Release the control connection lock */
CMT_UNLOCK(control->mutex);
return CMTSuccess;
loser:
/* Release the control connection lock */
CMT_UNLOCK(control->mutex);
return CMTFailure;
}
CMTStatus CMT_TransmitMessage(PCMT_CONTROL control, CMTItem * message)
{
CMTMessageHeader header;
CMUint32 sent, rv;
/* Set up the message header */
header.type = htonl(message->type);
header.len = htonl(message->len);
/* Send the message header */
sent = CMT_WriteThisMany(control, control->sock,
(void *)&header, sizeof(CMTMessageHeader));
if (sent != sizeof(CMTMessageHeader)) {
goto loser;
}
/* Send the message body */
sent = CMT_WriteThisMany(control, control->sock, (void *)message->data,
message->len);
if (sent != message->len) {
goto loser;
}
/* Free the buffer */
free(message->data);
message->data = NULL;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_ReceiveMessage(PCMT_CONTROL control, CMTItem * response)
{
CMTMessageHeader header;
CMUint32 numread, rv;
/* Get the message header */
numread = CMT_ReadThisMany(control, control->sock,
(void *)&header, sizeof(CMTMessageHeader));
if (numread != sizeof(CMTMessageHeader)) {
goto loser;
}
response->type = ntohl(header.type);
response->len = ntohl(header.len);
response->data = (unsigned char *) malloc(response->len);
if (response->data == NULL) {
goto loser;
}
numread = CMT_ReadThisMany(control, control->sock,
(void *)(response->data), response->len);
if (numread != response->len) {
goto loser;
}
#ifdef PRINT_RECEIVE_MESSAGES
LOG("About to print message received from PSM.\n");
prettyPrintMessage(response);
#endif /*PRINT_RECEIVE_MESSAGES*/
return CMTSuccess;
loser:
if (response->data) {
free(response->data);
}
return CMTFailure;
}
CMUint32 CMT_ReadThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany)
{
CMUint32 total = 0;
while (total < thisMany) {
int got;
got = control->sockFuncs.recv(sock, (void*)((char*)buffer + total),
thisMany-total);
if (got < 0 ) {
break;
}
total += got;
}
return total;
}
CMUint32 CMT_WriteThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany)
{
CMUint32 total = 0;
while (total < thisMany) {
CMInt32 got;
got = control->sockFuncs.send(sock, (void*)((char*)buffer+total),
thisMany-total);
if (got < 0) {
break;
}
total += got;
}
return total;
}
CMTItem* CMT_ConstructMessage(CMUint32 type, CMUint32 length)
{
CMTItem * p;
p = (CMTItem*)malloc(sizeof(CMTItem));
if (!p) {
goto loser;
}
p->type = type;
p->len = length;
p->data = (unsigned char *) malloc(length);
if (!p->data) {
goto loser;
}
return p;
loser:
CMT_FreeMessage(p);
return NULL;
}
void CMT_FreeMessage(CMTItem * p)
{
if (p != NULL) {
if (p->data != NULL) {
free(p->data);
}
free(p);
}
}
CMTStatus CMT_AddDataConnection(PCMT_CONTROL control, CMTSocket sock,
CMUint32 connectionID)
{
PCMT_DATA ptr;
/* This is the first connection */
if (control->cmtDataConnections == NULL) {
control->cmtDataConnections = ptr =
(PCMT_DATA)calloc(sizeof(CMT_DATA), 1);
if (!ptr) {
goto loser;
}
} else {
/* Position at the last entry */
for (ptr = control->cmtDataConnections; (ptr != NULL && ptr->next
!= NULL); ptr = ptr->next);
ptr->next = (PCMT_DATA)calloc(sizeof(CMT_DATA), 1);
if (!ptr->next) {
goto loser;
}
/* Fix up the pointers */
ptr->next->previous = ptr;
ptr = ptr->next;
}
/* Fill in the data */
ptr->sock = sock;
ptr->connectionID = connectionID;
return CMTSuccess;
loser:
return CMTFailure;
}
int
CMT_DestroyDataConnection(PCMT_CONTROL control, CMTSocket sock)
{
PCMT_DATA ptr, pptr = NULL;
int rv=CMTSuccess;
control->sockFuncs.close(sock);
for (ptr = control->cmtDataConnections; ptr != NULL;
pptr = ptr, ptr = ptr->next) {
if (ptr->sock == sock) {
if (pptr == NULL) {
/* node is at head */
control->cmtDataConnections = ptr->next;
if (ptr->priv != NULL)
ptr->priv->dest(ptr->priv);
free(ptr);
return rv;
}
/* node is elsewhere */
pptr->next = ptr->next;
if (ptr->priv != NULL)
ptr->priv->dest(ptr->priv);
free(ptr);
return rv;
}
}
return rv;
}
CMTStatus CMT_CloseDataConnection(PCMT_CONTROL control, CMUint32 connectionID)
{
/* PCMT_DATA ptr, pptr = NULL; */
CMTSocket sock;
/* int rv;*/
/* Get the socket for this connection */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
/* Free data connection associated with this socket */
if (CMT_DestroyDataConnection(control, sock) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_GetDataConnectionID(PCMT_CONTROL control, CMTSocket sock, CMUint32 * connectionID)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->sock == sock) {
*connectionID = ptr->connectionID;
return CMTSuccess;
}
}
return CMTFailure;
}
CMTStatus CMT_GetDataSocket(PCMT_CONTROL control, CMUint32 connectionID, CMTSocket * sock)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->connectionID == connectionID) {
*sock = ptr->sock;
return CMTSuccess;
}
}
return CMTFailure;
}
CMTStatus CMT_SetPrivate(PCMT_CONTROL control, CMUint32 connectionID,
CMTPrivate *cmtpriv)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->connectionID == connectionID) {
ptr->priv = cmtpriv;
return CMTSuccess;
}
}
return CMTFailure;
}
CMTPrivate *CMT_GetPrivate(PCMT_CONTROL control, CMUint32 connectionID)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->connectionID == connectionID) {
return ptr->priv;
}
}
return NULL;
}
void CMT_FreeItem(CMTItem *p)
{
CMT_FreeMessage(p);
}
CMTItem CMT_CopyPtrToItem(void* p)
{
CMTItem value = {0, NULL, 0};
if (!p) {
return value;
}
value.len = sizeof(p);
value.data = (unsigned char *) malloc(value.len);
memcpy(value.data, &p, value.len);
return value;
}
void * CMT_CopyItemToPtr(CMTItem value)
{
void * p = NULL;
if (value.len == sizeof(void*)) {
memcpy(&p, value.data, value.len);
}
return p;
}
CMTStatus CMT_ReferenceControlConnection(PCMT_CONTROL control)
{
CMT_LOCK(control->mutex);
control->refCount++;
CMT_UNLOCK(control->mutex);
return CMTSuccess;
}
void
CMT_LockConnection(PCMT_CONTROL control)
{
CMT_LOCK(control->mutex);
}
void
CMT_UnlockConnection(PCMT_CONTROL control)
{
CMT_UNLOCK(control->mutex);
}

View File

@@ -0,0 +1,75 @@
/*
* 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):
*
* 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 __CMTUTILS_H__
#define __CMTUTILS_H__
#include "cmtcmn.h"
#define New(type) (type*)malloc(sizeof(type))
#define NewArray(type, size) (type*)malloc(sizeof(type)*(size))
PCMT_EVENT CMT_GetEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID);
CMUint32 cmt_Strlen(char *str);
char *cmt_PackString(char *buf, char *str);
char *cmt_UnpackString(char *buf, char **str);
CMUint32 cmt_Bloblen(CMTItem* len);
char *cmt_PackBlob(char *buf, CMTItem * blob);
char *cmt_UnpackBlob(char *buf, CMTItem **blob);
CMTStatus CMT_SendMessage(PCMT_CONTROL control, CMTItem* message);
CMTStatus CMT_TransmitMessage(PCMT_CONTROL control, CMTItem * message);
CMTStatus CMT_ReceiveMessage(PCMT_CONTROL control, CMTItem * response);
CMUint32 CMT_ReadThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany);
CMUint32 CMT_WriteThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany);
CMTItem* CMT_ConstructMessage(CMUint32 type, CMUint32 length);
void CMT_FreeMessage(CMTItem * p);
CMTStatus CMT_AddDataConnection(PCMT_CONTROL control, CMTSocket sock, CMUint32 connectionID);
CMTStatus CMT_GetDataConnectionID(PCMT_CONTROL control, CMTSocket sock, CMUint32 * connectionID);
CMTStatus CMT_GetDataSocket(PCMT_CONTROL control, CMUint32 connectionID, CMTSocket * sock);
CMTStatus CMT_CloseDataConnection(PCMT_CONTROL control, CMUint32 connectionID);
CMTStatus CMT_SetPrivate(PCMT_CONTROL control, CMUint32 connectionID,
CMTPrivate *cmtpriv);
CMTPrivate *CMT_GetPrivate(PCMT_CONTROL control, CMUint32 connectionID);
void CMT_ServicePasswordRequest(PCMT_CONTROL cm_control, CMTItem * requestData);
void CMT_ProcessEvent(PCMT_CONTROL cm_control);
void CMT_DispatchEvent(PCMT_CONTROL cm_control, CMTItem * eventData);
CMTItem CMT_CopyPtrToItem(void* p);
void * CMT_CopyItemToPtr(CMTItem value);
#endif /* __CMTUTILS_H__ */

View File

@@ -0,0 +1,44 @@
#
# 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):
#
# 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.
#
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(LIBRARY)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PURE_LIBRARY =
PROGRAM =

View File

@@ -0,0 +1,125 @@
#//
#// 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):
#//
#// 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.
#//
IGNORE_MANIFEST=1
#//------------------------------------------------------------------------
#//
#// Makefile to build the ssl library
#//
#//------------------------------------------------------------------------
!if "$(MOZ_BITS)" == "16"
!ifndef MOZ_DEBUG
OPTIMIZER=-Os -UDEBUG -DNDEBUG
!endif
!endif
#//------------------------------------------------------------------------
#//
#// Specify the depth of the current directory relative to the
#// root of NS
#//
#//------------------------------------------------------------------------
DEPTH= ..\..\..\..
!ifndef MAKE_OBJ_TYPE
MAKE_OBJ_TYPE=EXE
!endif
#//------------------------------------------------------------------------
#//
#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...)
#//
#//------------------------------------------------------------------------
LIBNAME=cmt
PDBFILE=$(LIBNAME).pdb
LINCS = -I$(PUBLIC)\security \
-I$(PUBLIC)\nspr \
-I$(DEPTH)\include \
-I..\include
!ifndef OS_CONFIG
OS_CONFIG = WIN$(MOZ_BITS)
!endif
LCFLAGS = -DEXPORT_VERSION -DLIB_BUILD
#//------------------------------------------------------------------------
#//
#// Define the files necessary to build the target (ie. OBJS)
#//
#//------------------------------------------------------------------------
OBJS= \
.\$(OBJDIR)\cmtinit.obj \
.\$(OBJDIR)\cmtssl.obj \
.\$(OBJDIR)\cmtutils.obj \
.\$(OBJDIR)\cmtpkcs7.obj \
.\$(OBJDIR)\cmthash.obj \
.\$(OBJDIR)\cmtcert.obj \
.\$(OBJDIR)\cmtres.obj \
.\$(OBJDIR)\cmtjs.obj \
.\$(OBJDIR)\cmtevent.obj \
.\$(OBJDIR)\cmtpasswd.obj \
.\$(OBJDIR)\cmtadvisor.obj \
.\$(OBJDIR)\cmtrng.obj \
.\$(OBJDIR)\cmtsdr.obj \
$(NULL)
#//------------------------------------------------------------------------
#//
#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...)
#// (these must be defined before the common makefiles are included)
#//
#//------------------------------------------------------------------------
LIBRARY=.\$(OBJDIR)\$(LIBNAME).lib
#//------------------------------------------------------------------------
#//
#// install headers
#//
#//------------------------------------------------------------------------
INSTALL_DIR=$(PUBLIC)\security
INSTALL_FILE_LIST=cmtcmn.h cmtjs.h cmtclist.h
#//------------------------------------------------------------------------
#//
#// Include the common makefile rules
#//
#//------------------------------------------------------------------------
include <$(DEPTH)/config/rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
export:: INSTALL_FILES

View File

@@ -0,0 +1,64 @@
#
# 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):
#
# 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.
#
CORE_DEPTH = ../../..
DEPTH = ../../..
EXPORTS = \
cmtcmn.h \
cmtjs.h \
cmtclist.h \
$(NULL)
MODULE = security
CSRCS = cmtinit.c \
cmtssl.c \
cmtutils.c \
cmtcert.c \
cmthash.c \
cmtpkcs7.c \
cmtres.c \
cmtjs.c \
cmtevent.c \
cmtpasswd.c \
cmtadvisor.c \
cmtrng.c \
cmtsdr.c \
$(NULL)
REQUIRES = nspr security
LIBRARY_NAME = cmt
INCLUDES += -I$(CORE_DEPTH)/include

View File

@@ -0,0 +1,128 @@
#! 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):
#
# 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.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
ifneq ($(OS_ARCH), WINNT)
ifeq ($(OS_ARCH), Linux)
# On linux, we link with libstdc++
CPLUSPLUSRUNTIME = -L /usr/lib -lstdc++ -lm
else
# libC, presumably, is what we must link with elsewhere
CPLUSPLUSRUNTIME = -lC -lm
endif
endif
ifeq ($(OS_ARCH), SunOS)
ifeq ($(OS_RELEASE), 5.5.1)
OS_LIBS += -ldl -lsocket -lnsl -lthread -lposix4
endif
ifeq ($(OS_RELEASE), 5.6)
OS_LIBS += -ldl -lsocket -lnsl -lthread -lposix4
endif
endif
ifeq ($(OS_ARCH), Linux)
ifdef USE_PTHREADS
# Replace OS_LIBS, because the order of libpthread, libdl, and libc are
# very important. Otherwise you get horrible crashes.
OS_LIBS = -lpthread -ldl -lc
endif
endif
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################
ifeq ($(OS_ARCH), WINNT)
LDFLAGS += /NODEFAULTLIB:library
endif
EXTRA_LIBS = \
$(DIST)/lib/$(LIB_PREFIX)cmt.$(LIB_SUFFIX) \
$(DIST)/lib/$(LIB_PREFIX)protocol.$(LIB_SUFFIX) \
$(NULL)
ifeq ($(OS_ARCH), WINNT)
EXTRA_LIBS += wsock32.lib \
winmm.lib \
$(NULL)
endif
link:
if test -f $(PROGRAM); then \
echo "rm $(PROGRAM)"; \
rm $(PROGRAM); \
fi; \
gmake \
build_sample:
ifneq ($(OS_ARCH),WINNT)
cd $(CORE_DEPTH)/coreconf; gmake
endif
cd $(CORE_DEPTH)/security; gmake import; gmake export
cd ../../protocol; gmake
cd ..; gmake
gmake

View File

@@ -0,0 +1,250 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 "cmtcmn.h"
#include "appsock.h"
#ifdef XP_UNIX
#include <netinet/tcp.h>
#include <errno.h>
#endif
CMT_SocketFuncs socketFuncs = {
APP_GetSocket,
APP_Connect,
APP_VerifyUnixSocket,
APP_Send,
APP_Select,
APP_Receive,
APP_Shutdown,
APP_Close
};
CMTSocket APP_GetSocket(int unixSock)
{
APPSocket *sock;
int on = 1;
#ifndef XP_UNIX
if (unixSock) {
return NULL;
}
#endif
sock = malloc(sizeof(APPSocket));
if (sock == NULL) {
return NULL;
}
if (unixSock) {
sock->sock = socket(AF_UNIX, SOCK_STREAM, 0);
} else {
sock->sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
if (sock->sock < 0) {
free(sock);
return NULL;
}
if (!unixSock &&
setsockopt(sock->sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&on,
sizeof(on))) {
free(sock);
return NULL;
}
sock->isUnix = unixSock;
#ifdef XP_UNIX
memset (&sock->servAddr, 0, sizeof(struct sockaddr_un));
#endif
return (CMTSocket)sock;
}
CMTStatus APP_Connect(CMTSocket sock, short port, char *path)
{
APPSocket *cmSock = (APPSocket*)sock;
struct sockaddr_in iServAddr;
const struct sockaddr *servAddr;
size_t addrLen;
int error;
if (cmSock->isUnix){
#ifndef XP_UNIX
return CMTFailure;
#else
cmSock->servAddr.sun_family = AF_UNIX;
memcpy(&cmSock->servAddr.sun_path, path, strlen(path)+1);
servAddr = (const struct sockaddr*)&cmSock->servAddr;
addrLen = sizeof(cmSock->servAddr);
#endif
} else {
iServAddr.sin_family = AF_INET;
iServAddr.sin_port = htons(port);
iServAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
servAddr = (const struct sockaddr*)&iServAddr;
addrLen = sizeof(struct sockaddr_in);
}
while (connect(cmSock->sock, servAddr, addrLen) != 0) {
#ifdef WIN32
error = WSAGetLastError();
if (error == WSAEISCONN) {
break;
}
if ((error != WSAEINPROGRESS) && (error != WSAEWOULDBLOCK) &&
(error!= WSAEINVAL)) {
goto loser;
}
#else
error = errno;
if (error == EISCONN) {
break;
}
if (error != EINPROGRESS) {
goto loser;
}
#endif
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus APP_VerifyUnixSocket(CMTSocket sock)
{
#ifndef XP_UNIX
return CMTFailure;
#else
APPSocket *cmSock = (APPSocket*)sock;
int rv;
struct stat statbuf;
if (!cmSock->isUnix) {
return CMTFailure;
}
rv = stat(cmSock->servAddr.sun_path, &statbuf);
if (rv < 0) {
goto loser;
}
if (statbuf.st_uid != geteuid()) {
goto loser;
}
return CMTSuccess;
loser:
close(cmSock->sock);
free(cmSock);
return CMTFailure;
#endif
}
size_t APP_Send(CMTSocket sock, void *buffer, size_t length)
{
APPSocket *cmSock = (APPSocket*) sock;
return send(cmSock->sock, buffer, length, 0);
}
CMTSocket APP_Select(CMTSocket *socks, int numsocks, int poll)
{
APPSocket **sockArr = (APPSocket**)socks;
SOCKET nsocks = 0;
int i, rv;
struct timeval timeout;
fd_set readfds;
#ifdef WIN32
win_startover:
#endif
FD_ZERO(&readfds);
for (i=0; i<numsocks; i++) {
FD_SET(sockArr[i]->sock, &readfds);
if (sockArr[i]->sock > nsocks) {
nsocks = sockArr[i]->sock;
}
}
if (poll) {
timeout.tv_sec = 0;
timeout.tv_usec = 0;
}
rv = select(nsocks+1, &readfds, NULL, NULL, (poll) ? &timeout : NULL);
#ifdef WIN32
/* XXX Win95/98 Bug (Q177346)
* select() with no timeout might return even if there is no data
* pending or no error has occurred. To get around this problem,
* we loop if these erroneous conditions happen.
*/
if (poll == 0 && rv == 0) {
goto win_startover;
}
#endif
/* Figure out which socket was selected */
if (rv == -1 || rv == 0) {
goto loser;
}
for (i=0; i<numsocks; i++) {
if (FD_ISSET(sockArr[i]->sock, &readfds)) {
return (CMTSocket)sockArr[i];
}
}
loser:
return NULL;
}
size_t APP_Receive(CMTSocket sock, void *buffer, size_t bufSize)
{
APPSocket *cmSock = (APPSocket*)sock;
return recv(cmSock->sock, buffer, bufSize, 0);
}
CMTStatus APP_Shutdown(CMTSocket sock)
{
APPSocket *cmSock = (APPSocket*)sock;
int rv;
rv = shutdown(cmSock->sock, 1);
return (rv == 0) ? CMTSuccess : CMTFailure;
}
CMTStatus APP_Close(CMTSocket sock)
{
APPSocket *cmSock = (APPSocket*)sock;
int rv;
#ifdef XP_UNIX
rv = close(cmSock->sock);
#else
rv = closesocket(cmSock->sock);
#endif
free(cmSock);
return (rv == 0) ? CMTSuccess : CMTFailure;
}

View File

@@ -0,0 +1,69 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 _APPSOCK_H_
#define _APPSOCK_H_
#include "cmtcmn.h"
#ifdef XP_UNIX
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/stat.h>
typedef int SOCKET;
#endif
typedef struct APPSocketStr {
SOCKET sock;
int isUnix;
#ifdef XP_UNIX
struct sockaddr_un servAddr;
#endif
} APPSocket;
extern CMT_SocketFuncs socketFuncs;
CMTStatus APP_Close(CMTSocket sock);
CMTStatus APP_Shutdown(CMTSocket sock);
size_t APP_Receive(CMTSocket sock, void *buffer, size_t bufSize);
CMTSocket APP_Select(CMTSocket *socks, int numsocks, int poll);
size_t APP_Send(CMTSocket sock, void *buffer, size_t length);
CMTStatus APP_VerifyUnixSocket(CMTSocket sock);
CMTStatus APP_Connect(CMTSocket sock, short port, char *path);
CMTSocket APP_GetSocket(int unixSock);
#endif /* _APPSOCK_H_ */

View File

@@ -0,0 +1,44 @@
#
# 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):
#
# 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.
#
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(PROGRAM)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PURE_LIBRARY =
LIBRARY =

View File

@@ -0,0 +1,52 @@
#
# 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):
#
# 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.
#
CORE_DEPTH = ../../../../..
# MODULE public and private header directories are implicitly REQUIRED.
MODULE = cmtsample
EXPORTS = \
$(NULL)
CSRCS = \
sample.c \
appsock.c \
$(NULL)
INCLUDES += -I../../protocol -I..
# The MODULE is always implicitly required.
# Listing it here in REQUIRES makes it appear twice in the cc command line.
REQUIRES = security
PROGRAM = cmtsample

View File

@@ -0,0 +1,346 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 "cmtcmn.h"
#include "cmtjs.h"
#include "appsock.h"
#include <stdarg.h>
#include <string.h>
#ifdef XP_UNIX
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef WIN32
#include <direct.h>
#endif
/*
* This is a simple program that tries to detect if the psm server is loaded.
* If the server is not loaded, it will start it. The program will then
* connect to the server and fetch an HTML page from an SSL server.
*
* NOTE: This sample program does not implement a mutex for the libraries.
* If implementing a threaded application, then pass in a mutex structure
* so that connections to the psm server happen in a thread safe manner.
*/
#define NUM_CONNECT_TRIES 10
#define READ_BUFFER_SIZE 1024
void
usage(void)
{
printf("Usage:\n"
"\tcmtsample <secure site>\n\n"
"This program will then echo the retrieved HTML to the screen\n");
}
void
errorMessage(int err,char *msg, ...)
{
va_list args;
va_start(args, msg);
fprintf (stderr, "cmtSample%s: ", (err) ? " error" : "");
vfprintf (stderr, msg, args);
fprintf (stderr, "\n");
va_end(args);
if (err) {
exit (err);
}
}
#ifdef XP_UNIX
#define FILE_PATH_SEPARATOR '/'
#elif defined (WIN32)
#define FILE_PATH_SEPARATOR '\\'
#else
#error Tell me what the file path separator is.
#endif
PCMT_CONTROL
connect_to_psm(void)
{
PCMT_CONTROL control=NULL;
char path[256], *tmp;
#ifdef XP_UNIX
if (getcwd(path,256) == NULL) {
return NULL;
}
#elif defined(WIN32)
if (_getcwd(path,256) == NULL) {
return NULL;
}
#else
#error Teach me how to get the current working directory.
#endif
tmp = &path[strlen(path)];
sprintf(tmp,"%c%s", FILE_PATH_SEPARATOR, "psm");
return CMT_EstablishControlConnection(path, &socketFuncs, NULL);
}
#define HTTPS_STRING "https://"
char*
extract_host_from_url(char *url)
{
char *start, *end, *retString=NULL;
while(isspace(*url)) {
url++;
}
url = strdup(url);
start = strstr(url, HTTPS_STRING);
if (start == NULL) {
return NULL;
}
start += strlen(HTTPS_STRING);
/*
* Figure out the end of the host name.
*/
end = strchr(start, ':');
if (end != NULL) {
*end = '\0';
} else {
end = strchr(start, '/');
if (end != NULL) {
*end = '\0';
} else {
end = strchr(start, ' ');
if (end != NULL) {
*end = '\0';
}
}
}
retString = strdup(start);
return retString;
}
CMUint32
get_port_from_url(char *url)
{
char *colon, *port;
url = strdup(url);
colon = strrchr(url, ':');
if (colon == NULL ||
!isdigit(colon[1])) {
/* Return the default SSL port. */
free(url);
return 443;
}
colon++;
port = colon;
while(isdigit(*colon))
colon++;
colon[1] = '\0';
free(url);
return (CMUint32)atol(port);
}
char*
extract_get_target(char *url)
{
char *slash;
slash = strstr(url, "//");
slash += 2;
slash = strchr(slash, '/');
if (slash != NULL)
return strdup (slash);
else
return strdup ("/");
}
/*
* We'll use this function for prompting for a password.
*/
char*
passwordCallback(void *arg, char *prompt, void *cotext, int isPaswd)
{
char input[256];
printf(prompt);
fgets(input, 256, stdin);
return strdup(input);
}
void
freeCallback(char *userInput)
{
free (userInput);
}
#define NUM_PREFS 2
int
main(int argc, char **argv)
{
PCMT_CONTROL control;
CMTSocket sock, selSock;
char *hostname;
struct hostent *host;
char *ipAddress;
char buffer[READ_BUFFER_SIZE];
size_t bytesRead;
struct sockaddr_in destAddr;
char *getString;
char requestString[256];
char *profile;
CMTSetPrefElement prefs[NUM_PREFS];
char profileDir[256];
#ifdef WIN32
WORD WSAVersion = 0x0101;
WSADATA WSAData;
WSAStartup (WSAVersion, &WSAData);
#endif
if (argc < 2) {
usage();
return 1;
}
errorMessage (0,"cmtsample v1.0");
errorMessage (0,"Will try connecting to site %s", argv[1]);
if (strstr(argv[1], "https://") == NULL) {
errorMessage(2,"%s is not a secure site", argv[1]);
}
control = connect_to_psm();
if (control == NULL) {
errorMessage(3, "Could not connect to the psm server");
}
/*
* Now we have to send the hello message.
*/
#ifdef WIN32
profile = strdup("default");
sprintf(profileDir,"%s", "c:\\default");
#elif defined (XP_UNIX)
profile = getenv("LOGNAME");
sprintf(profileDir, "%s/.netscape", getenv("HOME"));
#else
#error Teach me how to fill in the user profile.
#endif
if (CMT_Hello(control, PROTOCOL_VERSION,
profile, profileDir) != CMTSuccess)
{
errorMessage(10, "Failed to send the Hello Message.");
}
CMT_SetPromptCallback(control, passwordCallback, NULL);
CMT_SetAppFreeCallback(control, freeCallback);
/*
* Now pass along some preferences to psm. We'll pass hard coded
* ones here, but apps should figure out a way to manage their user's
* preferences.
*/
prefs[0].key = "security.enable_ssl2";
prefs[0].value = "true";
prefs[0].type = CMT_PREF_BOOL;
prefs[1].key = "security.enable_ssl3";
prefs[1].value = "true";
prefs[1].type = CMT_PREF_BOOL;
CMT_PassAllPrefs(control, NUM_PREFS, prefs);
hostname = extract_host_from_url(argv[1]);
host = gethostbyname(hostname);
if (host == NULL) {
errorMessage(11, "gethostbyname for %s failed", hostname);
}
if (host->h_length != 4) {
errorMessage(4, "Site %s uses IV v6 socket. Not supported by psm.");
}
/* Create the socket we will use to get the decrypted data back from
* the psm server.
*/
sock = APP_GetSocket(0);
if (sock == NULL) {
errorMessage(5, "Could not create new socket for communication with "
"the psm server.");
}
memcpy(&(destAddr.sin_addr.s_addr), host->h_addr, host->h_length);
ipAddress = inet_ntoa(destAddr.sin_addr);
errorMessage(0, "Mapped %s to the following IP address: %s", argv[1],
ipAddress);
if (CMT_OpenSSLConnection(control, sock, SSM_REQUEST_SSL_DATA_SSL,
get_port_from_url(argv[1]), ipAddress,
hostname, CM_FALSE, NULL) != CMTSuccess) {
errorMessage(6, "Could not open SSL connection to %s.", argv[1]);
}
getString = extract_get_target(argv[1]);
sprintf(requestString,
"GET %s HTTP/1.0\r\n"
"\r\n", getString, hostname);
APP_Send(sock, requestString, strlen(requestString));
/*
* Now all we have to do is sit here and fetch the data from the
* socket.
*/
errorMessage (0, "About to print out the fetched page.");
while ((selSock=APP_Select(&sock, 1, 0)) != NULL) {
if (selSock == sock) {
bytesRead = APP_Receive(sock, buffer, READ_BUFFER_SIZE-1);
if (bytesRead == -1 || bytesRead == 0) {
break;
}
buffer[bytesRead] = '\0';
fprintf(stderr, buffer);
}
}
fprintf(stderr,"\n");
if (bytesRead == -1) {
errorMessage(7, "Error receiving decrypted data from psm.");
}
errorMessage(0, "Successfully read the entire page.");
if (CMT_DestroyDataConnection(control, sock) != CMTSuccess) {
errorMessage(8, "Error destroygin the SSL data connection "
"with the psm server.");
}
if (CMT_CloseControlConnection(control) != CMTSuccess) {
errorMessage(9, "Error closing the control connection.");
}
return 0;
}

View File

@@ -0,0 +1,99 @@
/*
* 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):
*
* 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 "cmt.h"
CMTStatus myCallback(CMTControl * control, CMTItem * event, void * arg);
int main(int argc, char ** argv)
{
CMTItem * msg, * event = NULL;
CMTStatus status;
int socket, datasocket;
int sent;
CMTControl * connect;
char * buffer = "some weird text that I feel like passing to server";
connect = CMT_ControlConnect(myCallback, event);
msg = CMT_ConstructMessage(10);
msg->type = (int)CMTClientMessage;
sprintf((char *)msg->data, "first msg!");
status = CMT_SendMessage(connect, msg, event);
if (status != SECSuccess)
perror("CMT_SendMessage");
CMT_FreeEvent(event);
event = NULL;
sprintf((char *)msg->data, "second msg");
status = CMT_SendMessage(connect, msg, event);
if (status != SECSuccess)
perror("CMT_SendMessage");
datasocket = CMT_DataConnect(connect, NULL);
if (datasocket < 0)
perror("CMT_DataConnect");
sent = write(datasocket, (void *)buffer, strlen(buffer));
sent = write(datasocket, (void *)buffer, strlen(buffer));
close(datasocket);
msg->type = (int)CMTClientMessage;
sprintf((char *)msg->data, "third msg!");
status = CMT_SendMessage(connect, msg, event);
if (status != SECSuccess)
perror("CMT_SendMessage");
status = CMT_CloseControlConnection(connect);
if (status != SECSuccess)
perror("CMT_CloseControl");
CMT_FreeMessage(msg);
CMT_FreeEvent(event);
}
CMTStatus myCallback(CMTControl * control, CMTItem * event, void * arg)
{
if (event)
printf("Event received is : type %d, data %s\n", event->type, event->data);
else printf("No event!\n");
if (arg)
printf("Arg is %s\n", (char *)arg);
else printf("No arg!\n");
return SECSuccess;
}

Binary file not shown.

View File

@@ -0,0 +1,3 @@
#include "MacPrefix.h"

View File

@@ -0,0 +1,2 @@
#include "MacPrefix_debug.h"

Binary file not shown.

View File

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

View File

@@ -0,0 +1,43 @@
#
# 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):
#
# 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.
#
#
CORE_DEPTH = ../..
DEPTH = ../..
DIRS = protocol client
#
# these dirs are not built at the moment
#
#NOBUILD_DIRS = jar

View File

@@ -0,0 +1,3 @@
obscure.h
rsrcids.h
ssmdefs.h

View File

@@ -0,0 +1,74 @@
#! 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):
#
# 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.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
include config.mk
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View File

@@ -0,0 +1,64 @@
#! 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):
#
# 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
LIBRARY_NAME = protocol
MODULE = security
EXPORTS = \
protocol.h \
protocolf.h \
protocolport.h \
protocolnspr20.h \
protocolshr.h \
ssmdefs.h \
rsrcids.h \
messages.h \
newproto.h \
$(NULL)
CSRCS = newproto.c \
templates.c \
protocolshr.c \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,44 @@
#
# 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):
#
# 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.
#
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(LIBRARY)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PURE_LIBRARY =
PROGRAM =

View File

@@ -0,0 +1,124 @@
#//
#// 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):
#//
#// 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.
#//
IGNORE_MANIFEST=1
#//------------------------------------------------------------------------
#//
#// Makefile to build the ssl library
#//
#//------------------------------------------------------------------------
!if "$(MOZ_BITS)" == "16"
!ifndef MOZ_DEBUG
OPTIMIZER=-Os -UDEBUG -DNDEBUG
!endif
!endif
#//------------------------------------------------------------------------
#//
#// Specify the depth of the current directory relative to the
#// root of NS
#//
#//------------------------------------------------------------------------
DEPTH= ..\..\..\..
!ifndef MAKE_OBJ_TYPE
MAKE_OBJ_TYPE=EXE
!endif
#//------------------------------------------------------------------------
#//
#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...)
#//
#//------------------------------------------------------------------------
LIBNAME=protocol
PDBFILE=$(LIBNAME).pdb
LINCS = -I$(PUBLIC)\security \
-I$(PUBLIC)\nspr \
-I$(DEPTH)\include \
-I..\include
!ifndef OS_CONFIG
OS_CONFIG = WIN$(MOZ_BITS)
!endif
LCFLAGS = -DEXPORT_VERSION -DLIB_BUILD
#//------------------------------------------------------------------------
#//
#// Define the files necessary to build the target (ie. OBJS)
#//
#//------------------------------------------------------------------------
OBJS= \
.\$(OBJDIR)\newproto.obj \
.\$(OBJDIR)\templates.obj \
.\$(OBJDIR)\protocolshr.obj \
$(NULL)
#//------------------------------------------------------------------------
#//
#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...)
#// (these must be defined before the common makefiles are included)
#//
#//------------------------------------------------------------------------
LIBRARY=.\$(OBJDIR)\$(LIBNAME).lib
#//------------------------------------------------------------------------
#//
#// install headers
#//
#//------------------------------------------------------------------------
INSTALL_DIR=$(PUBLIC)\security
INSTALL_FILE_LIST= protocol.h \
protocolf.h \
protocolport.h \
protocolnspr20.h \
protocolshr.h \
ssmdefs.h \
rsrcids.h \
messages.h \
newproto.h \
$(NULL)
#//------------------------------------------------------------------------
#//
#// Include the common makefile rules
#//
#//------------------------------------------------------------------------
include <$(DEPTH)/config/rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
export:: INSTALL_FILES

View File

@@ -0,0 +1,65 @@
#
# 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):
#
# 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.
#
CORE_DEPTH = ../../..
EXPORTS = \
protocol.h \
protocolf.h \
protocolport.h \
protocolnspr20.h \
protocolshr.h \
ssmdefs.h \
rsrcids.h \
messages.h \
newproto.h \
$(NULL)
MODULE = security
CSRCS = newproto.c \
protocolshr.c \
templates.c \
$(NULL)
ifeq ($(subst /,_,$(shell uname -s)),OS2)
CSRCS += os2_rand.c
endif
# mac_rand.c
# unix_rand.c
# win_rand.c
# prelib.c
REQUIRES = security dbm nspr
LIBRARY_NAME = protocol

View File

@@ -0,0 +1,620 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 __MESSAGES_H__
#define __MESSAGES_H__
#include "newproto.h"
typedef struct SingleNumMessage {
CMInt32 value;
} SingleNumMessage;
extern CMTMessageTemplate SingleNumMessageTemplate[];
typedef struct SingleStringMessage {
char *string;
} SingleStringMessage;
extern CMTMessageTemplate SingleStringMessageTemplate[];
typedef struct SingleItemMessage {
CMTItem item;
} SingleItemMessage;
extern CMTMessageTemplate SingleItemMessageTemplate[];
typedef struct HelloRequest {
CMInt32 version;
CMInt32 policy;
CMBool doesUI;
char *profile;
char* profileDir;
} HelloRequest;
extern CMTMessageTemplate HelloRequestTemplate[];
typedef struct HelloReply {
CMInt32 result;
CMInt32 sessionID;
CMInt32 version;
CMInt32 httpPort;
CMInt32 policy;
CMTItem nonce;
char *stringVersion;
} HelloReply;
extern CMTMessageTemplate HelloReplyTemplate[];
typedef struct SSLDataConnectionRequest {
CMInt32 flags;
CMInt32 port;
char *hostIP;
char *hostName;
CMBool forceHandshake;
CMTItem clientContext;
} SSLDataConnectionRequest;
extern CMTMessageTemplate SSLDataConnectionRequestTemplate[];
typedef struct TLSDataConnectionRequest {
CMInt32 port;
char* hostIP;
char* hostName;
} TLSDataConnectionRequest;
extern CMTMessageTemplate TLSDataConnectionRequestTemplate[];
typedef struct TLSStepUpRequest {
CMUint32 connID;
CMTItem clientContext;
} TLSStepUpRequest;
extern CMTMessageTemplate TLSStepUpRequestTemplate[];
typedef struct ProxyStepUpRequest {
CMUint32 connID;
CMTItem clientContext;
char* url;
} ProxyStepUpRequest;
extern CMTMessageTemplate ProxyStepUpRequestTemplate[];
typedef struct PKCS7DataConnectionRequest {
CMUint32 resID;
CMTItem clientContext;
} PKCS7DataConnectionRequest;
extern CMTMessageTemplate PKCS7DataConnectionRequestTemplate[];
typedef struct DataConnectionReply {
CMInt32 result;
CMInt32 connID;
CMInt32 port;
} DataConnectionReply;
extern CMTMessageTemplate DataConnectionReplyTemplate[];
typedef struct UIEvent {
CMInt32 resourceID;
CMInt32 width;
CMInt32 height;
CMBool isModal;
char *url;
CMTItem clientContext;
} UIEvent;
extern CMTMessageTemplate UIEventTemplate[];
extern CMTMessageTemplate OldUIEventTemplate[];
typedef struct TaskCompletedEvent {
CMInt32 resourceID;
CMInt32 numTasks;
CMInt32 result;
} TaskCompletedEvent;
extern CMTMessageTemplate TaskCompletedEventTemplate[];
typedef struct VerifyDetachedSigRequest {
CMInt32 pkcs7ContentID;
CMInt32 certUsage;
CMInt32 hashAlgID;
CMBool keepCert;
CMTItem hash;
} VerifyDetachedSigRequest;
extern CMTMessageTemplate VerifyDetachedSigRequestTemplate[];
typedef struct CreateSignedRequest {
CMInt32 scertRID;
CMInt32 ecertRID;
CMInt32 dig_alg;
CMTItem digest;
} CreateSignedRequest;
extern CMTMessageTemplate CreateSignedRequestTemplate[];
typedef struct CreateContentInfoReply {
CMInt32 ciRID;
CMInt32 result;
CMInt32 errorCode;
} CreateContentInfoReply;
extern CMTMessageTemplate CreateContentInfoReplyTemplate[];
typedef struct CreateEncryptedRequest {
CMInt32 scertRID;
CMInt32 nrcerts;
CMInt32 *rcertRIDs;
} CreateEncryptedRequest;
extern CMTMessageTemplate CreateEncryptedRequestTemplate[];
typedef struct CreateResourceRequest {
CMInt32 type;
CMTItem params;
} CreateResourceRequest;
extern CMTMessageTemplate CreateResourceRequestTemplate[];
typedef struct CreateResourceReply {
CMInt32 result;
CMInt32 resID;
} CreateResourceReply;
extern CMTMessageTemplate CreateResourceReplyTemplate[];
typedef struct GetAttribRequest {
CMInt32 resID;
CMInt32 fieldID;
} GetAttribRequest;
extern CMTMessageTemplate GetAttribRequestTemplate[];
typedef struct GetAttribReply {
CMInt32 result;
SSMAttributeValue value;
} GetAttribReply;
extern CMTMessageTemplate GetAttribReplyTemplate[];
typedef struct SetAttribRequest {
CMInt32 resID;
CMInt32 fieldID;
SSMAttributeValue value;
} SetAttribRequest;
extern CMTMessageTemplate SetAttribRequestTemplate[];
typedef struct PickleResourceReply {
CMInt32 result;
CMTItem blob;
} PickleResourceReply;
extern CMTMessageTemplate PickleResourceReplyTemplate[];
typedef struct UnpickleResourceRequest {
CMInt32 resourceType;
CMTItem resourceData;
} UnpickleResourceRequest;
extern CMTMessageTemplate UnpickleResourceRequestTemplate[];
typedef struct UnpickleResourceReply {
CMInt32 result;
CMInt32 resID;
} UnpickleResourceReply;
extern CMTMessageTemplate UnpickleResourceReplyTemplate[];
typedef struct PickleSecurityStatusReply {
CMInt32 result;
CMInt32 securityLevel;
CMTItem blob;
} PickleSecurityStatusReply;
extern CMTMessageTemplate PickleSecurityStatusReplyTemplate[];
typedef struct DupResourceReply {
CMInt32 result;
CMUint32 resID;
} DupResourceReply;
extern CMTMessageTemplate DupResourceReplyTemplate[];
typedef struct DestroyResourceRequest {
CMInt32 resID;
CMInt32 resType;
} DestroyResourceRequest;
extern CMTMessageTemplate DestroyResourceRequestTemplate[];
typedef struct VerifyCertRequest {
CMInt32 resID;
CMInt32 certUsage;
} VerifyCertRequest;
extern CMTMessageTemplate VerifyCertRequestTemplate[];
typedef struct AddTempCertToDBRequest {
CMInt32 resID;
char *nickname;
CMInt32 sslFlags;
CMInt32 emailFlags;
CMInt32 objSignFlags;
} AddTempCertToDBRequest;
extern CMTMessageTemplate AddTempCertToDBRequestTemplate[];
typedef struct MatchUserCertRequest {
CMInt32 certType;
CMInt32 numCANames;
char **caNames;
} MatchUserCertRequest;
extern CMTMessageTemplate MatchUserCertRequestTemplate[];
typedef struct MatchUserCertReply {
CMInt32 numCerts;
CMInt32 *certs;
} MatchUserCertReply;
extern CMTMessageTemplate MatchUserCertReplyTemplate[];
typedef struct EncodeCRMFReqRequest {
CMInt32 numRequests;
CMInt32 * reqIDs;
} EncodeCRMFReqRequest;
extern CMTMessageTemplate EncodeCRMFReqRequestTemplate[];
typedef struct CMMFCertResponseRequest {
char *nickname;
char *base64Der;
CMBool doBackup;
CMTItem clientContext;
} CMMFCertResponseRequest;
extern CMTMessageTemplate CMMFCertResponseRequestTemplate[];
typedef struct PasswordRequest {
CMInt32 tokenKey;
char *prompt;
CMTItem clientContext;
} PasswordRequest;
extern CMTMessageTemplate PasswordRequestTemplate[];
typedef struct PasswordReply {
CMInt32 result;
CMInt32 tokenID;
char * passwd;
} PasswordReply;
extern CMTMessageTemplate PasswordReplyTemplate[];
typedef struct KeyPairGenRequest {
CMInt32 keyGenCtxtID;
CMInt32 genMechanism;
CMInt32 keySize;
CMTItem params;
} KeyPairGenRequest;
extern CMTMessageTemplate KeyPairGenRequestTemplate[];
typedef struct DecodeAndCreateTempCertRequest {
CMInt32 type;
CMTItem cert;
} DecodeAndCreateTempCertRequest;
extern CMTMessageTemplate DecodeAndCreateTempCertRequestTemplate[];
typedef struct GenKeyOldStyleRequest {
char *choiceString;
char *challenge;
char *typeString;
char *pqgString;
} GenKeyOldStyleRequest;
extern CMTMessageTemplate GenKeyOldStyleRequestTemplate[];
typedef struct GenKeyOldStyleTokenRequest {
CMInt32 rid;
CMInt32 numtokens;
char ** tokenNames;
} GenKeyOldStyleTokenRequest;
extern CMTMessageTemplate GenKeyOldStyleTokenRequestTemplate[];
typedef struct GenKeyOldStyleTokenReply {
CMInt32 rid;
CMBool cancel;
char * tokenName;
} GenKeyOldStyleTokenReply;
extern CMTMessageTemplate GenKeyOldStyleTokenReplyTemplate[];
typedef struct GenKeyOldStylePasswordRequest {
CMInt32 rid;
char * tokenName;
CMBool internal;
CMInt32 minpwdlen;
CMInt32 maxpwdlen;
} GenKeyOldStylePasswordRequest;
extern CMTMessageTemplate GenKeyOldStylePasswordRequestTemplate[];
typedef struct GenKeyOldStylePasswordReply {
CMInt32 rid;
CMBool cancel;
char * password;
} GenKeyOldStylePasswordReply;
extern CMTMessageTemplate GenKeyOldStylePasswordReplyTemplate[];
typedef struct GetKeyChoiceListRequest {
char *type;
char *pqgString;
} GetKeyChoiceListRequest;
extern CMTMessageTemplate GetKeyChoiceListRequestTemplate[];
typedef struct GetKeyChoiceListReply {
CMInt32 nchoices;
char **choices;
} GetKeyChoiceListReply;
extern CMTMessageTemplate GetKeyChoiceListReplyTemplate[];
typedef struct AddNewSecurityModuleRequest {
char *moduleName;
char *libraryPath;
CMInt32 pubMechFlags;
CMInt32 pubCipherFlags;
} AddNewSecurityModuleRequest;
extern CMTMessageTemplate AddNewSecurityModuleRequestTemplate[];
typedef struct FilePathRequest {
CMInt32 resID;
char *prompt;
CMBool getExistingFile;
char *fileRegEx;
} FilePathRequest;
extern CMTMessageTemplate FilePathRequestTemplate[];
typedef struct FilePathReply {
CMInt32 resID;
char *filePath;
} FilePathReply;
extern CMTMessageTemplate FilePathReplyTemplate[];
typedef struct PasswordPromptReply {
CMInt32 resID;
char *promptReply;
} PasswordPromptReply;
extern CMTMessageTemplate PasswordPromptReplyTemplate[];
typedef struct SignTextRequest {
CMInt32 resID;
char *stringToSign;
char *hostName;
char *caOption;
CMInt32 numCAs;
char** caNames;
} SignTextRequest;
extern CMTMessageTemplate SignTextRequestTemplate[];
typedef struct GetLocalizedTextReply {
CMInt32 whichString;
char *localizedString;
} GetLocalizedTextReply;
extern CMTMessageTemplate GetLocalizedTextReplyTemplate[];
typedef struct ImportCertReply {
CMInt32 result;
CMInt32 resID;
} ImportCertReply;
extern CMTMessageTemplate ImportCertReplyTemplate[];
typedef struct PromptRequest {
CMInt32 resID;
char *prompt;
CMTItem clientContext;
} PromptRequest;
extern CMTMessageTemplate PromptRequestTemplate[];
typedef struct PromptReply {
CMInt32 resID;
CMBool cancel;
char *promptReply;
} PromptReply;
extern CMTMessageTemplate PromptReplyTemplate[];
typedef struct RedirectCompareReqeust {
CMTItem socketStatus1Data;
CMTItem socketStatus2Data;
} RedirectCompareRequest;
extern CMTMessageTemplate RedirectCompareRequestTemplate[];
typedef struct DecodeAndAddCRLRequest {
CMTItem derCrl;
CMUint32 type;
char *url;
} DecodeAndAddCRLRequest;
extern CMTMessageTemplate DecodeAndAddCRLRequestTemplate[];
typedef struct SecurityAdvisorRequest {
CMInt32 infoContext;
CMInt32 resID;
char * hostname;
char * senderAddr;
CMUint32 encryptedP7CInfo;
CMUint32 signedP7CInfo;
CMInt32 decodeError;
CMInt32 verifyError;
CMBool encryptthis;
CMBool signthis;
CMInt32 numRecipients;
char ** recipients;
} SecurityAdvisorRequest;
extern CMTMessageTemplate SecurityAdvisorRequestTemplate[];
/* "SecurityConfig" javascript related message templates */
typedef struct SCAddTempCertToPermDBRequest {
CMTItem certKey;
char* trustStr;
char* nickname;
} SCAddTempCertToPermDBRequest;
extern CMTMessageTemplate SCAddTempCertToPermDBRequestTemplate[];
typedef struct SCDeletePermCertsRequest {
CMTItem certKey;
CMBool deleteAll;
} SCDeletePermCertsRequest;
extern CMTMessageTemplate SCDeletePermCertsRequestTemplate[];
typedef struct TimeMessage {
CMInt32 year;
CMInt32 month;
CMInt32 day;
CMInt32 hour;
CMInt32 minute;
CMInt32 second;
} TimeMessage;
extern CMTMessageTemplate TimeMessageTemplate[];
typedef struct CertEnumElement {
char* name;
CMTItem certKey;
} CertEnumElement;
typedef struct SCCertIndexEnumReply {
int length;
CertEnumElement* list;
} SCCertIndexEnumReply;
extern CMTMessageTemplate SCCertIndexEnumReplyTemplate[];
/* Test message */
typedef struct TestListElement {
char * name;
char * value;
} TestListElement;
typedef struct TestList {
char *listName;
int numElements;
TestListElement *elements;
} TestList;
extern CMTMessageTemplate TestListTemplate[];
/* Preference-related structs */
typedef struct SetPrefElement {
char* key;
char* value;
CMInt32 type;
} SetPrefElement;
typedef struct SetPrefListMessage {
int length;
SetPrefElement* list;
} SetPrefListMessage;
extern CMTMessageTemplate SetPrefListMessageTemplate[];
typedef struct GetPrefElement {
char* key;
CMInt32 type;
} GetPrefElement;
typedef struct GetPrefListRequest {
int length;
GetPrefElement* list;
} GetPrefListRequest;
extern CMTMessageTemplate GetPrefListRequestTemplate[];
typedef struct GetCertExtension {
CMUint32 resID;
CMUint32 extension;
} GetCertExtension;
extern CMTMessageTemplate GetCertExtensionTemplate[];
typedef struct HTMLCertInfoRequest {
CMUint32 certID;
CMUint32 showImages;
CMUint32 showIssuer;
} HTMLCertInfoRequest;
extern CMTMessageTemplate HTMLCertInfoRequestTemplate[];
typedef struct EncryptRequestMessage
{
CMTItem keyid; /* May have length 0 for default */
CMTItem data;
CMTItem ctx; /* serialized void* ptr */
} EncryptRequestMessage;
extern CMTMessageTemplate EncryptRequestTemplate[];
typedef struct SingleItemMessage EncryptReplyMessage;
#define EncryptReplyTemplate SingleItemMessageTemplate
typedef struct DecryptRequestMessage
{
CMTItem data;
CMTItem ctx; /* serialized void* ptr */
} DecryptRequestMessage;
extern CMTMessageTemplate DecryptRequestTemplate[];
typedef struct SingleItemMessage DecryptReplyMessage;
#define DecryptReplyTemplate SingleItemMessageTemplate
#endif /* __MESSAGES_H__ */

View File

@@ -0,0 +1,602 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 <string.h>
#include <assert.h>
#ifdef WIN32
#include <winsock.h>
#endif
#ifdef XP_MAC
#include "macsocket.h"
#endif
#include "newproto.h"
char SSMVersionString[] = "1.1";
CMT_Alloc_fn cmt_alloc = malloc;
CMT_Free_fn cmt_free = free;
#define ASSERT(x) assert(x)
#define CM_ntohl ntohl
#define CM_htonl htonl
/*************************************************************
*
* CMT_Init
*
*
************************************************************/
void
CMT_Init(CMT_Alloc_fn allocfn, CMT_Free_fn freefn)
{
cmt_alloc = allocfn;
cmt_free = freefn;
}
static CMTStatus
decode_int(unsigned char **curptr, void *dest, CMInt32 *remaining)
{
CMInt32 datalen = sizeof(CMInt32);
if (*remaining < datalen)
return CMTFailure;
*(CMInt32 *)dest = ntohl(**(CMInt32 **)curptr);
*remaining -= datalen;
*curptr += datalen;
return CMTSuccess;
}
static CMTStatus
decode_string(unsigned char **curptr, CMInt32 *len,
unsigned char **data, CMInt32 *remaining)
{
CMTStatus rv;
CMInt32 datalen;
rv = decode_int(curptr, len, remaining);
if (rv != CMTSuccess)
return CMTFailure;
/* NULL string */
if (*len == 0) {
*data = NULL;
goto done;
}
datalen = (*len + 3) & ~3;
if (*remaining < datalen)
return CMTFailure;
*data = (unsigned char *) cmt_alloc(*len + 1);
if (*data == NULL)
return CMTFailure;
memcpy(*data, *curptr, *len);
(*data)[*len] = 0;
*remaining -= datalen;
*curptr += datalen;
done:
return CMTSuccess;
}
/*************************************************************
* CMT_DecodeMessage
*
* Decode msg into dest as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_DecodeMessage(CMTMessageTemplate *tmpl, void *dest, CMTItem *msg)
{
unsigned char *curptr, *destptr, *list;
void ** ptr;
CMInt32 remaining, len, choiceID = 0, listSize, listCount = 0;
CMBool inChoice = CM_FALSE, foundChoice = CM_FALSE, inList = CM_FALSE;
CMInt32 listItemSize = 0;
CMTStatus rv = CMTSuccess;
CMTMessageTemplate *startOfList, *p;
CMBool inStructList = CM_FALSE;
curptr = msg->data;
remaining = msg->len;
while(tmpl->type != CMT_DT_END) {
/* XXX Maybe this should be a more formal state machine? */
if (inChoice) {
if (tmpl->type == CMT_DT_END_CHOICE) {
if (!foundChoice)
goto loser;
inChoice = CM_FALSE;
foundChoice = CM_FALSE;
tmpl++;
continue;
}
if (choiceID != tmpl->choiceID) {
tmpl++;
continue; /* Not this option */
} else {
foundChoice = CM_TRUE;
}
}
if (inList) {
destptr = &list[listCount * listItemSize];
listCount++;
} else {
if (inStructList) {
destptr = tmpl->offset + list;
} else {
destptr = tmpl->offset + (unsigned char *)dest;
}
}
switch (tmpl->type) {
case CMT_DT_RID:
case CMT_DT_INT:
case CMT_DT_BOOL:
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_STRING:
rv = decode_string(&curptr, &len, (unsigned char **)destptr,
&remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_ITEM:
rv = decode_string(&curptr, (long *) &((CMTItem *)destptr)->len,
&((CMTItem *)destptr)->data, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_LIST:
/* XXX This is too complicated */
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)destptr;
tmpl++;
if (tmpl->type == CMT_DT_STRING) {
listItemSize = sizeof(unsigned char *);
} else if (tmpl->type == CMT_DT_ITEM) {
listItemSize = sizeof(CMTItem);
} else {
listItemSize = sizeof(CMInt32);
}
if (listSize == 0) {
list = NULL;
} else {
list = (unsigned char *) cmt_alloc(listSize * listItemSize);
}
*(void **)(tmpl->offset + (unsigned char *)dest) = list;
inList = CM_TRUE;
listCount = 0;
break;
case CMT_DT_STRUCT_LIST:
/* XXX This is too complicated */
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)destptr;
tmpl++;
if (tmpl->type != CMT_DT_STRUCT_PTR) {
goto loser;
}
ptr = (void**)(tmpl->offset + (unsigned char *)dest);
startOfList = tmpl;
p = tmpl;
listItemSize = 0;
while (p->type != CMT_DT_END_STRUCT_LIST) {
if (p->type == CMT_DT_STRING) {
listItemSize += sizeof(unsigned char *);
} else if (p->type == CMT_DT_ITEM) {
listItemSize += sizeof(CMTItem);
} else if (p->type == CMT_DT_INT) {
listItemSize += sizeof(CMInt32);
}
p++;
}
if (listSize == 0) {
list = NULL;
} else {
list = (unsigned char *) cmt_alloc(listSize * listItemSize);
}
*ptr = list;
inStructList = CM_TRUE;
listCount = 0;
break;
case CMT_DT_END_STRUCT_LIST:
listCount++;
if (listCount == listSize) {
inStructList = CM_FALSE;
} else {
list += listItemSize;
tmpl = startOfList;
}
break;
case CMT_DT_CHOICE:
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
choiceID = *(CMInt32 *)destptr;
inChoice = CM_TRUE;
foundChoice = CM_FALSE;
break;
case CMT_DT_END_CHOICE: /* Loop should exit before we see these. */
case CMT_DT_END:
default:
ASSERT(0);
break;
}
if (inList) {
if (listCount == listSize) {
inList = CM_FALSE;
tmpl++;
}
} else {
tmpl++;
}
}
loser:
/* Free the data buffer */
if (msg->data) {
cmt_free(msg->data);
msg->data = NULL;
}
return rv;
}
static CMTStatus
calc_msg_len(CMTMessageTemplate *tmpl, void *src, CMInt32 *len_out)
{
CMInt32 len = 0, choiceID = 0, listSize, listItemSize, listCount;
unsigned char *srcptr, *list;
CMBool inChoice = CM_FALSE, inList = CM_FALSE, foundChoice = CM_FALSE;
CMTMessageTemplate *startOfList, *p;
CMBool inStructList = CM_FALSE;
while(tmpl->type != CMT_DT_END) {
if (inChoice) {
if (tmpl->type == CMT_DT_END_CHOICE) {
if (!foundChoice)
goto loser;
inChoice = CM_FALSE;
foundChoice = CM_FALSE;
tmpl++;
continue;
}
if (choiceID != tmpl->choiceID) {
tmpl++;
continue; /* Not this option */
} else {
foundChoice = CM_TRUE;
}
}
if (inList) {
srcptr = &list[listCount * listItemSize];
listCount++;
} else if (inStructList) {
srcptr = tmpl->offset + list;
} else {
srcptr = tmpl->offset + (unsigned char *)src;
}
switch(tmpl->type) {
case CMT_DT_RID:
case CMT_DT_INT:
case CMT_DT_BOOL:
len += sizeof(CMInt32);
break;
case CMT_DT_STRING:
len += sizeof(CMInt32);
/* Non NULL string */
if (*(char**)srcptr) {
len += (strlen(*(char**)srcptr) + 4) & ~3;
}
break;
case CMT_DT_ITEM:
len += sizeof(CMInt32);
len += (((CMTItem *)srcptr)->len + 3) & ~3;
break;
case CMT_DT_LIST:
len += sizeof(CMInt32);
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type == CMT_DT_STRING) {
listItemSize = sizeof(unsigned char *);
} else if (tmpl->type == CMT_DT_ITEM) {
listItemSize = sizeof(CMTItem);
} else {
listItemSize = sizeof(CMInt32);
}
list = *(unsigned char **)(tmpl->offset + (unsigned char *)src);
listCount = 0;
inList = CM_TRUE;
break;
case CMT_DT_STRUCT_LIST:
len += sizeof(CMInt32);
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type != CMT_DT_STRUCT_PTR) {
goto loser;
}
list = *(unsigned char**)(tmpl->offset + (unsigned char*)src);
startOfList = tmpl;
p = tmpl;
listItemSize = 0;
while (p->type != CMT_DT_END_STRUCT_LIST) {
if (p->type == CMT_DT_STRING) {
listItemSize += sizeof(unsigned char *);
} else if (p->type == CMT_DT_ITEM) {
listItemSize += sizeof(CMTItem);
} else if (p->type == CMT_DT_INT) {
listItemSize += sizeof(CMInt32);
}
p++;
}
listCount = 0;
inStructList = CM_TRUE;
break;
case CMT_DT_END_STRUCT_LIST:
listCount++;
if (listCount == listSize) {
inStructList = CM_FALSE;
} else {
list += listItemSize;
tmpl = startOfList;
}
break;
case CMT_DT_CHOICE:
len += sizeof(CMInt32);
choiceID = *(CMInt32 *)srcptr;
inChoice = CM_TRUE;
foundChoice = CM_FALSE;
break;
case CMT_DT_END_CHOICE: /* Loop should exit before we see these. */
case CMT_DT_END:
default:
ASSERT(0);
break;
}
if (inList) {
if (listCount == listSize) {
inList = CM_FALSE;
tmpl++;
}
} else {
tmpl++;
}
}
*len_out = len;
return CMTSuccess;
loser:
return CMTFailure;
}
static CMTStatus
encode_int(unsigned char **curptr, void *src, CMInt32 *remaining)
{
CMInt32 datalen = sizeof(CMInt32);
if (*remaining < datalen)
return CMTFailure;
**(CMInt32 **)curptr = CM_htonl(*(CMInt32 *)src);
*remaining -= datalen;
*curptr += datalen;
return CMTSuccess;
}
static CMTStatus
encode_string(unsigned char **curptr, CMInt32 len,
unsigned char *data, CMInt32 *remaining)
{
CMTStatus rv;
CMInt32 datalen;
rv = encode_int(curptr, &len, remaining);
if (rv != CMTSuccess)
return CMTFailure;
/* NULL string */
if (len == 0) {
goto done;
}
datalen = (len + 3) & ~3;
if (*remaining < datalen)
return CMTFailure;
memcpy(*curptr, data, len);
*remaining -= datalen;
*curptr += datalen;
done:
return CMTSuccess;
}
/*************************************************************
* CMT_EncodeMessage
*
* Encode src into msg as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_EncodeMessage(CMTMessageTemplate *tmpl, CMTItem *msg, void *src)
{
CMInt32 choiceID = 0, listSize, listItemSize, listCount, remaining;
unsigned char *srcptr, *curptr, *list;
CMBool inChoice = CM_FALSE, inList = CM_FALSE, foundChoice = CM_FALSE;
CMTStatus rv = CMTSuccess;
CMTMessageTemplate *startOfList, *p;
CMBool inStructList = CM_FALSE;
rv = calc_msg_len(tmpl, src, (long *) &msg->len);
if (rv != CMTSuccess)
goto loser;
curptr = msg->data = (unsigned char *) cmt_alloc(msg->len);
if(msg->data == NULL)
goto loser;
remaining = msg->len;
while(tmpl->type != CMT_DT_END) {
if (inChoice) {
if (tmpl->type == CMT_DT_END_CHOICE) {
if (!foundChoice)
goto loser;
inChoice = CM_FALSE;
foundChoice = CM_FALSE;
tmpl++;
continue;
}
if (choiceID != tmpl->choiceID) {
tmpl++;
continue; /* Not this option */
} else {
foundChoice = CM_TRUE;
}
}
if (inList) {
srcptr = &list[listCount * listItemSize];
listCount++;
} else {
if (inStructList) {
srcptr = tmpl->offset + list;
} else {
srcptr = tmpl->offset + (unsigned char *)src;
}
}
switch(tmpl->type) {
case CMT_DT_RID:
case CMT_DT_INT:
case CMT_DT_BOOL:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_STRING:
if (*(char**)srcptr) {
/* Non NULL string */
rv = encode_string(&curptr, (long) strlen(*(char**)srcptr),
*(unsigned char**)srcptr, &remaining);
} else {
/* NULL string */
rv = encode_string(&curptr, 0L, *(unsigned char**)srcptr, &remaining);
}
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_ITEM:
rv = encode_string(&curptr, ((CMTItem *)srcptr)->len,
((CMTItem *)srcptr)->data, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_LIST:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type == CMT_DT_STRING) {
listItemSize = sizeof(unsigned char *);
} else if (tmpl->type == CMT_DT_ITEM) {
listItemSize = sizeof(CMTItem);
} else {
listItemSize = sizeof(CMInt32);
}
list = *(unsigned char **)(tmpl->offset + (unsigned char *)src);
listCount = 0;
inList = CM_TRUE;
break;
case CMT_DT_STRUCT_LIST:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type != CMT_DT_STRUCT_PTR) {
goto loser;
}
list = *(unsigned char**)(tmpl->offset + (unsigned char*)src);
startOfList = tmpl;
p = tmpl;
listItemSize = 0;
while (p->type != CMT_DT_END_STRUCT_LIST) {
if (p->type == CMT_DT_STRING) {
listItemSize += sizeof(unsigned char *);
} else if (p->type == CMT_DT_ITEM) {
listItemSize += sizeof(CMTItem);
} else if (p->type == CMT_DT_INT) {
listItemSize += sizeof(CMInt32);
}
p++;
}
listCount = 0;
inStructList = CM_TRUE;
break;
case CMT_DT_END_STRUCT_LIST:
listCount++;
if (listCount == listSize) {
inStructList = CM_FALSE;
} else {
list += listItemSize;
tmpl = startOfList;
}
break;
case CMT_DT_CHOICE:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
choiceID = *(CMInt32 *)srcptr;
inChoice = CM_TRUE;
foundChoice = CM_FALSE;
break;
case CMT_DT_END_CHOICE: /* Loop should exit before we see these. */
case CMT_DT_END:
default:
ASSERT(0);
break;
}
if (inList) {
if (listCount == listSize) {
inList = CM_FALSE;
tmpl++;
}
} else {
tmpl++;
}
}
return CMTSuccess;
loser:
return CMTFailure;
}

View File

@@ -0,0 +1,102 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 __NEWPROTO_H__
#define __NEWPROTO_H__
#include <stdlib.h>
#include "ssmdefs.h"
typedef enum CMTDataType {
CMT_DT_END,
CMT_DT_RID,
CMT_DT_INT,
CMT_DT_BOOL,
CMT_DT_STRING,
CMT_DT_ITEM,
CMT_DT_LIST,
CMT_DT_CHOICE,
CMT_DT_END_CHOICE,
CMT_DT_STRUCT_LIST,
CMT_DT_END_STRUCT_LIST,
CMT_DT_STRUCT_PTR
} CMTDataType;
typedef struct CMTMessageTemplate {
CMTDataType type;
CMUint32 offset;
CMInt32 validator;
CMInt32 choiceID;
} CMTMessageTemplate;
typedef struct CMTMessageHeader {
CMInt32 type;
CMInt32 len;
} CMTMessageHeader;
typedef void *(* CMT_Alloc_fn) (size_t size);
typedef void (* CMT_Free_fn)(void * ptr);
extern CMT_Alloc_fn cmt_alloc;
extern CMT_Free_fn cmt_free;
/*************************************************************
*
* CMT_Init
*
*
************************************************************/
void
CMT_Init(CMT_Alloc_fn allocfn, CMT_Free_fn freefn);
/*************************************************************
* CMT_DecodeMessage
*
* Decode msg into dest as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_DecodeMessage(CMTMessageTemplate *tmpl, void *dest, CMTItem *msg);
/*************************************************************
* CMT_EncodeMessage
*
* Encode src into msg as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_EncodeMessage(CMTMessageTemplate *tmpl, CMTItem *msg, void *src);
#endif /* __NEWPROTO_H__ */

View File

@@ -0,0 +1,187 @@
/*
* 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):
*
* 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.
*/
/* SAMPLE CODE
** Illustrates use of SSMObscure object methods.
**
** Author: Nelson Bolyard June 1999
*/
#include <stdio.h>
#include "obscure.h"
/* On error, returns -1.
** On success, returns non-negative number of unobscured bytes in buf
int
RecvInitObscureData(int fd, SSMObscureObject * obj, void * buf, int bufSize )
{
SSMObscureBool done = 0;
do {
int cc;
int rv;
cc = read(fd, buf, bufSize);
if (cc <= 0)
return -1;
rv = SSMObscure_RecvInit(obj, buf, cc, &done);
} while (!done);
return rv;
}
/* returns -1 on error, 0 on success. */
int
SendInitObscureData(int fd, SSMObscureObject * obj)
{
unsigned char * initBuf = NULL;
int rv = -1;
do {
int bufLen;
int len;
int cc;
bufLen = SSMObscure_SendInit(obj, NULL);
if (bufLen <= 0)
break;
initBuf = malloc(bufLen);
if (!initBuf)
break;
len = SSMObscure_SendInit(obj, initBuf);
if (len != bufLen)
break;
cc = write(fd, initBuf, len);
/* Note, this code assumes a blocking socket,
** and hence doesn't deal with short writes.
*/
if (cc < len)
break;
rv = 0;
} while (0);
if (initBuf) {
free(initBuf);
initBuf = NULL;
}
return rv;
}
/* This is like write, but it obscures the data first. */
/* This code assumes a blocking socket, and so it doesn't handle short
** writes.
*/
int
obscuredWrite(SSMObscureObject * obj, int fd, void * buf, int len)
{
int rv;
int cc;
cc = SSMObscure_Send(obj, buf, len);
if (cc <= 0)
return cc;
rv = write(fd, buf, cc);
ASSERT(rv == cc || rv < 0);
return rv;
}
/* This is like read, but it unobscures the data after reading it. */
int
obscuredRead(SSMObscureObject * obj, int fd, void * buf, int len)
{
int rv;
int cc;
do {
cc = read(fd, buf, len);
if (cc <= 0)
return cc;
rv = SSMObscure_Recv(obj, buf, len);
} while (rv == 0);
return rv;
}
SSMObscureObject * sobj;
unsigned char buf[8192];
/* Call this with fd for socket that has just been accepted.
** returns -1 on error,
** On success, returns non-negative number of bytes received in buf.
*/
int
InitClientObscureObject(int fd)
{
int rv;
sobj = SSMObscure_Create(0);
if (!sobj)
return -1;
rv = SendInitObscureData(fd, sobj);
if (rv < 0)
return rv;
rv = RecvInitObscureData(fd, sobj, buf, sizeof buf);
return rv;
}
/* Call this with fd for socket that has just been connected.
** returns -1 on error,
** On success, returns non-negative number of bytes received in buf.
*/
int
InitServerObscureObject(int fd)
{
int cc;
sobj = SSMObscure_Create(1);
if (!sobj)
return -1;
cc = RecvInitObscureData(fd, sobj, buf, sizeof buf);
if (cc < 0)
return cc;
rv = SendInitObscureData(fd, sobj);
if (rv < 0)
return rv;
return cc;
}

View File

@@ -0,0 +1,136 @@
/*
* 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):
*
* 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 <stdlib.h>
#include "obspriv.h"
#include "newproto.h"
/*
** Create a new Obscuring object
*/
SSMObscureObject *
SSMObscure_Create(SSMObscureBool IsServer)
{
SSMObscureObject * obj;
void * priv;
obj = (SSMObscureObject *) cmt_alloc(sizeof *obj);
if (!obj)
return obj;
/* This needs to be a little more elegant */
priv = SSMObscure_InitPrivate(obj, IsServer);
if (!priv) {
cmt_free(obj);
return NULL;
}
obj->privData = priv;
return obj;
}
/* Prepare initial buffer with initial message to send to other side to
** establish cryptographic * synchronization.
**
** If buf is NULL, function returns the size of the buffer that
** the caller needs to allocate for sending the initial message.
**
** If buf is non-null, function returns the number of bytes of data filled
** into buf, the amount that the caller should then send to the other side.
**
*/
int
SSMObscure_SendInit( SSMObscureObject * obj, void * buf)
{
int rv;
rv = obj->sendInit(obj->privData, buf);
return rv;
}
/*
** Obscure "len" bytes in "buf" before sending it.
*/
int
SSMObscure_Send( SSMObscureObject * obj,
void * buf,
unsigned int len)
{
int rv;
rv = obj->send(obj->privData, buf, len);
return rv;
}
/*
** UnObscure "len" bytes in "buf" after receiving it.
** This function may absorb some or all of the received bytes, leaving
** fewer bytes (possibly none) in the buffer for the application to use
** than were in the buffer when the function was called.
** Function returns the number of bytes of unobscured data remaining in
** buf. Zero means all data was used internally and no data remains
** for application use. Negative number means error occurred.
*/
int
SSMObscure_Recv( SSMObscureObject * obj,
void * buf,
unsigned int len)
{
int rv;
rv = obj->recv(obj->privData, buf, len);
return rv;
}
/* like _Recv, but returns a flag telling when all initialization info has
** been received.
*/
int
SSMObscure_RecvInit( SSMObscureObject * obj,
void * buf,
unsigned int len,
SSMObscureBool * done)
{
int rv;
rv = obj->recvInit(obj->privData, buf, len, done);
return rv;
}
/*
** Destroy the Obscure Object
*/
int
SSMObscure_Destroy(SSMObscureObject * obj)
{
int rv;
rv = obj->destroy(obj->privData);
cmt_free(obj);
return rv;
}

View File

@@ -0,0 +1,98 @@
/*
* 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):
*
* 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 __obscure_h__
#define __obscure_h__ 1
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned char SSMObscureBool;
typedef struct SSMObscureObjectStr SSMObscureObject;
/*
** Create a new Obscuring object
*/
extern SSMObscureObject * SSMObscure_Create(SSMObscureBool IsServer);
/* Prepare initial buffer with initial message to send to other side to
** establish cryptographic * synchronization.
**
** If buf is NULL, function returns the size of the buffer that
** the caller needs to allocate for sending the initial message.
**
** If buf is non-null, function returns the number of bytes of data filled
** into buf, the amount that the caller should then send to the other side.
**
*/
extern int SSMObscure_SendInit( SSMObscureObject * obj,
void * buf);
/*
** Obscure "len" bytes in "buf" before sending it.
*/
extern int SSMObscure_Send( SSMObscureObject * obj,
void * buf,
unsigned int len);
/*
** UnObscure "len" bytes in "buf" after receiving it.
** This function may absorb some or all of the received bytes, leaving
** fewer bytes (possibly none) in the buffer for the application to use
** than were in the buffer when the function was called.
** Function returns the number of bytes of unobscured data remaining in
** buf. Zero means all data was used internally and no data remains
** for application use. Negative number means error occurred.
*/
extern int SSMObscure_Recv( SSMObscureObject * obj,
void * buf,
unsigned int len);
/* like _Recv, but returns a flag telling when all initialization info has
** been received.
*/
extern int SSMObscure_RecvInit( SSMObscureObject * obj,
void * buf,
unsigned int len,
SSMObscureBool * done);
/*
** Destroy the Obscure Object
*/
extern int SSMObscure_Destroy(SSMObscureObject * obj);
#ifdef __cplusplus
}
#endif
#endif /* __obscure_h__ */

View File

@@ -0,0 +1,115 @@
/*
* 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):
*
* 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 "obspriv.h"
#include "newproto.h"
#include <string.h>
#include <assert.h>
#include <time.h>
/*
Originally this code was used to obscure the control messages
traveling between processes. With the relaxation of export rules,
this whole step is no longer necessary, and is included for
informational purposes only. (We need to finish removing the
obscuring code.)
*/
struct obscureNOPStr {
SSMObscureObject * obj;
};
typedef struct obscureNOPStr obscureV1;
static int
ssmObscure_Destroy(void * privData)
{
obscureV1 * priv = (obscureV1 *)privData;
memset(priv, 0, sizeof *priv);
cmt_free(priv);
return 0;
}
static int
ssmObscure_Send(void * privData, void * buf, unsigned int len)
{
/* obscureV1 * priv = (obscureV1 *)privData;*/
/* NOP */
return len;
}
static int
ssmObscure_Recv(void * privData, void * buf, unsigned int len)
{
/*obscureV1 * priv = (obscureV1 *)privData;*/
/* NOP */
return len;
}
static int
ssmObscure_SendInit(void * privData, void * buf)
{
/*obscureV1 * priv = (obscureV1 *)privData;*/
return 0;
}
static int
ssmObscure_RecvInit(void * privData, void * buf, unsigned int len,
SSMObscureBool * pDone)
{
return 0;
}
static void *
ssmObscure_InitPrivate(SSMObscureObject * obj, SSMObscureBool IsServer)
{
obscureV1 * priv = (obscureV1 *) cmt_alloc(sizeof (obscureV1));
if (!priv)
return NULL;
priv->obj = obj;
obj->privData = (void *)priv;
obj->destroy = ssmObscure_Destroy;
obj->send = ssmObscure_Send;
obj->recv = ssmObscure_Recv;
obj->sendInit = ssmObscure_SendInit;
obj->recvInit = ssmObscure_RecvInit;
return priv;
}
obsInitFn SSMObscure_InitPrivate = ssmObscure_InitPrivate;

View File

@@ -0,0 +1,63 @@
/*
* 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):
*
* 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 "obscure.h"
typedef void * (* obsInitFn) (SSMObscureObject * instance,
SSMObscureBool IsServer);
typedef int (* obsDestroyFn) (void * priv);
typedef int (* obsSendFn) (void * priv, void * buf, unsigned int len);
typedef int (* obsRecvFn) (void * priv, void * buf, unsigned int len);
typedef int (* obsSendInitFn)(void * priv, void * buf);
typedef int (* obsRecvInitFn)(void * priv, void * buf, unsigned int len,
SSMObscureBool * done);
struct SSMObscureObjectStr {
void * privData;
obsDestroyFn destroy;
obsSendFn send;
obsRecvFn recv;
obsSendInitFn sendInit;
obsRecvInitFn recvInit;
};
/* This is common to the beginning of all versions of the obscuring protocol */
struct SSMInitMsgHdrStr {
short version;
short length;
};
typedef struct SSMInitMsgHdrStr SSMInitMsgHdr;
extern obsInitFn SSMObscure_InitPrivate;

View File

@@ -0,0 +1,141 @@
/*
* 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):
*
* 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.
*/
/*
protocol.h - Definitions of various items to support the PSM protocol.
*/
#ifndef __PROTOCOL_H__
#define __PROTOCOL_H__
#include "rsrcids.h"
#define SSMPRStatus SSMStatus
#define SSMPR_SUCCESS SSM_SUCCESS
#define SSMPR_FAILURE SSM_FAILURE
#define SSMPR_INVALID_ARGUMENT_ERROR PR_INVALID_ARGUMENT_ERROR
#define SSMPR_OUT_OF_MEMORY_ERROR PR_OUT_OF_MEMORY_ERROR
#define SSMPRInt32 PRInt32
#define SSMPRUint32 PRUint32
#define SSMPR_ntohl PR_ntohl
#define SSMPR_htonl PR_htonl
#define SSMPORT_Free PORT_Free
#define SSMPORT_ZAlloc PORT_ZAlloc
#define SSMPR_SetError PR_SetError
#define SSMPR_GetError PR_GetError
#define SSMPORT_SetError PORT_SetError
#define SSMPORT_GetError PORT_GetError
/*
Current version of PSM protocol.
Increment this value when the protocol changes.
*/
#define SSMSTRING_PADDED_LENGTH(x) ((((x)+3)/4)*4)
#define SSMPORT_ZNEW(type) (type*)SSMPORT_ZAlloc(sizeof(type))
#define SSMPORT_ZNewArray(type,size) (type*)SSMPORT_ZAlloc(sizeof(type)*(size))
/* Various message structs */
struct _SSMHelloRequest {
CMUint32 m_version; /* Protocol version supported by client */
struct _SSMString m_profileName; /* Name of user profile (where to find
certs etc) */
};
struct _SSMHelloReply {
CMInt32 m_result; /* Error, if any, which occurred
(0 == success) */
CMUint32 m_version; /* Protocol version supported by PSM */
struct _SSMString m_nonce; /* Session nonce -- must be written to data channels */
};
struct _SSMRequestSSLDataConnection
{
CMUint32 m_flags; /* Flags to indicate to SSM what to do with
the connection */
CMUint32 m_port; /* Port number to connect to */
struct _SSMString m_hostIP; /* IP address of final target machine (not proxy) */
/* struct _SSMString m_hostName; Host name of target machine (for server auth) -- not accessed directly */
};
struct _SSMReplySSLDataConnection {
CMInt32 m_result; /* Error, if any, which occurred (0 == success) */
CMUint32 m_connectionID; /* Connection ID of newly opened channel */
CMUint32 m_port; /* Port number to which to connect on PSM */
};
struct _SSMRequestSecurityStatus {
CMUint32 m_connectionID; /* ID of connection of which to stat */
};
struct _SSMReplySecurityStatus {
CMInt32 m_result; /* Error, if any, which occurred (0 == success) */
CMUint32 m_keySize; /* Key size */
CMUint32 m_secretKeySize; /* Secret key size */
struct _SSMString m_cipherName; /* Name of cipher in use */
/* SSMString m_certificate; -- DER encoded cert
We do not access this as a field, we have to skip over m_cipherName */
};
/*
Use this macro to jump over strings.
For example, if you wanted to access m_certificate above,
use a line like the following:
char *ptr = &(reply->m_cipherName) + SSM_SIZEOF_STRING(reply->m_cipherName);
*/
#define SSM_SIZEOF_STRING(str) (SSMSTRING_PADDED_LENGTH(PR_ntohl((str).m_length)) + sizeof(CMUint32))
typedef struct _SSMHelloRequest SSMHelloRequest;
typedef struct _SSMHelloReply SSMHelloReply;
typedef struct _SSMRequestSSLDataConnection SSMRequestSSLDataConnection;
typedef struct _SSMReplySSLDataConnection SSMReplySSLDataConnection;
typedef struct _SSMRequestSecurityStatus SSMRequestSecurityStatus;
typedef struct _SSMReplySecurityStatus SSMReplySecurityStatus;
/*
Functions to convert between an SSMString and a C string.
Return values are allocated using PR_Malloc (which means that
SSMPR_Free must be used to free up the memory after use).
*/
CMTStatus SSM_StringToSSMString(SSMString ** ssmString, int len, char * string);
CMTStatus SSM_SSMStringToString(char ** string,int *len, SSMString * ssmString);
#endif /* __PROTOCOL_H__ */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,359 @@
/*
* 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):
*
* 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 __PROTOCOLF_H__
#define __PROTOCOLF_H__
/*************************************************************************
* For each type of message, parse and pack function is provided.
*
* Parse functions accept a ptr to the "blob" of data received from the
* network and fill in fields of the message, numbers in host-order, strings
* as C-style NULL-terminated strings. Return SSMPRStatus.
*
* Pack functions take all the info to construct a message and fill in a
* ptr to the "blob" of data to be sent. Return length of the data blob, or
* a zero in case of an error
*
* All functions set NSPR errors when necessary.
************************************************************************/
#include "protocol.h"
#include "cert.h"
SSMPRStatus SSM_ParseHelloRequest(void * helloRequest,
SSMPRUint32 * version,
PRBool * doesUI,
PRInt32 * policyType,
SSMPRUint32 * profileLen,
char ** profile);
SSMPRInt32 SSM_PackHelloReply(void ** helloReply, SSMPRInt32 result,
SSMPRUint32 sessionID, SSMPRUint32 version,
SSMPRUint32 httpPort, SSMPRUint32 nonceLen,
char * nonce, SSMPolicyType policy);
/* Parse data connections requests */
SSMPRStatus SSM_ParseSSLDataConnectionRequest(void *sslRequest,
SSMPRUint32 * flags,
SSMPRUint32 * port,
SSMPRUint32 * hostIPLen,
char ** hostIP,
SSMPRUint32 * hostNameLen,
char ** hostName);
SSMPRStatus SSM_ParseHashStreamRequest(void * hashStreamRequest,
SSMPRUint32 * type);
SSMPRStatus SSM_ParseP7EncodeConnectionRequest(void *request,
SSMPRUint32 *ciRID);
/* Messages to initiate PKCS7 data connection */
/* PKCS7DecodeRequest message has no data */
/* Single data connection reply */
SSMPRInt32 SSM_PackDataConnectionReply(void ** sslReply,
SSMPRInt32 result,
SSMPRUint32 connID,
SSMPRUint32 port);
SSMPRStatus SSM_ParseSSLSocketStatusRequest(void * statusRequest,
SSMPRUint32 * connID);
SSMPRInt32 SSM_PackSSLSocketStatusReply(void ** statusReply,
SSMPRInt32 result,
SSMPRUint32 resourceID);
/*
* UI event is an asynchroneous message sent from PSM server to the client
* NOTE: (context) is the actual context pointer, it is NOT a ptr-to-ptr.
* The value of (context) is copied into the packet.
*/
SSMPRInt32 SSM_PackUIEvent(void ** eventRequest, SSMPRUint32 resourceID,
SSMPRUint32 width, SSMPRUint32 height,
SSMPRUint32 urlLen, char * url);
SSMPRInt32 SSM_PackTaskCompletedEvent(void **event, SSMPRUint32 resourceID,
SSMPRUint32 numTasks, SSMPRUint32 result);
/* Verify raw signature */
SSMPRStatus SSM_ParseVerifyRawSigRequest(void * verifyRawSigRequest,
SSMPRUint32 * algorithmID,
SSMPRUint32 * paramsLen,
unsigned char ** params,
SSMPRUint32 * pubKeyLen,
unsigned char ** pubKey,
SSMPRUint32 * hashLen,
unsigned char ** hash,
SSMPRUint32 * signatureLen,
unsigned char ** signature);
SSMPRInt32 SSM_PackVerifyRawSigReply(void ** verifyRawSigReply,
SSMPRInt32 result);
/* Verify detached signature */
SSMPRStatus SSM_ParseVerifyDetachedSigRequest(void * request,
SSMPRInt32 * pkcs7ContentID,
SSMPRInt32 * certUsage,
SSMPRInt32 * hashAlgID,
SSMPRUint32 * keepCert,
SSMPRUint32 * digestLen,
unsigned char ** hash);
SSMPRInt32 SSM_PackVerifyDetachedSigReply(void ** verifyDetachedSigReply,
SSMPRInt32 result);
/* PKCS#7 functions */
SSMPRStatus SSM_ParseCreateSignedRequest(void *request,
SSMPRInt32 *scertRID,
SSMPRInt32 *ecertRID,
SSMPRUint32 *dig_alg,
SECItem **digest);
SSMPRInt32 SSM_PackCreateSignedReply(void **reply, SSMPRInt32 ciRID,
SSMPRUint32 result);
SSMPRStatus SSM_ParseCreateEncryptedRequest(void *request,
SSMPRInt32 *scertRID,
SSMPRInt32 *nrcerts,
SSMPRInt32 **rcertRIDs);
SSMPRInt32 SSM_PackCreateEncryptedReply(void **reply, SSMPRInt32 ciRID,
SSMPRUint32 result);
/* Resource functions */
SSMPRStatus SSM_ParseCreateResourceRequest(void *request,
SSMPRUint32 *type,
unsigned char **params,
SSMPRUint32 *paramLen);
SSMPRStatus SSM_PackCreateResourceReply(void **reply, SSMPRStatus rv,
SSMPRUint32 resID);
SSMPRStatus SSM_ParseGetAttribRequest(void * getAttribRequest,
SSMPRUint32 * resourceID,
SSMPRUint32 * fieldID);
void SSM_DestroyAttrValue(SSMAttributeValue *value, PRBool freeit);
SSMPRInt32 SSM_PackGetAttribReply(void **getAttribReply,
SSMPRInt32 result,
SSMAttributeValue *value);
SSMPRStatus SSM_ParseSetAttribRequest(SECItem *msg,
SSMPRInt32 *resourceID,
SSMPRInt32 *fieldID,
SSMAttributeValue *value);
/* Currently, there is no need for a pack version. There is nothing to send
* back except for the notice that the operation was successful.
*/
/* Pickle and unpickle resources. */
SSMPRStatus SSM_ParsePickleResourceRequest(void * pickleResourceRequest,
SSMPRUint32 * resourceID);
SSMPRInt32 SSM_PackPickleResourceReply(void ** pickleResourceReply,
SSMPRInt32 result,
SSMPRUint32 resourceLen,
void * resource);
SSMPRStatus SSM_ParseUnpickleResourceRequest(void * unpickleResourceRequest,
SSMPRUint32 blobSize,
SSMPRUint32 * resourceType,
SSMPRUint32 * resourceLen,
void ** resource);
SSMPRInt32 SSM_PackUnpickleResourceReply(void ** unpickleResourceReply,
SSMPRInt32 result,
SSMPRUint32 resourceID);
/* Destroy resource */
SSMPRStatus SSM_ParseDestroyResourceRequest(void * destroyResourceRequest,
SSMPRUint32 * resourceID,
SSMPRUint32 * resourceType);
SSMPRInt32 SSM_PackDestroyResourceReply(void ** destroyResourceReply,
SSMPRInt32 result);
/* Duplicate resource */
SSMPRStatus SSM_ParseDuplicateResourceRequest(void * request,
SSMPRUint32 * resourceID);
SSMPRInt32 SSM_PackDuplicateResourceReply(void ** reply, SSMPRInt32 result,
SSMPRUint32 resID);
/* Cert actions */
typedef struct MatchUserCertRequestData {
PRUint32 certType;
PRInt32 numCANames;
char ** caNames;
} MatchUserCertRequestData;
typedef struct SSMCertList {
PRCList certs;
PRInt32 count;
} SSMCertList;
typedef struct SSMCertListElement {
PRCList links;
PRUint32 certResID;
} SSMCertListElement;
#define SSM_CERT_LIST_ELEMENT_PTR(_q) (SSMCertListElement*)(_q);
SSMPRStatus SSM_ParseVerifyCertRequest(void * verifyCertRequest,
SSMPRUint32 * resourceID,
SSMPRInt32 * certUsage);
SSMPRInt32 SSM_PackVerifyCertReply(void ** verifyCertReply,
SSMPRInt32 result);
SSMPRStatus SSM_ParseImportCertRequest(void * importCertRequest,
SSMPRUint32 * blobLen,
void ** certBlob);
SSMPRInt32 SSM_PackImportCertReply(void ** importCertReply, SSMPRInt32 result,
SSMPRUint32 resourceID);
PRStatus SSM_ParseFindCertByNicknameRequest(void *request, char ** nickname);
PRInt32 SSM_PackFindCertByNicknameReply(void ** reply, PRUint32 resourceID);
PRStatus SSM_ParseFindCertByKeyRequest(void *request, SECItem ** key);
PRInt32 SSM_PackFindCertByKeyReply(void ** reply, PRUint32 resourceID);
PRStatus SSM_ParseFindCertByEmailAddrRequest(void *request, char ** emailAddr);
PRInt32 SSM_PackFindCertByEmailAddrReply(void ** reply, PRUint32 resourceID);
PRStatus SSM_ParseAddTempCertToDBRequest(void *request, PRUint32 *resourceID, char ** nickname, PRInt32 *ssl, PRInt32 *email, PRInt32 *objectSigning);
PRInt32 SSM_PackAddTempCertToDBReply(void ** reply);
PRStatus SSM_ParseMatchUserCertRequest(void *request, MatchUserCertRequestData** data);
PRInt32 SSM_PackMatchUserCertReply(void **reply, SSMCertList * certList);
SSMPRInt32 SSM_PackErrorMessage(void ** errorReply, SSMPRInt32 result);
/* PKCS11 actions */
SSMPRStatus SSM_ParseKeyPairGenRequest(void *keyPairGenRequest,
SSMPRInt32 requestLen,
SSMPRUint32 *keyPairCtxtID,
SSMPRUint32 *genMechanism,
SSMPRUint32 *keySize,
unsigned char **params,
SSMPRUint32 *paramLen);
SSMPRInt32 SSM_PackKeyPairGenResponse(void ** keyPairGenResponse,
SSMPRUint32 keyPairId);
PRStatus
SSM_ParseFinishKeyGenRequest(void *finishKeyGenRequest,
PRInt32 requestLen,
PRInt32 *keyGenContext);
/* CMMF/CRMF Actions */
SSMPRStatus SSM_ParseCreateCRMFReqRequest(void *crmfReqRequest,
SSMPRInt32 requestLen,
SSMPRUint32 *keyPairId);
SSMPRInt32 SSM_PackCreateCRMFReqReply(void **crmfReqReply,
SSMPRUint32 crmfReqId);
SSMPRStatus SSM_ParseEncodeCRMFReqRequest(void *encodeReq,
SSMPRInt32 requestLen,
SSMPRUint32 **crmfReqId,
SSMPRInt32 *numRequests);
SSMPRInt32 SSM_PackEncodeCRMFReqReply(void **encodeReply,
char *crmfDER,
SSMPRUint32 derLen);
SSMPRStatus SSM_ParseCMMFCertResponse(void *encodedRes,
SSMPRInt32 encodeLen,
char **nickname,
char **base64Der,
PRBool *doBackup);
PRStatus SSM_ParsePOPChallengeRequest(void *challenge,
PRInt32 len,
char **responseString);
PRInt32 SSM_PackPOPChallengeResponse(void **response,
char *responseString,
PRInt32 responseStringLen);
PRInt32 SSM_PackPasswdRequest(void ** passwdRequest, PRInt32 tokenID,
char * prompt, PRInt32 promptLen);
PRStatus SSM_ParsePasswordReply(void * passwdReply, PRInt32 * result,
PRInt32 * tokenID,
char ** passwd, PRInt32 * passwdLen);
/* Sign Text Actions */
typedef struct {
char *stringToSign;
char *hostName;
char *caOption;
PRInt32 numCAs;
char **caNames;
} signTextRequestData;
PRStatus SSM_ParseSignTextRequest(void* signTextRequest, PRInt32 len, PRUint32* resID, signTextRequestData ** data);
PRStatus SSM_ParseGetLocalizedTextRequest(void *data,
SSMLocalizedString *whichString);
PRInt32 SSM_PackGetLocalizedTextResponse(void **data,
SSMLocalizedString whichString,
char *retString);
PRStatus SSM_ParseAddNewSecurityModuleRequest(void *data,
char **moduleName,
char **libraryPath,
unsigned long *pubMechFlags,
unsigned long *pubCipherFlags);
PRInt32 SSM_PackAddNewModuleResponse(void **data, PRInt32 rv);
PRStatus SSM_ParseDeleteSecurityModuleRequest(void *data, char **moduleName);
PRInt32 SSM_PackDeleteModuleResponse(void **data, PRInt32 moduleType);
PRInt32 SSM_PackFilePathRequest(void **data, PRInt32 resID, char *prompt,
PRBool shouldFileExist, char *fileSuffix);
PRStatus SSM_ParseFilePathReply(void *message, char **filePath,
PRInt32 *rid);
PRInt32 SSM_PackPromptRequestEvent(void **data, PRInt32 resID, char *prompt);
PRStatus SSM_ParsePasswordPromptReply(void *data, PRInt32 *resID,
char **reply);
/* messages for importing certs *the traditional way* */
PRInt32 SSM_PackDecodeCertReply(void ** data, PRInt32 certID);
PRStatus SSM_ParseDecodeCertRequest(void * data, PRInt32 * len,
char ** buffer);
PRStatus SSM_ParseGetKeyChoiceListRequest(void * data, PRUint32 dataLen,
char ** type, PRUint32 *typeLen,
char ** pqgString, PRUint32 *pqgLen);
PRInt32 SSM_PackGetKeyChoiceListReply(void **data, char ** list);
PRStatus SSM_ParseGenKeyOldStyleRequest(void * data, PRUint32 datalen,
char ** choiceString,
char ** challenge,
char ** typeString,
char ** pqgString);
PRInt32 SSM_PackGenKeyOldStyleReply(void ** data, char * keydata);
PRStatus SSM_ParseDecodeAndCreateTempCertRequest(void * data,
char ** certbuf, PRUint32 * certlen, int * certClass);
#endif /*PROTOCOLF_H_*/

View File

@@ -0,0 +1,74 @@
/*
* 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):
*
* 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 NULL
#define NULL 0x00000000
#endif
#define SSMPR_BYTES_PER_INT 4
#define SSMPR_BYTES_PER_LONG 4
/******************************************************************
* No NSPR - define all the SSMPR values and functions here
******************************************************************
*/
#define SSMPRStatus PRStatus
#define SSMPR_SUCCESS PR_SUCCESS
#define SSMPR_FAILURE PR_FAILURE
#define SSMPR_INVALID_ARGUMENT_ERROR PR_INVALID_ARGUMENT_ERROR
#define SSMPR_OUT_OF_MEMORY_ERROR PR_OUT_OF_MEMORY_ERROR
#define SSMPRInt32 PRInt32
#define SSMPRUint32 PRUint32
#define SSMPR_ntohl PR_ntohl
#define SSMPR_htonl PR_htonl
#define SSMPORT_Free PORT_Free
#define SSMPORT_ZAlloc PORT_ZAlloc
#define SSMPR_SetError PR_SetError
#define SSMPR_GetError PR_GetError
#define SSMPORT_SetError PORT_SetError
#define SSMPORT_GetError PORT_GetError

View File

@@ -0,0 +1,49 @@
/*
* 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):
*
* 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.
*/
/*************************************************************************
*
* PSM portable run-time. (Used when NSPR20 is not available.)
*
*************************************************************************
*/
SSMPRInt32 ssmprErrno;
void SSMPORT_SetError(SSMPRInt32 errorcode)
{ ssmprErrno = errorcode; }
SSMPRInt32 SSMPORT_GetError(void)
{ return ssmprErrno; }

View File

@@ -0,0 +1,93 @@
/*
* 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):
*
* 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 NULL
#define NULL 0x00000000
#endif
#define SSMPR_BYTES_PER_INT 4
#define SSMPR_BYTES_PER_LONG 4
/******************************************************************
* No NSPR - define all the SSMPR values and functions here
******************************************************************
*/
typedef enum { SSMPR_SUCCESS = 0, SSMPR_FAILURE = -1 } SSMPRStatus;
enum {
SSMPR_INVALID_ARGUMENT_ERROR = -6000,
SSMPR_OUT_OF_MEMORY_ERROR = -5987
};
#if SSMPR_BYTES_PER_INT == 4
typedef unsigned int SSMPRUint32;
typedef int SSMPRInt32;
#elif SSMPR_BYTES_PER_LONG == 4
typedef unsigned long SSMPRUint32;
typedef long SSMPRInt32;
#else
#error No suitable type for SSMPRInt32/SSMPRUint32
#endif
/*******************************************************************
* Use libc functions instead
*******************************************************************
*/
#include <sys/types.h>
#ifdef WIN32
#include <winsock.h>
#else
#include <netinet/in.h>
#endif
#define SSMPR_ntohl ntohl
#define SSMPR_htonl htonl
#include <stdlib.h>
#define SSMPORT_Free free
#define SSMPR_sprint printf
#define SSMPORT_ZAlloc malloc
extern SSMPRInt32 ssmprErrno;
#define SSMPR_SetError(x, y) SSMPORT_SetError(x)
#define SSMPR_GetError SSMPORT_GetError
void SSMPORT_SetError(SSMPRInt32 errorcode);

View File

@@ -0,0 +1,169 @@
/*
* 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):
*
* 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 "string.h"
#include "protocol.h"
#include "protocolshr.h"
#include "messages.h"
/* Forward ref */
static void encrypt(CMTItem *data);
static void decrypt(CMTItem *data);
const char *kPrefix = "Encrypted";
/* encryption request */
CMTStatus
CMT_DoEncryptionRequest(CMTItem *message)
{
CMTStatus rv = CMTSuccess;
EncryptRequestMessage request;
EncryptReplyMessage reply;
CMUint32 pLen = strlen(kPrefix);
/* Initialize */
request.keyid.data = 0;
request.data.data = 0;
reply.item.data = 0;
/* Decode incoming message */
rv = CMT_DecodeMessage(EncryptRequestTemplate, &request, message);
if (rv != CMTSuccess) goto loser; /* Protocol error */
/* Free incoming message */
free(message->data);
message->data = NULL;
/* "Encrypt" by prefixing the data */
reply.item.len = request.data.len + pLen;
reply.item.data = calloc(reply.item.len, 1);
if (!reply.item.data) {
rv = CMTFailure;
goto loser;
}
if (pLen) memcpy(reply.item.data, kPrefix, pLen);
encrypt(&request.data);
memcpy(&reply.item.data[pLen], request.data.data, request.data.len);
/* Generate response */
message->type = SSM_SDR_ENCRYPT_REPLY;
rv = CMT_EncodeMessage(EncryptReplyTemplate, message, &reply);
if (rv != CMTSuccess) goto loser; /* Unknown error */
loser:
if (request.keyid.data) free(request.keyid.data);
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv;
}
/* decryption request */
CMTStatus
CMT_DoDecryptionRequest(CMTItem *message)
{
CMTStatus rv = CMTSuccess;
DecryptRequestMessage request;
DecryptReplyMessage reply;
CMUint32 pLen = strlen(kPrefix);
/* Initialize */
request.data.data = 0;
request.ctx.data = 0;
reply.item.data = 0;
/* Decode the message */
rv = CMT_DecodeMessage(DecryptRequestTemplate, &request, message);
if (rv != CMTSuccess) goto loser;
/* Free incoming message */
free(message->data);
message->data = NULL;
/* "Decrypt" the message by removing the key */
if (pLen && memcmp(request.data.data, kPrefix, pLen) != 0) {
rv = CMTFailure; /* Invalid format */
goto loser;
}
reply.item.len = request.data.len - pLen;
reply.item.data = calloc(reply.item.len, 1);
if (!reply.item.data) { rv = CMTFailure; goto loser; }
memcpy(reply.item.data, &request.data.data[pLen], reply.item.len);
decrypt(&reply.item);
/* Create reply message */
message->type = SSM_SDR_DECRYPT_REPLY;
rv = CMT_EncodeMessage(DecryptReplyTemplate, message, &reply);
if (rv != CMTSuccess) goto loser;
loser:
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv;
}
/* "encrypt" */
static unsigned char mask[64] = {
0x73, 0x46, 0x1a, 0x05, 0x24, 0x65, 0x43, 0xb4, 0x24, 0xee, 0x79, 0xc1, 0xcc,
0x49, 0xc7, 0x27, 0x11, 0x91, 0x2e, 0x8f, 0xaa, 0xf7, 0x62, 0x75, 0x41, 0x7e,
0xb2, 0x42, 0xde, 0x1b, 0x42, 0x7b, 0x1f, 0x33, 0x49, 0xca, 0xd1, 0x6a, 0x85,
0x05, 0x6c, 0xf9, 0x0e, 0x3e, 0x72, 0x02, 0xf2, 0xd8, 0x9d, 0xa1, 0xb8, 0x6e,
0x03, 0x18, 0x3e, 0x82, 0x86, 0x34, 0x1a, 0x61, 0xd9, 0x65, 0xb6, 0x7f
};
static void
encrypt(CMTItem *data)
{
unsigned int i, j;
j = 0;
for(i = 0;i < data->len;i++)
{
data->data[i] ^= mask[j];
if (++j >= 64) j = 0;
}
}
static void
decrypt(CMTItem *data)
{
encrypt(data);
}

View File

@@ -0,0 +1,48 @@
/*
* 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):
*
* 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.
*/
/*
protocolshr.h - Definitions of shared routines for both client and server
These are mostly for testing.
*/
#ifndef __PROTOCOLSHR_H__
#define __PROTOCOLSHR_H__
CMTStatus
CMT_DoEncryptionRequest(CMTItem *message);
CMTStatus
CMT_DoDecryptionRequest(CMTItem *meessage);
#endif /* __PROTOCOLSHR_H__ */

View File

@@ -0,0 +1,207 @@
/*
* 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):
*
* 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 "protocolf.h"
#include <stdio.h>
int main()
{
void * blob, * recvd;
int blobSize;
SSMPRUint32 version, flags, port, connID, keySize, secretKeySize;
SSMPRUint32 sessionID, httpPort;
SSMPRInt32 result;
char *profile, * nonce, * hostIP, * hostName, * cipher, * CA;
SSMPRStatus rv;
/*
* Test functions to pack and parse HelloRequest message
*/
version = 3;
profile = (char *)SSMPORT_ZAlloc(strlen("profile"));
sprintf(profile, "profile");
printf("HelloRequest, packing version #%d, profile %s\n",
version, profile);
blobSize = SSM_PackHelloRequest(&blob, version, profile);
if (!blobSize)
printf("Error in PackHelloRequest: %d\n", SSMPR_GetError());
SSMPORT_Free(profile);
version = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseHelloRequest(recvd, &version, &profile);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseHelloRequest: %d\n", SSMPR_GetError());
printf("HelloRequest, parsing version #%d, profile %s\n",
version, profile);
/*
* Test functions to parse and pack HelloReply message
*/
version = 5;
result = 2;
sessionID = 34567;
httpPort = 87654;
nonce = (char *)SSMPORT_ZAlloc(strlen("some secret nonce"));
sprintf(nonce, "some secret nonce");
printf("HelloReply, packing result %d, sessionID %d, version #%d, httpPort %d,\n nonce %s\n",
result, sessionID, version, httpPort, nonce);
blobSize = SSM_PackHelloReply(&blob, result, sessionID, version, httpPort,
nonce);
if (!blobSize)
printf("Error in PackHelloReply: %d\n", SSMPR_GetError());
memset(nonce, 0, strlen(nonce));
SSMPORT_Free(nonce);
version = result = sessionID = httpPort = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseHelloReply(recvd, &result, &sessionID, &version, &httpPort,
&nonce);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseHelloReply: %d\n", SSMPR_GetError());
printf("HelloReply, parsing result %d, sessionID %d, version #%d, httpPort %d, \n nonce %s\n",
result, sessionID, version, httpPort, nonce);
/*
* Test functions to parse and pack SSLDataConnectionRequest message
*/
flags = 0x00044000;
port = 34567;
hostIP = (char *)SSMPORT_ZAlloc(strlen("somehostIP"));
sprintf(hostIP, "somehostIP");
hostName = (char *)SSMPORT_ZAlloc(strlen("somehostName"));
sprintf(hostName, "somehostName");
printf("SSLDataConnRequest, packing flags %x, port %d, hostIP %s, hostName %s\n",
flags, port, hostIP, hostName);
blobSize = SSM_PackSSLDataConnectionRequest(&blob, flags, port, hostIP,
hostName);
if (!blobSize)
printf("Error in PackSSLDataConnectionRequest: %d\n", SSMPR_GetError());
SSMPORT_Free(hostIP);
SSMPORT_Free(hostName);
flags = port = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSSLDataConnectionRequest(recvd, &flags, &port, &hostIP,
&hostName);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSSLDataConnectionRequest: %d\n", SSMPR_GetError());
printf(
"SSLDataConnRequest, parsing flags %x, port %d, hostIP %s, hostName %s\n",
flags, port, hostIP, hostName);
SSMPORT_Free(hostIP);
SSMPORT_Free(hostName);
/*
* Test functions to parse and pack SSLDataConnectionReply message
*/
result = 2;
connID = 713259;
port = 57402;
printf("SSLDataConnReply, packing result %d, connectionID %d, port %d\n",
result, connID, port);
blobSize = SSM_PackSSLDataConnectionReply(&blob, result, connID, port);
if (!blobSize)
printf("Error in PackSSLDataConnReply: %d\n", SSMPR_GetError());
result = connID = port = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSSLDataConnectionReply(recvd, &result, &connID, &port);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSSLDataConnectionReply: %d\n", SSMPR_GetError());
printf("SSLDataConnReply, parsing result %d, connectionID %d, port %d\n",
result, connID, port);
/*
* Test functions to parse and pack SecurityStatusRequest message
*/
connID = 45375;
printf("SecurityStatusRequest, packing connection ID %d\n", connID);
blobSize = SSM_PackSecurityStatusRequest(&blob, connID);
if (!blobSize)
printf("Error in PackSecurityStatusRequest: %d\n", SSMPR_GetError());
connID = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSecurityStatusRequest(recvd, &connID);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSecurityStatusRequest: %d\n", SSMPR_GetError());
printf("SecurityStatusRequest, parsing connection ID %d\n", connID);
/*
* Test functions to parse and pack SecurityStatusReply message
*/
result = 2;
keySize = 256;
secretKeySize = 511;
cipher = (char *)SSMPORT_ZAlloc(strlen("My Cipher"));
sprintf(cipher, "My Cipher");
CA = (char *)SSMPORT_ZAlloc(strlen("My CA issuer"));
sprintf(CA, "My CA issuer");
printf("SecurityStatusReply, packing result %d, keysize %d, secretKeySize %d, cipher %s, CA %s\n", result, keySize, secretKeySize, cipher, CA);
blobSize = SSM_PackSecurityStatusReply(&blob, result, keySize, secretKeySize, cipher, CA);
if (!blobSize)
printf("Error in PackSecurityStatusReply: %d\n", SSMPR_GetError());
result = keySize = secretKeySize = 0;
SSMPORT_Free(cipher);
SSMPORT_Free(CA);
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSecurityStatusReply(recvd, &result, &keySize, &secretKeySize,
&cipher, &CA);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSecurityStatusReply: %d\n", SSMPR_GetError());
printf("SecurityStatusReply, parsing result %d, keysize %d, secretKeySize %d, cipher %s, CA %s\n", result, keySize, secretKeySize, cipher, CA);
}

View File

@@ -0,0 +1,130 @@
/*
* 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):
*
* 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 "protocol.h"
#include "prmem.h"
#include "prnetdb.h"
#include <string.h>
#ifndef NSPR20
#include "protocolport.c"
#endif
CMStatus SSM_SSMStringToString(char ** string,
int *len,
SSMString * ssmString)
{
char * str = NULL;
int realLen;
PRStatus rv =PR_SUCCESS;
if (!ssmString || !string ) {
rv = PR_INVALID_ARGUMENT_ERROR;
goto loser;
}
/* in case we fail */
*string = NULL;
if (len) *len = 0;
/* Convert from net byte order */
realLen = SSMPR_ntohl(ssmString->m_length);
str = (char *)PR_CALLOC(realLen+1); /* add 1 byte for end 0 */
if (!str) {
rv = PR_OUT_OF_MEMORY_ERROR;
goto loser;
}
memcpy(str, (char *) &(ssmString->m_data), realLen);
/* str[realLen]=0; */
if (len) *len = realLen;
*string = str;
return rv;
loser:
if (str)
PR_Free(str);
if (string && *string) {
PR_Free(*string);
*string = NULL;
}
if (rv == PR_SUCCESS)
rv = PR_FAILURE;
return rv;
}
CMStatus SSM_StringToSSMString(SSMString ** ssmString, int length,
char * string)
{
SSMPRUint32 len;
SSMString *result = NULL;
PRStatus rv = PR_SUCCESS;
if (!string || !ssmString) {
rv = PR_INVALID_ARGUMENT_ERROR;
goto loser;
}
*ssmString = NULL; /* in case we fail */
if (length) len = length;
else len = strlen(string);
if (len <= 0) {
rv = PR_INVALID_ARGUMENT_ERROR;
goto loser;
}
result = (SSMString *) PR_CALLOC(sizeof(PRUint32) +
SSMSTRING_PADDED_LENGTH(len));
if (!result) {
rv = PR_OUT_OF_MEMORY_ERROR;
goto loser;
}
result->m_length = SSMPR_htonl(len);
memcpy((char *) (&(result->m_data)), string, len);
*ssmString = result;
goto done;
loser:
if (result)
PR_Free(result);
*ssmString = NULL;
if (rv == PR_SUCCESS)
rv = PR_FAILURE;
done:
return rv;
}

View File

@@ -0,0 +1,165 @@
/* -*- mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 __SSM_RSRCIDS_H__
#define __SSM_RSRCIDS_H__
#include "ssmdefs.h"
/*
* IMPORTANT:
*
* To preserve backward compatibility as much as possible, always add new
* values to either one of the enumeration tables at the end of the table.
*/
typedef enum
{
SSM_RESTYPE_NULL = 0L,
SSM_RESTYPE_RESOURCE,
SSM_RESTYPE_CONNECTION,
SSM_RESTYPE_CONTROL_CONNECTION,
SSM_RESTYPE_DATA_CONNECTION,
SSM_RESTYPE_SSL_DATA_CONNECTION,
SSM_RESTYPE_PKCS7_DECODE_CONNECTION,
SSM_RESTYPE_PKCS7_ENCODE_CONNECTION,
SSM_RESTYPE_HASH_CONNECTION,
SSM_RESTYPE_CERTIFICATE,
SSM_RESTYPE_SSL_SOCKET_STATUS,
SSM_RESTYPE_PKCS7_CONTENT_INFO,
SSM_RESTYPE_KEY_PAIR,
SSM_RESTYPE_CRMF_REQUEST,
SSM_RESTYPE_KEYGEN_CONTEXT,
SSM_RESTYPE_SECADVISOR_CONTEXT,
SSM_RESTYPE_SIGNTEXT,
SSM_RESTYPE_PKCS12_CONTEXT,
SSM_RESTYPE_MAX
} SSMResourceType;
/* Attribute/resource types */
/* Attribute IDs */
typedef enum
{
SSM_FID_NULL = (CMUint32) 0, /* placeholder */
/* Connection attributes */
SSM_FID_CONN_ALIVE,
SSM_FID_CONN_PARENT,
/* Data connection attributes */
SSM_FID_CONN_DATA_PENDING,
/* SSL data connection attributes */
SSM_FID_SSLDATA_SOCKET_STATUS,
SSM_FID_SSLDATA_ERROR_VALUE,
/* PKCS7 decode connection attributes */
SSM_FID_P7CONN_CONTENT_INFO,
SSM_FID_P7CONN_RETURN_VALUE,
SSM_FID_P7CONN_ERROR_VALUE,
/* Hash connection attributes */
SSM_FID_HASHCONN_RESULT,
/* Certificate attributes */
SSM_FID_CERT_SUBJECT_NAME,
SSM_FID_CERT_ISSUER_NAME,
SSM_FID_CERT_SERIAL_NUMBER,
SSM_FID_CERT_EXP_DATE,
SSM_FID_CERT_FINGERPRINT,
SSM_FID_CERT_COMMON_NAME,
SSM_FID_CERT_NICKNAME,
SSM_FID_CERT_ORG_NAME,
SSM_FID_CERT_HTML_CERT,
SSM_FID_CERT_PICKLE_CERT,
SSM_FID_CERT_CERTKEY,
SSM_FID_CERT_FIND_CERT_ISSUER,
SSM_FID_CERT_EMAIL_ADDRESS,
SSM_FID_CERT_ISPERM,
/* SSL socket status attributes */
SSM_FID_SSS_KEYSIZE,
SSM_FID_SSS_SECRET_KEYSIZE,
SSM_FID_SSS_CERT_ID,
SSM_FID_SSS_CIPHER_NAME,
SSM_FID_SSS_SECURITY_LEVEL,
SSM_FID_SSS_HTML_STATUS,
/* PKCS7 content info attributes */
SSM_FID_P7CINFO_IS_SIGNED,
SSM_FID_P7CINFO_IS_ENCRYPTED,
SSM_FID_P7CINFO_SIGNER_CERT,
/* CRMF ID's */
SSM_FID_CRMFREQ_REGTOKEN,
SSM_FID_CRMFREQ_AUTHENTICATOR,
SSM_FID_CRMFREQ_EXTENSIONS,
SSM_FID_CRMFREQ_KEY_TYPE,
SSM_FID_CRMFREQ_DN,
/* Security advisor context */
SSM_FID_SECADVISOR_URL,
SSM_FID_SECADVISOR_WIDTH,
SSM_FID_SECADVISOR_HEIGHT,
/* Sign Text */
SSM_FID_SIGNTEXT_RESULT,
/* Key Gen ID's */
SSM_FID_KEYGEN_ESCROW_AUTHORITY,
/* Key Pair ID's */
SSM_FID_KEYPAIR_KEY_GEN_TYPE,
/* Session Attributes */
SSM_FID_DEFAULT_EMAIL_RECIPIENT_CERT,
SSM_FID_DEFAULT_EMAIL_SIGNER_CERT,
/* Client Context Attribute */
SSM_FID_CLIENT_CONTEXT,
/* Resource Error */
SSM_FID_RESOURCE_ERROR,
SSM_FID_KEYGEN_SLOT_NAME,
SSM_FID_DISABLE_ESCROW_WARN,
SSM_FID_KEYGEN_TOKEN_NAME,
SSM_FID_SSLDATA_DISCARD_SOCKET_STATUS,
SSM_FID_MAX /* placeholder */
} SSMAttributeID;
#endif

View File

@@ -0,0 +1,324 @@
/* -*- mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 __SSMDEFS_H__
#define __SSMDEFS_H__
/* Basic type definitions for both client and server. */
typedef long CMInt32;
typedef unsigned long CMUint32;
typedef long SSMResourceID;
typedef int SSMStatus;
#define PSM_PORT 11111
#define PSM_DATA_PORT 11113 /* needs to be removed */
typedef enum _CMTStatus {
CMTFailure = -1,
CMTSuccess = 0
} CMTStatus;
typedef enum {
CM_FALSE = 0,
CM_TRUE = 1
} CMBool;
typedef struct CMTItemStr {
CMUint32 type;
unsigned char *data;
unsigned int len;
} CMTItem;
/* A length-encoded string. */
struct _SSMString {
CMUint32 m_length;
char m_data;
};
typedef struct _SSMString SSMString;
#define SSM_PROTOCOL_VERSION 0x00000051
#define SSM_INVALID_RESOURCE 0x00000000
#define SSM_GLOBAL_RESOURCE 0x00000001
#define SSM_SESSION_RESOURCE 0x00000002
/* Message category flags */
#define SSM_REQUEST_MESSAGE 0x10000000
#define SSM_REPLY_OK_MESSAGE 0x20000000
#define SSM_REPLY_ERR_MESSAGE 0x30000000
#define SSM_EVENT_MESSAGE 0x40000000
/* Message types */
#define SSM_DATA_CONNECTION 0x00001000
#define SSM_OBJECT_SIGNING 0x00002000
#define SSM_RESOURCE_ACTION 0x00003000
#define SSM_CERT_ACTION 0x00004000
#define SSM_PKCS11_ACTION 0x00005000
#define SSM_CRMF_ACTION 0x00006000
#define SSM_FORMSIGN_ACTION 0x00007000
#define SSM_LOCALIZED_TEXT 0x00008000
#define SSM_HELLO_MESSAGE 0x00009000
#define SSM_SECURITY_ADVISOR 0x0000a000
#define SSM_SEC_CFG_ACTION 0x0000b000
#define SSM_KEYGEN_TAG 0x0000c000
#define SSM_PREF_ACTION 0x0000d000
#define SSM_MISC_ACTION 0x0000f000
/* Data connection messages subtypes */
#define SSM_SSL_CONNECTION 0x00000100
#define SSM_PKCS7DECODE_STREAM 0x00000200
#define SSM_PKCS7ENCODE_STREAM 0x00000300
#define SSM_HASH_STREAM 0x00000400
#define SSM_TLS_CONNECTION 0x00000500
#define SSM_PROXY_CONNECTION 0x00000600
/* Object signing message subtypes */
#define SSM_VERIFY_RAW_SIG 0x00000100
#define SSM_VERIFY_DETACHED_SIG 0x00000200
#define SSM_CREATE_SIGNED 0x00000300
#define SSM_CREATE_ENCRYPTED 0x00000400
/* Resource access messages subtypes */
#define SSM_CREATE_RESOURCE 0x00000100
#define SSM_DESTROY_RESOURCE 0x00000200
#define SSM_GET_ATTRIBUTE 0x00000300
#define SSM_CONSERVE_RESOURCE 0x00000400
#define SSM_DUPLICATE_RESOURCE 0x00000500
#define SSM_SET_ATTRIBUTE 0x00000600
#define SSM_TLS_STEPUP 0x00000700
#define SSM_PROXY_STEPUP 0x00000800
/* Further specification for resource access messages */
#define SSM_SSLSocket_Status 0x00000010
#define SSM_NO_ATTRIBUTE 0x00000000
#define SSM_NUMERIC_ATTRIBUTE 0x00000010
#define SSM_STRING_ATTRIBUTE 0x00000020
#define SSM_RID_ATTRIBUTE 0x00000030
#define SSM_PICKLE_RESOURCE 0x00000010
#define SSM_UNPICKLE_RESOURCE 0x00000020
#define SSM_PICKLE_SECURITY_STATUS 0x00000030
/* Certificate access message subtypes */
#define SSM_IMPORT_CERT 0x00000100
#define SSM_VERIFY_CERT 0x00000200
#define SSM_FIND_BY_NICKNAME 0x00000300
#define SSM_FIND_BY_KEY 0x00000400
#define SSM_FIND_BY_EMAILADDR 0x00000500
#define SSM_ADD_TO_DB 0x00000600
#define SSM_DECODE_CERT 0x00000700
#define SSM_MATCH_USER_CERT 0x00000800
#define SSM_DESTROY_CERT 0x00000900
#define SSM_DECODE_TEMP_CERT 0x00000a00
#define SSM_REDIRECT_COMPARE 0x00000b00
#define SSM_DECODE_CRL 0x00000c00
#define SSM_EXTENSION_VALUE 0x00000d00
#define SSM_HTML_INFO 0x00000e00
/* message subtypes used for KEYGEN form tag */
#define SSM_GET_KEY_CHOICE 0x00000100
#define SSM_KEYGEN_START 0x00000200
#define SSM_KEYGEN_TOKEN 0x00000300
#define SSM_KEYGEN_PASSWORD 0x00000400
#define SSM_KEYGEN_DONE 0x00000500
#define SSM_CREATE_KEY_PAIR 0x00000100
#define SSM_FINISH_KEY_GEN 0x00000200
#define SSM_ADD_NEW_MODULE 0x00000300
#define SSM_DEL_MODULE 0x00000400
#define SSM_LOGOUT_ALL 0x00000500
#define SSM_ENABLED_CIPHERS 0x00000600
#define SSM_CREATE_CRMF_REQ 0x00000100
#define SSM_DER_ENCODE_REQ 0x00000200
#define SSM_PROCESS_CMMF_RESP 0x00000300
#define SSM_CHALLENGE 0x00000400
#define SSM_SIGN_TEXT 0x00000100
/* Security Config subtypes */
#define SSM_ADD_CERT_TO_TEMP_DB 0x00000100
#define SSM_ADD_TEMP_CERT_TO_DB 0x00000200
#define SSM_DELETE_PERM_CERTS 0x00000300
#define SSM_FIND_CERT_KEY 0x00000400
#define SSM_GET_CERT_PROP_BY_KEY 0x00000500
#define SSM_CERT_INDEX_ENUM 0x00000600
/* subcategories for SSM_FIND_CERT_KEY and SSM_CERT_INDEX_ENUM */
#define SSM_FIND_KEY_BY_NICKNAME 0x00000010
#define SSM_FIND_KEY_BY_EMAIL_ADDR 0x00000020
#define SSM_FIND_KEY_BY_DN 0x00000030
/* subcategories for SSM_GET_CERT_PROP_BY_KEY */
#define SSM_SECCFG_GET_NICKNAME 0x00000010
#define SSM_SECCFG_GET_EMAIL_ADDR 0x00000020
#define SSM_SECCFG_GET_DN 0x00000030
#define SSM_SECCFG_GET_TRUST 0x00000040
#define SSM_SECCFG_CERT_IS_PERM 0x00000050
#define SSM_SECCFG_GET_NOT_BEFORE 0x00000060
#define SSM_SECCFG_GET_NOT_AFTER 0x00000070
#define SSM_SECCFG_GET_SERIAL_NO 0x00000080
#define SSM_SECCFG_GET_ISSUER 0x00000090
#define SSM_SECCFG_GET_ISSUER_KEY 0x000000a0
#define SSM_SECCFG_GET_SUBJECT_NEXT 0x000000b0
#define SSM_SECCFG_GET_SUBJECT_PREV 0x000000c0
/* Misc requests */
#define SSM_MISC_GET_RNG_DATA 0x00000100
#define SSM_MISC_PUT_RNG_DATA 0x00000200
#define SSM_MISC_SDR_ENCRYPT 0x00000300
#define SSM_MISC_SDR_DECRYPT 0x00000400
#define SSM_MISC_UI 0x00000500
/* specific UI requests */
#define SSM_UI_CHANGE_PASSWORD 0x00000010
#define SSM_SDR_ENCRYPT_REQUEST \
(SSM_REQUEST_MESSAGE|SSM_MISC_ACTION|SSM_MISC_SDR_ENCRYPT)
#define SSM_SDR_ENCRYPT_REPLY \
(SSM_REPLY_OK_MESSAGE|SSM_MISC_ACTION|SSM_MISC_SDR_ENCRYPT)
#define SSM_SDR_DECRYPT_REQUEST \
(SSM_REQUEST_MESSAGE|SSM_MISC_ACTION|SSM_MISC_SDR_DECRYPT)
#define SSM_SDR_DECRYPT_REPLY \
(SSM_REPLY_OK_MESSAGE|SSM_MISC_ACTION|SSM_MISC_SDR_DECRYPT)
/* Type masks for message types */
#define SSM_CATEGORY_MASK 0xF0000000
#define SSM_TYPE_MASK 0x0000F000
#define SSM_SUBTYPE_MASK 0x00000F00
#define SSM_SPECIFIC_MASK 0x000000F0
typedef struct SSMAttributeValue {
CMUint32 type;
union {
SSMResourceID rid;
CMTItem string;
CMInt32 numeric;
} u;
} SSMAttributeValue;
typedef enum {
rsaEnc, rsaDualUse, rsaSign, rsaNonrepudiation, rsaSignNonrepudiation,
dhEx, dsaSignNonrepudiation, dsaSign, dsaNonrepudiation, invalidKeyGen
} SSMKeyGenType;
typedef enum {
ssmUnknownPolicy= -1,ssmDomestic=0, ssmExport=1, ssmFrance=2
} SSMPolicyType;
/* These are the localized strings that PSM can feed back to
* the plug-in. These will initially be used by the plug-in for
* JavaScript purposes to pop up alert/confirm dialogs that would
* cause nightmares to do if we sent UI events.
*/
typedef enum {
SSM_STRING_BAD_PK11_LIB_PARAM,
SSM_STRING_BAD_PK11_LIB_PATH,
SSM_STRING_ADD_MOD_SUCCESS,
SSM_STRING_DUP_MOD_FAILURE,
SSM_STRING_ADD_MOD_FAILURE,
SSM_STRING_BAD_MOD_NAME,
SSM_STRING_EXT_MOD_DEL,
SSM_STRING_INT_MOD_DEL,
SSM_STRING_MOD_DEL_FAIL,
SSM_STRING_ADD_MOD_WARN,
SSM_STRING_MOD_PROMPT,
SSM_STRING_DLL_PROMPT,
SSM_STRING_DEL_MOD_WARN,
SSM_STRING_INVALID_CRL,
SSM_STRING_INVALID_CKL,
SSM_STRING_ROOT_CKL_CERT_NOT_FOUND,
SSM_STRING_BAD_CRL_SIGNATURE,
SSM_STRING_BAD_CKL_SIGNATURE,
SSM_STRING_ERR_ADD_CRL,
SSM_STRING_ERR_ADD_CKL,
SSM_STRING_JAVASCRIPT_DISABLED
} SSMLocalizedString;
/* Event types */
#define SSM_UI_EVENT 0x00001000
#define SSM_TASK_COMPLETED_EVENT 0x00002000
#define SSM_FILE_PATH_EVENT 0x00003000
#define SSM_PROMPT_EVENT 0x00004000
#define SSM_AUTH_EVENT 0x00007000
#define SSM_SAVE_PREF_EVENT 0x00008000
#define SSM_MISC_EVENT 0x0000f000
/* Flags used in Create SSL Data request */
#define SSM_REQUEST_SSL_DATA_SSL 0x00000001
#define SSM_REQUEST_SSL_DATA_PROXY 0x00000002
#define SSM_REQUEST_SSL_CONNECTION_MASK 0x00000003
/* Create typedefs for the various #defines */
typedef CMUint32 SSMMessageCategory;
typedef CMUint32 SSMMessageType;
typedef CMUint32 SSMDataConnectionSType;
typedef CMUint32 SSMObjSignSType;
typedef CMUint32 SSMResourceAccessSType;
typedef CMUint32 SSMCreateResource;
typedef CMUint32 SSMResourceAttrType;
typedef CMUint32 SSMResourceConsv;
typedef CMUint32 SSMCertAccessSType;
typedef CMUint32 SSMKeyGenTagProcessType;
typedef CMUint32 SSMPKCS11Actions;
typedef CMUint32 SSMCRMFAction;
typedef CMUint32 SSMFormSignAction;
typedef CMUint32 SSMSecCfgAction;
typedef CMUint32 SSMSecCfgFindByType;
typedef CMUint32 SSMSecCfgGetCertPropType;
typedef CMUint32 SSMMiscRequestType;
typedef CMUint32 SSMMessageMaskType;
typedef CMUint32 SSMEventType;
typedef CMUint32 SSMSSLConnectionRequestType;
/*
* This string is version that can be used to assemble any
* version information by the apllication using the protocol
* library.
*/
extern char SSMVersionString[];
/* What type of client */
typedef enum
{
SSM_NOINFO,
SSM_COMPOSE,
SSM_MAIL_MESSAGE,
SSM_NEWS_MESSAGE,
SSM_SNEWS_MESSAGE,
SSM_BROWSER
} SSMClientType;
#endif /* __SSMDEFS_H__ */

View File

@@ -0,0 +1,628 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* 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):
*
* 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 "stddef.h"
#include "messages.h"
CMTMessageTemplate SingleNumMessageTemplate[] =
{
{ CMT_DT_INT, offsetof(SingleNumMessage, value) },
{ CMT_DT_END }
};
CMTMessageTemplate SingleStringMessageTemplate[] =
{
{ CMT_DT_STRING, offsetof(SingleStringMessage, string) },
{ CMT_DT_END }
};
CMTMessageTemplate SingleItemMessageTemplate[] =
{
{ CMT_DT_ITEM, offsetof(SingleItemMessage, item) },
{ CMT_DT_END }
};
CMTMessageTemplate HelloRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(HelloRequest, version) },
{ CMT_DT_INT, offsetof(HelloRequest, policy) },
{ CMT_DT_BOOL, offsetof(HelloRequest, doesUI) },
{ CMT_DT_STRING, offsetof(HelloRequest, profile) },
{ CMT_DT_STRING, offsetof(HelloRequest, profileDir) },
{ CMT_DT_END }
};
CMTMessageTemplate HelloReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(HelloReply, result) },
{ CMT_DT_INT, offsetof(HelloReply, sessionID) },
{ CMT_DT_INT, offsetof(HelloReply, version) },
{ CMT_DT_STRING, offsetof(HelloReply, stringVersion) },
{ CMT_DT_INT, offsetof(HelloReply, httpPort) },
{ CMT_DT_INT, offsetof(HelloReply, policy) },
{ CMT_DT_ITEM, offsetof(HelloReply, nonce) },
{ CMT_DT_END }
};
CMTMessageTemplate SSLDataConnectionRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(SSLDataConnectionRequest, flags) },
{ CMT_DT_INT, offsetof(SSLDataConnectionRequest, port) },
{ CMT_DT_STRING, offsetof(SSLDataConnectionRequest, hostIP) },
{ CMT_DT_STRING, offsetof(SSLDataConnectionRequest, hostName) },
{ CMT_DT_BOOL, offsetof(SSLDataConnectionRequest, forceHandshake) },
{ CMT_DT_ITEM, offsetof(SSLDataConnectionRequest, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate TLSDataConnectionRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(TLSDataConnectionRequest, port) },
{ CMT_DT_STRING, offsetof(TLSDataConnectionRequest, hostIP) },
{ CMT_DT_STRING, offsetof(TLSDataConnectionRequest, hostName) },
{ CMT_DT_END }
};
CMTMessageTemplate TLSStepUpRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(TLSStepUpRequest, connID) },
{ CMT_DT_ITEM, offsetof(TLSStepUpRequest, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate ProxyStepUpRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(ProxyStepUpRequest, connID) },
{ CMT_DT_ITEM, offsetof(ProxyStepUpRequest, clientContext) },
{ CMT_DT_STRING, offsetof(ProxyStepUpRequest, url) },
{ CMT_DT_END }
};
CMTMessageTemplate PKCS7DataConnectionRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(PKCS7DataConnectionRequest, resID) },
{ CMT_DT_ITEM, offsetof(PKCS7DataConnectionRequest, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate DataConnectionReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(DataConnectionReply, result) },
{ CMT_DT_INT, offsetof(DataConnectionReply, connID) },
{ CMT_DT_INT, offsetof(DataConnectionReply, port) },
{ CMT_DT_END }
};
CMTMessageTemplate UIEventTemplate[] =
{
{ CMT_DT_INT, offsetof(UIEvent, resourceID) },
{ CMT_DT_INT, offsetof(UIEvent, width) },
{ CMT_DT_INT, offsetof(UIEvent, height) },
{ CMT_DT_BOOL, offsetof(UIEvent, isModal) },
{ CMT_DT_STRING, offsetof(UIEvent, url) },
{ CMT_DT_ITEM, offsetof(UIEvent, clientContext) },
{ CMT_DT_END }
};
/*
* The old UI Event was missing the modal indication.
* As a transition aid, we use the old template if the
* "modern" version doesn't work. Model is true in that case
*/
CMTMessageTemplate OldUIEventTemplate[] =
{
{ CMT_DT_INT, offsetof(UIEvent, resourceID) },
{ CMT_DT_INT, offsetof(UIEvent, width) },
{ CMT_DT_INT, offsetof(UIEvent, height) },
{ CMT_DT_STRING, offsetof(UIEvent, url) },
{ CMT_DT_ITEM, offsetof(UIEvent, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate TaskCompletedEventTemplate[] =
{
{ CMT_DT_INT, offsetof(TaskCompletedEvent, resourceID) },
{ CMT_DT_INT, offsetof(TaskCompletedEvent, numTasks) },
{ CMT_DT_INT, offsetof(TaskCompletedEvent, result) },
{ CMT_DT_END }
};
CMTMessageTemplate VerifyDetachedSigRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(VerifyDetachedSigRequest, pkcs7ContentID) },
{ CMT_DT_INT, offsetof(VerifyDetachedSigRequest, certUsage) },
{ CMT_DT_INT, offsetof(VerifyDetachedSigRequest, hashAlgID) },
{ CMT_DT_BOOL, offsetof(VerifyDetachedSigRequest, keepCert) },
{ CMT_DT_ITEM, offsetof(VerifyDetachedSigRequest, hash) },
{ CMT_DT_END }
};
CMTMessageTemplate CreateSignedRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(CreateSignedRequest, scertRID) },
{ CMT_DT_INT, offsetof(CreateSignedRequest, ecertRID) },
{ CMT_DT_INT, offsetof(CreateSignedRequest, dig_alg) },
{ CMT_DT_ITEM, offsetof(CreateSignedRequest, digest) },
{ CMT_DT_END }
};
CMTMessageTemplate CreateContentInfoReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(CreateContentInfoReply, ciRID) },
{ CMT_DT_INT, offsetof(CreateContentInfoReply, result) },
{ CMT_DT_INT, offsetof(CreateContentInfoReply, errorCode) },
{ CMT_DT_END }
};
CMTMessageTemplate CreateEncryptedRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(CreateEncryptedRequest, scertRID) },
{ CMT_DT_LIST, offsetof(CreateEncryptedRequest, nrcerts) },
{ CMT_DT_INT, offsetof(CreateEncryptedRequest, rcertRIDs) },
{ CMT_DT_END }
};
CMTMessageTemplate CreateResourceRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(CreateResourceRequest, type) },
{ CMT_DT_ITEM, offsetof(CreateResourceRequest, params) },
{ CMT_DT_END }
};
CMTMessageTemplate CreateResourceReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(CreateResourceReply, result) },
{ CMT_DT_INT, offsetof(CreateResourceReply, resID) },
{ CMT_DT_END }
};
CMTMessageTemplate GetAttribRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(GetAttribRequest, resID) },
{ CMT_DT_INT, offsetof(GetAttribRequest, fieldID) },
{ CMT_DT_END }
};
CMTMessageTemplate GetAttribReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(GetAttribReply, result) },
{ CMT_DT_CHOICE, offsetof(GetAttribReply, value.type) },
{ CMT_DT_RID, offsetof(GetAttribReply, value.u.rid), 0, SSM_RID_ATTRIBUTE },
{ CMT_DT_INT, offsetof(GetAttribReply, value.u.numeric), 0,
SSM_NUMERIC_ATTRIBUTE },
{ CMT_DT_ITEM, offsetof(GetAttribReply, value.u.string), 0,
SSM_STRING_ATTRIBUTE},
{ CMT_DT_END_CHOICE },
{ CMT_DT_END }
};
CMTMessageTemplate SetAttribRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(SetAttribRequest, resID) },
{ CMT_DT_INT, offsetof(SetAttribRequest, fieldID) },
{ CMT_DT_CHOICE, offsetof(SetAttribRequest, value.type) },
{ CMT_DT_RID, offsetof(SetAttribRequest, value.u.rid), 0, SSM_RID_ATTRIBUTE },
{ CMT_DT_INT, offsetof(SetAttribRequest, value.u.numeric), 0,
SSM_NUMERIC_ATTRIBUTE },
{ CMT_DT_ITEM, offsetof(SetAttribRequest, value.u.string), 0,
SSM_STRING_ATTRIBUTE},
{ CMT_DT_END_CHOICE },
{ CMT_DT_END }
};
CMTMessageTemplate PickleResourceReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(PickleResourceReply, result) },
{ CMT_DT_ITEM, offsetof(PickleResourceReply, blob) },
{ CMT_DT_END }
};
CMTMessageTemplate UnpickleResourceRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(UnpickleResourceRequest, resourceType) },
{ CMT_DT_ITEM, offsetof(UnpickleResourceRequest, resourceData) },
{ CMT_DT_END }
};
CMTMessageTemplate UnpickleResourceReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(UnpickleResourceReply, result) },
{ CMT_DT_INT, offsetof(UnpickleResourceReply, resID) },
{ CMT_DT_END }
};
CMTMessageTemplate PickleSecurityStatusReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(PickleSecurityStatusReply, result) },
{ CMT_DT_INT, offsetof(PickleSecurityStatusReply, securityLevel) },
{ CMT_DT_ITEM, offsetof(PickleSecurityStatusReply, blob) },
{ CMT_DT_END }
};
CMTMessageTemplate DupResourceReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(DupResourceReply, result) },
{ CMT_DT_RID, offsetof(DupResourceReply, resID), 0, SSM_RID_ATTRIBUTE },
{ CMT_DT_END }
};
CMTMessageTemplate DestroyResourceRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(DestroyResourceRequest, resID) },
{ CMT_DT_INT, offsetof(DestroyResourceRequest, resType) },
{ CMT_DT_END }
};
CMTMessageTemplate VerifyCertRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(VerifyCertRequest, resID) },
{ CMT_DT_INT, offsetof(VerifyCertRequest, certUsage) },
{ CMT_DT_END }
};
CMTMessageTemplate AddTempCertToDBRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(AddTempCertToDBRequest, resID) },
{ CMT_DT_STRING, offsetof(AddTempCertToDBRequest, nickname) },
{ CMT_DT_INT, offsetof(AddTempCertToDBRequest, sslFlags) },
{ CMT_DT_INT, offsetof(AddTempCertToDBRequest, emailFlags) },
{ CMT_DT_INT, offsetof(AddTempCertToDBRequest, objSignFlags) },
{ CMT_DT_END }
};
CMTMessageTemplate MatchUserCertRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(MatchUserCertRequest, certType) },
{ CMT_DT_LIST, offsetof(MatchUserCertRequest, numCANames) },
{ CMT_DT_STRING, offsetof(MatchUserCertRequest, caNames) },
{ CMT_DT_END }
};
CMTMessageTemplate MatchUserCertReplyTemplate[] =
{
{ CMT_DT_LIST, offsetof(MatchUserCertReply, numCerts) },
{ CMT_DT_INT, offsetof(MatchUserCertReply, certs) },
{ CMT_DT_END }
};
CMTMessageTemplate EncodeCRMFReqRequestTemplate[] =
{
{ CMT_DT_LIST, offsetof(EncodeCRMFReqRequest, numRequests) },
{ CMT_DT_INT, offsetof(EncodeCRMFReqRequest, reqIDs) },
{ CMT_DT_END }
};
CMTMessageTemplate CMMFCertResponseRequestTemplate[] =
{
{ CMT_DT_STRING, offsetof(CMMFCertResponseRequest, nickname) },
{ CMT_DT_STRING, offsetof(CMMFCertResponseRequest, base64Der) },
{ CMT_DT_INT, offsetof(CMMFCertResponseRequest, doBackup) },
{ CMT_DT_ITEM, offsetof(CMMFCertResponseRequest, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate PasswordRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(PasswordRequest, tokenKey) },
{ CMT_DT_STRING, offsetof(PasswordRequest, prompt) },
{ CMT_DT_ITEM, offsetof(PasswordRequest, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate PasswordReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(PasswordReply, result) },
{ CMT_DT_INT, offsetof(PasswordReply, tokenID) },
{ CMT_DT_STRING, offsetof(PasswordReply, passwd) },
{ CMT_DT_END }
};
CMTMessageTemplate KeyPairGenRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(KeyPairGenRequest, keyGenCtxtID) },
{ CMT_DT_INT, offsetof(KeyPairGenRequest, genMechanism) },
{ CMT_DT_INT, offsetof(KeyPairGenRequest, keySize) },
{ CMT_DT_ITEM, offsetof(KeyPairGenRequest, params) },
{ CMT_DT_END }
};
CMTMessageTemplate DecodeAndCreateTempCertRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(DecodeAndCreateTempCertRequest, type) },
{ CMT_DT_ITEM, offsetof(DecodeAndCreateTempCertRequest, cert) },
{ CMT_DT_END }
};
CMTMessageTemplate GenKeyOldStyleRequestTemplate[] =
{
{ CMT_DT_STRING, offsetof(GenKeyOldStyleRequest, choiceString) },
{ CMT_DT_STRING, offsetof(GenKeyOldStyleRequest, challenge) },
{ CMT_DT_STRING, offsetof(GenKeyOldStyleRequest, typeString) },
{ CMT_DT_STRING, offsetof(GenKeyOldStyleRequest, pqgString) },
{ CMT_DT_END }
};
CMTMessageTemplate GenKeyOldStyleTokenRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(GenKeyOldStyleTokenRequest, rid) },
{ CMT_DT_LIST, offsetof(GenKeyOldStyleTokenRequest, numtokens) },
{ CMT_DT_STRING,offsetof(GenKeyOldStyleTokenRequest, tokenNames)},
{ CMT_DT_END }
};
CMTMessageTemplate GenKeyOldStyleTokenReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(GenKeyOldStyleTokenReply, rid) },
{ CMT_DT_BOOL, offsetof(GenKeyOldStyleTokenReply, cancel) },
{ CMT_DT_STRING, offsetof(GenKeyOldStyleTokenReply, tokenName) },
{ CMT_DT_END }
};
CMTMessageTemplate GenKeyOldStylePasswordRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(GenKeyOldStylePasswordRequest, rid) },
{ CMT_DT_STRING, offsetof(GenKeyOldStylePasswordRequest, tokenName) },
{ CMT_DT_BOOL, offsetof(GenKeyOldStylePasswordRequest, internal) },
{ CMT_DT_INT, offsetof(GenKeyOldStylePasswordRequest, minpwdlen) },
{ CMT_DT_INT, offsetof(GenKeyOldStylePasswordRequest, maxpwdlen) },
{ CMT_DT_END }
};
CMTMessageTemplate GenKeyOldStylePasswordReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(GenKeyOldStylePasswordReply, rid) },
{ CMT_DT_BOOL, offsetof(GenKeyOldStylePasswordReply, cancel) },
{ CMT_DT_STRING, offsetof(GenKeyOldStylePasswordReply, password) },
{ CMT_DT_END }
};
CMTMessageTemplate GetKeyChoiceListRequestTemplate[] =
{
{ CMT_DT_STRING, offsetof(GetKeyChoiceListRequest, type) },
{ CMT_DT_STRING, offsetof(GetKeyChoiceListRequest, pqgString) },
{ CMT_DT_END }
};
CMTMessageTemplate GetKeyChoiceListReplyTemplate[] =
{
{ CMT_DT_LIST, offsetof(GetKeyChoiceListReply, nchoices) },
{ CMT_DT_STRING, offsetof(GetKeyChoiceListReply, choices) },
{ CMT_DT_END }
};
CMTMessageTemplate AddNewSecurityModuleRequestTemplate[] =
{
{ CMT_DT_STRING, offsetof(AddNewSecurityModuleRequest, moduleName) },
{ CMT_DT_STRING, offsetof(AddNewSecurityModuleRequest, libraryPath) },
{ CMT_DT_INT, offsetof(AddNewSecurityModuleRequest, pubMechFlags) },
{ CMT_DT_INT, offsetof(AddNewSecurityModuleRequest, pubCipherFlags) },
{ CMT_DT_END }
};
CMTMessageTemplate FilePathRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(FilePathRequest, resID) },
{ CMT_DT_STRING, offsetof(FilePathRequest, prompt) },
{ CMT_DT_BOOL, offsetof(FilePathRequest, getExistingFile) },
{ CMT_DT_STRING, offsetof(FilePathRequest, fileRegEx) },
{ CMT_DT_END }
};
CMTMessageTemplate FilePathReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(FilePathReply, resID) },
{ CMT_DT_STRING, offsetof(FilePathReply, filePath) },
{ CMT_DT_END }
};
CMTMessageTemplate PasswordPromptReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(PasswordPromptReply, resID) },
{ CMT_DT_STRING, offsetof(PasswordPromptReply, promptReply) },
{ CMT_DT_END }
};
CMTMessageTemplate SignTextRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(SignTextRequest, resID) },
{ CMT_DT_STRING, offsetof(SignTextRequest, stringToSign) },
{ CMT_DT_STRING, offsetof(SignTextRequest, hostName) },
{ CMT_DT_STRING, offsetof(SignTextRequest, caOption) },
{ CMT_DT_LIST, offsetof(SignTextRequest, numCAs) },
{ CMT_DT_STRING, offsetof(SignTextRequest, caNames) },
{ CMT_DT_END }
};
CMTMessageTemplate GetLocalizedTextReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(GetLocalizedTextReply, whichString) },
{ CMT_DT_STRING, offsetof(GetLocalizedTextReply, localizedString) },
{ CMT_DT_END }
};
CMTMessageTemplate ImportCertReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(ImportCertReply, result) },
{ CMT_DT_INT, offsetof(ImportCertReply, resID) },
{ CMT_DT_END }
};
CMTMessageTemplate PromptRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(PromptRequest, resID) },
{ CMT_DT_STRING, offsetof(PromptRequest, prompt) },
{ CMT_DT_ITEM, offsetof(PromptRequest, clientContext) },
{ CMT_DT_END }
};
CMTMessageTemplate PromptReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(PromptReply, resID) },
{ CMT_DT_BOOL, offsetof(PromptReply, cancel) },
{ CMT_DT_STRING, offsetof(PromptReply, promptReply) },
{ CMT_DT_END }
};
CMTMessageTemplate RedirectCompareRequestTemplate[] =
{
{ CMT_DT_ITEM, offsetof(RedirectCompareRequest, socketStatus1Data) },
{ CMT_DT_ITEM, offsetof(RedirectCompareRequest, socketStatus2Data) },
{ CMT_DT_END }
};
CMTMessageTemplate DecodeAndAddCRLRequestTemplate[] =
{
{ CMT_DT_ITEM, offsetof(DecodeAndAddCRLRequest, derCrl) },
{ CMT_DT_INT, offsetof(DecodeAndAddCRLRequest, type) },
{ CMT_DT_STRING, offsetof(DecodeAndAddCRLRequest, url) },
{ CMT_DT_END }
};
CMTMessageTemplate SecurityAdvisorRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(SecurityAdvisorRequest, infoContext) },
{ CMT_DT_INT, offsetof(SecurityAdvisorRequest, resID) },
{ CMT_DT_STRING, offsetof(SecurityAdvisorRequest, hostname) },
{ CMT_DT_STRING, offsetof(SecurityAdvisorRequest, senderAddr) },
{ CMT_DT_INT, offsetof(SecurityAdvisorRequest, encryptedP7CInfo) },
{ CMT_DT_INT, offsetof(SecurityAdvisorRequest, signedP7CInfo) },
{ CMT_DT_INT, offsetof(SecurityAdvisorRequest, decodeError) },
{ CMT_DT_INT, offsetof(SecurityAdvisorRequest, verifyError) },
{ CMT_DT_BOOL, offsetof(SecurityAdvisorRequest, encryptthis) },
{ CMT_DT_BOOL, offsetof(SecurityAdvisorRequest, signthis) },
{ CMT_DT_LIST, offsetof(SecurityAdvisorRequest, numRecipients) },
{ CMT_DT_STRING, offsetof(SecurityAdvisorRequest, recipients) },
{ CMT_DT_END }
};
CMTMessageTemplate SCAddTempCertToPermDBRequestTemplate[] =
{
{ CMT_DT_ITEM, offsetof(SCAddTempCertToPermDBRequest, certKey) },
{ CMT_DT_STRING, offsetof(SCAddTempCertToPermDBRequest, trustStr) },
{ CMT_DT_STRING, offsetof(SCAddTempCertToPermDBRequest, nickname) },
{ CMT_DT_END }
};
CMTMessageTemplate SCDeletePermCertsRequestTemplate[] =
{
{ CMT_DT_ITEM, offsetof(SCDeletePermCertsRequest, certKey) },
{ CMT_DT_BOOL, offsetof(SCDeletePermCertsRequest, deleteAll) },
{ CMT_DT_END }
};
CMTMessageTemplate TimeMessageTemplate[] =
{
{ CMT_DT_INT, offsetof(TimeMessage, year) },
{ CMT_DT_INT, offsetof(TimeMessage, month) },
{ CMT_DT_INT, offsetof(TimeMessage, day) },
{ CMT_DT_INT, offsetof(TimeMessage, hour) },
{ CMT_DT_INT, offsetof(TimeMessage, minute) },
{ CMT_DT_INT, offsetof(TimeMessage, second) },
{ CMT_DT_END }
};
CMTMessageTemplate SCCertIndexEnumReplyTemplate[] =
{
{ CMT_DT_INT, offsetof(SCCertIndexEnumReply, length) },
{ CMT_DT_STRUCT_PTR, offsetof(SCCertIndexEnumReply, list) },
{ CMT_DT_STRING, offsetof(CertEnumElement, name) },
{ CMT_DT_ITEM, offsetof(CertEnumElement, certKey) },
{ CMT_DT_END_STRUCT_LIST },
{ CMT_DT_END }
};
/* Test template */
CMTMessageTemplate TestListTemplate[] =
{
{ CMT_DT_STRING, offsetof(TestList, listName) },
{ CMT_DT_STRUCT_LIST, offsetof(TestList, numElements) },
{ CMT_DT_STRUCT_PTR, offsetof(TestList, elements) },
{ CMT_DT_STRING, offsetof(TestListElement, name) },
{ CMT_DT_STRING, offsetof(TestListElement, value) },
{ CMT_DT_END_STRUCT_LIST},
{ CMT_DT_END}
};
CMTMessageTemplate SetPrefListMessageTemplate[] =
{
{ CMT_DT_STRUCT_LIST, offsetof(SetPrefListMessage, length) },
{ CMT_DT_STRUCT_PTR, offsetof(SetPrefListMessage, list) },
{ CMT_DT_STRING, offsetof(SetPrefElement, key) },
{ CMT_DT_STRING, offsetof(SetPrefElement, value) },
{ CMT_DT_INT, offsetof(SetPrefElement, type) },
{ CMT_DT_END_STRUCT_LIST },
{ CMT_DT_END }
};
CMTMessageTemplate GetPrefListRequestTemplate[] =
{
{ CMT_DT_STRUCT_LIST, offsetof(GetPrefListRequest, length) },
{ CMT_DT_STRUCT_PTR, offsetof(GetPrefListRequest, list) },
{ CMT_DT_STRING, offsetof(GetPrefElement, key) },
{ CMT_DT_INT, offsetof(GetPrefElement, type) },
{ CMT_DT_END_STRUCT_LIST },
{ CMT_DT_END }
};
CMTMessageTemplate GetCertExtensionTemplate[] =
{
{ CMT_DT_INT, offsetof(GetCertExtension, resID) },
{ CMT_DT_INT, offsetof(GetCertExtension, extension) },
{ CMT_DT_END }
};
CMTMessageTemplate HTMLCertInfoRequestTemplate[] =
{
{ CMT_DT_INT, offsetof(HTMLCertInfoRequest, certID) },
{ CMT_DT_INT, offsetof(HTMLCertInfoRequest, showImages) },
{ CMT_DT_INT, offsetof(HTMLCertInfoRequest, showIssuer) },
{ CMT_DT_END }
};
CMTMessageTemplate EncryptRequestTemplate[] =
{
{ CMT_DT_ITEM, offsetof(EncryptRequestMessage, keyid) },
{ CMT_DT_ITEM, offsetof(EncryptRequestMessage, data) },
{ CMT_DT_ITEM, offsetof(EncryptRequestMessage, ctx) },
{ CMT_DT_END }
};
CMTMessageTemplate DecryptRequestTemplate[] =
{
{ CMT_DT_ITEM, offsetof(DecryptRequestMessage, data) },
{ CMT_DT_ITEM, offsetof(DecryptRequestMessage, ctx) },
{ CMT_DT_END }
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 B

View File

@@ -1,97 +0,0 @@
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
# Myk Melez <myk@mozilla.org>
############################################################################
# Module Initialization
############################################################################
use diagnostics;
use strict;
package Attachment;
# This module requires that its caller have said "require CGI.pl" to import
# relevant functions from that script and its companion globals.pl.
############################################################################
# Functions
############################################################################
sub query
{
# Retrieves and returns an array of attachment records for a given bug.
# This data should be given to attachment/list.atml in an
# "attachments" variable.
my ($bugid) = @_;
my $in_editbugs = &::UserInGroup($::userid, "editbugs");
# Retrieve a list of attachments for this bug and write them into an array
# of hashes in which each hash represents a single attachment.
&::SendSQL("
SELECT attach_id, creation_ts, mimetype, description, ispatch,
isobsolete, submitter_id
FROM attachments WHERE bug_id = $bugid ORDER BY attach_id
");
my @attachments = ();
while (&::MoreSQLData()) {
my %a;
my $submitter_id;
($a{'attachid'}, $a{'date'}, $a{'contenttype'}, $a{'description'},
$a{'ispatch'}, $a{'isobsolete'}, $submitter_id) = &::FetchSQLData();
# Format the attachment's creation/modification date into a standard
# format (YYYY-MM-DD HH:MM)
if ($a{'date'} =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/) {
$a{'date'} = "$1-$2-$3 $4:$5";
}
# Retrieve a list of status flags that have been set on the attachment.
&::PushGlobalSQLState();
&::SendSQL("
SELECT name
FROM attachstatuses, attachstatusdefs
WHERE attach_id = $a{'attachid'}
AND attachstatuses.statusid = attachstatusdefs.id
ORDER BY sortkey
");
my @statuses = ();
while (&::MoreSQLData()) {
my ($status) = &::FetchSQLData();
push @statuses , $status;
}
$a{'statuses'} = \@statuses;
&::PopGlobalSQLState();
# We will display the edit link if the user can edit the attachment;
# ie the are the submitter, or they have canedit.
# Also show the link if the user is not logged in - in that cae,
# They'll be prompted later
$a{'canedit'} = ($::userid == 0 || $submitter_id == $::userid ||
$in_editbugs);
push @attachments, \%a;
}
return \@attachments;
}
1;

View File

@@ -1,525 +0,0 @@
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Dawn Endico <endico@mozilla.org>
# Terry Weissman <terry@mozilla.org>
# Chris Yeh <cyeh@bluemartini.com>
use diagnostics;
use strict;
use DBI;
use RelationSet;
use vars qw($unconfirmedstate $legal_keywords);
require "globals.pl";
require "CGI.pl";
package Bug;
use CGI::Carp qw(fatalsToBrowser);
my %ok_field;
for my $key (qw (bug_id product version rep_platform op_sys bug_status
resolution priority bug_severity component assigned_to
reporter bug_file_loc short_desc target_milestone
qa_contact status_whiteboard creation_ts
delta_ts votes whoid comment query error) ){
$ok_field{$key}++;
}
# create a new empty bug
#
sub new {
my $type = shift();
my %bug;
# create a ref to an empty hash and bless it
#
my $self = {%bug};
bless $self, $type;
# construct from a hash containing a bug's info
#
if ($#_ == 1) {
$self->initBug(@_);
} else {
confess("invalid number of arguments \($#_\)($_)");
}
# bless as a Bug
#
return $self;
}
# dump info about bug into hash unless user doesn't have permission
# user_id 0 is used when person is not logged in.
#
sub initBug {
my $self = shift();
my ($bug_id, $user_id) = (@_);
my $old_bug_id = $bug_id;
if ((! defined $bug_id) || (!$bug_id) || (!&::detaint_natural($bug_id))) {
# no bug number given
$self->{'bug_id'} = $old_bug_id;
$self->{'error'} = "InvalidBugId";
return $self;
}
# default userid 0, or get DBID if you used an email address
unless (defined $user_id) {
$user_id = 0;
}
else {
if ($user_id =~ /^\@/) {
$user_id = &::DBname_to_id($user_id);
}
}
&::ConnectToDatabase();
&::GetVersionTable();
# this verification should already have been done by caller
# my $loginok = quietly_check_login();
$self->{'whoid'} = $user_id;
# First check that we can see it
if (!&::CanSeeBug($bug_id, $user_id)) {
# is it not there, or are we just forbidden to see it?
&::SendSQL("SELECT bug_id FROM bugs WHERE bug_id = $bug_id");
if (&::FetchSQLData()) {
$self->{'error'} = "NotPermitted";
} else {
$self->{'error'} = "NotFound";
}
$self->{'bug_id'} = $bug_id;
return $self;
}
my $query = "";
if ($::driver eq 'mysql') {
$query = "
select
bugs.bug_id, product, version, rep_platform, op_sys, bug_status,
resolution, priority, bug_severity, component, assigned_to, reporter,
bug_file_loc, short_desc, target_milestone, qa_contact,
status_whiteboard, date_format(creation_ts,'%Y-%m-%d %H:%i'),
delta_ts, sum(votes.count)
from bugs left join votes using(bug_id)
where bugs.bug_id = $bug_id
group by bugs.bug_id";
} elsif ($::driver eq 'Pg') {
$query = "
select
bugs.bug_id, product, version, rep_platform, op_sys, bug_status,
resolution, priority, bug_severity, component, assigned_to, reporter,
bug_file_loc, short_desc, target_milestone, qa_contact,
status_whiteboard, creation_ts,
delta_ts, sum(votes.count)
from bugs left join votes using(bug_id)
where bugs.bug_id = $bug_id
group by bugs.bug_id, product, version, rep_platform, op_sys, bug_status,
resolution, priority, bug_severity, component, assigned_to, reporter,
bug_file_loc, short_desc, target_milestone, qa_contact, status_whiteboard,
creation_ts, delta_ts";
}
&::SendSQL($query);
my @row;
@row = &::FetchSQLData();
my $count = 0;
my %fields;
foreach my $field ("bug_id", "product", "version", "rep_platform",
"op_sys", "bug_status", "resolution", "priority",
"bug_severity", "component", "assigned_to", "reporter",
"bug_file_loc", "short_desc", "target_milestone",
"qa_contact", "status_whiteboard", "creation_ts",
"delta_ts", "votes") {
$fields{$field} = shift @row;
if ($fields{$field}) {
$self->{$field} = $fields{$field};
}
$count++;
}
$self->{'assigned_to'} = &::DBID_to_name($self->{'assigned_to'});
$self->{'reporter'} = &::DBID_to_name($self->{'reporter'});
my $ccSet = new RelationSet;
$ccSet->mergeFromDB("select who from cc where bug_id=$bug_id");
my @cc = $ccSet->toArrayOfStrings();
if (@cc) {
$self->{'cc'} = \@cc;
}
if (&::Param("useqacontact") && (defined $self->{'qa_contact'}) ) {
my $name = $self->{'qa_contact'} > 0 ? &::DBID_to_name($self->{'qa_contact'}) :"";
if ($name) {
$self->{'qa_contact'} = $name;
}
}
if (@::legal_keywords) {
&::SendSQL("SELECT keyworddefs.name
FROM keyworddefs, keywords
WHERE keywords.bug_id = $bug_id
AND keyworddefs.id = keywords.keywordid
ORDER BY keyworddefs.name");
my @list;
while (&::MoreSQLData()) {
push(@list, &::FetchOneColumn());
}
if (@list) {
$self->{'keywords'} = join(', ', @list);
}
}
&::SendSQL("select attach_id, creation_ts, description
from attachments
where bug_id = $bug_id");
my @attachments;
while (&::MoreSQLData()) {
my ($attachid, $date, $desc) = (&::FetchSQLData());
if ($date =~ /^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/) {
$date = "$3/$4/$2 $5:$6";
my %attach;
$attach{'attachid'} = $attachid;
$attach{'date'} = $date;
$attach{'desc'} = $desc;
push @attachments, \%attach;
}
}
if (@attachments) {
$self->{'attachments'} = \@attachments;
}
&::SendSQL("select bug_id, who, bug_when, thetext
from longdescs
where bug_id = $bug_id");
my @longdescs;
while (&::MoreSQLData()) {
my ($bug_id, $who, $bug_when, $thetext) = (&::FetchSQLData());
my %longdesc;
$longdesc{'who'} = $who;
$longdesc{'bug_when'} = $bug_when;
$longdesc{'thetext'} = $thetext;
push @longdescs, \%longdesc;
}
if (@longdescs) {
$self->{'longdescs'} = \@longdescs;
}
if (&::Param("usedependencies")) {
my @depends = EmitDependList("blocked", "dependson", $bug_id);
if ( @depends ) {
$self->{'dependson'} = \@depends;
}
my @blocks = EmitDependList("dependson", "blocked", $bug_id);
if ( @blocks ) {
$self->{'blocks'} = \@blocks;
}
}
return $self;
}
# given a bug hash, emit xml for it. with file header provided by caller
#
sub emitXML {
( $#_ == 0 ) || confess("invalid number of arguments");
my $self = shift();
my $xml;
if (exists $self->{'error'}) {
$xml .= "<bug error=\"$self->{'error'}\">\n";
$xml .= " <bug_id>$self->{'bug_id'}</bug_id>\n";
$xml .= "</bug>\n";
return $xml;
}
$xml .= "<bug>\n";
foreach my $field ("bug_id", "bug_status", "product",
"priority", "version", "rep_platform", "assigned_to", "delta_ts",
"component", "reporter", "target_milestone", "bug_severity",
"creation_ts", "qa_contact", "op_sys", "resolution", "bug_file_loc",
"short_desc", "keywords", "status_whiteboard") {
if ($self->{$field}) {
$xml .= " <$field>" . QuoteXMLChars($self->{$field}) . "</$field>\n";
}
}
foreach my $field ("dependson", "blocks", "cc") {
if (defined $self->{$field}) {
for (my $i=0 ; $i < @{$self->{$field}} ; $i++) {
$xml .= " <$field>" . $self->{$field}[$i] . "</$field>\n";
}
}
}
if (defined $self->{'longdescs'}) {
for (my $i=0 ; $i < @{$self->{'longdescs'}} ; $i++) {
$xml .= " <long_desc>\n";
$xml .= " <who>" . &::DBID_to_name($self->{'longdescs'}[$i]->{'who'})
. "</who>\n";
$xml .= " <bug_when>" . $self->{'longdescs'}[$i]->{'bug_when'}
. "</bug_when>\n";
$xml .= " <thetext>" . QuoteXMLChars($self->{'longdescs'}[$i]->{'thetext'})
. "</thetext>\n";
$xml .= " </long_desc>\n";
}
}
if (defined $self->{'attachments'}) {
for (my $i=0 ; $i < @{$self->{'attachments'}} ; $i++) {
$xml .= " <attachment>\n";
$xml .= " <attachid>" . $self->{'attachments'}[$i]->{'attachid'}
. "</attachid>\n";
$xml .= " <date>" . $self->{'attachments'}[$i]->{'date'} . "</date>\n";
$xml .= " <desc>" . QuoteXMLChars($self->{'attachments'}[$i]->{'desc'}) . "</desc>\n";
# $xml .= " <type>" . $self->{'attachments'}[$i]->{'type'} . "</type>\n";
# $xml .= " <data>" . $self->{'attachments'}[$i]->{'data'} . "</data>\n";
$xml .= " </attachment>\n";
}
}
$xml .= "</bug>\n";
return $xml;
}
sub EmitDependList {
my ($myfield, $targetfield, $bug_id) = (@_);
my @list;
&::SendSQL("select dependencies.$targetfield, bugs.bug_status
from dependencies, bugs
where dependencies.$myfield = $bug_id
and bugs.bug_id = dependencies.$targetfield
order by dependencies.$targetfield");
while (&::MoreSQLData()) {
my ($i, $stat) = (&::FetchSQLData());
push @list, $i;
}
return @list;
}
sub QuoteXMLChars {
$_[0] =~ s/&/&amp;/g;
$_[0] =~ s/</&lt;/g;
$_[0] =~ s/>/&gt;/g;
$_[0] =~ s/'/&apos;/g;
$_[0] =~ s/"/&quot;/g;
# $_[0] =~ s/([\x80-\xFF])/&XmlUtf8Encode(ord($1))/ge;
return($_[0]);
}
sub XML_Header {
my ($urlbase, $version, $maintainer, $exporter) = (@_);
my $xml;
$xml = "<?xml version=\"1.0\" standalone=\"yes\"?>\n";
$xml .= "<!DOCTYPE bugzilla SYSTEM \"$urlbase";
if (! ($urlbase =~ /.+\/$/)) {
$xml .= "/";
}
$xml .= "bugzilla.dtd\">\n";
$xml .= "<bugzilla";
if (defined $exporter) {
$xml .= " exporter=\"$exporter\"";
}
$xml .= " version=\"$version\"";
$xml .= " urlbase=\"$urlbase\"";
$xml .= " maintainer=\"$maintainer\">\n";
return ($xml);
}
sub XML_Footer {
return ("</bugzilla>\n");
}
sub UserInGroup {
my $self = shift();
my ($groupname) = (@_);
return &::UserInGroup($self->{'whoid'}, $groupname);
}
sub CanChangeField {
my $self = shift();
my ($f, $oldvalue, $newvalue) = (@_);
my $UserInEditGroup = -1;
my $UserInCanConfirmGroup = -1;
my $ownerid;
my $reporterid;
my $qacontactid;
if ($f eq "assigned_to" || $f eq "reporter" || $f eq "qa_contact") {
if ($oldvalue =~ /^\d+$/) {
if ($oldvalue == 0) {
$oldvalue = "";
} else {
$oldvalue = &::DBID_to_name($oldvalue);
}
}
}
if ($oldvalue eq $newvalue) {
return 1;
}
if (&::trim($oldvalue) eq &::trim($newvalue)) {
return 1;
}
if ($f =~ /^longdesc/) {
return 1;
}
if ($UserInEditGroup < 0) {
$UserInEditGroup = UserInGroup($self, "editbugs");
}
if ($UserInEditGroup) {
return 1;
}
&::SendSQL("SELECT reporter, assigned_to, qa_contact FROM bugs " .
"WHERE bug_id = $self->{'bug_id'}");
($reporterid, $ownerid, $qacontactid) = (&::FetchSQLData());
# Let reporter change bug status, even if they can't edit bugs.
# If reporter can't re-open their bug they will just file a duplicate.
# While we're at it, let them close their own bugs as well.
if ( ($f eq "bug_status") && ($self->{'whoid'} eq $reporterid) ) {
return 1;
}
if ($f eq "bug_status" && $newvalue ne $::unconfirmedstate &&
&::IsOpenedState($newvalue)) {
# Hmm. They are trying to set this bug to some opened state
# that isn't the UNCONFIRMED state. Are they in the right
# group? Or, has it ever been confirmed? If not, then this
# isn't legal.
if ($UserInCanConfirmGroup < 0) {
$UserInCanConfirmGroup = &::UserInGroup($self->{'whoid'},"canconfirm");
}
if ($UserInCanConfirmGroup) {
return 1;
}
&::SendSQL("SELECT everconfirmed FROM bugs WHERE bug_id = $self->{'bug_id'}");
my $everconfirmed = FetchOneColumn();
if ($everconfirmed) {
return 1;
}
} elsif ($reporterid eq $self->{'whoid'} || $ownerid eq $self->{'whoid'} ||
$qacontactid eq $self->{'whoid'}) {
return 1;
}
$self->{'error'} = "
Only the owner or submitter of the bug, or a sufficiently
empowered user, may make that change to the $f field."
}
sub Collision {
my $self = shift();
my $write = "WRITE"; # Might want to make a param to control
# whether we do LOW_PRIORITY ...
if ($::driver eq 'mysql') {
&::SendSQL("LOCK TABLES bugs $write, bugs_activity $write, cc $write, " .
"cc AS selectVisible_cc $write, " .
"profiles $write, dependencies $write, votes $write, " .
"keywords $write, longdescs $write, fielddefs $write, " .
"keyworddefs READ, groups READ, attachments READ, products READ");
}
&::SendSQL("SELECT delta_ts FROM bugs where bug_id=$self->{'bug_id'}");
my $delta_ts = &::FetchOneColumn();
if ($::driver eq 'mysql') {
&::SendSQL("unlock tables");
}
if ($self->{'delta_ts'} ne $delta_ts) {
return 1;
}
else {
return 0;
}
}
sub AppendComment {
my $self = shift();
my ($comment) = (@_);
$comment =~ s/\r\n/\n/g; # Get rid of windows-style line endings.
$comment =~ s/\r/\n/g; # Get rid of mac-style line endings.
if ($comment =~ /^\s*$/) { # Nothin' but whitespace.
return;
}
&::SendSQL("INSERT INTO longdescs (bug_id, who, bug_when, thetext) " .
"VALUES($self->{'bug_id'}, $self->{'whoid'}, now(), " . &::SqlQuote($comment) . ")");
&::SendSQL("UPDATE bugs SET delta_ts = now() WHERE bug_id = $self->{'bug_id'}");
}
#from o'reilley's Programming Perl
sub display {
my $self = shift;
my @keys;
if (@_ == 0) { # no further arguments
@keys = sort keys(%$self);
} else {
@keys = @_; # use the ones given
}
foreach my $key (@keys) {
print "\t$key => $self->{$key}\n";
}
}
sub CommitChanges {
#snapshot bug
#snapshot dependencies
#check can change fields
#check collision
#lock and change fields
#notify through mail
}
sub AUTOLOAD {
use vars qw($AUTOLOAD);
my $self = shift;
my $type = ref($self) || $self;
my $attr = $AUTOLOAD;
$attr =~ s/.*:://;
return unless $attr=~ /[^A-Z]/;
if (@_) {
$self->{$attr} = shift;
return;
}
confess ("invalid bug attribute $attr") unless $ok_field{$attr};
if (defined $self->{$attr}) {
return $self->{$attr};
} else {
return '';
}
}
1;

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +0,0 @@
* This README is no longer used to house installation instructions. Instead,
it contains pointers to where you may find the information you need.
* Installation instructions are now found in docs/, with a variety of document
types available. Please refer to these documents when installing, configuring,
and maintaining your Bugzilla installation. A helpful starting point is
docs/txt/Bugzilla-Guide.txt, or with a web browser at docs/html/index.html.
* Release notes for people upgrading to a new version of Bugzilla are
available at docs/rel_notes.txt.
* If you wish to contribute to the documentation, please read docs/README.docs.
* The Bugzilla web site is at "http://www.mozilla.org/projects/bugzilla/".
This site will contain the latest Bugzilla information, including how to
report bugs and how to get help with Bugzilla.

View File

@@ -1,268 +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 Bugzilla Bug Tracking System.
#
# 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): Dan Mosedale <dmose@mozilla.org>
# Terry Weissman <terry@mozilla.org>
# Dave Miller <justdave@syndicomm.com>
# This object models a set of relations between one item and a group
# of other items. An example is the set of relations between one bug
# and the users CCed on that bug. Currently, the relation objects are
# expected to be bugzilla userids. However, this could and perhaps
# should be generalized to work with non userid objects, such as
# keywords associated with a bug. That shouldn't be hard to do; it
# might involve turning this into a virtual base class, and having
# UserSet and KeywordSet types that inherit from it.
use diagnostics;
use strict;
# Everything that uses RelationSet should already have globals.pl loaded
# so we don't want to load it here. Doing so causes a loop in Perl because
# globals.pl turns around and does a 'use RelationSet'
# See http://bugzilla.mozilla.org/show_bug.cgi?id=72862
#require "globals.pl";
package RelationSet;
use CGI::Carp qw(fatalsToBrowser);
# create a new empty RelationSet
#
sub new {
my $type = shift();
# create a ref to an empty hash and bless it
#
my $self = {};
bless $self, $type;
# construct from a comma-delimited string
#
if ($#_ == 0) {
$self->mergeFromString($_[0]);
}
# unless this was a constructor for an empty list, somebody screwed up.
#
elsif ( $#_ != -1 ) {
confess("invalid number of arguments");
}
# bless as a RelationSet
#
return $self;
}
# Assumes that the set of relations "FROM $table WHERE $constantSql and
# $column = $value" is currently represented by $self, and this set should
# be updated to look like $other.
#
# Returns an array of two strings, one INSERT and one DELETE, which will
# make this change. Either or both strings may be the empty string,
# meaning that no INSERT or DELETE or both (respectively) need to be done.
#
# THE CALLER IS RESPONSIBLE FOR ANY DESIRED LOCKING AND/OR CONSISTENCY
# CHECKS (not to mention doing the SendSQL() calls).
#
sub generateSqlDeltas {
($#_ == 5) || confess("invalid number of arguments");
my ( $self, # instance ptr to set representing the existing state
$endState, # instance ptr to set representing the desired state
$table, # table where these relations are kept
$invariantName, # column held const for a RelationSet (often "bug_id")
$invariantValue, # what to hold the above column constant at
$columnName # the column which varies (often a userid)
) = @_;
# construct the insert list by finding relations which exist in the
# end state but not the current state.
#
my @endStateRelations = keys(%$endState);
my @insertList = ();
foreach ( @endStateRelations ) {
push ( @insertList, $_ ) if ( ! exists $$self{"$_"} );
}
# we've built the list. If it's non-null, add required sql chrome.
#
my $sqlInsert="";
if ( $#insertList > -1 ) {
$sqlInsert = "INSERT INTO $table ($invariantName, $columnName) VALUES " .
join (",",
map ( "($invariantValue, $_)" , @insertList )
);
}
# construct the delete list by seeing which relations exist in the
# current state but not the end state
#
my @selfRelations = keys(%$self);
my @deleteList = ();
foreach ( @selfRelations ) {
push (@deleteList, $_) if ( ! exists $$endState{"$_"} );
}
# we've built the list. if it's non-empty, add required sql chrome.
#
my $sqlDelete = "";
if ( $#deleteList > -1 ) {
$sqlDelete = "DELETE FROM $table WHERE $invariantName = $invariantValue " .
"AND $columnName IN ( " . join (",", @deleteList) . " )";
}
return ($sqlInsert, $sqlDelete);
}
# compare the current object with another.
#
sub isEqual {
($#_ == 1) || confess("invalid number of arguments");
my $self = shift();
my $other = shift();
# get arrays of the keys for faster processing
#
my @selfRelations = keys(%$self);
my @otherRelations = keys(%$other);
# make sure the arrays are the same size
#
return 0 if ( $#selfRelations != $#otherRelations );
# bail out if any of the elements are different
#
foreach my $relation ( @selfRelations ) {
return 0 if ( !exists $$other{$relation})
}
# we made it!
#
return 1;
}
# merge the results of a SQL command into this set
#
sub mergeFromDB {
( $#_ == 1 ) || confess("invalid number of arguments");
my $self = shift();
&::SendSQL(shift());
while (my @row = &::FetchSQLData()) {
$$self{$row[0]} = 1;
}
return;
}
# merge a set in string form into this set
#
sub mergeFromString {
($#_ == 1) || confess("invalid number of arguments");
my $self = shift();
# do the merge
#
foreach my $person (split(/[ ,]/, shift())) {
if ($person ne "") {
$$self{&::DBNameToIdAndCheck($person)} = 1;
}
}
}
# remove a set in string form from this set
#
sub removeItemsInString {
($#_ == 1) || confess("invalid number of arguments");
my $self = shift();
# do the merge
#
foreach my $person (split(/[ ,]/, shift())) {
if ($person ne "") {
my $dbid = &::DBNameToIdAndCheck($person);
if (exists $$self{$dbid}) {
delete $$self{$dbid};
}
}
}
}
# remove a set in array form from this set
#
sub removeItemsInArray {
($#_ > 0) || confess("invalid number of arguments");
my $self = shift();
# do the merge
#
while (my $person = shift()) {
if ($person ne "") {
my $dbid = &::DBNameToIdAndCheck($person);
if (exists $$self{$dbid}) {
delete $$self{$dbid};
}
}
}
}
# return the number of elements in this set
#
sub size {
my $self = shift();
my @k = keys(%$self);
return $#k++;
}
# return this set in array form
#
sub toArray {
my $self= shift();
return keys(%$self);
}
# return this set as an array of strings
#
sub toArrayOfStrings {
($#_ == 0) || confess("invalid number of arguments");
my $self = shift();
my @result = ();
foreach my $i ( keys %$self ) {
push @result, &::DBID_to_name($i);
}
return sort { lc($a) cmp lc($b) } @result;
}
# return this set in string form (comma-separated and sorted)
#
sub toString {
($#_ == 0) || confess("invalid number of arguments");
my $self = shift();
my @result = ();
foreach my $i ( keys %$self ) {
push @result, &::DBID_to_name($i);
}
return join(',', sort(@result));
}
1;

View File

@@ -1,273 +0,0 @@
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Myk Melez <myk@mozilla.org>
################################################################################
# Module Initialization
################################################################################
# Make it harder for us to do dangerous things in Perl.
use diagnostics;
use strict;
# Bundle the functions in this file together into the "Token" package.
package Token;
use Date::Format;
# This module requires that its caller have said "require CGI.pl" to import
# relevant functions from that script and its companion globals.pl.
################################################################################
# Constants
################################################################################
# The maximum number of days a token will remain valid.
my $maxtokenage = 3;
################################################################################
# Functions
################################################################################
sub IssueEmailChangeToken {
my ($userid, $old_email, $new_email) = @_;
my $token_ts = time();
my $issuedate = time2str("%Y-%m-%d %H:%M", $token_ts);
# Generate a unique token and insert it into the tokens table.
# We have to lock the tokens table before generating the token,
# since the database must be queried for token uniqueness.
&::SendSQL("LOCK TABLES tokens WRITE");
my $token = GenerateUniqueToken();
my $quotedtoken = &::SqlQuote($token);
my $quoted_emails = &::SqlQuote($old_email . ":" . $new_email);
&::SendSQL("INSERT INTO tokens ( userid , issuedate , token ,
tokentype , eventdata )
VALUES ( $userid , '$issuedate' , $quotedtoken ,
'emailold' , $quoted_emails )");
my $newtoken = GenerateUniqueToken();
$quotedtoken = &::SqlQuote($newtoken);
&::SendSQL("INSERT INTO tokens ( userid , issuedate , token ,
tokentype , eventdata )
VALUES ( $userid , '$issuedate' , $quotedtoken ,
'emailnew' , $quoted_emails )");
&::SendSQL("UNLOCK TABLES");
# Mail the user the token along with instructions for using it.
my $template = $::template;
my $vars = $::vars;
$vars->{'oldemailaddress'} = $old_email . &::Param('emailsuffix');
$vars->{'newemailaddress'} = $new_email . &::Param('emailsuffix');
$vars->{'max_token_age'} = $maxtokenage;
$vars->{'token_ts'} = $token_ts;
$vars->{'token'} = $token;
$vars->{'emailaddress'} = $old_email . &::Param('emailsuffix');
my $message;
$template->process("account/email/change-old.txt.tmpl", $vars, \$message)
|| &::ThrowTemplateError($template->error());
open SENDMAIL, "|/usr/lib/sendmail -t -i";
print SENDMAIL $message;
close SENDMAIL;
$vars->{'token'} = $newtoken;
$vars->{'emailaddress'} = $new_email . &::Param('emailsuffix');
$message = "";
$template->process("account/email/change-new.txt.tmpl", $vars, \$message)
|| &::ThrowTemplateError($template->error());
open SENDMAIL, "|/usr/lib/sendmail -t -i";
print SENDMAIL $message;
close SENDMAIL;
}
sub IssuePasswordToken {
# Generates a random token, adds it to the tokens table, and sends it
# to the user with instructions for using it to change their password.
my ($loginname) = @_;
# Retrieve the user's ID from the database.
my $quotedloginname = &::SqlQuote($loginname);
&::SendSQL("SELECT userid FROM profiles WHERE login_name = $quotedloginname");
my ($userid) = &::FetchSQLData();
my $token_ts = time();
my $issuedate = time2str("%Y-%m-%d %H:%M", $token_ts);
# Generate a unique token and insert it into the tokens table.
# We have to lock the tokens table before generating the token,
# since the database must be queried for token uniqueness.
&::SendSQL("LOCK TABLE tokens WRITE") if $::driver eq 'mysql';
my $token = GenerateUniqueToken();
my $quotedtoken = &::SqlQuote($token);
my $quotedipaddr = &::SqlQuote($::ENV{'REMOTE_ADDR'});
&::SendSQL("INSERT INTO tokens ( userid , issuedate , token , tokentype , eventdata )
VALUES ( $userid , '$issuedate' , $quotedtoken , 'password' , $quotedipaddr )");
&::SendSQL("UNLOCK TABLES") if $::driver eq 'mysql';
# Mail the user the token along with instructions for using it.
my $template = $::template;
my $vars = $::vars;
$vars->{'token'} = $token;
$vars->{'emailaddress'} = $loginname . &::Param('emailsuffix');
$vars->{'max_token_age'} = $maxtokenage;
$vars->{'token_ts'} = $token_ts;
my $message = "";
$template->process("account/password/forgotten-password.txt.tmpl",
$vars, \$message)
|| &::ThrowTemplateError($template->error());
open SENDMAIL, "|/usr/lib/sendmail -t -i";
print SENDMAIL $message;
close SENDMAIL;
}
sub CleanTokenTable {
&::SendSQL("LOCK TABLES tokens WRITE") if $::driver eq 'mysql';
if ($::driver eq 'mysql') {
&::SendSQL("DELETE FROM tokens WHERE TO_DAYS(NOW()) - TO_DAYS(issuedate) >= " . $maxtokenage);
} elsif ($::driver eq 'Pg') {
&::SendSQL("DELETE FROM tokens WHERE now() - issuedate >= '$maxtokenage days'");
}
&::SendSQL("UNLOCK TABLES") if $::driver eq 'mysql';
}
sub GenerateUniqueToken {
# Generates a unique random token. Uses &GenerateRandomPassword
# for the tokens themselves and checks uniqueness by searching for
# the token in the "tokens" table. Gives up if it can't come up
# with a token after about one hundred tries.
my $token;
my $duplicate = 1;
my $tries = 0;
while ($duplicate) {
++$tries;
if ($tries > 100) {
&::DisplayError("Something is seriously wrong with the token generation system.");
exit;
}
$token = &::GenerateRandomPassword();
&::SendSQL("SELECT userid FROM tokens WHERE token = " . &::SqlQuote($token));
$duplicate = &::FetchSQLData();
}
return $token;
}
sub Cancel {
# Cancels a previously issued token and notifies the system administrator.
# This should only happen when the user accidentally makes a token request
# or when a malicious hacker makes a token request on behalf of a user.
my ($token, $cancelaction) = @_;
# Quote the token for inclusion in SQL statements.
my $quotedtoken = &::SqlQuote($token);
# Get information about the token being cancelled.
&::SendSQL("SELECT issuedate , tokentype , eventdata , login_name , realname
FROM tokens, profiles
WHERE tokens.userid = profiles.userid
AND token = $quotedtoken");
my ($issuedate, $tokentype, $eventdata, $loginname, $realname) = &::FetchSQLData();
# Get the email address of the Bugzilla maintainer.
my $maintainer = &::Param('maintainer');
# Format the user's real name and email address into a single string.
my $username = $realname ? $realname . " <" . $loginname . ">" : $loginname;
my $template = $::template;
my $vars = $::vars;
$vars->{'emailaddress'} = $username;
$vars->{'maintainer'} = $maintainer;
$vars->{'remoteaddress'} = $::ENV{'REMOTE_ADDR'};
$vars->{'token'} = $token;
$vars->{'tokentype'} = $tokentype;
$vars->{'issuedate'} = $issuedate;
$vars->{'eventdata'} = $eventdata;
$vars->{'cancelaction'} = $cancelaction;
# Notify the user via email about the cancellation.
my $message;
$template->process("account/cancel-token.txt.tmpl", $vars, \$message)
|| &::ThrowTemplateError($template->error());
open SENDMAIL, "|/usr/lib/sendmail -t -i";
print SENDMAIL $message;
close SENDMAIL;
# Delete the token from the database.
&::SendSQL("LOCK TABLE tokens WRITE") if $::driver eq 'mysql';
&::SendSQL("DELETE FROM tokens WHERE token = $quotedtoken");
&::SendSQL("UNLOCK TABLES") if $::driver eq 'mysql';
}
sub HasPasswordToken {
# Returns a password token if the user has one.
my ($userid) = @_;
&::SendSQL("SELECT token FROM tokens
WHERE userid = $userid AND tokentype = 'password' LIMIT 1");
my ($token) = &::FetchSQLData();
return $token;
}
sub HasEmailChangeToken {
# Returns an email change token if the user has one.
my ($userid) = @_;
&::SendSQL("SELECT token FROM tokens
WHERE userid = $userid
AND tokentype = 'emailnew'
OR tokentype = 'emailold' LIMIT 1");
my ($token) = &::FetchSQLData();
return $token;
}
1;

View File

@@ -1,3 +0,0 @@
Please consult The Bugzilla Guide for instructions on how to upgrade
Bugzilla from an older version. The Guide can be found with this
distribution, in docs/html, docs/txt, and docs/sgml.

View File

@@ -1,407 +0,0 @@
This file contains only important changes made to Bugzilla before release
2.8. If you are upgrading from version older than 2.8, please read this file.
If you are upgrading from 2.8 or newer, please read the Installation and
Upgrade instructions in The Bugzilla Guide, found with this distribution in
docs/html, docs/txt, and docs/sgml.
For a complete list of what changes, use Bonsai
(http://cvs-mirror.mozilla.org/webtools/bonsai/cvsqueryform.cgi) to
query the CVS tree. For example,
http://cvs-mirror.mozilla.org/webtools/bonsai/cvsquery.cgi?module=all&branch=HEAD&branchtype=match&dir=mozilla%2Fwebtools%2Fbugzilla&file=&filetype=match&who=&whotype=match&sortby=Date&hours=2&date=week&mindate=&maxdate=&cvsroot=%2Fcvsroot
will tell you what has been changed in the last week.
10/12/99 The CHANGES file is now obsolete! There is a new file called
checksetup.pl. You should get in the habit of running that file every time
you update your installation of Bugzilla. That file will be constantly
updated to automatically update your installation to match any code changes.
If you're curious as to what is going on, changes are commented in that file,
at the end.
Many thanks to Holger Schurig <holgerschurig@nikocity.de> for writing this
script!
10/11/99 Restructured voting database to add a cached value in each
bug recording how many total votes that bug has. While I'm at it, I
removed the unused "area" field from the bugs database. It is
distressing to realize that the bugs table has reached the maximum
number of indices allowed by MySQL (16), which may make future
enhancements awkward.
You must feed the following to MySQL:
alter table bugs drop column area;
alter table bugs add column votes mediumint not null, add index (votes);
You then *must* delete the data/versioncache file when you make this
change, as it contains references to the "area" field. Deleting it is safe,
bugzilla will correctly regenerate it.
If you have been using the voting feature at all, then you will then
need to update the voting cache. You can do this by visiting the
sanitycheck.cgi page, and taking it up on its offer to rebuild the
votes stuff.
10/7/99 Added voting ability. You must run the new script
"makevotestable.sh". You must also feed the following to mysql:
alter table products add column votesperuser smallint not null;
9/15/99 Apparently, newer alphas of MySQL won't allow you to have
"when" as a column name. So, I have had to rename a column in the
bugs_activity table. You must feed the below to mysql or you won't
work at all.
alter table bugs_activity change column when bug_when datetime not null;
8/16/99 Added "OpenVMS" to the list of OS's. Feed this to mysql:
alter table bugs change column op_sys op_sys enum("All", "Windows 3.1", "Windows 95", "Windows 98", "Windows NT", "Mac System 7", "Mac System 7.5", "Mac System 7.6.1", "Mac System 8.0", "Mac System 8.5", "Mac System 8.6", "AIX", "BSDI", "HP-UX", "IRIX", "Linux", "FreeBSD", "OSF/1", "Solaris", "SunOS", "Neutrino", "OS/2", "BeOS", "OpenVMS", "other") not null;
6/22/99 Added an entry to the attachments table to record who the submitter
was. Nothing uses this yet, but it still should be recorded.
alter table attachments add column submitter_id mediumint not null;
You should also run this script to populate the new field:
#!/usr/bonsaitools/bin/perl -w
use diagnostics;
use strict;
require "globals.pl";
$|=1;
ConnectToDatabase();
SendSQL("select bug_id, attach_id from attachments order by bug_id");
my @list;
while (MoreSQLData()) {
my @row = FetchSQLData();
push(@list, \@row);
}
foreach my $ref (@list) {
my ($bug, $attach) = (@$ref);
SendSQL("select long_desc from bugs where bug_id = $bug");
my $comment = FetchOneColumn() . "Created an attachment (id=$attach)";
if ($comment =~ m@-* Additional Comments From ([^ ]*)[- 0-9/:]*\nCreated an attachment \(id=$attach\)@) {
print "Found $1\n";
SendSQL("select userid from profiles where login_name=" .
SqlQuote($1));
my $userid = FetchOneColumn();
if (defined $userid && $userid > 0) {
SendSQL("update attachments set submitter_id=$userid where attach_id = $attach");
}
} else {
print "Bug $bug can't find comment for attachment $attach\n";
}
}
6/14/99 Added "BeOS" to the list of OS's. Feed this to mysql:
alter table bugs change column op_sys op_sys enum("All", "Windows 3.1", "Windows 95", "Windows 98", "Windows NT", "Mac System 7", "Mac System 7.5", "Mac System 7.6.1", "Mac System 8.0", "Mac System 8.5", "Mac System 8.6", "AIX", "BSDI", "HP-UX", "IRIX", "Linux", "FreeBSD", "OSF/1", "Solaris", "SunOS", "Neutrino", "OS/2", "BeOS", "other") not null;
5/27/99 Added support for dependency information. You must run the new
"makedependenciestable.sh" script. You can turn off dependencies with the new
"usedependencies" param, but it defaults to being on. Also, read very
carefully the description for the new "webdotbase" param; you will almost
certainly need to tweak it.
5/24/99 Added "Mac System 8.6" and "Neutrino" to the list of OS's.
Feed this to mysql:
alter table bugs change column op_sys op_sys enum("All", "Windows 3.1", "Windows 95", "Windows 98", "Windows NT", "Mac System 7", "Mac System 7.5", "Mac System 7.6.1", "Mac System 8.0", "Mac System 8.5", "Mac System 8.6", "AIX", "BSDI", "HP-UX", "IRIX", "Linux", "FreeBSD", "OSF/1", "Solaris", "SunOS", "Neutrino", "OS/2", "other") not null;
5/12/99 Added a pref to control how much email you get. This needs a new
column in the profiles table, so feed the following to mysql:
alter table profiles add column emailnotification enum("ExcludeSelfChanges", "CConly", "All") not null default "ExcludeSelfChanges";
5/5/99 Added the ability to search by creation date. To make this perform
well, you ought to do the following:
alter table bugs change column creation_ts creation_ts datetime not null, add index (creation_ts);
4/30/99 Added a new severity, "blocker". To get this into your running
Bugzilla, do the following:
alter table bugs change column bug_severity bug_severity enum("blocker", "critical", "major", "normal", "minor", "trivial", "enhancement") not null;
4/22/99 There was a bug where the long descriptions of bugs had a variety of
newline characters at the end, depending on the operating system of the browser
that submitted the text. This bug has been fixed, so that no further changes
like that will happen. But to fix problems that have already crept into your
database, you can run the following perl script (which is slow and ugly, but
does work:)
#!/usr/bonsaitools/bin/perl -w
use diagnostics;
use strict;
require "globals.pl";
$|=1;
ConnectToDatabase();
SendSQL("select bug_id from bugs order by bug_id");
my @list;
while (MoreSQLData()) {
push(@list, FetchOneColumn());
}
foreach my $id (@list) {
if ($id % 50 == 0) {
print "\n$id ";
}
SendSQL("select long_desc from bugs where bug_id = $id");
my $comment = FetchOneColumn();
my $orig = $comment;
$comment =~ s/\r\n/\n/g; # Get rid of windows-style line endings.
$comment =~ s/\r/\n/g; # Get rid of mac-style line endings.
if ($comment ne $orig) {
SendSQL("update bugs set long_desc = " . SqlQuote($comment) .
" where bug_id = $id");
print ".";
} else {
print "-";
}
}
4/8/99 Added ability to store patches with bugs. This requires a new table
to store the data, so you will need to run the "makeattachmenttable.sh" script.
3/25/99 Unfortunately, the HTML::FromText CPAN module had too many bugs, and
so I had to roll my own. We no longer use the HTML::FromText CPAN module.
3/24/99 (This entry has been removed. It used to say that we required the
HTML::FromText CPAN module, but that's no longer true.)
3/22/99 Added the ability to query by fields which have changed within a date
range. To make this perform a bit better, we need a new index:
alter table bugs_activity add index (field);
3/10/99 Added 'groups' stuff, where we have different group bits that we can
put on a person or on a bug. Some of the group bits control access to bugzilla
features. And a person can't access a bug unless he has every group bit set
that is also set on the bug. See the comments in makegroupstable.sh for a bit
more info.
The 'maintainer' param is now used only as an email address for people to send
complaints to. The groups table is what is now used to determine permissions.
You will need to run the new script "makegroupstable.sh". And then you need to
feed the following lines to MySQL (replace XXX with the login name of the
maintainer, the person you wish to be all-powerful).
alter table bugs add column groupset bigint not null;
alter table profiles add column groupset bigint not null;
update profiles set groupset=0x7fffffffffffffff where login_name = XXX;
3/8/99 Added params to control how priorities are set in a new bug. You can
now choose whether to let submitters of new bugs choose a priority, or whether
they should just accept the default priority (which is now no longer hardcoded
to "P2", but is instead a param.) The default value of the params will cause
the same behavior as before.
3/3/99 Added a "disallownew" field to the products table. If non-zero, then
don't let people file new bugs against this product. (This is for when a
product is retired, but you want to keep the bug reports around for posterity.)
Feed this to MySQL:
alter table products add column disallownew tinyint not null;
2/8/99 Added FreeBSD to the list of OS's. Feed this to MySQL:
alter table bugs change column op_sys op_sys enum("All", "Windows 3.1", "Windows 95", "Windows 98", "Windows NT", "Mac System 7", "Mac System 7.5", "Mac System 7.6.1", "Mac System 8.0", "Mac System 8.5", "AIX", "BSDI", "HP-UX", "IRIX", "Linux", "FreeBSD", "OSF/1", "Solaris", "SunOS", "OS/2", "other") not null;
2/4/99 Added a new column "description" to the components table, and added
links to a new page which will use this to describe the components of a
given product. Feed this to MySQL:
alter table components add column description mediumtext not null;
2/3/99 Added a new column "initialqacontact" to the components table that gives
an initial QA contact field. It may be empty if you wish the initial qa
contact to be empty. If you're not using the QA contact field, you don't need
to add this column, but you might as well be safe and add it anyway:
alter table components add column initialqacontact tinytext not null;
2/2/99 Added a new column "milestoneurl" to the products table that gives a URL
which is to describe the currently defined milestones for a product. If you
don't use target milestone, you might be able to get away without adding this
column, but you might as well be safe and add it anyway:
alter table products add column milestoneurl tinytext not null;
1/29/99 Whoops; had a misspelled op_sys. It was "Mac System 7.1.6"; it should
be "Mac System 7.6.1". It turns out I had no bugs with this value set, so I
could just do the below simple command. If you have bugs with this value, you
may need to do something more complicated.
alter table bugs change column op_sys op_sys enum("All", "Windows 3.1", "Windows 95", "Windows 98", "Windows NT", "Mac System 7", "Mac System 7.5", "Mac System 7.6.1", "Mac System 8.0", "Mac System 8.5", "AIX", "BSDI", "HP-UX", "IRIX", "Linux", "OSF/1", "Solaris", "SunOS", "OS/2", "other") not null;
1/20/99 Added new fields: Target Milestone, QA Contact, and Status Whiteboard.
These fields are all optional in the UI; there are parameters to turn them on.
However, whether or not you use them, the fields need to be in the DB. There
is some code that needs them, even if you don't.
To update your DB to have these fields, send the following to MySQL:
alter table bugs add column target_milestone varchar(20) not null,
add column qa_contact mediumint not null,
add column status_whiteboard mediumtext not null,
add index (target_milestone), add index (qa_contact);
1/18/99 You can now query by CC. To make this perform reasonably, the CC table
needs some indices. The following MySQL does the necessary stuff:
alter table cc add index (bug_id), add index (who);
1/15/99 The op_sys field can now be queried by (and more easily tweaked).
To make this perform reasonably, it needs an index. The following MySQL
command will create the necessary index:
alter table bugs add index (op_sys);
12/2/98 The op_sys and rep_platform fields have been tweaked. op_sys
is now an enum, rather than having the legal values all hard-coded in
perl. rep_platform now no longer allows a value of "X-Windows".
Here's how I ported to the new world. This ought to work for you too.
Actually, it's probably overkill. I had a lot of illegal values for op_sys
in my tables, from importing bugs from strange places. If you haven't done
anything funky, then much of the below will be a no-op.
First, send the following commands to MySQL to make sure all your values for
rep_platform and op_sys are legal in the new world..
update bugs set rep_platform="Sun" where rep_platform="X-Windows" and op_sys like "Solaris%";
update bugs set rep_platform="SGI" where rep_platform="X-Windows" and op_sys = "IRIX";
update bugs set rep_platform="SGI" where rep_platform="X-Windows" and op_sys = "HP-UX";
update bugs set rep_platform="DEC" where rep_platform="X-Windows" and op_sys = "OSF/1";
update bugs set rep_platform="PC" where rep_platform="X-Windows" and op_sys = "Linux";
update bugs set rep_platform="other" where rep_platform="X-Windows";
update bugs set rep_platform="other" where rep_platform="";
update bugs set op_sys="Mac System 7" where op_sys="System 7";
update bugs set op_sys="Mac System 7.5" where op_sys="System 7.5";
update bugs set op_sys="Mac System 8.0" where op_sys="8.0";
update bugs set op_sys="OSF/1" where op_sys="Digital Unix 4.0";
update bugs set op_sys="IRIX" where op_sys like "IRIX %";
update bugs set op_sys="HP-UX" where op_sys like "HP-UX %";
update bugs set op_sys="Windows NT" where op_sys like "NT %";
update bugs set op_sys="OSF/1" where op_sys like "OSF/1 %";
update bugs set op_sys="Solaris" where op_sys like "Solaris %";
update bugs set op_sys="SunOS" where op_sys like "SunOS%";
update bugs set op_sys="other" where op_sys = "Motif";
update bugs set op_sys="other" where op_sys = "Other";
Next, send the following commands to make sure you now have only legal
entries in your table. If either of the queries do not come up empty, then
you have to do more stuff like the above.
select bug_id,op_sys,rep_platform from bugs where rep_platform not regexp "^(All|DEC|HP|Macintosh|PC|SGI|Sun|X-Windows|Other)$";
select bug_id,op_sys,rep_platform from bugs where op_sys not regexp "^(All|Windows 3.1|Windows 95|Windows 98|Windows NT|Mac System 7|Mac System 7.5|Mac System 7.1.6|Mac System 8.0|AIX|BSDI|HP-UX|IRIX|Linux|OSF/1|Solaris|SunOS|other)$";
Finally, once that's all clear, alter the table to make enforce the new legal
entries:
alter table bugs change column op_sys op_sys enum("All", "Windows 3.1", "Windows 95", "Windows 98", "Windows NT", "Mac System 7", "Mac System 7.5", "Mac System 7.1.6", "Mac System 8.0", "AIX", "BSDI", "HP-UX", "IRIX", "Linux", "OSF/1", "Solaris", "SunOS", "other") not null, change column rep_platform rep_platform enum("All", "DEC", "HP", "Macintosh", "PC", "SGI", "Sun", "Other");
11/20/98 Added searching of CC field. To better support this, added
some indexes to the CC table. You probably want to execute the following
mysql commands:
alter table cc add index (bug_id);
alter table cc add index (who);
10/27/98 security check for legal products in place. bug charts are not
available as an option if collectstats.pl has never been run. all products
get daily stats collected now. README updated: Chart::Base is listed as
a requirement, instructions for using collectstats.pl included as
an optional step. also got silly and added optional quips to bug
reports.
10/17/98 modified README installation instructions slightly.
10/7/98 Added a new table called "products". Right now, this is used
only to have a description for each product, and that description is
only used when initially adding a new bug. Anyway, you *must* create
the new table (which you can do by running the new makeproducttable.sh
script). If you just leave it empty, things will work much as they
did before, or you can add descriptions for some or all of your
products.
9/15/98 Everything has been ported to Perl. NO MORE TCL. This
transition should be relatively painless, except for the "params"
file. This is the file that contains parameters you've set up on the
editparams.cgi page. Before changing to Perl, this was a tcl-syntax
file, stored in the same directory as the code; after the change to
Perl, it becomes a perl-syntax file, stored in a subdirectory named
"data". See the README file for more details on what version of Perl
you need.
So, if updating from an older version of Bugzilla, you will need to
edit data/param, change the email address listed for
$::param{'maintainer'}, and then go revisit the editparams.cgi page
and reset all the parameters to your taste. Fortunately, your old
params file will still be around, and so you ought to be able to
cut&paste important bits from there.
Also, note that the "whineatnews" script has changed name (it now has
an extension of .pl instead of .tcl), so you'll need to change your
cron job.
And the "comments" file has been moved to the data directory. Just do
"cat comments >> data/comments" to restore any old comments that may
have been lost.
9/2/98 Changed the way password validation works. We now keep a
crypt'd version of the password in the database, and check against
that. (This is silly, because we're also keeping the plaintext
version there, but I have plans...) Stop passing the plaintext
password around as a cookie; instead, we have a cookie that references
a record in a new database table, logincookies.
IMPORTANT: if updating from an older version of Bugzilla, you must run
the following commands to keep things working:
./makelogincookiestable.sh
echo "alter table profiles add column cryptpassword varchar(64);" | mysql bugs
echo "update profiles set cryptpassword = encrypt(password,substring(rand(),3, 4));" | mysql bugs

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

View File

@@ -1,792 +0,0 @@
#!/usr/bonsaitools/bin/perl -wT
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
# Myk Melez <myk@mozilla.org>
################################################################################
# Script Initialization
################################################################################
# Make it harder for us to do dangerous things in Perl.
use diagnostics;
use strict;
use lib qw(.);
use vars qw(
$template
$vars
);
# Include the Bugzilla CGI and general utility library.
require "CGI.pl";
# Establish a connection to the database backend.
ConnectToDatabase();
# Check whether or not the user is logged in and, if so, set the $userid
my $userid = quietly_check_login();
################################################################################
# Main Body Execution
################################################################################
# All calls to this script should contain an "action" variable whose value
# determines what the user wants to do. The code below checks the value of
# that variable and runs the appropriate code.
# Determine whether to use the action specified by the user or the default.
my $action = $::FORM{'action'} || 'view';
if ($action eq "view")
{
validateID();
view();
}
elsif ($action eq "viewall")
{
ValidateBugID($::FORM{'bugid'}, $userid);
viewall();
}
elsif ($action eq "enter")
{
my $userid = confirm_login();
ValidateBugID($::FORM{'bugid'}, $userid);
enter();
}
elsif ($action eq "insert")
{
my $userid = confirm_login();
ValidateBugID($::FORM{'bugid'}, $userid);
ValidateComment($::FORM{'comment'});
validateFilename();
validateData();
validateDescription();
validateIsPatch();
validateContentType() unless $::FORM{'ispatch'};
validateObsolete() if $::FORM{'obsolete'};
insert();
}
elsif ($action eq "edit")
{
quietly_check_login();
validateID();
validateCanEdit($::FORM{'id'});
edit();
}
elsif ($action eq "update")
{
my $userid = confirm_login();
UserInGroup($userid, "editbugs")
|| DisplayError("You are not authorized to edit attachments.")
&& exit;
ValidateComment($::FORM{'comment'});
validateID();
validateCanEdit($::FORM{'id'});
validateDescription();
validateIsPatch();
validateContentType() unless $::FORM{'ispatch'};
validateIsObsolete();
validateStatuses();
update();
}
else
{
DisplayError("I could not figure out what you wanted to do.")
}
exit;
################################################################################
# Data Validation / Security Authorization
################################################################################
sub validateID
{
# Validate the value of the "id" form field, which must contain an
# integer that is the ID of an existing attachment.
detaint_natural($::FORM{'id'})
|| DisplayError("You did not enter a valid attachment number.")
&& exit;
# Make sure the attachment exists in the database.
SendSQL("SELECT bug_id FROM attachments WHERE attach_id = $::FORM{'id'}");
MoreSQLData()
|| DisplayError("Attachment #$::FORM{'id'} does not exist.")
&& exit;
# Make sure the user is authorized to access this attachment's bug.
my ($bugid) = FetchSQLData();
ValidateBugID($bugid, $userid);
}
sub validateCanEdit
{
my ($attach_id) = (@_);
# If the user is not logged in, claim that they can edit. This allows
# the edit scrren to be displayed to people who aren't logged in.
# People not logged in can't actually commit changes, because that code
# calls confirm_login, not quietly_check_login, before calling this sub
return if $userid == 0;
# People in editbugs can edit all attachments
return if UserInGroup($userid, "editbugs");
# Bug 97729 - the submitter can edit their attachments
SendSQL("SELECT attach_id FROM attachments WHERE " .
"attach_id = $attach_id AND submitter_id = $userid");
FetchSQLData()
|| DisplayError("You are not authorised to edit attachment #$attach_id")
&& exit;
}
sub validateDescription
{
$::FORM{'description'}
|| DisplayError("You must enter a description for the attachment.")
&& exit;
}
sub validateIsPatch
{
# Set the ispatch flag to zero if it is undefined, since the UI uses
# an HTML checkbox to represent this flag, and unchecked HTML checkboxes
# do not get sent in HTML requests.
$::FORM{'ispatch'} = $::FORM{'ispatch'} ? 1 : 0;
# Set the content type to text/plain if the attachment is a patch.
$::FORM{'contenttype'} = "text/plain" if $::FORM{'ispatch'};
}
sub validateContentType
{
if (!$::FORM{'contenttypemethod'})
{
DisplayError("You must choose a method for determining the content type,
either <em>auto-detect</em>, <em>select from list</em>, or <em>enter
manually</em>.");
exit;
}
elsif ($::FORM{'contenttypemethod'} eq 'autodetect')
{
# The user asked us to auto-detect the content type, so use the type
# specified in the HTTP request headers.
if ( !$::FILE{'data'}->{'contenttype'} )
{
DisplayError("You asked Bugzilla to auto-detect the content type, but
your browser did not specify a content type when uploading the file,
so you must enter a content type manually.");
exit;
}
$::FORM{'contenttype'} = $::FILE{'data'}->{'contenttype'};
}
elsif ($::FORM{'contenttypemethod'} eq 'list')
{
# The user selected a content type from the list, so use their selection.
$::FORM{'contenttype'} = $::FORM{'contenttypeselection'};
}
elsif ($::FORM{'contenttypemethod'} eq 'manual')
{
# The user entered a content type manually, so use their entry.
$::FORM{'contenttype'} = $::FORM{'contenttypeentry'};
}
else
{
my $htmlcontenttypemethod = html_quote($::FORM{'contenttypemethod'});
DisplayError("Your form submission got corrupted somehow. The <em>content
method</em> field, which specifies how the content type gets determined,
should have been either <em>autodetect</em>, <em>list</em>,
or <em>manual</em>, but was instead <em>$htmlcontenttypemethod</em>.");
exit;
}
if ( $::FORM{'contenttype'} !~ /^(application|audio|image|message|model|multipart|text|video)\/.+$/ )
{
my $htmlcontenttype = html_quote($::FORM{'contenttype'});
DisplayError("The content type <em>$htmlcontenttype</em> is invalid.
Valid types must be of the form <em>foo/bar</em> where <em>foo</em>
is either <em>application, audio, image, message, model, multipart,
text,</em> or <em>video</em>.");
exit;
}
}
sub validateIsObsolete
{
# Set the isobsolete flag to zero if it is undefined, since the UI uses
# an HTML checkbox to represent this flag, and unchecked HTML checkboxes
# do not get sent in HTML requests.
$::FORM{'isobsolete'} = $::FORM{'isobsolete'} ? 1 : 0;
}
sub validateStatuses
{
# Get a list of attachment statuses that are valid for this attachment.
PushGlobalSQLState();
SendSQL("SELECT attachstatusdefs.id
FROM attachments, bugs, attachstatusdefs
WHERE attachments.attach_id = $::FORM{'id'}
AND attachments.bug_id = bugs.bug_id
AND attachstatusdefs.product = bugs.product");
my @statusdefs;
push(@statusdefs, FetchSQLData()) while MoreSQLData();
PopGlobalSQLState();
foreach my $status (@{$::MFORM{'status'}})
{
grep($_ == $status, @statusdefs)
|| DisplayError("One of the statuses you entered is not a valid status
for this attachment.")
&& exit;
# We have tested that the status is valid, so it can be detainted
detaint_natural($status);
}
}
sub validateData
{
$::FORM{'data'}
|| DisplayError("The file you are trying to attach is empty!")
&& exit;
my $len = length($::FORM{'data'});
my $maxpatchsize = Param('maxpatchsize');
my $maxattachmentsize = Param('maxattachmentsize');
# Makes sure the attachment does not exceed either the "maxpatchsize" or
# the "maxattachmentsize" parameter.
if ( $::FORM{'ispatch'} && $maxpatchsize && $len > $maxpatchsize*1024 )
{
my $lenkb = sprintf("%.0f", $len/1024);
DisplayError("The file you are trying to attach is ${lenkb} kilobytes (KB) in size.
Patches cannot be more than ${maxpatchsize}KB in size.
Try breaking your patch into several pieces.");
exit;
} elsif ( !$::FORM{'ispatch'} && $maxattachmentsize && $len > $maxattachmentsize*1024 ) {
my $lenkb = sprintf("%.0f", $len/1024);
DisplayError("The file you are trying to attach is ${lenkb} kilobytes (KB) in size.
Non-patch attachments cannot be more than ${maxattachmentsize}KB.
If your attachment is an image, try converting it to a compressable
format like JPG or PNG, or put it elsewhere on the web and
link to it from the bug's URL field or in a comment on the bug.");
exit;
}
}
sub validateFilename
{
defined $::FILE{'data'}
|| DisplayError("You did not specify a file to attach.")
&& exit;
}
sub validateObsolete
{
# Make sure the attachment id is valid and the user has permissions to view
# the bug to which it is attached.
foreach my $attachid (@{$::MFORM{'obsolete'}}) {
detaint_natural($attachid)
|| DisplayError("The attachment number of one of the attachments
you wanted to obsolete is invalid.")
&& exit;
SendSQL("SELECT bug_id, isobsolete, description
FROM attachments WHERE attach_id = $attachid");
# Make sure the attachment exists in the database.
MoreSQLData()
|| DisplayError("Attachment #$attachid does not exist.")
&& exit;
my ($bugid, $isobsolete, $description) = FetchSQLData();
if ($bugid != $::FORM{'bugid'})
{
$description = html_quote($description);
DisplayError("Attachment #$attachid ($description) is attached
to bug #$bugid, but you tried to flag it as obsolete while
creating a new attachment to bug #$::FORM{'bugid'}.");
exit;
}
if ( $isobsolete )
{
$description = html_quote($description);
DisplayError("Attachment #$attachid ($description) is already obsolete.");
exit;
}
# Check that the user can modify this attachment
validateCanEdit($attachid);
}
}
################################################################################
# Functions
################################################################################
sub view
{
# Display an attachment.
# Retrieve the attachment content and its content type from the database.
SendSQL("SELECT mimetype, thedata FROM attachments WHERE attach_id = $::FORM{'id'}");
my ($contenttype, $thedata) = FetchSQLData();
# Return the appropriate HTTP response headers.
print "Content-Type: $contenttype\n\n";
print $thedata;
}
sub viewall
{
# Display all attachments for a given bug in a series of IFRAMEs within one HTML page.
# Retrieve the attachments from the database and write them into an array
# of hashes where each hash represents one attachment.
SendSQL("SELECT attach_id, creation_ts, mimetype, description, ispatch, isobsolete
FROM attachments WHERE bug_id = $::FORM{'bugid'} ORDER BY attach_id");
my @attachments; # the attachments array
while (MoreSQLData())
{
my %a; # the attachment hash
($a{'attachid'}, $a{'date'}, $a{'contenttype'},
$a{'description'}, $a{'ispatch'}, $a{'isobsolete'}) = FetchSQLData();
# Format the attachment's creation/modification date into something readable.
if ($a{'date'} =~ /^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/) {
$a{'date'} = "$3/$4/$2&nbsp;$5:$6";
}
# Flag attachments as to whether or not they can be viewed (as opposed to
# being downloaded). Currently I decide they are viewable if their MIME type
# is either text/*, image/*, or application/vnd.mozilla.*.
# !!! Yuck, what an ugly hack. Fix it!
$a{'isviewable'} = ( $a{'contenttype'} =~ /^(text|image|application\/vnd\.mozilla\.)/ );
# Retrieve a list of status flags that have been set on the attachment.
PushGlobalSQLState();
SendSQL("SELECT name
FROM attachstatuses, attachstatusdefs
WHERE attach_id = $a{'attachid'}
AND attachstatuses.statusid = attachstatusdefs.id
ORDER BY sortkey");
my @statuses;
push(@statuses, FetchSQLData()) while MoreSQLData();
$a{'statuses'} = \@statuses;
PopGlobalSQLState();
# Add the hash representing the attachment to the array of attachments.
push @attachments, \%a;
}
# Retrieve the bug summary for displaying on screen.
SendSQL("SELECT short_desc FROM bugs WHERE bug_id = $::FORM{'bugid'}");
my ($bugsummary) = FetchSQLData();
# Define the variables and functions that will be passed to the UI template.
$vars->{'bugid'} = $::FORM{'bugid'};
$vars->{'bugsummary'} = $bugsummary;
$vars->{'attachments'} = \@attachments;
# Return the appropriate HTTP response headers.
print "Content-Type: text/html\n\n";
# Generate and return the UI (HTML page) from the appropriate template.
$template->process("attachment/show-multiple.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
}
sub enter
{
# Display a form for entering a new attachment.
# Retrieve the attachments the user can edit from the database and write
# them into an array of hashes where each hash represents one attachment.
my $canEdit = "";
if (!UserInGroup($userid, "editbugs")) {
$canEdit = "AND submitter_id = $userid";
}
SendSQL("SELECT attach_id, description
FROM attachments
WHERE bug_id = $::FORM{'bugid'}
AND isobsolete = 0 $canEdit
ORDER BY attach_id");
my @attachments; # the attachments array
while ( MoreSQLData() ) {
my %a; # the attachment hash
($a{'id'}, $a{'description'}) = FetchSQLData();
# Add the hash representing the attachment to the array of attachments.
push @attachments, \%a;
}
# Retrieve the bug summary for displaying on screen.
SendSQL("SELECT short_desc FROM bugs WHERE bug_id = $::FORM{'bugid'}");
my ($bugsummary) = FetchSQLData();
# Define the variables and functions that will be passed to the UI template.
$vars->{'bugid'} = $::FORM{'bugid'};
$vars->{'bugsummary'} = $bugsummary;
$vars->{'attachments'} = \@attachments;
# Return the appropriate HTTP response headers.
print "Content-Type: text/html\n\n";
# Generate and return the UI (HTML page) from the appropriate template.
$template->process("attachment/create.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
}
sub insert
{
# Insert a new attachment into the database.
# Escape characters in strings that will be used in SQL statements.
my $filename = SqlQuote($::FILE{'data'}->{'filename'});
my $description = SqlQuote($::FORM{'description'});
my $contenttype = SqlQuote($::FORM{'contenttype'});
my $thedata = SqlQuote($::FORM{'data'});
# Insert the attachment into the database.
SendSQL("INSERT INTO attachments (bug_id, filename, description, mimetype, ispatch, submitter_id, thedata)
VALUES ($::FORM{'bugid'}, $filename, $description, $contenttype, $::FORM{'ispatch'}, $userid, $thedata)");
# Retrieve the ID of the newly created attachment record.
my $attachid = CurrId('attachments_attach_id_seq');
# Insert a comment about the new attachment into the database.
my $comment = "Created an attachment (id=$attachid)\n$::FORM{'description'}\n";
$comment .= ("\n" . $::FORM{'comment'}) if $::FORM{'comment'};
use Text::Wrap;
$Text::Wrap::columns = 80;
$Text::Wrap::huge = 'overflow';
$comment = Text::Wrap::wrap('', '', $comment);
AppendComment($::FORM{'bugid'},
$::COOKIE{"Bugzilla_login"},
$comment);
# Make existing attachments obsolete.
my $fieldid = GetFieldID('attachments.isobsolete');
foreach my $attachid (@{$::MFORM{'obsolete'}}) {
SendSQL("UPDATE attachments SET isobsolete = 1 WHERE attach_id = $attachid");
SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when, fieldid, removed, added)
VALUES ($::FORM{'bugid'}, $attachid, $userid, NOW(), $fieldid, '0', '1')");
}
# Send mail to let people know the attachment has been created. Uses a
# special syntax of the "open" and "exec" commands to capture the output of
# "processmail", which "system" doesn't allow, without running the command
# through a shell, which backticks (``) do.
#system ("./processmail", $bugid , $userid);
#my $mailresults = `./processmail $bugid $::userid`;
my $mailresults = '';
open(PMAIL, "-|") or exec('./processmail', $::FORM{'bugid'}, $::COOKIE{'Bugzilla_login'});
$mailresults .= $_ while <PMAIL>;
close(PMAIL);
# Define the variables and functions that will be passed to the UI template.
$vars->{'bugid'} = $::FORM{'bugid'};
$vars->{'attachid'} = $attachid;
$vars->{'description'} = $description;
$vars->{'mailresults'} = $mailresults;
$vars->{'contenttypemethod'} = $::FORM{'contenttypemethod'};
$vars->{'contenttype'} = $::FORM{'contenttype'};
# Return the appropriate HTTP response headers.
print "Content-Type: text/html\n\n";
# Generate and return the UI (HTML page) from the appropriate template.
$template->process("attachment/created.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
SendSQL("SELECT short_desc FROM bugs WHERE bug_id = $::FORM{'bugid'}");
}
sub edit
{
# Edit an attachment record. Users with "editbugs" privileges, (or the
# original attachment's submitter) can edit the attachment's description,
# content type, ispatch and isobsolete flags, and statuses, and they can
# also submit a comment that appears in the bug.
# Users cannot edit the content of the attachment itself.
# Retrieve the attachment from the database.
SendSQL("SELECT description, mimetype, bug_id, ispatch, isobsolete
FROM attachments WHERE attach_id = $::FORM{'id'}");
my ($description, $contenttype, $bugid, $ispatch, $isobsolete) = FetchSQLData();
# Flag attachment as to whether or not it can be viewed (as opposed to
# being downloaded). Currently I decide it is viewable if its content
# type is either text/.* or application/vnd.mozilla.*.
# !!! Yuck, what an ugly hack. Fix it!
my $isviewable = ( $contenttype =~ /^(text|image|application\/vnd\.mozilla\.)/ );
# Retrieve a list of status flags that have been set on the attachment.
my %statuses;
SendSQL("SELECT id, name
FROM attachstatuses, attachstatusdefs
WHERE attachstatuses.statusid = attachstatusdefs.id
AND attach_id = $::FORM{'id'}");
while ( my ($id, $name) = FetchSQLData() )
{
$statuses{$id} = $name;
}
# Retrieve a list of statuses for this bug's product, and build an array
# of hashes in which each hash is a status flag record.
# ???: Move this into versioncache or its own routine?
my @statusdefs;
SendSQL("SELECT id, name
FROM attachstatusdefs, bugs
WHERE bug_id = $bugid
AND attachstatusdefs.product = bugs.product
ORDER BY sortkey");
while ( MoreSQLData() )
{
my ($id, $name) = FetchSQLData();
push @statusdefs, { 'id' => $id , 'name' => $name };
}
# Retrieve a list of attachments for this bug as well as a summary of the bug
# to use in a navigation bar across the top of the screen.
SendSQL("SELECT attach_id FROM attachments WHERE bug_id = $bugid ORDER BY attach_id");
my @bugattachments;
push(@bugattachments, FetchSQLData()) while (MoreSQLData());
SendSQL("SELECT short_desc FROM bugs WHERE bug_id = $bugid");
my ($bugsummary) = FetchSQLData();
# Define the variables and functions that will be passed to the UI template.
$vars->{'attachid'} = $::FORM{'id'};
$vars->{'description'} = $description;
$vars->{'contenttype'} = $contenttype;
$vars->{'bugid'} = $bugid;
$vars->{'bugsummary'} = $bugsummary;
$vars->{'ispatch'} = $ispatch;
$vars->{'isobsolete'} = $isobsolete;
$vars->{'isviewable'} = $isviewable;
$vars->{'statuses'} = \%statuses;
$vars->{'statusdefs'} = \@statusdefs;
$vars->{'attachments'} = \@bugattachments;
# Return the appropriate HTTP response headers.
print "Content-Type: text/html\n\n";
# Generate and return the UI (HTML page) from the appropriate template.
$template->process("attachment/edit.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
}
sub update
{
# Update an attachment record.
# Get the bug ID for the bug to which this attachment is attached.
SendSQL("SELECT bug_id FROM attachments WHERE attach_id = $::FORM{'id'}");
my $bugid = FetchSQLData()
|| DisplayError("Cannot figure out bug number.")
&& exit;
# Lock database tables in preparation for updating the attachment.
if ($::driver eq 'mysql') {
SendSQL("LOCK TABLES attachments WRITE , attachstatuses WRITE ,
attachstatusdefs READ , fielddefs READ , bugs_activity WRITE");
}
# Get a copy of the attachment record before we make changes
# so we can record those changes in the activity table.
SendSQL("SELECT description, mimetype, ispatch, isobsolete
FROM attachments WHERE attach_id = $::FORM{'id'}");
my ($olddescription, $oldcontenttype, $oldispatch, $oldisobsolete) = FetchSQLData();
# Get the list of old status flags.
SendSQL("SELECT attachstatusdefs.name
FROM attachments, attachstatuses, attachstatusdefs
WHERE attachments.attach_id = $::FORM{'id'}
AND attachments.attach_id = attachstatuses.attach_id
AND attachstatuses.statusid = attachstatusdefs.id
ORDER BY attachstatusdefs.sortkey
");
my @oldstatuses;
while (MoreSQLData()) {
push(@oldstatuses, FetchSQLData());
}
my $oldstatuslist = join(', ', @oldstatuses);
# Update the database with the new status flags.
SendSQL("DELETE FROM attachstatuses WHERE attach_id = $::FORM{'id'}");
foreach my $statusid (@{$::MFORM{'status'}})
{
SendSQL("INSERT INTO attachstatuses (attach_id, statusid) VALUES ($::FORM{'id'}, $statusid)");
}
# Get the list of new status flags.
SendSQL("SELECT attachstatusdefs.name
FROM attachments, attachstatuses, attachstatusdefs
WHERE attachments.attach_id = $::FORM{'id'}
AND attachments.attach_id = attachstatuses.attach_id
AND attachstatuses.statusid = attachstatusdefs.id
ORDER BY attachstatusdefs.sortkey
");
my @newstatuses;
while (MoreSQLData()) {
push(@newstatuses, FetchSQLData());
}
my $newstatuslist = join(', ', @newstatuses);
# Quote the description and content type for use in the SQL UPDATE statement.
my $quoteddescription = SqlQuote($::FORM{'description'});
my $quotedcontenttype = SqlQuote($::FORM{'contenttype'});
# Update the attachment record in the database.
# Sets the creation timestamp to itself to avoid it being updated automatically.
SendSQL("UPDATE attachments
SET description = $quoteddescription ,
mimetype = $quotedcontenttype ,
ispatch = $::FORM{'ispatch'} ,
isobsolete = $::FORM{'isobsolete'} ,
creation_ts = creation_ts
WHERE attach_id = $::FORM{'id'}
");
# Record changes in the activity table.
if ($olddescription ne $::FORM{'description'}) {
my $quotedolddescription = SqlQuote($olddescription);
my $fieldid = GetFieldID('attachments.description');
SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when, fieldid, removed, added)
VALUES ($bugid, $::FORM{'id'}, $userid, NOW(), $fieldid, $quotedolddescription, $quoteddescription)");
}
if ($oldcontenttype ne $::FORM{'contenttype'}) {
my $quotedoldcontenttype = SqlQuote($oldcontenttype);
my $fieldid = GetFieldID('attachments.mimetype');
SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when, fieldid, removed, added)
VALUES ($bugid, $::FORM{'id'}, $userid, NOW(), $fieldid, $quotedoldcontenttype, $quotedcontenttype)");
}
if ($oldispatch ne $::FORM{'ispatch'}) {
my $fieldid = GetFieldID('attachments.ispatch');
SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when, fieldid, removed, added)
VALUES ($bugid, $::FORM{'id'}, $userid, NOW(), $fieldid, $oldispatch, $::FORM{'ispatch'})");
}
if ($oldisobsolete ne $::FORM{'isobsolete'}) {
my $fieldid = GetFieldID('attachments.isobsolete');
SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when, fieldid, removed, added)
VALUES ($bugid, $::FORM{'id'}, $userid, NOW(), $fieldid, $oldisobsolete, $::FORM{'isobsolete'})");
}
if ($oldstatuslist ne $newstatuslist) {
my ($removed, $added) = DiffStrings($oldstatuslist, $newstatuslist);
my $quotedremoved = SqlQuote($removed);
my $quotedadded = SqlQuote($added);
my $fieldid = GetFieldID('attachstatusdefs.name');
SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when, fieldid, removed, added)
VALUES ($bugid, $::FORM{'id'}, $userid, NOW(), $fieldid, $quotedremoved, $quotedadded)");
}
# Unlock all database tables now that we are finished updating the database.
if ($::driver eq 'mysql') {
SendSQL("UNLOCK TABLES");
}
# If this installation has enabled the request manager, let the manager know
# an attachment was updated so it can check for requests on that attachment
# and fulfill them. The request manager allows users to request database
# changes of other users and tracks the fulfillment of those requests. When
# an attachment record is updated and the request manager is called, it will
# fulfill those requests that were requested of the user performing the update
# which are requests for the attachment being updated.
#my $requests;
#if (Param('userequestmanager'))
#{
# use Request;
# # Specify the fieldnames that have been updated.
# my @fieldnames = ('description', 'mimetype', 'status', 'ispatch', 'isobsolete');
# # Fulfill pending requests.
# $requests = Request::fulfillRequest('attachment', $::FORM{'id'}, @fieldnames);
# $vars->{'requests'} = $requests;
#}
# If the user submitted a comment while editing the attachment,
# add the comment to the bug.
if ( $::FORM{'comment'} )
{
use Text::Wrap;
$Text::Wrap::columns = 80;
$Text::Wrap::huge = 'wrap';
# Append a string to the comment to let users know that the comment came from
# the "edit attachment" screen.
my $comment = qq|(From update of attachment $::FORM{'id'})\n| . $::FORM{'comment'};
my $wrappedcomment = "";
foreach my $line (split(/\r\n|\r|\n/, $comment))
{
if ( $line =~ /^>/ )
{
$wrappedcomment .= $line . "\n";
}
else
{
$wrappedcomment .= wrap('', '', $line) . "\n";
}
}
# Get the user's login name since the AppendComment function needs it.
my $who = DBID_to_name($userid);
# Append the comment to the list of comments in the database.
AppendComment($bugid, $who, $wrappedcomment);
}
# Send mail to let people know the bug has changed. Uses a special syntax
# of the "open" and "exec" commands to capture the output of "processmail",
# which "system" doesn't allow, without running the command through a shell,
# which backticks (``) do.
#system ("./processmail", $bugid , $userid);
#my $mailresults = `./processmail $bugid $userid`;
my $mailresults = '';
open(PMAIL, "-|") or exec('./processmail', $bugid, DBID_to_name($userid));
$mailresults .= $_ while <PMAIL>;
close(PMAIL);
# Define the variables and functions that will be passed to the UI template.
$vars->{'attachid'} = $::FORM{'id'};
$vars->{'bugid'} = $bugid;
$vars->{'mailresults'} = $mailresults;
# Return the appropriate HTTP response headers.
print "Content-Type: text/html\n\n";
# Generate and return the UI (HTML page) from the appropriate template.
$template->process("attachment/updated.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
}

View File

@@ -1,366 +0,0 @@
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
# Dave Miller <justdave@syndicomm.com>
use diagnostics;
use strict;
use RelationSet;
# Use the Attachment module to display attachments for the bug.
use Attachment;
sub show_bug {
# Shut up misguided -w warnings about "used only once". For some reason,
# "use vars" chokes on me when I try it here.
sub bug_form_pl_sillyness {
my $zz;
$zz = %::FORM;
$zz = %::proddesc;
$zz = %::prodmaxvotes;
$zz = @::enterable_products;
$zz = @::settable_resolution;
$zz = $::unconfirmedstate;
$zz = $::milestoneurl;
$zz = $::template;
$zz = $::vars;
$zz = @::legal_priority;
$zz = @::legal_platform;
$zz = @::legal_severity;
$zz = @::legal_bug_status;
$zz = @::target_milestone;
$zz = @::components;
$zz = @::legal_keywords;
$zz = @::versions;
$zz = @::legal_opsys;
}
# Use templates
my $template = $::template;
my $vars = $::vars;
$vars->{'GetBugLink'} = \&GetBugLink;
$vars->{'quoteUrls'} = \&quoteUrls,
$vars->{'lsearch'} = \&lsearch,
$vars->{'header_done'} = (@_),
my $userid = quietly_check_login();
my $id = $::FORM{'id'};
if (!defined($id)) {
$template->process("bug/choose.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
exit;
}
my %user = %{$vars->{'user'}};
my %bug;
# Populate the bug hash with the info we get directly from the DB.
my $query = "
SELECT
bugs.bug_id,
product,
version,
rep_platform,
op_sys,
bug_status,
resolution,
priority,
bug_severity,
component,
assigned_to,
reporter,
bug_file_loc,
short_desc,
target_milestone,
qa_contact,
status_whiteboard, ";
if ($::driver eq 'mysql') {
$query .= "
date_format(creation_ts, '%Y-%m-%d %H:%i'),
delta_ts, ";
} elsif ($::driver eq 'Pg') {
$query .= "
TO_CHAR(creation_ts, 'YYYY-MM-DD HH24:MI:SS'),
TO_CHAR(delta_ts, 'YYYYMMDDHH24MISS'), ";
}
$query .= "
SUM(votes.count)
FROM
bugs LEFT JOIN votes USING(bug_id)
WHERE
bugs.bug_id = $id
GROUP BY
bugs.bug_id,
product,
version,
rep_platform,
op_sys,
bug_status,
resolution,
priority,
bug_severity,
component,
assigned_to,
reporter,
bug_file_loc,
short_desc,
target_milestone,
qa_contact,
status_whiteboard,
creation_ts,
delta_ts ";
SendSQL($query);
my $value;
my @row = FetchSQLData();
foreach my $field ("bug_id", "product", "version", "rep_platform",
"op_sys", "bug_status", "resolution", "priority",
"bug_severity", "component", "assigned_to", "reporter",
"bug_file_loc", "short_desc", "target_milestone",
"qa_contact", "status_whiteboard", "creation_ts",
"delta_ts", "votes")
{
$value = shift(@row);
$bug{$field} = defined($value) ? $value : "";
}
# General arrays of info about the database state
GetVersionTable();
# Fiddle the product list.
my $seen_curr_prod;
my @prodlist;
foreach my $product (@::enterable_products) {
if ($product eq $bug{'product'}) {
# if it's the product the bug is already in, it's ALWAYS in
# the popup, period, whether the user can see it or not, and
# regardless of the disallownew setting.
$seen_curr_prod = 1;
push(@prodlist, $product);
next;
}
next if !CanSeeProduct($userid, $product);
push(@prodlist, $product);
}
# The current product is part of the popup, even if new bugs are no longer
# allowed for that product
if (!$seen_curr_prod) {
push (@prodlist, $bug{'product'});
@prodlist = sort @prodlist;
}
$vars->{'product'} = \@prodlist;
$vars->{'rep_platform'} = \@::legal_platform;
$vars->{'priority'} = \@::legal_priority;
$vars->{'bug_severity'} = \@::legal_severity;
$vars->{'op_sys'} = \@::legal_opsys;
$vars->{'bug_status'} = \@::legal_bug_status;
# Hack - this array contains "" for some reason. See bug 106589.
shift @::settable_resolution;
$vars->{'resolution'} = \@::settable_resolution;
$vars->{'component_'} = $::components{$bug{'product'}};
$vars->{'version'} = $::versions{$bug{'product'}};
$vars->{'target_milestone'} = $::target_milestone{$bug{'product'}};
$bug{'milestoneurl'} = $::milestoneurl{$bug{'product'}} ||
"notargetmilestone.html";
$vars->{'use_votes'} = $::prodmaxvotes{$bug{'product'}};
# Add additional, calculated fields to the bug hash
if (@::legal_keywords) {
$vars->{'use_keywords'} = 1;
SendSQL("SELECT keyworddefs.name
FROM keyworddefs, keywords
WHERE keywords.bug_id = $id
AND keyworddefs.id = keywords.keywordid
ORDER BY keyworddefs.name");
my @keywords;
while (MoreSQLData()) {
push(@keywords, FetchOneColumn());
}
$bug{'keywords'} = \@keywords;
}
# Attachments
$bug{'attachments'} = Attachment::query($id);
# Dependencies
my @list;
SendSQL("SELECT dependson FROM dependencies WHERE
blocked = $id ORDER BY dependson");
while (MoreSQLData()) {
my ($i) = FetchSQLData();
push(@list, $i);
}
$bug{'dependson'} = \@list;
my @list2;
SendSQL("SELECT blocked FROM dependencies WHERE
dependson = $id ORDER BY blocked");
while (MoreSQLData()) {
my ($i) = FetchSQLData();
push(@list2, $i);
}
$bug{'blocked'} = \@list2;
# Groups
my @groups;
my (%buggroups, %usergroups);
# Find out if this bug is private to any group
SendSQL("SELECT group_id FROM bug_group_map WHERE bug_id = $id");
while (my $group_id = FetchOneColumn()) {
$buggroups{$group_id} = 1;
}
# Get a list of active groups the user is in, subject to the above conditions
if ($userid) {
# NB - the number of groups is likely to be small - should we just select
# everything, and weed manually? OTOH, the number of products is likely
# to be small, too. This buggroup stuff needs to be rethought
SendSQL("SELECT groups.group_id, groups.isactive " .
"FROM user_group_map, " .
"groups LEFT JOIN products ON groups.name = products.product " .
"WHERE groups.group_id = user_group_map.group_id AND " .
"user_group_map.user_id = $userid AND groups.isbuggroup != 0 AND " .
"(groups.name = " . SqlQuote($bug{'product'}) . " OR " .
"products.product IS NULL)");
while (my $group_id = FetchOneColumn()) {
$usergroups{$group_id} = 1;
}
# Now get information about each group
SendSQL("SELECT group_id, name, description " .
"FROM groups " .
# "WHERE group_id IN (" . join(',', @groups) . ") " .
"ORDER BY description");
while (MoreSQLData()) {
my ($group_id, $name, $description) = FetchSQLData();
my ($ison, $ingroup);
if ($buggroups{$group_id} ||
($usergroups{$group_id} && (($name eq $bug{'product'}) ||
(!defined $::proddesc{$name}))))
{
$user{'inallgroups'} &= $ingroup;
push (@groups, { "bit" => $group_id,
"ison" => $buggroups{$group_id},
"ingroup" => $usergroups{$group_id},
"description" => $description });
}
}
# If the bug is restricted to a group, display checkboxes that allow
# the user to set whether or not the reporter
# and cc list can see the bug even if they are not members of all
# groups to which the bug is restricted.
if (%buggroups) {
$bug{'inagroup'} = 1;
# Determine whether or not the bug is always accessible by the
# reporter, QA contact, and/or users on the cc: list.
SendSQL("SELECT reporter_accessible, cclist_accessible
FROM bugs
WHERE bug_id = $id
");
($bug{'reporter_accessible'},
$bug{'cclist_accessible'}) = FetchSQLData();
}
}
$vars->{'groups'} = \@groups;
my $movers = Param("movers");
$user{'canmove'} = Param("move-enabled")
&& (defined $::COOKIE{"Bugzilla_login"})
&& ($::COOKIE{"Bugzilla_login"} =~ /\Q$movers\E/);
# User permissions
# In the below, if the person hasn't logged in ($::userid == 0), then
# we treat them as if they can do anything. That's because we don't
# know why they haven't logged in; it may just be because they don't
# use cookies. Display everything as if they have all the permissions
# in the world; their permissions will get checked when they log in
# and actually try to make the change.
$user{'canedit'} = $::userid == 0
|| $::userid == $bug{'reporter'}
|| $::userid == $bug{'qa_contact'}
|| $::userid == $bug{'assigned_to'}
|| UserInGroup($userid, "editbugs");
$user{'canconfirm'} = ($::userid == 0) || UserInGroup($userid, "canconfirm");
# Bug states
$bug{'isunconfirmed'} = ($bug{'bug_status'} eq $::unconfirmedstate);
$bug{'isopened'} = IsOpenedState($bug{'bug_status'});
# People involved with the bug
$bug{'assigned_to_email'} = DBID_to_name($bug{'assigned_to'});
$bug{'assigned_to'} = DBID_to_real_or_loginname($bug{'assigned_to'});
$bug{'reporter'} = DBID_to_real_or_loginname($bug{'reporter'});
$bug{'qa_contact'} = $bug{'qa_contact'} > 0 ?
DBID_to_name($bug{'qa_contact'}) : "";
my $ccset = new RelationSet;
$ccset->mergeFromDB("SELECT who FROM cc WHERE bug_id=$id");
my @cc = $ccset->toArrayOfStrings();
$bug{'cc'} = \@cc if $cc[0];
# Next bug in list (if there is one)
my @bug_list;
if ($::COOKIE{"BUGLIST"} && $id)
{
@bug_list = split(/:/, $::COOKIE{"BUGLIST"});
}
$vars->{'bug_list'} = \@bug_list;
$bug{'comments'} = GetComments($bug{'bug_id'});
# This is length in number of comments
$bug{'longdesclength'} = scalar(@{$bug{'comments'}});
# Add the bug and user hashes to the variables
$vars->{'bug'} = \%bug;
$vars->{'user'} = \%user;
# Generate and return the UI (HTML page) from the appropriate template.
$template->process("bug/edit.html.tmpl", $vars)
|| ThrowTemplateError($template->error());
}
1;

View File

@@ -1,206 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<!--
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 Bugzilla Bug Tracking System.
The Initial Developer of the Original Code is Netscape Communications
Corporation. Portions created by Netscape are
Copyright (C) 1998 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
Contributor(s): Terry Weissman <terry@mozilla.org>
-->
<head>
<TITLE>A Bug's Life Cycle</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1 ALIGN=CENTER>A Bug's Life Cycle</h1>
The <B>status</B> and <B>resolution</B> field define and track the
life cycle of a bug.
<a name="status"></a>
<p>
<TABLE BORDER=1 CELLPADDING=4>
<TR ALIGN=CENTER VALIGN=TOP>
<TD WIDTH="50%"><H1>STATUS</H1> <TD><H1>RESOLUTION</H1>
<TR VALIGN=TOP>
<TD>The <B>status</B> field indicates the general health of a bug. Only
certain status transitions are allowed.
<TD>The <b>resolution</b> field indicates what happened to this bug.
<TR VALIGN=TOP><TD>
<DL><DT><B>
<A HREF="confirmhelp.html">UNCONFIRMED</A></B>
<DD> This bug has recently been added to the database. Nobody has
validated that this bug is true. Users who have the "canconfirm"
permission set may confirm this bug, changing its state to NEW.
Or, it may be directly resolved and marked RESOLVED.
<DT><B>NEW</B>
<DD> This bug has recently been added to the assignee's list of bugs
and must be processed. Bugs in this state may be accepted, and
become <B>ASSIGNED</B>, passed on to someone else, and remain
<B>NEW</B>, or resolved and marked <B>RESOLVED</B>.
<DT><B>ASSIGNED</B>
<DD> This bug is not yet resolved, but is assigned to the proper
person. From here bugs can be given to another person and become
<B>NEW</B>, or resolved and become <B>RESOLVED</B>.
<DT><B>REOPENED</B>
<DD>This bug was once resolved, but the resolution was deemed
incorrect. For example, a <B>WORKSFORME</B> bug is
<B>REOPENED</B> when more information shows up and the bug is now
reproducible. From here bugs are either marked <B>ASSIGNED</B>
or <B>RESOLVED</B>.
</DL>
<TD>
<DL>
<DD> No resolution yet. All bugs which are in one of these "open" states
have the resolution set to blank. All other bugs
will be marked with one of the following resolutions.
</DL>
<TR VALIGN=TOP><TD>
<DL>
<DT><B>RESOLVED</B>
<DD> A resolution has been taken, and it is awaiting verification by
QA. From here bugs are either re-opened and become
<B>REOPENED</B>, are marked <B>VERIFIED</B>, or are closed for good
and marked <B>CLOSED</B>.
<DT><B>VERIFIED</B>
<DD> QA has looked at the bug and the resolution and agrees that the
appropriate resolution has been taken. Bugs remain in this state
until the product they were reported against actually ships, at
which point they become <B>CLOSED</B>.
<DT><B>CLOSED</B>
<DD> The bug is considered dead, the resolution is correct. Any zombie
bugs who choose to walk the earth again must do so by becoming
<B>REOPENED</B>.
</DL>
<TD>
<DL>
<DT><B>FIXED</B>
<DD> A fix for this bug is checked into the tree and tested.
<DT><B>INVALID</B>
<DD> The problem described is not a bug
<DT><B>WONTFIX</B>
<DD> The problem described is a bug which will never be fixed.
<DT><B>LATER</B>
<DD> The problem described is a bug which will not be fixed in this
version of the product.
<DT><B>REMIND</B>
<DD> The problem described is a bug which will probably not be fixed in this
version of the product, but might still be.
<DT><B>DUPLICATE</B>
<DD> The problem is a duplicate of an existing bug. Marking a bug
duplicate requires the bug# of the duplicating bug and will at
least put that bug number in the description field.
<DT><B>WORKSFORME</B>
<DD> All attempts at reproducing this bug were futile, reading the
code produces no clues as to why this behavior would occur. If
more information appears later, please re-assign the bug, for
now, file it.
</DL>
</TABLE>
<H1>Other Fields</H1>
<table border=1 cellpadding=4><tr><td>
<h2><a name="severity">Severity</a></h2>
This field describes the impact of a bug.
<p>
<p>
<table>
<tr><th>Blocker</th><td>Blocks development and/or testing work
<tr><th>Critical</th><td>crashes, loss of data, severe memory leak
<tr><th>Major</th><td>major loss of function
<tr><th>Minor</th><td>minor loss of function, or other problem where easy workaround is present
<tr><th>Trivial</th><td>cosmetic problem like misspelled words or misaligned text
<tr><th>Enhancement</th><td>Request for enhancement
</table>
</td><td>
<h2><a name="priority">Priority</a></h2>
This field describes the importance and order in which a bug should be
fixed. This field is utilized by the programmers/engineers to
prioritize their work to be done. The available priorities are:
<p>
<p>
<table>
<tr><th>P1</th><td>Most important
<tr><th>P2</th><td>
<tr><th>P3</th><td>
<tr><th>P4</th><td>
<tr><th>P5</th><td>Least important
</table>
</tr></table>
<h2><a name="rep_platform">Platform</a></h2>
This is the hardware platform against which the bug was reported. Legal
platforms include:
<UL>
<LI> All (happens on all platform; cross-platform bug)
<LI> Macintosh
<LI> PC
<LI> Sun
<LI> HP
</UL>
<b>Note:</b> Selecting the option "All" does not select bugs assigned against all platforms. It
merely selects bugs that <b>occur</b> on all platforms.
<h2><a name="op_sys">Operating System</a></h2>
This is the operating system against which the bug was reported. Legal
operating systems include:
<UL>
<LI> All (happens on all operating systems; cross-platform bug)
<LI> Windows 95
<LI> Mac System 8.0
<LI> Linux
</UL>
Note that the operating system implies the platform, but not always.
For example, Linux can run on PC and Macintosh and others.
<h2><a name="assigned_to">Assigned To</a></h2>
This is the person in charge of resolving the bug. Every time this
field changes, the status changes to <B>NEW</B> to make it easy to see
which new bugs have appeared on a person's list.
The default status for queries is set to NEW, ASSIGNED and REOPENED. When
searching for bugs that have been resolved or verified, remember to set the
status field appropriately.
<hr>
<!-- hhmts start -->
Last modified: Sun Apr 14 12:51:23 EST 2002
<!-- hhmts end -->
</body> </html>

File diff suppressed because it is too large Load Diff

View File

@@ -1,392 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>Bug Writing Guidelines</title>
</head>
<body>
<center>
<h1>Bug Writing Guidelines</h1>
</center>
<h3>Why You Should Read This</h3>
<blockquote>
<p>Simply put, the more effectively you report a bug, the more
likely an engineer will actually fix it.</p>
<p>These guidelines are a general
tutorial to teach novice and intermediate bug reporters how to compose effective bug reports. Not every sentence may precisely apply to
your software project.</p>
</blockquote>
<h3>How to Write a Useful Bug Report</h3>
<blockquote>
<p>Useful bug reports are ones that get bugs fixed. A useful bug
report normally has two qualities:</p>
<ol>
<li><b>Reproducible.</b> If an engineer can't see the bug herself to prove that it exists, she'll probably stamp your bug report "WORKSFORME" or "INVALID" and move on to the next bug. Every detail you can provide helps.<br>
<br>
</li>
<li><b>Specific.</b> The quicker the engineer can isolate the bug
to a specific area, the more likely she'll expediently fix it.
(If a programmer or tester has to decypher a bug, they may spend
more time cursing the submitter than solving the problem.)
<br>
<br>
[ <a href="#tips" name="Anchor">Tell Me More</a> ]
</li>
</ol>
<p>Let's say the application you're testing is a web browser. You
crash at foo.com, and want to write up a bug report:</p>
<blockquote>
<p><b>BAD:</b> "My browser crashed. I think I was on www.foo.com. I play golf with Bill Gates, so you better fix this problem, or I'll report you to him. By the way, your Back icon looks like a squashed rodent. UGGGLY. And my grandmother's home page is all messed up in your browser. Thx 4 UR help."
</p>
<p>
<b>GOOD:</b> "I crashed each time I went to www.foo.com, using
the 2002-02-25 build on a Windows 2000 system. I also
rebooted into Linux, and reproduced this problem using the 2002-02-24
Linux build.
</p>
<p>
It again crashed each time upon drawing the Foo banner at the top
of the page. I broke apart the page, and discovered that the
following image link will crash the application reproducibly,
unless you remove the "border=0" attribute:
</p>
<p>
<tt>&lt;IMG SRC="http://www.foo.com/images/topics/topicfoos.gif"
width="34" height="44" border="0" alt="News"&gt;</tt>
</p>
</blockquote>
</blockquote>
<h3>How to Enter your Useful Bug Report into Bugzilla:</h3>
<blockquote>
<p>Before you enter your bug, use Bugzilla's
<a href="query.cgi">search page</a> to determine whether the defect you've discovered is a known, already-reported bug. If your bug is the 37th duplicate of a known issue, you're more likely to annoy the engineer. (Annoyed
engineers fix fewer bugs.)
</p>
<p>
Next, be sure to reproduce your bug using a recent
build. Engineers tend to be most interested in problems affecting
the code base that they're actively working on. After all, the bug you're reporting
may already be fixed.
</p>
<p>
If you've discovered a new bug using a current build, report it in
Bugzilla:
</p>
<ol>
<li>From your Bugzilla main page, choose
"<a href="enter_bug.cgi">Enter a new bug</a>".</li>
<li>Select the product that you've found a bug in.</li>
<li>Enter your e-mail address, password, and press the "Login"
button. (If you don't yet have a password, leave the password field empty,
and press the "E-mail me a password" button instead.
You'll quickly receive an e-mail message with your password.)</li>
</ol>
<p>Now, fill out the form. Here's what it all means:</p>
<p><b>Where did you find the bug?</b></p>
<blockquote>
<p><b>Product: In which product did you find the bug?</b><br>
You just specified this on the last page, so you can't edit it here.</p>
<p><b>Version: In which product version did you find the
bug?</b><br>
(If applicable)</p>
<p><b>Component: In which component does the bug exist?</b><br>
Bugzilla requires that you select a component to enter a bug. (Not sure which to choose?
Click on the Component link. You'll see a description of each component, to help you make the best choice.)</p>
<p><b>OS: On which Operating System (OS) did you find this bug?</b>
(e.g. Linux, Windows 2000, Mac OS 9.)<br>
If you know the bug happens on all OSs, choose 'All'. Otherwise,
select the OS that you found the bug on, or "Other" if your OS
isn't listed.</p>
</blockquote>
<p><b>How important is the bug?</b></p>
<blockquote>
<p><b>Severity: How damaging is the bug?</b><br>
This item defaults to 'normal'. If you're not sure what severity your bug deserves, click on the Severity link.
You'll see a description of each severity rating. <br>
</p>
</blockquote>
<p><b>Who will be following up on the bug?</b></p>
<blockquote>
<p><b>Assigned To: Which engineer should be responsible for fixing
this bug?</b><br>
Bugzilla will automatically assign the bug to a default engineer
upon submitting a bug report. If you'd prefer to directly assign the bug to
someone else, enter their e-mail address into this field. (To see the list of
default engineers for each component, click on the Component
link.)</p>
<p><b>Cc: Who else should receive e-mail updates on changes to this
bug?</b><br>
List the full e-mail addresses of other individuals who should
receive an e-mail update upon every change to the bug report. You
can enter as many e-mail addresses as you'd like, separated by spaces or commas, as long as those
people have Bugzilla accounts.</p>
</blockquote>
<p><b>What else can you tell the engineer about the bug?</b></p>
<blockquote>
<p><b>Summary:</b> <b>How would you describe the bug, in
approximately 60 or fewer characters?</b><br>
A good summary should <b>quickly and uniquely identify a bug
report</b>. Otherwise, an engineer cannot meaningfully identify
your bug by its summary, and will often fail to pay attention to
your bug report when skimming through a 10 page bug list.<br>
<br>
A useful summary might be
"<tt>PCMCIA install fails on Tosh Tecra 780DVD w/ 3c589C</tt>".
"<tt>Software fails</tt>" or "<tt>install problem</tt>" would be
examples of a bad summary.<br>
<br>
[ <a href="#summary">Tell Me More</a> ]<br>
<br>
<b>Description: </b><br>
Please provide a detailed problem report in this field.
Your bug's recipients will most likely expect the following information:</p>
<blockquote>
<p><b>Overview Description:</b> More detailed expansion of
summary.</p>
<blockquote>
<pre>
Drag-selecting any page crashes Mac builds in NSGetFactory
</pre>
</blockquote>
<p><b>Steps to Reproduce:</b> Minimized, easy-to-follow steps that will
trigger the bug. Include any special setup steps.</p>
<blockquote>
<pre>
1) View any web page. (I used the default sample page,
resource:/res/samples/test0.html)
2) Drag-select the page. (Specifically, while holding down
the mouse button, drag the mouse pointer downwards from any
point in the browser's content region to the bottom of the
browser's content region.)
</pre>
</blockquote>
<p>
<b>Actual Results:</b> What the application did after performing
the above steps.
</p>
<blockquote>
<pre>
The application crashed. Stack crawl appended below from MacsBug.
</pre>
</blockquote>
<p><b>Expected Results:</b> What the application should have done,
were the bug not present.</p>
<blockquote>
<pre>
The window should scroll downwards. Scrolled content should be selected.
(Or, at least, the application should not crash.)
</pre>
</blockquote>
<p><b>Build Date &amp; Platform:</b> Date and platform of the build
that you first encountered the bug in.</p>
<blockquote>
<pre>
Build 2002-03-15 on Mac OS 9.0
</pre>
</blockquote>
<p><b>Additional Builds and Platforms:</b> Whether or not the bug
takes place on other platforms (or browsers, if applicable).</p>
<blockquote>
<pre>
- Also Occurs On
Mozilla (2002-03-15 build on Windows NT 4.0)
- Doesn't Occur On
Mozilla (2002-03-15 build on Red Hat Linux; feature not supported)
Internet Explorer 5.0 (shipping build on Windows NT 4.0)
Netscape Communicator 4.5 (shipping build on Mac OS 9.0)
</pre>
</blockquote>
<p><b>Additional Information:</b> Any other debugging information.
For crashing bugs:</p>
<ul>
<li><b>Win32:</b> if you receive a Dr. Watson error, please note
the type of the crash, and the module that the application crashed
in. (e.g. access violation in apprunner.exe)</li>
<li><b>Mac OS:</b> if you're running MacsBug, please provide the
results of a <b>how</b> and an <b>sc</b>:</li>
</ul>
<blockquote>
<pre>
*** MACSBUG STACK CRAWL OF CRASH (Mac OS)
Calling chain using A6/R1 links
Back chain ISA Caller
00000000 PPC 0BA85E74
03AEFD80 PPC 0B742248
03AEFD30 PPC 0B50FDDC NSGetFactory+027FC
PowerPC unmapped memory exception at 0B512BD0 NSGetFactory+055F0
</pre>
</blockquote>
</blockquote>
</blockquote>
<p>You're done!<br>
<br>
After double-checking your entries for any possible errors, press
the "Commit" button, and your bug report will now be in the
Bugzilla database.<br>
</p>
</blockquote>
<hr>
<h3>More Information on Writing Good Bugs</h3>
<blockquote>
<p><b><a name="tips"></a> 1. General Tips for a Useful Bug
Report</b>
</p>
<blockquote>
<p>
<b>Use an explicit structure, so your bug reports are easy to
skim.</b> Bug report users often need immediate access to specific
sections of your bug. If your Bugzilla installation supports the
Bugzilla Helper, use it.
</p>
<p>
<b>Avoid cuteness if it costs clarity.</b> Nobody will be laughing
at your funny bug title at 3:00 AM when they can't remember how to
find your bug.
</p>
<p>
<b>One bug per report.</b> Completely different people typically
fix, verify, and prioritize different bugs. If you mix a handful of
bugs into a single report, the right people probably won't discover
your bugs in a timely fashion, or at all. Certain bugs are also
more important than others. It's impossible to prioritize a bug
report when it contains four different issues, all of differing
importance.
</p>
<p>
<b>No bug is too trivial to report.</b> Unless you're reading the
source code, you can't see actual software bugs, like a dangling
pointer -- you'll see their visible manifestations, such as the
segfault when the application finally crashes. Severe software
problems can manifest themselves in superficially trivial ways.
File them anyway.<br>
</p>
</blockquote>
<p><b><a name="summary"></a>2. How and Why to Write Good Bug Summaries</b>
</p>
<blockquote>
<p><b>You want to make a good first impression on the bug
recipient.</b> Just like a New York Times headline guides readers
towards a relevant article from dozens of choices, will your bug summary
suggest that your bug report is worth reading from dozens or hundreds of
choices?
</p>
<p>
Conversely, a vague bug summary like <tt>install problem</tt> forces anyone
reviewing installation bugs to waste time opening up your bug to
determine whether it matters.
</p>
<p>
<b>Your bug will often be searched by its summary.</b> Just as
you'd find web pages with Google by searching by keywords through
intuition, so will other people locate your bugs. Descriptive bug
summaries are naturally keyword-rich, and easier to find.
</p>
<p>
For example, you'll find a bug titled "<tt>Dragging icons from List View to
gnome-terminal doesn't paste path</tt>" if you search on "List",
"terminal", or "path". Those search keywords wouldn't have found a
bug titled "<tt>Dragging icons
doesn't paste</tt>".
</p>
<p>
Ask yourself, "Would someone understand my bug from just this
summary?" If so, you've written a fine summary.
</p>
<p><b>Don't write titles like these:</b></p>
<ol>
<li>"Can't install" - Why can't you install? What happens when you
try to install?</li>
<li>"Severe Performance Problems" - ...and they occur when you do
what?</li>
<li>"back button does not work" - Ever? At all?</li>
</ol>
<p><b>Good bug titles:</b></p>
<ol>
<li>"1.0 upgrade installation fails if Mozilla M18 package present"
- Explains problem and the context.</li>
<li>"RPM 4 installer crashes if launched on Red Hat 6.2 (RPM 3)
system" - Explains what happens, and the context.</li>
</ol>
</blockquote>
</blockquote>
<p>(Written and maintained by
<a href="http://www.prometheus-music.com/eli">Eli Goldberg</a>. Claudius
Gayle, Gervase Markham, Peter Mock, Chris Pratt, Tom Schutter and Chris Yeh also
contributed significant changes. Constructive
<a href="mailto:eli@prometheus-music.com">suggestions</a> welcome.)</p>
</body>
</html>

View File

@@ -1,46 +0,0 @@
<!ELEMENT bugzilla (bug+)>
<!ATTLIST bugzilla
version CDATA #REQUIRED
urlbase CDATA #REQUIRED
maintainer CDATA #REQUIRED
exporter CDATA #IMPLIED
>
<!ELEMENT bug (bug_id, (bug_status, product, priority, version, rep_platform, assigned_to, delta_ts, component, reporter, target_milestone?, bug_severity, creation_ts, qa_contact?, op_sys, resolution?, bug_file_loc?, short_desc?, keywords*, status_whiteboard?, dependson*, blocks*, cc*, long_desc*, attachment*)?)>
<!ATTLIST bug
error (NotFound | NotPermitted | InvalidBugId) #IMPLIED
>
<!ELEMENT bug_id (#PCDATA)>
<!ELEMENT exporter (#PCDATA)>
<!ELEMENT urlbase (#PCDATA)>
<!ELEMENT bug_status (#PCDATA)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT priority (#PCDATA)>
<!ELEMENT version (#PCDATA)>
<!ELEMENT rep_platform (#PCDATA)>
<!ELEMENT assigned_to (#PCDATA)>
<!ELEMENT delta_ts (#PCDATA)>
<!ELEMENT component (#PCDATA)>
<!ELEMENT reporter (#PCDATA)>
<!ELEMENT target_milestone (#PCDATA)>
<!ELEMENT bug_severity (#PCDATA)>
<!ELEMENT creation_ts (#PCDATA)>
<!ELEMENT qa_contact (#PCDATA)>
<!ELEMENT status_whiteboard (#PCDATA)>
<!ELEMENT op_sys (#PCDATA)>
<!ELEMENT resolution (#PCDATA)>
<!ELEMENT bug_file_loc (#PCDATA)>
<!ELEMENT short_desc (#PCDATA)>
<!ELEMENT keywords (#PCDATA)>
<!ELEMENT dependson (#PCDATA)>
<!ELEMENT blocks (#PCDATA)>
<!ELEMENT cc (#PCDATA)>
<!ELEMENT long_desc (who, bug_when, thetext)>
<!ELEMENT who (#PCDATA)>
<!ELEMENT bug_when (#PCDATA)>
<!ELEMENT thetext (#PCDATA)>
<!ELEMENT attachment (attachid, date, desc, type?, data?)>
<!ELEMENT attachid (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT desc (#PCDATA)>
<!ELEMENT type (#PCDATA)>
<!ELEMENT data (#PCDATA)>

View File

@@ -1,39 +0,0 @@
#!/usr/bonsaitools/bin/perl -wT
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
use strict;
print q{Content-type: text/html
<HTML>
<HEAD>
<META HTTP-EQUIV="Refresh"
CONTENT="0; URL=userprefs.cgi">
</HEAD>
<BODY>
This URL is obsolete. Forwarding you to the correct one.
<P>
Going to <A HREF="userprefs.cgi">userprefs.cgi</A>
<BR>
</BODY>
</HTML>
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,156 +0,0 @@
#!/usr/bonsaitools/bin/perl -wT
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
use diagnostics;
use strict;
use lib qw(.);
use vars qw(
@legal_keywords
$buffer
$template
$vars
);
require "CGI.pl";
# Use the template toolkit (http://www.template-toolkit.org/) to generate
# the user interface (HTML pages and mail messages) using templates in the
# "template/" subdirectory.
use Template;
# Create the global template object that processes templates and specify
# configuration parameters that apply to all templates processed in this script.
my $template = Template->new(
{
# Colon-separated list of directories containing templates.
INCLUDE_PATH => "template/custom:template/default",
# Allow templates to be specified with relative paths.
RELATIVE => 1,
PRE_CHOMP => 1,
});
# Define the global variables and functions that will be passed to the UI
# template. Individual functions add their own values to this hash before
# sending them to the templates they process.
my $vars =
{
# Function for retrieving global parameters.
'Param' => \&Param,
# Function for processing global parameters that contain references
# to other global parameters.
'PerformSubsts' => \&PerformSubsts,
# Function to search an array for a value
'lsearch' => \&lsearch,
};
print "Content-type: text/html\n";
# The master list not only says what fields are possible, but what order
# they get displayed in.
ConnectToDatabase();
GetVersionTable();
my @masterlist = ("opendate", "changeddate", "severity", "priority",
"platform", "owner", "reporter", "status", "resolution",
"product", "component", "version", "os", "votes");
if (Param("usetargetmilestone")) {
push(@masterlist, "target_milestone");
}
if (Param("useqacontact")) {
push(@masterlist, "qa_contact");
}
if (Param("usestatuswhiteboard")) {
push(@masterlist, "status_whiteboard");
}
if (@::legal_keywords) {
push(@masterlist, "keywords");
}
push(@masterlist, ("summary", "summaryfull"));
$vars->{masterlist} = \@masterlist;
my @collist;
if (defined $::FORM{'rememberedquery'}) {
my $splitheader = 0;
if (defined $::FORM{'resetit'}) {
@collist = @::default_column_list;
} else {
foreach my $i (@masterlist) {
if (defined $::FORM{"column_$i"}) {
push @collist, $i;
}
}
if (exists $::FORM{'splitheader'}) {
$splitheader = $::FORM{'splitheader'};
}
}
my $list = join(" ", @collist);
my $urlbase = Param("urlbase");
my $cookiepath = Param("cookiepath");
print "Set-Cookie: COLUMNLIST=$list ; path=$cookiepath ; expires=Sun, 30-Jun-2029 00:00:00 GMT\n";
print "Set-Cookie: SPLITHEADER=$::FORM{'splitheader'} ; path=$cookiepath ; expires=Sun, 30-Jun-2029 00:00:00 GMT\n";
print "Refresh: 0; URL=buglist.cgi?$::FORM{'rememberedquery'}\n";
print "\n";
print "<META HTTP-EQUIV=Refresh CONTENT=\"1; URL=$urlbase"."buglist.cgi?$::FORM{'rememberedquery'}\">\n";
print "<TITLE>What a hack.</TITLE>\n";
PutHeader ("Change columns");
print "Resubmitting your query with new columns...\n";
exit;
}
if (defined $::COOKIE{'COLUMNLIST'}) {
@collist = split(/ /, $::COOKIE{'COLUMNLIST'});
} else {
@collist = @::default_column_list;
}
$vars->{collist} = \@collist;
$vars->{splitheader} = 0;
if ($::COOKIE{'SPLITHEADER'}) {
$vars->{splitheader} = 1;
}
my %desc = ();
foreach my $i (@masterlist) {
$desc{$i} = $i;
}
$desc{'summary'} = "Summary (first 60 characters)";
$desc{'summaryfull'} = "Full Summary";
$vars->{desc} = \%desc;
$vars->{buffer} = $::buffer;
# Generate and return the UI (HTML page) from the appropriate template.
print "Content-type: text/html\n\n";
$template->process("list/change-columns.html.tmpl", $vars)
|| ThrowTemplateError($template->error());

View File

@@ -1,202 +0,0 @@
#!/usr/bonsaitools/bin/perl -w
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>,
# Harrison Page <harrison@netscape.com>
# Gervase Markham <gerv@gerv.net>
# Run me out of cron at midnight to collect Bugzilla statistics.
use AnyDBM_File;
use diagnostics;
use strict;
use vars @::legal_product;
require "globals.pl";
# tidy up after graphing module
if (chdir("graphs")) {
unlink <./*.gif>;
unlink <./*.png>;
chdir("..");
}
ConnectToDatabase(1);
GetVersionTable();
my @myproducts;
push( @myproducts, "-All-", @::legal_product );
foreach (@myproducts) {
my $dir = "data/mining";
&check_data_dir ($dir);
&collect_stats ($dir, $_);
}
&calculate_dupes();
sub check_data_dir {
my $dir = shift;
if (! -d) {
mkdir $dir, 0777;
chmod 0777, $dir;
}
}
sub collect_stats {
my $dir = shift;
my $product = shift;
my $when = localtime (time);
# NB: Need to mangle the product for the filename, but use the real
# product name in the query
my $file_product = $product;
$file_product =~ s/\//-/gs;
my $file = join '/', $dir, $file_product;
my $exists = -f $file;
if (open DATA, ">>$file") {
push my @row, &today;
foreach my $status ('NEW', 'ASSIGNED', 'REOPENED', 'UNCONFIRMED', 'RESOLVED', 'VERIFIED', 'CLOSED') {
if( $product eq "-All-" ) {
SendSQL("select count(bug_status) from bugs where bug_status='$status'");
} else {
SendSQL("select count(bug_status) from bugs where bug_status='$status' and product='$product'");
}
push @row, FetchOneColumn();
}
foreach my $resolution ('FIXED', 'INVALID', 'WONTFIX', 'LATER', 'REMIND', 'DUPLICATE', 'WORKSFORME', 'MOVED') {
if( $product eq "-All-" ) {
SendSQL("select count(resolution) from bugs where resolution='$resolution'");
} else {
SendSQL("select count(resolution) from bugs where resolution='$resolution' and product='$product'");
}
push @row, FetchOneColumn();
}
if (! $exists) {
print DATA <<FIN;
# Bugzilla Daily Bug Stats
#
# Do not edit me! This file is generated.
#
# fields: DATE|NEW|ASSIGNED|REOPENED|UNCONFIRMED|RESOLVED|VERIFIED|CLOSED|FIXED|INVALID|WONTFIX|LATER|REMIND|DUPLICATE|WORKSFORME|MOVED
# Product: $product
# Created: $when
FIN
}
print DATA (join '|', @row) . "\n";
close DATA;
} else {
print "$0: $file, $!";
}
}
sub calculate_dupes {
SendSQL("SELECT * FROM duplicates");
my %dupes;
my %count;
my @row;
my $key;
my $changed = 1;
my $today = &today_dash;
# Save % count here in a date-named file
# so we can read it back in to do changed counters
# First, delete it if it exists, so we don't add to the contents of an old file
if (my @files = <data/duplicates/dupes$today*>) {
unlink @files;
}
dbmopen(%count, "data/duplicates/dupes$today", 0644) || die "Can't open DBM dupes file: $!";
# Create a hash with key "a bug number", value "bug which that bug is a
# direct dupe of" - straight from the duplicates table.
while (@row = FetchSQLData()) {
my $dupe_of = shift @row;
my $dupe = shift @row;
$dupes{$dupe} = $dupe_of;
}
# Total up the number of bugs which are dupes of a given bug
# count will then have key = "bug number",
# value = "number of immediate dupes of that bug".
foreach $key (keys(%dupes))
{
my $dupe_of = $dupes{$key};
if (!defined($count{$dupe_of})) {
$count{$dupe_of} = 0;
}
$count{$dupe_of}++;
}
# Now we collapse the dupe tree by iterating over %count until
# there is no further change.
while ($changed == 1)
{
$changed = 0;
foreach $key (keys(%count)) {
# if this bug is actually itself a dupe, and has a count...
if (defined($dupes{$key}) && $count{$key} > 0) {
# add that count onto the bug it is a dupe of,
# and zero the count; the check is to avoid
# loops
if ($count{$dupes{$key}} != 0) {
$count{$dupes{$key}} += $count{$key};
$count{$key} = 0;
$changed = 1;
}
}
}
}
# Remove the values for which the count is zero
foreach $key (keys(%count))
{
if ($count{$key} == 0) {
delete $count{$key};
}
}
dbmclose(%count);
}
sub today {
my ($dom, $mon, $year) = (localtime(time))[3, 4, 5];
return sprintf "%04d%02d%02d", 1900 + $year, ++$mon, $dom;
}
sub today_dash {
my ($dom, $mon, $year) = (localtime(time))[3, 4, 5];
return sprintf "%04d-%02d-%02d", 1900 + $year, ++$mon, $dom;
}

View File

@@ -1,168 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<!--
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 Bugzilla Bug Tracking System.
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): Terry Weissman <terry@mozilla.org>
-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Understanding the UNCONFIRMED state, and other recent changes</title>
</head>
<body>
<h1>Understanding the UNCONFIRMED state, and other recent changes</h1>
<p>
[This document is aimed primarily at people who have used Bugzilla
before the UNCONFIRMED state was implemented. It might be helpful for
newer users as well.]
</p>
<p>
New bugs in some products will now show up in a new state,
UNCONFIRMED. This means that we have nobody has confirmed that the
bug is real. Very busy engineers will probably generally ignore
UNCONFIRMED that have been assigned to them, until they have been
confirmed in one way or another. (Engineers with more time will
hopefully glance over their UNCONFIRMED bugs regularly.)
</p>
<p>
The <a href="bug_status.html">page describing bug fields</a> has been
updated to include UNCONFIRMED.
</p>
<p>
There are two basic ways that a bug can become confirmed (and enter
the NEW) state.
</p>
<ul>
<li> A user with the appropriate permissions (see below for more on
permissions) decides that the bug is a valid one, and confirms
it. We hope to gather a small army of responsible volunteers
to regularly go through bugs for us.</li>
<li> The bug gathers a certain number of votes. <b>Any</b> valid Bugzilla user may vote for
bugs (each user gets a certain number of bugs); any UNCONFIRMED bug which
gets enough votes becomes automatically confirmed, and enters the NEW state.</li>
</ul>
<p>
One implication of this is that it is worth your time to search the
bug system for duplicates of your bug to vote on them, before
submitting your own bug. If we can spread around knowledge of this
fact, it ought to help cut down the number of duplicate bugs in the
system.
</p>
<h2>Permissions.</h2>
<p>
Users now have a certain set of permissions. To see your permissions,
check out the
<a href="userprefs.cgi?bank=permissions">user preferences</a> page.
</p>
<p>
If you have the "Can confirm a bug" permission, then you will be able
to move UNCONFIRMED bugs into the NEW state.
</p>
<p>
If you have the "Can edit all aspects of any bug" permission, then you
can tweak anything about any bug. If not, you may only edit those
bugs that you have submitted, or that you have assigned to you (or
qa-assigned to you). However, anyone may add a comment to any bug.
</p>
<p>
Some people (initially, the initial owners and initial qa-contacts for
components in the system) have the ability to give the above two
permissions to other people. So, if you really feel that you ought to
have one of these permissions, a good person to ask (via private
email, please!) is the person who is assigned a relevant bug.
</p>
<h2>Other details.</h2>
<p>
An initial stab was taken to decide who would be given which of the
above permissions. This was determined by some simple heurstics of
who was assigned bugs, and who the default owners of bugs were, and a
look at people who seem to have submitted several bugs that appear to
have been interesting and valid. Inevitably, we have failed to give
someone the permissions they deserve. Please don't take it
personally; just bear with us as we shake out the new system.
</p>
<p>
People with one of the two bits above can easily confirm their own
bugs, so bugs they submit will actually start out in the NEW state.
They can override this when submitting a bug.
</p>
<p>
People can ACCEPT or RESOLVE a bug assigned to them, even if they
aren't allowed to confirm it. However, the system remembers, and if
the bug gets REOPENED or reassigned to someone else, it will revert
back to the UNCONFIRMED state. If the bug has ever been confirmed,
then REOPENing or reassigning will cause it to go to the NEW or
REOPENED state.
</p>
<p>
Note that only some products support the UNCONFIRMED state. In other
products, all new bugs will automatically start in the NEW state.
</p>
<h2>Things still to be done.</h2>
<p>
There probably ought to be a way to get a bug back into the
UNCONFIRMED state, but there isn't yet.
</p>
<p>
If a person has submitted several bugs that get confirmed, then this
is probably a person who understands the system well, and deserves the
"Can confirm a bug" permission. This kind of person should be
detected and promoted automatically.
</p>
<p>
There should also be a way to automatically promote people to get the
"Can edit all aspects of any bug" permission.
</p>
<p>
The "enter a new bug" page needs to be revamped with easy ways for new
people to educate themselves on the benefit of searching for a bug
like the one they're about to submit and voting on it, rather than
adding a new useless duplicate.
</p>
<hr>
<p>
<!-- hhmts start -->
Last modified: Sun Apr 14 12:55:14 EST 2002
<!-- hhmts end -->
</p>
</body> </html>

View File

@@ -1,79 +0,0 @@
# -*- Mode: perl; indent-tabs-mode: nil -*-
# 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.
#
# This code is based on code found in bug_email.pl from the bugzilla
# email tracker. Initial contributors are ::
# Terry Weissman <terry@mozilla.org>
# Gregor Fischer <fischer@suse.de>
# Klaas Freitag <freitag@suse.de>
# Seth Landsman <seth@dworkin.net>
# The purpose of this module is to abstract out a bunch of the code
# that is central to email interfaces to bugzilla and its database
# Contributor : Seth Landsman <seth@dworkin.net>
# Initial checkin : 03/15/00 (SML)
# findUser() function moved from bug_email.pl to here
push @INC, "../."; # this script now lives in contrib
require "globals.pl";
use diagnostics;
use strict;
my $EMAIL_TRANSFORM_NONE = "email_transform_none";
my $EMAIL_TRANSFORM_BASE_DOMAIN = "email_transform_base_domain";
my $EMAIL_TRANSFORM_NAME_ONLY = "email_transform_name_only";
# change to do incoming email address fuzzy matching
my $email_transform = $EMAIL_TRANSFORM_NAME_ONLY;
# findUser()
# This function takes an email address and returns the user email.
# matching is sloppy based on the $email_transform parameter
sub findUser($) {
my ($address) = @_;
# if $email_transform is $EMAIL_TRANSFORM_NONE, return the address, otherwise, return undef
if ($email_transform eq $EMAIL_TRANSFORM_NONE) {
my $stmt = "SELECT login_name FROM profiles WHERE profiles.login_name = \'$address\';";
SendSQL($stmt);
my $found_address = FetchOneColumn();
return $found_address;
} elsif ($email_transform eq $EMAIL_TRANSFORM_BASE_DOMAIN) {
my ($username) = ($address =~ /(.+)@/);
my $stmt = "SELECT login_name FROM profiles WHERE profiles.login_name RLIKE \'$username\';";
SendSQL($stmt);
my $domain;
my $found = undef;
my $found_address;
my $new_address = undef;
while ((!$found) && ($found_address = FetchOneColumn())) {
($domain) = ($found_address =~ /.+@(.+)/);
if ($address =~ /$domain/) {
$found = 1;
$new_address = $found_address;
}
}
return $new_address;
} elsif ($email_transform eq $EMAIL_TRANSFORM_NAME_ONLY) {
my ($username) = ($address =~ /(.+)@/);
my $stmt = "SELECT login_name FROM profiles WHERE profiles.login_name RLIKE \'$username\';";
SendSQL($stmt);
my $found_address = FetchOneColumn();
return $found_address;
}
}
1;

View File

@@ -1,22 +0,0 @@
This directory contains contributed software related to Bugzilla.
Things in here have not necessarily been tested or tried by anyone
except the original contributor, so tred carefully. But it may still
be useful to you.
This directory includes:
mysqld-watcher.pl -- This script can be installed as a frequent cron
job to clean up stalled/dead queries.
gnats2bz.pl -- A perl script to help import bugs from a GNATS
database into a Bugzilla database. Contributed by
Tom Schutter <tom@platte.com>
bug_email.pl -- A perl script that can receive email containing
bug reports (email-interface). Contributed by
Klaas Freitag <freitag@SuSE.de>
README.Mailif -- Readme describing the mail interface.
bugmail_help.html -- User help page for the mail interface.
yp_nomail.sh -- Script you can run via cron that regularly updates
the nomail file for terminated employees

View File

@@ -1,80 +0,0 @@
The Bugzilla Mail interface
===========================
(UPDATE 03/14/00 to better reflect reality by SML)
The Bugzilla Mail interface allows to submit bugs to Bugzilla by email.
The Mail Interface Contribution consists of three files:
README.Mailif - this readme.
bug_email.pl - the script
bugmail_help.html - a user help html site
Installation:
Next is to add a user who receives the bugmails, e. g. bugmail. Create a
mail account and a home directory for the user.
The mailinterface script bug_email.pl needs to get the mail through stdin.
I use procmail for that, with the following line in the .procmailrc:
BUGZILLA_HOME=/usr/local/httpd/htdocs/bugzilla
:0 c
|(cd $BUGZILLA_HOME/contrib; ./bug_email.pl)
This defines the Bugzilla directory as the variable BUGZILLA_HOME and passes
all incoming mail to the script after cd'ing into the bugzilla home.
In some cases, it is necessary to alter the headers of incoming email. The
additional line to procmail :
:0 fhw
| formail -I "From " -a "From "
fixes many problems.
See bugzilla.procmailrc for a sample procmailrc that works for me (SML) and
also deals with bugzilla_email_append.pl
Customation:
There are some values inside the script which need to be customized for your
needs:
1. In sub-routine Reply (search 'sub Reply':
there is the line
print MAIL "From: Bugzilla Mailinterface<yourmail\@here.com>\n";
^^^^^^^^^^^^^^^^^^^^
Fill in your correct mail here. That will make it easy for people to reply
to the mail.
2. check, if your sendmail resides in /usr/sbin/sendmail, change the path if neccessary.
Search the script after 'default' - you find some default-Settings for bug
reports, which are used, if the sender did not send a field for it. The defaults
should be checked and changed.
Thats hopefully all, we will come up with any configuration file or something.
If your mail works, your script will insert mails from now on.
The mailinterface supports two commandline switches:
There are two command line switches :
-t: Testmode
The mailinterface does not really insert the bug into the database, but
writes some debug output to stdout and writes the mail into the file
bug_email_test.log in the data-dir.
-r: restricted mode
All lines before the first line with a keyword character are skipped.
In not restricted, default mode, these lines are added to the long
description of the bug.
02/2000 - Klaas Freitag, SuSE GmbH <freitag@suse.de>
03/2000 - Seth M. Landsman <seth@cs.brandeis.edu>
bug_email.pl now lives out of bugzilla/contrib
added line about formail

File diff suppressed because it is too large Load Diff

View File

@@ -1,223 +0,0 @@
<HTML>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<!--
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 Bugzilla Bug Tracking System.
Contributor(s): Klaas Freitag <Freitag@SuSE.de>
-->
<HEAD> <TITLE>Bugzilla Mail Interface</TITLE> </HEAD>
<BODY BGCOLOR="#FFFFFF">
<CENTER><H1>The Bugzilla Mail Interface</H1>
Contributor: <A HREF="mailto:freitag@suse.de">Klaas Freitag</A>, SuSE GmbH
</CENTER>
<P>
The bugzilla Mail interface allows the registered bugzilla users to submit bugs by
sending email with a bug description. This is usefull for people, who do not work
inhouse and want to submitt bugs to the bugzilla system.
<p>
I know, show me the <A HREF="#examplemail">example-mail !</A>
<H2>What do you need to do to submitt a bug by mail ?</H2>
You need to send a email in the described format to the bugmail-user of the
bugzilla-system. This is <A HREF="mailto:our_bugzilla@xyz.com">yourbugzilla@here.com</A>
You receive a reply mail with the new bug-ID if your request was ok.
If not, you get a mail with
some help on the bugmail system and a specific analysis of your request.
<P>
Please dont refuse to send one or two wrong mails, you will get all the information
you need in the replies, and <I>only</I> in the mail replies. The information on this
page, concerning available products, versions and so on, is not dynamicly generated and
may be old therefore.
<H1>The Mail Format</H1>
The bugmail needs a special format , which consists of some keywords and suitable
values for them and a description text. Note that the keyword block needs to be
above of the description text.
<H2>Keywords</H2>
You need to tell bugzilla some properties of the bugs. This is done by keywords, which
start on a new line with a @, followed by the keyword and and equal-sign, followed by a
hopefully valid value.
<TABLE BORDER=4 FRAME=box CELLSPACING="5" width=95%> <COLGROUP> <col width="2*">
<col width="5*"> <col width="1*"> </COLGROUP>
<TR>
<TH>Keyword</TH>
<TH>Value description</TH>
<TH>required and default value</TH>
</TR>
<TR>
<TD>@product</TD>
<TD>The product which has a bug</TD>
<TD>yes. <br> This is the most important information. Many other
fields depend on the product.</TD>
</TR>
<TR>
<TD>@component</TD>
<TD>the desired component which is affected by the bug</TD>
<TD>yes. <br> As the @product, this is a very important
field.</TD>
</TR>
<TR>
<TD>@version</TD>
<TD>The version of the product</TD>
<TD>yes. <br>See @product and @component</TD>
</TR>
<TR>
<TD>@short_desc</TD>
<TD>A summary of your bug report</TD>
<TD>yes. <br>This summary of the error you want to report
describes what happen. You may skip the long description,
but not this summary.<br>
<b>Note:</b>The short description may be given in the mail subject
instead of using the keyword !</TD>
</TR>
<TR>
<TD>@rep_platform</TD>
<TD>The desired platform</TD>
<TD>no.<br>If you dont give a value, this field is set to <I>All</I>.</TD>
</TR>
<TR>
<TD>@bug_severity</TD>
<TD>The severity of the bug</TD>
<TD>no. <br> If you dont give a value, this field is set to
<I>normal</I></TD>
</TR>
<TR>
<TD>@priority</TD>
<TD>The priority of the bug</TD>
<TD>no.<br>If you dont give a value, this field is set to <I>P3</I></TD>
</TR>
<TR>
<TD>@op_sys</TD>
<TD>The operating system</TD>
<TD>no.<br>If you dont give a value, this field is set to <I>Linux</I>.</TD>
</TR>
<TR>
<TD>@assigned_to</TD>
<TD>The one to whom the bug is assigned to</TD>
<TD>no. <br>There is an initial owner for every product/version/component.
He owns the bug by default. The initial owner can only be found if
product, version and component are valid.</TD>
</TR>
<TR>
<TD>@bug_file_loc</TD>
<TD>?</TD>
<TD>no.</TD>
</TR>
<TR>
<TD>@status_whiteboard</TD>
<TD>?</TD>
<TD>no.</TD>
</TR>
<TR>
<TD>@target_milestone</TD>
<TD>?</TD>
<TD>no.</TD>
</TR>
<TR>
<TD>@groupset</TD>
<TD>rules the visibility of the bug.</TD>
<TD>no.<br>This value defaults to the smallest of the available groups,
which is <I>readInternal</I>.</TD>
</TR>
<TR>
<TD>@qa_contact</TD>
<TD>the quality manager for the product</TD>
<TD>no.<br>This value can be retrieved from product, component and
version</TD>
</TR>
</TABLE>
<H2>Valid values</H2>
Give string values for the most keys above. Some keywords require special values:<br>
<ol>
<li>E-Mail adresses: If you want to set the qa-contact, specify a email-adress for @qa_contact. The email must be known by bugzilla of course.</li>
<li>Listvalues: Most of the values have to be one of a list of valid values. Try by sending
a mail and read the reply. Skip fields if you dont get help for them unless you dont know
which values you may choose.</li>
<li>free Text: The descriptions may be free text. </li>
<li>Special: The field groupset may be specified in different in three different kinds:
<ol>
<li> A plain numeric way, which is one usually huge number, e. g. <I>65536</I></li>
<li> a string with added numbers e.g. <I>65536+131072</I></li>
<li> a string list, e.g. <I>ReadInternal, ReadBeta </I></li>
</ol>
</li>
</ol>
<p>
But most of them need <b>valid</b> values.
<p>
Sorry, you will not find lists of valid products, components and the other stuff
here. Send a mail to with any text, and you will get a list of valid keywords in the reply.
<p>
Some of the values must be choosen from a list:<br>
<ol>
<li>bug_severity: blocker, critical, major, normal, minor, trivial, enhancement</li>
<li>op_sys: Linux </li>
<li>priority: P1, P2, P3, P4, P5</li>
<li>rep_platform: All, i386, AXP, i686, Other</li></ol>
<p>
After you have specified the required keywords and maybe some other value, you may
describe your bug. You dont need a keyword for starting your bug description. All
text which follows the keyword block is handled as long description of the bug.
<p>
The bugmail interface is able to find required information by itself. E.g. if you specify
a product which has exactly one component, this component will be found by the interface
automatically.
<H1>Attachments</H1>
The mail interface is able to cope with MIME-attachments.
People could for example add a logfile as a mail attachment, and it will appear in
bugzilla as attachment. A comment for the attachment should be added, it will describe
the attachment in bugzilla.
<H1><A NAME="examplemail">Example Mail</A></H1>
See the example of the mail <b>body</b> (Dont forget to specify the short description
in the mail subject):<hr><pre>
@product = Bugzilla
@component = general
@version = All
@groupset = ReadWorld ReadPartners
@op_sys = Linux
@priority = P3
@rep_platform = i386
This is the description of the bug I found. It is not neccessary to start
it with a keyword.
Note: The short_description is neccessary and may be given with the keyword
@short_description or will be retrieved from the mail subject.
</pre><hr>
</BODY>
</HTML>

View File

@@ -1,30 +0,0 @@
:0 fhw
| formail -I "From " -a "From "
BUGZILLA_HOME=/home/bugzilla/WEB/bugzilla/contrib
:0
* ^Subject: .*\[Bug .*\]
RESULT=|(cd $BUGZILLA_HOME && ./bugzilla_email_append.pl)
# Feed mail to stdin of bug_email.pl
:0 Ec
#* !^Subject: .*[Bug .*]
RESULT=|(cd $BUGZILLA_HOME && ./bug_email.pl )
# write result to a logfile
:0 c
|echo `date '+%d.%m.%y %H:%M: '` $RESULT >> $HOME/bug_email.log
:0 c
|echo "----------------------------------" >> $HOME/bug_email.log
:0 c
$HOME/bug_email.log
# Move mail to the inbox
:0
$HOME/Mail/INBOX

View File

@@ -1,189 +0,0 @@
#!/usr/bin/perl -w
# -*- Mode: perl; indent-tabs-mode: nil -*-
# 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 purpose of this script is to take an email message, which
# specifies a bugid and append it to the bug as part of the longdesc
# table
# Contributor : Seth M. Landsman <seth@dworkin.net>
# 03/15/00 : Initial version by SML
# 03/15/00 : processmail gets called
# Email subject must be of format :
# .* Bug ### .*
# replying to a typical bugzilla email should be valid
# TODO :
# 1. better way to get the body text (I don't know what dump_entity() is
# actually doing
use diagnostics;
use strict;
use MIME::Parser;
push @INC, "../."; # this script lives in contrib
require "globals.pl";
require "BugzillaEmail.pm";
# Create a new MIME parser:
my $parser = new MIME::Parser;
my $Comment = "";
# Create and set the output directory:
# FIXME: There should be a $BUGZILLA_HOME variable (SML)
(-d "../data/mimedump-tmp") or mkdir "../data/mimedump-tmp",0755 or die "mkdir: $!";
(-w "../data/mimedump-tmp") or die "can't write to directory";
$parser->output_dir("../data/mimedump-tmp");
# Read the MIME message:
my $entity = $parser->read(\*STDIN) or die "couldn't parse MIME stream";
$entity->remove_sig(10); # Removes the signature in the last 10 lines
# Getting values from parsed mail
my $Sender = $entity->get( 'From' );
$Sender ||= $entity->get( 'Reply-To' );
my $Message_ID = $entity->get( 'Message-Id' );
die (" *** Cant find Sender-adress in sent mail ! ***\n" ) unless defined( $Sender );
chomp( $Sender );
chomp( $Message_ID );
print "Dealing with the sender $Sender\n";
ConnectToDatabase();
my $SenderShort = $Sender;
$SenderShort =~ s/^.*?([a-zA-Z0-9_.-]+?\@[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_.-]+).*$/$1/;
$SenderShort = findUser($SenderShort);
print "SenderShort is $SenderShort\n";
if (!defined($SenderShort)) {
$SenderShort = $Sender;
$SenderShort =~ s/^.*?([a-zA-Z0-9_.-]+?\@[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_.-]+).*$/$1/;
}
print "The sendershort is now $SenderShort\n";
if (!defined($SenderShort)) {
DealWithError("No such user $SenderShort exists.");
}
my $Subject = $entity->get('Subject');
print "The subject is $Subject\n";
my ($bugid) = ($Subject =~ /\[Bug ([\d]+)\]/);
print "The bugid is $bugid\n";
# make sure the bug exists
SendSQL("SELECT bug_id FROM bugs WHERE bug_id = $bugid;");
my $found_id = FetchOneColumn();
print "Did we find the bug? $found_id-\n";
if (!defined($found_id)) {
DealWithError("Bug $bugid does not exist");
}
# get the user id
SendSQL("SELECT userid FROM profiles WHERE login_name = \'$SenderShort\';");
my $userid = FetchOneColumn();
if (!defined($userid)) {
DealWithError("Userid not found for $SenderShort");
}
# parse out the text of the message
dump_entity($entity);
# Get rid of the bug id
$Subject =~ s/\[Bug [\d]+\]//;
#my $Comment = "This is only a test ...";
my $Body = "Subject: " . $Subject . "\n" . $Comment;
# shove it in the table
my $long_desc_query = "INSERT INTO longdescs SET bug_id=$found_id, who=$userid, bug_when=NOW(), thetext=" . SqlQuote($Body) . ";";
SendSQL($long_desc_query);
system("cd .. ; ./processmail $found_id '$SenderShort'");
sub DealWithError {
my ($reason) = @_;
print $reason . "\n";
}
# Yanking this wholesale from bug_email, 'cause I know this works. I'll
# figure out what it really does later
#------------------------------
#
# dump_entity ENTITY, NAME
#
# Recursive routine for parsing a mime coded mail.
# One mail may contain more than one mime blocks, which need to be
# handled. Therefore, this function is called recursively.
#
# It gets the for bugzilla important information from the mailbody and
# stores them into the global attachment-list @attachments. The attachment-list
# is needed in storeAttachments.
#
sub dump_entity {
my ($entity, $name) = @_;
defined($name) or $name = "'anonymous'";
my $IO;
# Output the body:
my @parts = $entity->parts;
if (@parts) { # multipart...
my $i;
foreach $i (0 .. $#parts) { # dump each part...
dump_entity($parts[$i], ("$name, part ".(1+$i)));
}
} else { # single part...
# Get MIME type, and display accordingly...
my $msg_part = $entity->head->get( 'Content-Disposition' );
$msg_part ||= "";
my ($type, $subtype) = split('/', $entity->head->mime_type);
my $body = $entity->bodyhandle;
my ($data, $on_disk );
if( $msg_part =~ /^attachment/ ) {
# Attached File
my $des = $entity->head->get('Content-Description');
$des ||= "";
if( defined( $body->path )) { # Data is on disk
$on_disk = 1;
$data = $body->path;
} else { # Data is in core
$on_disk = 0;
$data = $body->as_string;
}
# push ( @attachments, [ $data, $entity->head->mime_type, $on_disk, $des ] );
} else {
# Real Message
if ($type =~ /^(text|message)$/) { # text: display it...
if ($IO = $body->open("r")) {
$Comment .= $_ while (defined($_ = $IO->getline));
$IO->close;
} else { # d'oh!
print "$0: couldn't find/open '$name': $!";
}
} else { print "Oooops - no Body !\n"; }
}
}
}

View File

@@ -1,94 +0,0 @@
#!/bin/sh
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is
# Andreas Franke <afranke@ags.uni-sb.de>.
# Corporation. Portions created by Andreas Franke are
# Copyright (C) 2001 Andreas Franke. All
# Rights Reserved.
#
# Contributor(s):
conf="`dirname $0`/query.conf"
query="http://bugzilla.mozilla.org/buglist.cgi?cmd=doit"
defaultcolumnlist="severity priority platform status resolution target_milestone status_whiteboard keywords summaryfull"
chart=0
and=0
while test "$1" != ""; do
arg=$1
arg_len=`expr length ${arg}`
if test `expr substr "${arg}" 1 2` == "--"; then
eq_pos=`expr match ${arg} '--.*='`
if test "${eq_pos}" == "0"; then
echo 'Missing value for long option '"${arg}"' ("=" not found)' 1>&2
exit 1;
fi
# extract option name
let name_len=${eq_pos}-3
name=`expr substr ${arg} 3 ${name_len}`
# extract option value
let val_start=${eq_pos}+1
let val_len=${arg_len}-${eq_pos}
val=`expr substr ${arg} ${val_start} ${val_len}`
elif test `expr substr ${arg} 1 1` == "-" &&
test "`expr substr ${arg} 2 1`" != ""; then
# extract
name=`expr substr ${arg} 2 1`
let val_len=${arg_len}-2
val=`expr substr ${arg} 3 ${val_len}`
else
name="default"
val="${arg}"
#echo "Unrecognized option ${arg}" 1>&2
#exit 1
fi
# find field and comparison type for option ${name}
field=`grep '"'${name}'"' ${conf} | awk '{printf $1}'`
type=`grep '"'${name}'"' ${conf} | awk '{printf $2}'`
if test "${field}" == "" || test "${type}" == ""; then
echo "Field name & comparison type not found for option ${name}." 1>&2
exit 1;
fi
or=0
while test "${val}" != ""; do
comma_idx=`expr index ${val} ,`
if test ${comma_idx} == "0"; then
val1="${val}"
val=""
else
let val1_len=${comma_idx}-1
val1=`expr substr ${val} 1 ${val1_len}`
val_len=`expr length ${val}`
let rest_start=${comma_idx}+1
let rest_len=${val_len}-${comma_idx}
val=`expr substr ${val} ${rest_start} ${rest_len}`
fi
query="${query}&field${chart}-${and}-${or}=${field}"
query="${query}&type${chart}-${and}-${or}=${type}"
query="${query}&value${chart}-${and}-${or}=${val1}"
#echo "----- ${name} : ${field} : ${type} : ${val1} -----" 1>&2
let or=${or}+1
done
let chart=${chart}+1
shift
done
outputfile="/dev/stdout"
#outputfile="buglist.html"
#\rm -f ${outputfile}
wget -q -O ${outputfile} --header="Cookie: COLUMNLIST=${COLUMNLIST-${defaultcolumnlist}}" "${query}"

View File

@@ -1,31 +0,0 @@
#!/bin/sh
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is
# Andreas Franke <afranke@ags.uni-sb.de>.
# Corporation. Portions created by Andreas Franke are
# Copyright (C) 2001 Andreas Franke. All
# Rights Reserved.
#
# Contributor(s):
buglist="`dirname $0`/buglist"
htmlfile="`dirname $0`/buglist.html"
${buglist} "$@" 2>&1 1>${htmlfile}
if test ${?} == "0"; then
echo `grep 'TR VALIGN=TOP ALIGN=LEFT CLASS=' ${htmlfile} | sed -e 's/<TR.*id=//' | sed -e 's/".*//'` | sed -e 's/ /\,/g'
else
cat ${htmlfile} 1>&2
exit 1
fi

View File

@@ -1,49 +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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is
# Andreas Franke <afranke@ags.uni-sb.de>.
# Corporation. Portions created by Andreas Franke are
# Copyright (C) 2001 Andreas Franke. All
# Rights Reserved.
#
# Contributor(s):
#
# This is `query.conf', the config file for `buglist'.
#
# Columns: 1: field_name, 2: comparison_type, 3: cmd-line options
#
bug_status substring "s","status"
resolution substring "r","resolution"
rep_platform substring "p","platform"
op_sys substring "o","os","opsys"
priority substring "p","priority"
bug_severity substring "S","severity"
assigned_to substring "A","O","owner","assignedto"
reporter substring "R","reporter"
qa_contact substring "Q","qa","qacontact"
cc substring "C","cc"
product substring "product"
version substring "V","version"
component substring "c","component"
target_milestone substring "M","milestone"
short_desc substring "default","summary"
longdesc substring "d","description","longdesc"
bug_file_loc substring "u","url"
status_whiteboard substring "w","whiteboard"
keywords substring "k","K","keywords"
attachments.description substring "attachdesc"
attachments.thedata substring "attachdata"
attachments.mimetype substring "attachmime"
dependson substring # bug 30823
blocked substring # bug 30823

View File

@@ -1,40 +0,0 @@
#!/bin/sh
#
# 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 Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Dawn Endico <endico@mozilla.org>
# Keep a record of all cvs updates made from a given directory.
#
# Later, if changes need to be backed out, look at the log file
# and run the cvs command with the date that you want to back
# out to. (Probably the second to last entry).
#DATE=`date +%e/%m/%Y\ %k:%M:%S\ %Z`
DATE=`date`
COMMAND="cvs update -d -P -D"
echo $COMMAND \"$DATE\" >> cvs-update.log
$COMMAND "$DATE"
# sample log file
#cvs update -P -D "11/04/2000 20:22:08 PDT"
#cvs update -P -D "11/05/2000 20:22:22 PDT"
#cvs update -P -D "11/07/2000 20:26:29 PDT"
#cvs update -P -D "11/08/2000 20:27:10 PDT"

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