
    hM                        d Z ddlZddlZddlmZmZ erddlmZ nddlmZ ddl	m
Z
mZmZmZ ddlmZmZ ddlmZmZ dZ ee      Zd	Z ee      Zd
Zd Zd ZefdZh dZeD  ch c]  } |  c} eD  ch c]  } e|    	 c} z  Zd Zd Z d Z!d Z"ddZ#d dZ$efdZ% ejL                  d ejN                  d      z   dz         Z( e)g d      Z*eddddfdZ+e,dk(  rAddl-Z-ddl.Z.	  e-jZ                   e+e.j^                  d                 e.jd                  d       yyc c} w c c} w # e$ rZ0 e1e0       Y dZ0[00dZ0[0ww xY w)!z*Tools to parse and validate a MongoDB URI.    N)string_typePY3)unquote_plus)get_validated_optionsINTERNAL_URI_OPTION_NAME_MAPURI_OPTIONS_DEPRECATION_MAP_CaseInsensitiveDictionary)ConfigurationError
InvalidURI)_HAVE_DNSPYTHON_SrvResolverz
mongodb://zmongodb+srv://ii  c                     d| v s| j                  d      dkD  rt        rd}nd}t        d|z        | j                  d      \  }}}|st        d      t	        |      t	        |      fS )a  Validates the format of user information in a MongoDB URI.
    Reserved characters like ':', '/', '+' and '@' must be escaped
    following RFC 3986.

    Returns a 2-tuple containing the unescaped username followed
    by the unescaped password.

    :Paramaters:
        - `userinfo`: A string of the form <username>:<password>

    .. versionchanged:: 2.2
       Now uses `urllib.unquote_plus` so `+` characters must be escaped.
    @:   zurllib.parse.quote_pluszurllib.quote_pluszFUsername and password must be escaped according to RFC 3986, use %s().z'The empty string is not valid username.)countr   r   	partitionr   )userinfoquote_fnuser_passwds        U/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/uri_parser.pyparse_userinfor   )   s|     h(..-10H*H /19: ; 	;((-OD!VBCC|F333    c                     | j                  d      dk(  rt        d      | j                  d      }|dk(  r| dd |fS | d| | |dz   d fS )a  Validates an IPv6 literal host:port string.

    Returns a 2-tuple of IPv6 literal followed by port where
    port is default_port if it wasn't specified in entity.

    :Parameters:
        - `entity`: A string that represents an IPv6 literal enclosed
                    in braces (e.g. '[::1]' or '[::1]:27017').
        - `default_port`: The port number to use when one wasn't
                          specified in entity.
    ]zNan IPv6 address literal must be enclosed in '[' and ']' according to RFC 2732.z]:r      N)find
ValueError)entitydefault_portis      r   parse_ipv6_literal_hostr%   E   sj     {{32 ( ) 	) 	DABwa|\))!Q<A''r   c                    | }|}| d   dk(  rt        | |      \  }}n]| j                  d      r| |fS | j                  d      dk7  r4| j                  d      dkD  rt	        d      |j                  dd      \  }}t        |t              rE|j                         rt        |      dkD  st        |      dk  rt	        d	|      t        |      }|j                         |fS )
a  Validates a host string

    Returns a 2-tuple of host followed by port where port is default_port
    if it wasn't specified in the string.

    :Parameters:
        - `entity`: A host or host:port string where host could be a
                    hostname or IP address.
        - `default_port`: The port number to use when one wasn't
                          specified in entity.
    r   [.sockr   r   r   zReserved characters such as ':' must be escaped according RFC 2396. An IPv6 address literal must be enclosed in '[' and ']' according to RFC 2732.i  z-Port must be an integer between 0 and 65535: )r%   endswithr    r   r!   split
