
    Df9A                     2   d Z ddlZddlZddlZddlZddlZddlZ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 ddlmZmZ ddlmZmZmZ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 epeZ e
j!        "                     e#ed
           d          Z$e
j!        "                    ed          Z% e
j&        d          d             Z'e
j&        d             Z(e
j&        d             Z)d Z*d Z+e
j!        ,                    de-e.e/e0f          d             Z1d Z2e
j!        ,                    deef          d             Z3e$d             Z4e$d             Z5dZ6dZ7 G d de          Z8e
j&        d              Z9e$e%e
j!        :                    d!d"          d#                                     Z;e
j!        "                    e d$          e$e%d%                                     Z<e
j!        "                    ed&          e
j!        ,                    d'd(d)*          e
j!        =                    d+          d,                                     Z>e
j!        "                     e#ed-           d.          e
j!        ,                    deef          d/                         Z?eZ@ese@se
j!        A                    e>          Z>e
j&        d0             ZBe
j&        d1             ZCe
j&        d2             ZDe
j!        ,                    d3d4d5 eEd6          fd4d7 eEd6          fd8d9d4 eEd6           eEd6          fdd5 eEd6          fdd7 eEd6          fd:d eEd6           eEd6          ff	          d;             ZFe
j!        ,                    d<d=          d>             ZGd? ZHdS )@zTests for the HTTP server.    N)	DefaultGc   )btonntob)IS_LINUXIS_MACOS
IS_WINDOWSSYS_PLATFORM)IS_UID_GID_RESOLVABLEGateway
HTTPServer)
ThreadPool)ANY_INTERFACE_IPV4ANY_INTERFACE_IPV6EPHEMERAL_PORTAF_UNIXz:UNIX domain sockets are only available under UNIX-based OSreasonz9Peercreds lookup does not work under macOS/BSD currently.)abstractfile)paramsc                 ^     dj         di t                      }|                     |          S )9Check that bound UNIX socket address is stored in server.zunix_{request.param}_sock )formatlocalsgetfixturevalue)requestnames     G/var/www/media/lib/python3.11/site-packages/cheroot/test/test_server.pyunix_sock_filer!   ,   s5     .&-9999D""4(((    c            	         t           s-t          j        d                    t                               d                    dt          t          t          j	                                        f          
                                S )z'Return an abstract UNIX socket address.z2{os} does not support an abstract socket namespace)osr"   s    cheroot-test-socket)r   pytestskipr   r
   joinr   struuiduuid4decoder   r"   r    unix_abstract_sockr,   3   sx      
%vv66	
 	
 	
 88"S   vxxr"   c               #      K   t          j                    \  } }|V  t          j        |            t          j        |           dS )zYield a unix file socket.N)tempfilemkstempr$   closeunlink)tmp_sock_fhtmp_sock_fnames     r    unix_file_sockr4   A   sM       #+"2"4"4K
H[Inr"   c                  T   t          t          t          ft                    } | j        rJ | j        j        rJ |                                  | j        sJ | j        j        sJ | j        j        D ]}|j        sJ |                                  | j        j        rJ | j        rJ dS )zBCheck that prepare() makes the server ready, and stop() clears it.	bind_addrgatewayN)	r   r   r   r   readyrequests_threadspreparestop)
httpserverthrs     r    test_prepare_makes_server_readyr@   L   s    %~6  J
 "++++''''"+  yOO"++++r"   c                     t          t          t          ft                    } |                                  t          j        | j                  }|                                 |	                    d           |
                                sJ |                                  |	                    d           |
                                rJ dS )0Check that stop() interrupts running of serve().r6   target      ?N)r   r   r   r   r<   	threadingThreadservestartr'   is_aliver=   )r>   serve_threads     r    test_stop_interrupts_serverL   c   s    %~6  J
 #:+;<<<Lc  """""OOc$$&&&&&&&r"   exc_clsc                 l    d                     t          j                              t                      t	          t
          t          ft                    t          j	                     fd}
                                 t          j        |          }|                                 |                    d           |                                sJ             _        |                    d           |                                rJ                                 u sJ dS )z0Check that assigning interrupt stops the server.zshould catch {uuid!s})r)   r6   c                      	                                   d S # $ r9} t          |           k    r                               Y d } ~ d S Y d } ~ d S d } ~ ww xY wN)rH   r(   put)erM   r>   interrupt_msgraise_marker_sentinelresult_qs    r    rK   z+test_server_interrupt.<locals>.serve_thread   s    	4 	4 	4 	41vv&&2333333333 '&&&&&	4s    A(AArC   rE   N)r   r)   r*   objectr   r   r   r   queueQueuer<   rF   rG   rI   r'   rJ   	interrupt
