o
    b>                     @   s   d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlm	Z	m
Z
 d dlmZ d dlmZmZmZ d dlmZ d dlmZmZmZmZ edkrNed	d
d ZG dd de	jZdd ZG dd de	jZdd ZG dd de	jZ dS )    N)	copyrightlogger)appservice)IReactorDaemonize)loglogfileusage)platformType)gidFromString	switchUIDuidFromStringuntilConcludeswin32z%_twistd_unix doesn't work on Windows.c                 C   s
   t | dS )N   )int)value r   >/usr/lib/python3/dist-packages/twisted/scripts/_twistd_unix.py_umask   s   
r   c                
   @   s   e Zd ZdZg dg dg dg dgZg dg dg dd	d
ddegddddegddddeggZe	j
e	de	jdde	jdde	jdde	jddddZdd Zdd ZdS )ServerOptionszUsage: twistd [options])nodaemonnz0don't daemonize, don't use default umask of 0077)originalnameNz$Don't try to change the process name)syslogNzLog to syslog, not to file)euid a  Set only effective user-id rather than real user-id. (This option has no effect unless the server is running as root, in which case it means not to shed all privileges after binding ports, retaining the option to regain privileges in cases such as spawning processes. Use with caution.))prefixNtwistedz$use the given prefix when syslogging)pidfiler   z
twistd.pidzName of the pidfile)chrootNNz-Chroot to a supplied directory before runninguiduNzThe uid to run as.gidgzbThe gid to run as.  If not specified, the default gid associated with the specified --uid is used.umaskz(The (octal) file creation mask to apply.z*.pidzchroot directory)descrzgid to run aszuid to run aszsyslog prefix)r   r    r#   r!   r   )
optActionsc                 C   s2   t dtj | jd t tj| jd t  dS )z5
        Print version information and exit.
        ztwistd (the Twisted daemon) )fileN)printr   versionstdoutsysexitselfr   r   r   opt_versionH   s   zServerOptions.opt_versionc                 C   s0   t j|  | d rtj| d | d< d S d S )Nr   )r   r   postOptionsospathabspathr.   r   r   r   r1   P   s   zServerOptions.postOptions)__name__
__module____qualname__synopsisoptFlagsr   r   r   optParametersr	   CompletionsCompleteFilesCompleteDirsCompleteGroupsCompleteUsernames	CompletercompDatar0   r1   r   r   r   r   r      s:    




r   c              
   C   s  | sd S t j| rzt| }t| }W d    n1 s w   Y  W n ty8   td|  d Y nw zt 	|d W n: t
y{ } z.|jtjkr_tjd|  dd t |  ntd|| | W Y d }~d S W Y d }~d S d }~ww td| d S d S )	NzPidfile z contains non-numeric valuer   zRemoving stale pidfile T)isErrorz0Can't check status of PID {} from pidfile {}: {}a  Another twistd server is running, PID {}

This could either be a previously started instance of your application or a
different application entirely. To start a new one, either run it in some other
directory, or use the --pidfile and --logfile parameters to avoid clashes.
)r2   r3   existsopenr   read
ValueErrorr,   r-   killOSErrorerrnoESRCHr   msgremoveformat)r   fpidwhyr   r   r   checkPIDV   s@   
rQ   c                   @   s    e Zd ZdZdd Zdd ZdS )UnixAppLoggera  
    A logger able to log to syslog, to files, and to stdout.

    @ivar _syslog: A flag indicating whether to use syslog instead of file
        logging.
    @type _syslog: C{bool}

    @ivar _syslogPrefix: If C{sysLog} is C{True}, the string prefix to use for
        syslog messages.
    @type _syslogPrefix: C{str}

    @ivar _nodaemon: A flag indicating the process will not be daemonizing.
    @type _nodaemon: C{bool}
    c                 C   s<   t j| | |dd| _|dd| _|dd| _d S )Nr   Fr   r   r   )r   	AppLogger__init__get_syslog_syslogPrefix	_nodaemon)r/   optionsr   r   r   rT      s   zUnixAppLogger.__init__c                    s   | j rddlm} || jjS | jdkr!| jst	d tj
 n:| jr+| js+tj
 n0| js1d| _tj| j zddl}W n	 tyG   Y nw ||js[ fdd}||j| t S )	a  
        Create and return a suitable log observer for the given configuration.

        The observer will go to syslog using the prefix C{_syslogPrefix} if
        C{_syslog} is true.  Otherwise, it will go to the file named
        C{_logfilename} or, if C{_nodaemon} is true and C{_logfilename} is
        C{"-"}, to stdout.

        @return: An object suitable to be passed to C{log.addObserver}.
        r   )r   -z&Daemons cannot log to stdout, exiting!z