isinstancer   isdigitintlower)r"   r#   hostports       r   
parse_hostr1   [   s     DDayC,V\B
d		!|##	S	R	<<q  > ? ? ZZQ'
d$$||~TU!2c$i1n $' ( (4y ::<r   >   tlsallowinvalidhostnamestlsallowinvalidcertificatestlsdisableocspendpointcheckc                 ^   t               }| j                  |      D ]  }|j                  d      \  }}|j                         dk(  r"|j                  |g       j	                  |       L||v rt        j                  d|d       |j                         dk(  r|}nt        |      }|||<    |S )zHelper method for split_options which creates the options dict.
    Also handles the creation of a list for the URI tag_sets/
    readpreferencetags portion, and the use of a unicode options string.=readpreferencetagszDuplicate URI option 'z'.authmechanismproperties)r	   r*   r.   
setdefaultappendwarningswarnr   )optsdelimoptionsurioptkeyvaluevals          r   _parse_optionsrD      s     )*G**U# \\#&
U99;..sB'..u5g~cCDyy{77"5)GCL Nr   c                 d     j                  d      }|?t        D ]6  }| v sd}t        | j                  d       j                  |      fz          fd} |d      }|.d v r!d}t        |d j                  d      fz        |du rd d<    |d      }|+dD ]&  } j                  |      du sd	}t        ||fz         d
 v rfd v rbd } | j                  d
             | j                  d            k7  r0d}t        | j                  d
       j                  d      fz         S )zRaise appropriate errors when conflicting TLS options are present in
    the options dictionary.

    :Parameters:
        - `options`: Instance of _CaseInsensitiveDictionary containing
          MongoDB URI options.
    tlsinsecurez9URI options %s and %s cannot be specified simultaneously.c                 Z    j                  |       xs j                  t        |          S )N)getr   )optr?   s    r   _getoptz)_handle_security_options.<locals>._getopt   s,    C  ?8=>	@r   r3   r4   T