get_nowait)rM   rK   r>   rS   rT   rU   s   ` @@@@r    test_server_interruptr[   w   sQ    ,22
2EEM"HH%~6  J
 {}}H4 4 4 4 4 4 4 4 4 #<888Lc  """"" #7=11Jc$$&&&&&  $9999999r"   c                     t          t          t          ft                    } |                                  d }|| j        j        _        t          j	        | j
                  }|                                 |                    | j        t          rdndz             |                                rJ | j        j        rJ |                                  dS )rB   r6   c                      t                      rP   )KeyboardInterrupt)argskwargss     r    raise_keyboard_interruptzTtest_serving_is_false_and_stop_returns_after_ctrlc.<locals>.raise_keyboard_interrupt   s    !!!r"   rC      r   N)r   r   r   r   r<   _connections	_selectorselectrF   rG   rH   rI   r'   expiration_intervalIS_SLOW_ENVrJ   _servingr=   )r>   ra   rK   s      r    2test_serving_is_false_and_stop_returns_after_ctrlcri      s    %~6  J
 " " " 0HJ%,#:+;<<<L &{*A!!B   $$&&&&&&////OOr"   ip_addrc                     |                      |t          f          }|j        d         |k    sJ |j        d         t          k    sJ dS )z0Check that bound IP address is stored in server.r      N)sendr   r7   )http_serverrj   r>   s      r    test_bind_addr_inetro      sT     !!7N";<<J"g----"n444444r"   c                 J    |                      |          }|j        |k    sJ dS )r   Nrm   r7   rn   r!   r>   s      r    test_bind_addr_unixrs      s1     !!.11J>111111r"   c                 J    |                      |          }|j        |k    sJ dS )zBCheck that bound UNIX abstract socket address is stored in server.Nrq   )rn   r,   r>   s      r    test_bind_addr_unix_abstractru      s3     !!"455J#5555555r"   z/peer_creds/idsz/peer_creds/textsc                   $     e Zd Z fdZd Z xZS )_TestGatewayc                    | j         }|j        }t          |j                  }|t          k    rQ|j        |j        |j        f}|                     d	                    t          t          |                               d S |t          k    r6|                     d	                    |j        |j        f                     d S t          t           |                                           S )N|!)reqconnr   uriPEERCRED_IDS_URIpeer_pidpeer_uidpeer_gidsend_payloadr'   mapr(   PEERCRED_TEXTS_URI	peer_user
peer_groupsuperrw   respond)selfr{   r|   req_uri
peer_creds	__class__s        r    r   z_TestGateway.respond   s    hxsw--&&&t}DJchhs3
';';<<===F***chh'HIIJJJF\4((00222r"   c                     | j         }d|_        |                                 |                    t	          |                     d S )Ns   200 OK)r{   statusensure_headers_sentwriter   )r   payloadr{   s      r    r   z_TestGateway.send_payload   s@    h
!!!		$w--     r"   )__name__
__module____qualname__r   r   __classcell__)r   s   @r    rw   rw      sG        3 3 3 3 3! ! ! ! ! ! !r"   rw   c                 V    |                      |          }t          |_        d|_        |S )z3Construct a test server with ``peercreds_enabled``.T)rm   rw   r8   peercreds_enabledrr   s      r    peercreds_enabled_serverr      s-     !!.11J%J#'J r"      )rerunsreruns_delayc                    |}|j         }t          |t                    r|                                }t          j                            |d          } dj        di t                      }t          j
                    t          j                    t          j                    f}d                    t          t          |                    }t!          j                    5  t%          j        |t(          z   |           }|                                 |j        |k    sJ t%          j        |t.          z   |           }|j        dk    sJ 	 ddd           dS # 1 swxY w Y   dS )	z2Check that ``PEERCRED`` lookup works when enabled. safehttp+unix://{quoted}ry   timeouti  Nr   )r7   
isinstancebytesr+   urllibparsequoter   r   r$   getpidgetuidgetgidr'   r   r(   requests_unixsocketmonkeypatchr:   getr~   raise_for_statustextr   status_code)	http_request_timeoutr   r>   r7   quotedunix_base_uriexpected_peercredspeercreds_resppeercreds_text_resps	            r    test_peercreds_unix_sockr     s   
 *J$I)U## '$$&&	 \	33F1*1==FHH==Mbikk29;;>#c+=">">??		(	*	* 6 6!,,(
 
 
 	'')))"&88888&l..(
 
 
 #.#555556 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6s    A+EE EzDModules `grp` and `pwd` are not available under the current platformc                    |}d|_         |j        }t          |t                    r|                                }t
          j                            |d          } dj        d	i t                      }ddl
}ddl}|                    t          j                              j        |                    t          j                              j        f}d                    t)          t*          |                    }t-          j                    5  t1          j        |t4          z   |           }	|	                                 |	j        |k    sJ 	 ddd           dS # 1 swxY w Y   dS )
z6Check that ``PEERCRED`` resolution works when enabled.Tr   r   r   r   Nrz   r   r   )peercreds_resolve_enabledr7   r   r   r+   r   r   r   r   r   grppwdgetpwuidr$   r   pw_namegetgrgidr   gr_namer'   r   r(   r   r   r:   r   r   r   r   )
r   r   r>   r7   r   r   r   r   expected_textcredsr   s
             r    $test_peercreds_unix_sock_with_lookupr   "  s    *J+/J($I)U## '$$&&	 \	33F1*1==FHH==MJJJJJJRY[[!!)RY[[!!) #c+=">">??		(	*	* > >&l..(
 
 
 	,,..."'+======> > > > > > > > > > > > > > > > > >s   A EE"Ez\This regression test is for a Linux bug, and the resource module is not available on Windowsresource_limit)i   i   )r   )indirectmany_open_socketsc                    | j         j        fdt                      _        | j         _        |                     d           t          j                  dk    sJ t          fdj        D                       sJ dS )a>  Test the server does not crash with a high file-descriptor value.

    This test shouldn't cause a server crash when trying to access
    file-descriptor higher than 1024.

    The earlier implementation used to rely on ``select()`` syscall that
    doesn't support file descriptors with numbers higher than 1024.
    c                 |    j                             | j                                                    |           S rP   )filenosaddsocketfileno)r|   _old_process_connnative_process_conns    r    r   zAtest_high_number_of_file_descriptors.<locals>.native_process_conng  s9    #''(:(:(<(<===  &&&r"   /r   c              3   $   K   | ]
}|k    V  d S rP   r   ).0fnr   s     r    	<genexpr>z7test_high_number_of_file_descriptors.<locals>.<genexpr>u  s(      JJr^#JJJJJJr"   N)server_instanceprocess_connsetr   connectlenany)native_server_clientr   r   r   s    `@@r    $test_high_number_of_file_descriptorsr   J  s    6 -<I' ' ' ' ' ' #&%%8K(5   %%% "*++a//// JJJJ.A.IJJJJJJJJJJr"   SO_REUSEPORTz5socket.SO_REUSEPORT is not supported on this platformc                     t          j        |t                    d         d         }t          j         |          }|                    t           j        t           j        d           |                    |t          f           t          |                                dd         t          d          }|
                    |d          }|                                 |                                 |                                 |j        J dS )z5Check that port initialized externally can be reused.r   rl   Nr   T)r7   r8   