twistd.logNc                    s   ddl m} | j d S )Nr   reactor)twisted.internetr\   callFromThreadrotate)signalframer\   logFiler   r   	rotateLog   s   z0UnixAppLogger._getLogObserver.<locals>.rotateLog)rV   twisted.pythonr   SyslogObserverrW   emit_logfilenamerX   r,   r-   r+   r   LogFilefromFullPathr`   ImportError	getsignalSIGUSR1r   textFileLogObserver)r/   r   r`   rd   r   rb   r   _getLogObserver   s*   


zUnixAppLogger._getLogObserverN)r5   r6   r7   __doc__rT   ro   r   r   r   r   rR   y   s    rR   c                 C   s`   | r,| t jd kr.tjt j}td|   t|| t jd dgt jdd    d S d S d S )Nr   zChanging process name to z--originalname   )	r,   argvr2   r3   realpath
executabler   rK   execv)nameexer   r   r   launchWithName   s
   *rx   c                   @   sf   e Zd ZdZeZdd Zdd Zdd Zdd	 Z	d
d Z
dd ZdedefddZdd Zdd ZdS )UnixApplicationRunnerzx
    An ApplicationRunner which does Unix-specific things, like fork,
    shed privileges, and maintain a PID file.
    c                 C   s<   t | jd  | jd p| jd | jd< tj| _tj| _dS )z4
        Do pre-application-creation setup.
        r   r   debugN)rQ   configr,   r+   	oldstdoutstderr	oldstderrr.   r   r   r   preApplication   s   z$UnixApplicationRunner.preApplicationc                 C   s8   t |j|d }d|  }|dd}|dd S )aC  
        Format the C{exception} in preparation for writing to the
        status pipe.  This does the right thing on Python 2 if the
        exception's message is Unicode, and in all cases limits the
        length of the message afte* encoding to 100 bytes.

        This means the returned message may be truncated in the middle
        of a unicode escape.

        @type exception: L{Exception}
        @param exception: The exception to format.

        @return: The formatted message, suitable for writing to the
            status pipe.
        @rtype: L{bytes}
        z1 asciibackslashreplaceNd   )	tracebackformat_exception_only	__class__stripencode)r/   	exceptionexceptionLineformattedMessager   r   r   _formatChildException   s   	z+UnixApplicationRunner._formatChildExceptionc              
   C   s   z|  | j W n2 ty: } z&| jdd}|dur-| |}ttj|| ttj	| | 
| jd   d}~ww | jdd}|durSttj|d ttj	| | d| j| j | 
| jd  dS )z
        To be called after the application is created: start the application
        and run the reactor. After the reactor stops, clean up PID files and
        such.
        
statusPipeNr      0)startApplicationapplication	Exceptionr{   rU   r   r   r2   writeclose	removePIDstartReactorr|   r~   )r/   exr   messager   r   r   postApplication   s$   
	z%UnixApplicationRunner.postApplicationc              
   C   s   |sdS zt | W dS  ty> } z&|jtjks |jtjkr&td nt|d W Y d}~dS W Y d}~dS d}~w t	yM   tdd Y dS w )z
        Remove the specified PID file, if possible.  Errors are logged, not
        raised.

        @type pidfile: C{str}
        @param pidfile: The path to the PID tracking file.
        Nz)Warning: No permission to delete pid filezFailed to unlink PID file:)
r2   unlinkrH   rI   EACCESEPERMr   rK   errBaseException)r/   r   er   r   r   r     s   zUnixApplicationRunner.removePIDc           	      C   s   | }|durt | |dkrd}t | |r|du rd}|dur(t | |r8ddlm} | || jd< |r\t|d}|	d	t 
 f  W d   dS 1 sUw   Y  dS dS )
a  
        Set the filesystem root, the working directory, and daemonize.

        @type chroot: C{str} or L{None}
        @param chroot: If not None, a path to use as the filesystem root (using
            L{os.chroot}).

        @type rundir: C{str}
        @param rundir: The path to set as the working directory.

        @type nodaemon: C{bool}
        @param nodaemon: A flag which, if set, indicates that daemonization
            should not be done.

        @type umask: C{int} or L{None}
        @param umask: The value to which to change the process umask.

        @type pidfile: C{str} or L{None}
        @param pidfile: If not L{None}, the path to a file into which to put
            the PID of this process.
        N./?   r   r[   r   wbs   %d)r2   r    chdirr%   r]   r\   	daemonizer{   rD   r   getpid)	r/   r    rundirr   r%   r   daemonr\   rN   r   r   r   setupEnvironment#  s$   


"z&UnixApplicationRunner.setupEnvironmentc                 C   s   t |r	|  t \}}t r"| |}t| t| t	  t r/td t
dtj}tdD ]#}zt|| W q: ty] } z|jtjkrS W Y d}~q:d}~ww t| t |rl|  |S )a7  
        Daemonizes the application on Unix. This is done by the usual double
        forking approach.

        @see: U{http://code.activestate.com/recipes/278731/}
        @see: W. Richard Stevens,
            "Advanced Programming in the Unix Environment",
            1992, Addison-Wesley, ISBN 0-201-56317-7

        @param reactor: The reactor in use.  If it provides
            L{IReactorDaemonize}, its daemonization-related callbacks will be
            invoked.

        @return: A writable pipe to be used to report errors.
        @rtype: C{int}
        r   z	/dev/null   N)r   
providedBybeforeDaemonizer2   pipefork_waitForStartr   _exitsetsidrD   O_RDWRrangedup2rH   rI   EBADFafterDaemonize)r/   r\   rwcodenullir   r   r   r   r   L  s0   






zUnixApplicationRunner.daemonizereadPipereturnc                 C   sF   t tj|d}t|dd }|dkr!d|}t tjj| dS dS )a  
        Wait for the daemonization success.

        @param readPipe: file descriptor to read start information from.
        @type readPipe: C{int}

        @return: code to be passed to C{os._exit}: 0 for success, 1 for error.
        @rtype: C{int}
        r      Nr   zHAn error has occurred: {}
Please look at log file for more information.
rq   r   )r   r2   rE   reprrM   r,   
__stderr__r   )r/   r   datadataReprrK   r   r   r   r   x  s   
z#UnixApplicationRunner._waitForStartc              
   C   s   |dus|durO|rdpd}| d| d| d| }zt ||| W n! tyD } ztd|| td W Y d}~dS d}~ww td	|  dS dS )
a  
        Change the UID and GID or the EUID and EGID of this process.

        @type euid: C{bool}
        @param euid: A flag which, if set, indicates that only the I{effective}
            UID and GID should be set.

        @type uid: C{int} or L{None}
        @param uid: If not L{None}, the UID to which to switch.

        @type gid: C{int} or L{None}
        @param gid: If not L{None}, the GID to which to switch.
        Nr   r   zuid/zgid r   z0failed to set {}: {} (are you root?) -- exiting.rq   zset )r   rH   r   rK   rM   r,   r-   )r/   r   r!   r#   extradescr   r   r   r   shedPrivileges  s   z$UnixApplicationRunner.shedPrivilegesc                 C   s   t |}| jd st|j | | jd | jd | jd | jd | jd  t |  | jd | jd }}|d	u r@|j}|d	u rG|j	}|d	urU|d	u rUt
|j}| | jd
 || t|| jd   d	S )z
        Configure global process state based on the given application and run
        the application.

        @param application: An object which can be adapted to
            L{service.IProcess} and L{service.IService}.
        r   r    r   r   r%   r   r!   r#   Nr   no_save)r   IProcessr{   rx   processNamer   IServiceprivilegedStartServicer!   r#   pwdgetpwuidpw_gidr   r   r   )r/   r   processr!   r#   r   r   r   r     s(   


z&UnixApplicationRunner.startApplicationN)r5   r6   r7   rp   rR   loggerFactoryr   r   r   r   r   r   r   r   r   r   r   r   r   r   ry      s    	%),ry   )!rI   r2   r   r,   r   r   r   r   twisted.applicationr   r   twisted.internet.interfacesr   re   r   r   r	   twisted.python.runtimer
   twisted.python.utilr   r   r   r   rk   r   r   rQ   rS   rR   rx   ApplicationRunnerry   r   r   r   r   <module>   s&   ;#A