tlscrlfile)rF   r3   r4   zDURI option %s=True cannot be specified when CRL checking is enabled.ssltlsc                 <    | dv r| dk(  S t        | t              r| S | S )N)truefalserO   )r+   bool)rC   s    r   truth_valuez-_handle_security_options.<locals>.truth_value   s)    ''f}$#t$
Jr   z=Can not specify conflicting values for URI options %s and %s.)rH   _TLSINSECURE_EXCLUDE_OPTSr   	cased_key)r?   rF   rI   err_msgrJ   tlsallowinvalidcertsrK   rR   s   `       r   _handle_security_optionsrW      s    ++m,K, 	OCg~- %%m4g6G6G6L,N "N O O		O@
 ##@A'(G3)GW-w/@/@103(4 4 5 5  4'59G12 &J3 	3C{{34'6 C6!122	3 EW,	 w{{5)*k'++e:L.MM GW!!%('*;*;E*B(D D E E Nr   c                    t        |       D ]  }|t        v st        |   \  }}|dk(  r|}|| v rSd}t        j                  || j	                  |      | j	                  |      fz  t
        d       | j                  |       vd}t        j                  || j	                  |      |fz  t
        d       |dk(  sd}t        j                  || j	                  |      |fz  t
        d        | S )aM  Issue appropriate warnings when deprecated options are present in the
    options dictionary. Removes deprecated option key, value pairs if the
    options dictionary is found to also have the renamed option.

    :Parameters:
        - `options`: Instance of _CaseInsensitiveDictionary containing
          MongoDB URI options.
    renamedz0Deprecated option '%s' ignored in favor of '%s'.r   )
stacklevelz,Option '%s' is deprecated, use '%s' instead.removedzOption '%s' is deprecated. %s.)listr   r;   r<   rT   DeprecationWarningpop)r?   optnamemodemessage
newoptnamewarn_msgs         r   _handle_option_deprecationsrd      s    = 6117@MD'y $
(!(HMM G$5$5g$>$+$5$5j$A$C C*q: KK(I 1 1' :JGG&16 "; 1 1' :GDD&16)60 Nr   c                     | j                  d      }|t        D ]  }t        |   }| | |<    t        |       D ]/  }t        j                   |d      }|| j	                  |      | |<   1 | S )a  Normalizes option names in the options dictionary by converting them to
    their internally-used names. Also handles use of the tlsInsecure option.

    :Parameters:
        - `options`: Instance of _CaseInsensitiveDictionary containing
          MongoDB URI options.
    rF   N)rH   _IMPLICIT_TLSINSECURE_OPTSr   r\   r^   )r?   rF   rI   intnamer_   s        r   _normalize_optionsrh     s     ++m,K- 	/C237G#.GG	/
 = 4.227DA&{{73GG4
 Nr   Fc                     t        | |      S )a  Validates and normalizes options passed in a MongoDB URI.

    Returns a new dictionary of validated and normalized options. If warn is
    False then errors will be thrown for invalid options, otherwise they will
    be ignored and a warning will be issued.

    :Parameters:
        - `opts`: A dict of MongoDB URI options.
        - `warn` (optional): If ``True`` then warnings will be logged and
          invalid options will be ignored. Otherwise invalid options will
          cause errors.
    )r   )r=   r<   s     r   validate_optionsrj     s     !t,,r   Tc                    | j                  d      }| j                  d      }	 |dk\  r|dk\  rt        d      |dk\  rt        | d      }n9|dk\  rt        | d      }n'| j                  d      dk7  rt        | d      }nt        t	        |      }t        |      }|r+t        ||      }|j                  d	      d
k(  rt        d      |rt        |      }|S # t        $ r t        d      w xY w)a  Takes the options portion of a MongoDB URI, validates each option
    and returns the options in a dictionary.

    :Parameters:
        - `opt`: A string representing MongoDB URI options.
        - `validate`: If ``True`` (the default), validate and normalize all
          options.
        - `warn`: If ``False`` (the default), suppress all warnings raised
          during validation of options.
        - `normalize`: If ``True`` (the default), renames all options to their
          internally-used names.
    &;r   z.Can not mix '&' and ';' for option separators.r6   r   Nz(MongoDB URI options are key=value pairs.
authsource z1the authSource database cannot be an empty string)	r    r   rD   r!   rW   rd   rj   rH   rh   )r=   validater<   	normalizeand_idxsemi_idxr?   s          r   split_optionsrt   )  s     iinGyy~HEa<HMMNN\$T3/G]$T3/GYYs^r!$T40G 'w/G)'2G"7D1;;|$*CE E $W-N!  ECDDEs   A C C+c                     g }| j                  d      D ]?  }|st        d      |}|j                  d      rd}|j                  t	        ||             A |S )a  Takes a string of the form host1[:port],host2[:port]... and
    splits it into (host, port) tuples. If [:port] isn't present the
    default_port is used.

    Returns a set of 2-tuples containing the host name (or IP) followed by
    port number.

    :Parameters:
        - `hosts`: A string of the form host1[:port],host2[:port],...
        - `default_port`: The port number to use when one wasn't specified
          for a host.
    ,z)Empty host (or extra comma in host list).r(   N)r*   r
   r)   r:   r1   )hostsr#   nodesr"   r0   s        r   split_hostsry   V  si     E++c" /$ &F G G??7#DZ-./ Lr   r'   z/ "$r   )rn   
authSource
replicaset
replicaSetc                    | j                  t              rd}| t        d }nL| j                  t              rt        st        d      d}| t        d }nt        dt        dt        d      |st        d      d}d}	d}
d}t               }|j                  d	      \  }}}|s|}d
}|sd|v rt        d      |r|j                  d      \  }
}}|
rGt        |
      }
d|
v r|
j                  dd      \  }
}t        j                  |
      rt        d|
z        d}
|r|j                  t        ||||             d|v r$|j!                  d      \  }}}t#        |      \  }}	n|}d	|v rt        d|z        t        |      }d}|r|j%                  d      rt        dt        d      t'        |d      }t)        |      dk7  rt        t        d      |d   \  }}|t        t        d      |xs |j%                  d      }t+        ||      }|j-                         }|j/                         }|rMt        ||||      }t1        |      t2        z
  rt        d      |j5                         D ]  \  }}||vs|||<    d|vrA|rdnd|d<   n7t'        ||      }t)        |      dkD  r|j%                  d      rt        d      |||	|
|||dS ) a  Parse and validate a MongoDB URI.

    Returns a dict of the form::

        {
            'nodelist': <list of (host, port) tuples>,
            'username': <username> or None,
            'password': <password> or None,
            'database': <database name> or None,
            'collection': <collection name> or None,
            'options': <dict of MongoDB URI options>,
            'fqdn': <fqdn of the MongoDB+SRV URI> or None
        }

    If the URI scheme is "mongodb+srv://" DNS SRV and TXT lookups will be done
    to build nodelist and options.

    :Parameters:
        - `uri`: The MongoDB URI to parse.
        - `default_port`: The port number to use when one wasn't specified
          for a host in the URI.
        - `validate` (optional): If ``True`` (the default), validate and
          normalize all options. Default: ``True``.
        - `warn` (optional): When validating, if ``True`` then will warn
          the user then ignore any invalid options or values. If ``False``,
          validation will error when options are unsupported or values are
          invalid. Default: ``False``.
        - `normalize` (optional): If ``True``, convert names of URI options
          to their internally-used names. Default: ``True``.
        - `connect_timeout` (optional): The maximum time in milliseconds to
          wait for a response from the DNS server.

    .. versionchanged:: 3.9
        Added the ``normalize`` parameter.

    .. versionchanged:: 3.6
        Added support for mongodb+srv:// URIs.

    .. versionchanged:: 3.5
        Return the original value of the ``readPreference`` MongoDB URI option
        instead of the validated read preference mode.

    .. versionchanged:: 3.1
        ``warn`` added so invalid options can be ignored.
    FNzCThe "dnspython" module must be installed to use mongodb+srv:// URIsTz)Invalid URI scheme: URI must begin with 'z' or ''z)Must provide at least one hostname or IP./ro   ?z8A '/' is required between the host list and any options..r   zBad database name "%s"r   z;Any '/' in a unix domain socket must be percent-encoded: %sdirectConnectionz*Cannot specify directConnection=true with z URIs)r#   z. URIs must include one, and only one, hostnamer   z$ URIs must not include a port numberconnectTimeoutMS)connect_timeoutz5Only authSource and replicaSet are supported from DNSrL   rO   z8Cannot specify multiple hosts with directConnection=true)nodelistusernamepassworddatabase
collectionr?   fqdn)
startswithSCHEME
SCHEME_LEN
SRV_SCHEMEr   r
   SRV_SCHEME_LENr   r	   r   r   r*   _BAD_DB_CHARSsearchupdatert   
rpartitionr   rH   ry   lenr   	get_hostsget_optionsset_ALLOWED_TXT_OPTSitems)urir#   rp   r<   rq   r   is_srvscheme_freer   r   dbaser   r?   	host_partr   	path_partr=   r   rw   r   rx   r0   dns_resolverdns_optionsparsed_dns_optionsrI   rC   s                              r   	parse_urir   x  sQ   ^ ~~f*+&	
	#$ &L M M./*6<jJ K 	K DEEDFEJ(*G)33C8Iq)			) : ; 	; ",,S1q$ 'Ee|$)KKQ$7!z##E* !9E!ABBENN=xyIJ
i&11#6!U%h/f
e| 02;< = 	= ED;;)*$'*+ + E5u:?,69: : 1X
d<FHJ J
 *LW[[9K-L#D/J&&("..0!.XtY"8%&)::(KM M.446 'Sg%#&GCL' %-T6GENE=u:>gkk*<=$JL L   r   __main__r   )F)TFT)3__doc__rer;   bson.py3compatr   r   urllib.parser   urllibpymongo.commonr   r   r   r	   pymongo.errorsr
   r   pymongo.srv_resolverr   r   r   r   r   r   r   DEFAULT_PORTr   r%   r1   rf   rS   rD   rW   rd   rh   rj   rt   ry   compileescaper   	frozensetr   r   __name__pprintsysargvexcprintexit)ks   0r   <module>r      s{    1 	  +)#= = : > 
[

Z48(, %1 #N$  //q/2LMQ	%a	(M	N 
*9x!H.- *Z %1 8 

37!33c9:<>  !-t%dWt zi,- CHHQK S 	0MZ  c

s$   '	D"6D')%D, ,E1D>>E