reuse_portr<   )r   getaddrinfor   
setsockopt
SOL_SOCKETr   bindr   getsocknamer   spyr<   r=   r0   spy_exception)rn   rj   mockerfamilysserverr   s          r    test_reuse_portr   x  s     88;A>FfALL"F$7;;;FFG^$%%%--//"1"%w4  F **VY
'
'C
NN
KKMMMGGIII$$$$$r"   c               #      K   t                                                      5  dV  ddd           dS # 1 swxY w Y   dS )z7Disable garbage collection when this fixture is in use.N)r   nogcr   r"   r    _garbage_binr     s       
				                   s   599c              #   L  K   t          j        dd          }|                    |j                  \  }}|                    |j        | j        dz  |f           	 | j        V  |                    |j        ||f           dS # |                    |j        ||f           w xY w)z7Set the resource limit two times bigger then requested.resourcez&The "resource" module is Unix-specificr   r   N)r%   importorskip	getrlimitRLIMIT_NOFILE	setrlimitparam)r   r   
soft_limit
hard_limits       r    r   r     s       "7  H &//0FGGJ

 		J'  
Mm 	81J
3KLLLLL81J
3KLLLLs   	B B#c              #     K   |                      d           g }	 t          |          D ]D}t          j                    }|                    |           |                                |k    r nE|d                                         }||k    sJ |V  |D ]}|                                 dS # |D ]}|                                 w xY w)z<Allocate a lot of file descriptors by opening dummy sockets.r   N)r   ranger   appendr   r0   )r   r   test_sockets_sockthe_highest_filenotest_sockets          r    r   r     s      N+++ L ~&& 	 	A=??D%%%{{}}.. / *"-4466!^3333     ( 	  	 K	  	 < 	  	 K	 s   A:B0 0C)
minthreads
maxthreadsinited_maxthreadsrl   infr   )rl   rl   rl   )rl   r   r   )r   r   r   c                 ^    t          d| |          }|j        | k    sJ |j        |k    sJ dS )zTest setting the number of threads in a ThreadPool.

    The ThreadPool should properly set the min+max number of the threads to use
    in the pool if those limits are valid.
    Nr   minmax)r   r  r  )r   r   r   tps       r    test_threadpool_threadrange_setr    sP    4 

 
 
B
 6Z6&&&&&&&r"   r   r   error))r   r   min=-1 must be > 0)r   r   r  )r   rl   r  )r   r   r  )r   r   min=0 must be > 0)r   r   r  )r   rl   r  )r   r   r  )rl   r   KExpected an integer or the infinity value for the `max` argument but got 0.)rl   rE   zMExpected an integer or the infinity value for the `max` argument but got 0.5.)r   r   r  )r   1zMExpected an integer or the infinity value for the `max` argument but got '1'.)r   rl   zmax=1 must be > min=2c                     t          j        t          t          f|          5  t	          d| |           ddd           dS # 1 swxY w Y   dS )zTest that a ThreadPool rejects invalid min/max values.

    The ThreadPool should raise an error with the proper message when
    initialized with an invalid min+max number of threads.
    matchNr  )r%   raises
ValueError	TypeErrorr   r	  s      r    #test_threadpool_invalid_threadranger    s    0 

I.e	<	<	< 
 
	
 	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   AA
Ac                    |                      t          dd            t          d          }|                                 t          j        t
          d          5  |                                 ddd           dS # 1 swxY w Y   dS )zTest for ThreadPool multi-start behavior.

    Tests that when calling start() on a ThreadPool multiple times raises a
    :exc:`RuntimeError`
    _spawn_workerc                 ,    t          j        d          S )NT)r9   )typesSimpleNamespace)r   s    r    <lambda>z7test_threadpool_multistart_validation.<locals>.<lambda>(  s    %'d333 r"   N)r   z%Threadpools can only be started once.r  )setattrr   rI   r%   r  RuntimeError)r   r  s     r    %test_threadpool_multistart_validationr    s     33   
4	 	 	 BHHJJJ	|+R	S	S	S  



                 s   A??BB)I__doc__r$   rW   r   r.   rF   r  r)   urllib.parser   r%   r:   r   pypytools.gc.customr   _compatr   r   r   r   r	   r
   r   r   r   r   workers.threadpoolr   testingr   r   r   rg   markskipifhasattrunix_only_sock_testnon_macos_sock_testfixturer!   r,   r4   r@   rL   parametrizeIOErrorr^   OSErrorr  r[   ri   ro   rs   ru   r~   r   rw   r   flakyr   r   usefixturesr   r   ISSUE511forkedr   r   r   floatr  r  r  r   r"   r    <module>r3     s}       				                    ) ) ) ) ) )                 B B B B B B B B B B B B ? ? ? ? ? ? ? ? ? ? + + + + + +          $* k((	"""G )    k((F )    +,,,) ) -,) 
 
 
        .' ' '( 	 !: !: !:H  8  5 5 5 2 2 2 6 6 6 % ( ! ! ! ! !7 ! ! !*    !!,,6 6 -,  6< (   
 > >   >B :   
  !    ,--K K .-  K@ '''B     % % 	 %    ( +1;+=+=,, ,(
    M M M2      8 5
 E%LL	
 
Be	
EE%LL%%,,'	
Be	
Be	
EE%LL%%,,' (' ') (' ) $
 
% $
    r"   