📄 unixdmon.cpp
字号:
/*____________________________________________________________________________*\
*
Copyright (c) 1997-2003 John Roy, Holger Zimmermann. All rights reserved.
These sources, libraries and applications are
FREE FOR COMMERCIAL AND NON-COMMERCIAL USE
as long as the following conditions are adhered to.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*____________________________________________________________________________*|
*
* $Source: /cvsroot/pi3web/Pi3Web_200/Source/Server/UNIXDmon.cpp,v $
* $Date: 2003/06/09 09:42:56 $
*
Description:
UNIX daemon server class.
\*____________________________________________________________________________*/
//$SourceTop:$
#include <iostream.h>
#include <assert.h>
#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#if POSIX
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#if !(defined __rlimit_resource)
#define __rlimit_resource int
#endif
#endif
#include "Pi2API.h"
/*____________________________________________________________________________*\
*
Description:
\*____________________________________________________________________________*/
#define KEY_CONF_MESSAGE "Message"
#define KEY_CONF_SERVEROBJECT "ServerObject"
#define KEY_CONF_PIDFILE "PIDFile"
#define KEY_CONF_RLIMITCORE "RLimitCore"
#define KEY_CONF_RLIMITCPU "RLimitCPU"
#define KEY_CONF_RLIMITDATA "RLimitData"
#define KEY_CONF_RLIMITFSIZE "RLimitFSize"
#define KEY_CONF_USER "User"
#define KEY_CONF_GROUP "Group"
#define KEY_CONF_NUMBEROFPROCESSES "NumberOfProcesses"
#define KEY_CONF_LOCKFILENAME "LockFileName"
#define KEY_CONF_MESSAGE "Message"
#define CONFIG_ERR(this, msg) \
{ PILog_addMessage( PIObject_getDB(this), \
PIObject_getConfigurationDB(this), PILOG_ERROR, (msg) ); }
/* ---
Write error message to stderr, quoting this server as the
source
--- */
inline ostream &Cerr()
{
cerr << "UNIXDaemon[" << PIPlatform_getProcess() << ":" <<
(int)PIThread_getSystemHandle( PIThread_getCurrent() ) << "]: ";
return cerr;
};
/*
#define D { Cerr() << __FILE__ << ", " << __LINE__ << endl; };
*/
#define D
/* ---
When a user and group is specified determine whether the main process
will change to the user, or only child processes
--- */
#define RUN_MAIN_AS_ROOT 0
/*____________________________________________________________________________*\
*
Description:
Documentation.
\*____________________________________________________________________________*/
#if 0
/*
** HTML documentation for this server
*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
UNIXDaemon
Description:
This object performs some UNIX daemon actions, including changing the
effective user and setting resource limits. This class also handles
forking multiple child processes to handle requests.
Note:
On non UNIX systems execution of this object will cause the object
specified with 'ServerObject' to be executed after the message
specified with 'Message' is displayed. All other options and actions
are ignored.
Options:
<H5>Overview</H5>
<TABLE BORDER=1>
<TH>Option
<TH>Default
<TH>Values
<TH>Short Description
<TH>Example(s)
<TR>
<TD>ServerObject
<TD>+
<TD>a Pi3 object name
<TD>A Pi3 object
<TD>ServerObject "ServerObject"
<TR>
<TD>PIDFile
<TD>-
<TD><filepath>
<TD>Path to PID file
<TD>PIDFile "logs/pid.log"
<TR>
<TD>NumberOfProcesses
<TD>5
<TD>1..10000
<TD>Number of child processes
<TD>NumberOfProcesses 10
<TR>
<TD>RLimitCore
<TD>-
<TD>Number or 'Maximum'
<TD>Limit on corefile
<TD>RLimitCore 2000000
<TR>
<TD>RLimitCpu
<TD>-
<TD>Number or 'Maximum'
<TD>Limit on CPU time
<TD>RLimitCPU Maximum
<TR>
<TD>RLimitData
<TD>-
<TD>Number or 'Maximum'
<TD>Limit on data segment
<TD>RLimitData Maximum
<TR>
<TD>RLimitFSize
<TD>-
<TD>Number or 'Maximum'
<TD>Maximum filesize creatable
<TD>RLimitFSize Maximum
<TR>
<TD>User
<TD>-
<TD>username or #number
<TD>Child process user id
<TD>User jroy
<TR>
<TD>Group
<TD>-
<TD>groupname of #number
<TD>Child process group id
<TD>Group #-1
<TR>
<TD>LockFileName
<TD>-
<TD><filename>
<TD>server unique filename
<TD>LockFileName "Logs/lockfile.txt"
<TR>
<TD>Message
<TD>-
<TD><text>
<TD>Startup message
<TD>Message "Welcome to OZ"
</TABLE>
<STRONG>-</STRONG> in the <IT>default</IT> indicates no default<BR>
<STRONG>+</STRONG> in the <IT>default</IT> indicates the field is mandatory<BR>
<H4>Description of Options</H4>
<H5>
ServerObject
</H5>
Specify the server object which handles requests.
<H5>
PIDFile
</H5>
Specifies a file to write the process identifier. This directive can be
repeated multiple times to create multiple PID files. This path can be
absolute or relative. If a relative path is given, the file will be
created relative to the servers current directory.
<H5>
NumberOfProcesses
</H5>
Gives the number of child processes to generate. As child processes
die, the parent monitor process will create new ones. When the
parent process dies, it will kill all child processes.
<H5>
RLimitCore
</H5>
<H5>
RLimitCPU
</H5>
<H5>
RLimitData
</H5>
<H5>
RLimitFSize
</H5>
Respectively reset the soft resource limit on corefile size, CPU time,
data segment size and largest creatable file for child processes of
this UNIX Daemon.
<H5>
User
</H5>
Specifies the user that child processes will execute as. A username can
be supplied or an id is assumed if the first letter is '#'
<H5>
Group
</H5>
Specifies the group that child processes will execute as. A groupname can
be supplied an id is assumed if the first letter is '#'.
<H5>
LockFileName
</H5>
Specifies a file into which this class will write a temporary filename
unique to this server and process group instance.
The path can be absolute or relative from the current directory. This
class will attempt to unlink the temporary file on exiting to this
directive should not be repeated more than once.
<H5>
Message
</H5>
Specifies a message to be written to standard output just before the
server enters its processing loop.
Returns:
PIAPI_COMPLETED on success.
PIAPI_CONTINUE if no action taken.
PIAPI_ERROR and PIAPI_ABORT respectively for generic and severe
error conditions.
Example:
<PRE>
<Object>
Name UNIXDaemon
Class UNIXDaemonClass
ServerObject DefaultServerObject
PIDFile "Logs/pid.log"
NumberOfProcesses 10
RLimitCore Maximum
RLimitCPU Maximum
RLimitData Maximum
RLimitFSize Maximum
User jroy
Group #-1
LockFileName "Logs/lockfile.txt"
</Object>
</PRE>
/*___+++HTMLDOC_END+++___*/
#endif
#define FLG_UID 0x0001
#define FLG_GID 0x0002
#define FLG_RCORE 0x0004
#define FLG_RCPU 0x0008
#define FLG_RDATA 0x0010
#define FLG_RFSIZE 0x0020
/*____________________________________________________________________________*\
*
Class:
Description:
\*____________________________________________________________________________*/
class UNIXDaemon
{
private:
PIObject *pObject;
PIObject *pServerObject;
int iOK;
char *pMessage;
#if POSIX
int iFlags;
uid_t tId;
gid_t tGid;
int iNumberOfProcesses;
pid_t *pProcessIds;
struct rlimit tRCore;
struct rlimit tRCPU;
struct rlimit tRData;
struct rlimit tRFSize;
char *pMainLockFileName;
char *pLockFileName;
pid_t tParentPid; /* parents pid */
/* --- lookup user id, returns 1 on success, else 0 --- */
int GetUid( const char *pValue )
{
assert( pValue );
if ( !pValue )
{ return 0; };
/* --- must be root --- */
if ( getuid() )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"%s", "UNIXDaemon: Must be root for 'User' directive." );
return 0;
};
if ( *pValue == '#' )
{ tId = atoi( &(pValue[1]) ); }
else
{
int iFound = 0;
struct passwd *pEnt = 0;
PIPlatform_beforeUnsafeBlock();
pEnt = getpwnam( pValue );
if ( pEnt )
{
iFound = 1;
tId = pEnt->pw_uid;
};
PIPlatform_afterUnsafeBlock();
if ( !iFound )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"UNIXDaemon: Failed to get uid for user '%s'",
pValue );
return 0;
};
};
iFlags |= FLG_UID;
return 1;
};
/* --- lookup group id, returns 1 on success, else 0 --- */
int GetGid( const char *pValue )
{
assert( pValue );
if ( !pValue )
{ return 0; };
/* --- must be root --- */
if ( getuid() )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"%s", "UNIXDaemon: Must be root for 'Group' directive." );
return 0;
};
if ( *pValue == '#' )
{ tGid = atoi( &(pValue[1]) ); }
else
{
int iFound = 0;
struct group *pEnt = 0;
PIPlatform_beforeUnsafeBlock();
pEnt = getgrnam( pValue );
if ( pEnt )
{
iFound = 1;
tGid = pEnt->gr_gid;
};
PIPlatform_afterUnsafeBlock();
if ( !iFound )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"UNIXDaemon: Failed to get gid for group '%s'", pValue );
return 0;
};
};
iFlags |= FLG_GID;
return 1;
};
protected:
/* ---
return 1 on success, 0 on failure
--- */
int AddResourceLimit( int iResource, const char *pName, const char *pValue,
struct rlimit *pLimit )
{
assert( pName && pValue && pLimit );
if ( !pName || !pValue || !pLimit )
{ return 0; };
/* --- get the limits --- */
if ( ::getrlimit(iResource, pLimit )<0 )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"UNIXDaemon: getrlimit() failed for resource: '%s'", pName );
return 0;
};
/* --- set the limits --- */
if ( PIUtil_stricmp( pValue, "Maximum" ) )
{ pLimit->rlim_cur = atoi( pValue ); }
else
{ pLimit->rlim_cur = pLimit->rlim_max; };
return 1;
};
/* --- set the limits --- */
int SetRLimit( int iResource, struct rlimit *pLimit, const char *pName )
{
assert( pLimit && pName );
if ( !pLimit || !pName )
{ return 0; };
if ( ::setrlimit(iResource, pLimit )<0 )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"UNIXDaemon: setrlimit() failed for resource: '%s'",
pName );
Cerr() << "UNIXDaemon: setrlimit() failed for resource: '" <<
pName << "'" << endl;
return 0;
};
return 1;
};
/* ---
Generate a temporary lockfile and write its name into the main
lockfile.
Return 1 on success, 0 on failure
--- */
int GenerateLockFile()
{
if ( !*pLockFileName )
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"UNIXDaemon: Could not generate lockfile name." );
return 0;
};
ofstream ofs( pLockFileName );
if ( ofs.good() )
{
ofs.close();
/* --- file is readable and writable by this user only --- */
::chmod( pLockFileName, S_IRUSR | S_IWUSR );
}
else
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"UNIXDaemon: Could not create or change access to \
file '%s'.", pLockFileName );
return 0;
};
return 1;
}
#endif
/* ---
Parameters
--- */
int Parameter( const char *pVariable, const char *pValue,
const char *pWhere )
{
assert( pVariable && pValue );
if ( !pVariable || !pValue )
{ return 0; };
if ( !PIUtil_stricmp( KEY_CONF_SERVEROBJECT, pVariable ) )
{
/* ---
loaded in constructor after all parameters have been read
--- */
}
else if ( !PIUtil_stricmp( KEY_CONF_MESSAGE, pVariable ) )
{
pMessage = PIUtil_strdup( pValue );
}
#if POSIX
else if ( !PIUtil_stricmp( KEY_CONF_NUMBEROFPROCESSES, pVariable ) )
{
int iTmp = atoi( pValue );
if ( iTmp<1 || iTmp>10000 ) /* if this changed, then change the
documentation above */
{
PILog_addMessage( PIObject_getDB( pObject ),
PIObject_getConfigurationDB( pObject ), PILOG_ERROR,
"%sUNIXDaemon: Number of processes must be between 1 \
and 10,000, the value specified is: '%d'", pWhere, iTmp );
return 0;
};
iNumberOfProcesses = iTmp;
}
else if ( !PIUtil_stricmp( KEY_CONF_RLIMITCORE, pVariable ) )
{
if ( AddResourceLimit( RLIMIT_CORE, "RLIMIT_CORE", pValue,
&tRCore ) )
{ iFlags |= FLG_RCORE; }
else
{ return 0; };
}
else if ( !PIUtil_stricmp( KEY_CONF_RLIMITCPU, pVariable ) )
{
if ( AddResourceLimit( RLIMIT_CPU, "RLIMIT_CPU", pValue,
&tRCPU ) )
{ iFlags |= FLG_RCPU; }
else
{ return 0; };
}
else if ( !PIUtil_stricmp( KEY_CONF_RLIMITDATA, pVariable ) )
{
if ( AddResourceLimit( RLIMIT_DATA, "RLIMIT_DATA", pValue,
&tRData ) )
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -