
    [j]                       d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlmZmZmZmZmZ ddlmZmZ dd	lmZmZ dd
lm Z  erddl!m"Z" dZ# e$e#          Z%dZ& e$e&          Z'dZ(dIdZ)dJdZ*dKdZ+e(fdLdZ,h dZ-dMd#Z.dNd%Z/dNd&Z0dNd'Z1dOdPd,Z2	 dQdRd0Z3e(fdSd3Z4 ej5        d4 ej6        d5          z   d6z             Z7 e8g d7          Z9dTd;Z:e(d-d(d-dddfdUdBZ;dVdFZ<e=dGk    rYddl>Z>	  e>j>         e;ej?        dH                              n# e$ rZ@ eAe@           Y dZ@[@ndZ@[@ww xY w ejB        d           dS dS )Wz*Tools to parse and validate a MongoDB URI.    )annotationsN)TYPE_CHECKINGAnyMappingMutableMappingOptionalSizedUnioncast)unquote_plus)_parse_ssl_options)INTERNAL_URI_OPTION_NAME_MAPSRV_SERVICE_NAMEURI_OPTIONS_DEPRECATION_MAP_CaseInsensitiveDictionaryget_validated_options)ConfigurationError
InvalidURI)_HAVE_DNSPYTHON_SrvResolver)_Address)
SSLContextz
mongodb://zmongodb+srv://ii  sstrreturnboolc                    t          t          |                     D ]1}| |         dk    r#| ||dz            }t          |          |k    r dS 2dS )zCheck for unescaped percent signs.

    :Parameters:
        - `s`: A string. `s` can have things like '%25', '%2525',
           and '%E2%85%A8' but cannot have unquoted percent like '%foo'.
    %   TF)rangelenr   )r   isubs      V/var/www/app.qaans.com/backend/venv/lib/python3.11/site-packages/pymongo/uri_parser.py_unquoted_percentr%   8   s_     3q66]]  Q43;;AAI,C C  C''tt5    userinfotuple[str, str]c                   d| v s(|                      d          dk    st          |           rt          d          |                     d          \  }}}|st          d          t	          |          t	          |          fS )al  Validates the format of user information in a MongoDB URI.
    Reserved characters that are gen-delimiters (":", "/", "?", "#", "[",
    "]", "@") as per RFC 3986 must be escaped.

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

    :Parameters:
        - `userinfo`: A string of the form <username>:<password>
    @:   zXUsername and password must be escaped according to RFC 3986, use urllib.parse.quote_plusz'The empty string is not valid username.)countr%   r   	partitionr   )r'   user_passwds       r$   parse_userinfor2   I   s     h(..--115Fx5P5P14
 
 	

 ((--OD!V DBCCC|F3333r&   entitydefault_portOptional[int]%tuple[str, Optional[Union[str, int]]]c                    |                      d          dk    rt          d          |                      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)r3   r4   r"   s      r$   parse_ipv6_literal_hostr=   b   s~     {{32\
 
 	
 	DABwwad|\))!A#;q1uww''r&   r   c                <   | }|}| d         dk    rt          | |          \  }}ns|                     d          r| |fS |                     d          dk    rA|                     d          dk    rt	          d          |                    dd          \  }}t          |t                    r[|                                r&t          |          dk    st          |          dk    rt	          d	|          t          |          }|
                                |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+   r9   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)r3   r4   hostports       r$   
parse_hostrI   z   s'    D&2DayC,V\BB
dd		!	! 
(|##	S		R		<<q  1   ZZQ''
d$ ||~~ 	WTU!2!2c$ii1nnUTUUVVV4yy ::<<r&   >   tlsallowinvalidhostnamestlsallowinvalidcertificatestlsdisableocspendpointcheckoptsdelimOptional[str]r   c                   t                      }|                     |          D ]}|                    d          \  }}|                                dk    r*|                    |g                               |           \||v rt          j        d| dd           |                                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'.r:   
stacklevelauthmechanismproperties)r   rB   rF   
setdefaultappendwarningswarnr   )rM   rN   optionsurioptkeyvaluevals          r$   _parse_optionsr_      s    
 )**G**U##  \\#&&
U99;;...sB''..u5555g~~>s>>>1MMMMyy{{777"5))GCLLNr&   rZ   c                   |                      d          }|Jt          D ]B}|| v r<d}t          ||                     d          |                     |          fz            C|                      d          }|6d| v r)d}t          |d|                     d          fz            |du rd| d<   |                      d          }|1dD ].}|                      |          du rd	}t          ||fz            /d
| v rd| v r~dd} ||                      d
                     ||                      d                    k    r<d}t          ||                     d
          |                     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.
    tlsinsecureNz9URI options %s and %s cannot be specified simultaneously.rK   rL   T
tlscrlfile)ra   rK   rL   zDURI option %s=True cannot be specified when CRL checking is enabled.ssltlsr^   r   r   c                H    | dv r| dk    S t          | t                    r| S | S )N)truefalserf   )rC   r   )r^   s    r$   truth_valuez-_handle_security_options.<locals>.truth_value   s4    '''f}$#t$$ 
Jr&   z=Can not specify conflicting values for URI options %s and %s.)r^   r   r   r   )get_IMPLICIT_TLSINSECURE_OPTSr   	cased_key)rZ   ra   opterr_msgtlsallowinvalidcertsrb   rh   s          r$   _handle_security_optionsro      s    ++m,,K- 	 	Cg~~U w00??ARARSVAWAWXX    #;;'DEE'(G33QG0'2C2CDa2b2bcd    4''59G12 \**J` 	3 	3C{{34''` C6!1222 ( EW,,	 	 	 	 ;w{{5))**kk'++e:L:L.M.MMMUGW(9(9%(@(@'BSBSTYBZBZ'[[\\\Nr&   c                   t          |           D ]}|t          v rt          |         \  }}|dk    r|}|| v r_d}t          j        ||                     |          |                     |          fz  t
          d           |                     |           d}t          j        ||                     |          |fz  t
          d           |dk    r6d}t          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:   rS   z,Option '%s' is deprecated, use '%s' instead.removedzOption '%s' is deprecated. %s.)listr   rX   rY   rk   DeprecationWarningpop)rZ   optnamemodemessage
newoptnamewarn_msgs         r$   _handle_option_deprecationsr{      sK    ==  1117@MD'y  $
((QHM G$5$5g$>$>@Q@QR\@]@]#^^*#$   
 KK(((I 1 1' : :JGG&     
 ""; 1 1' : :GDD&     Nr&   c                    |                      d          }|t          D ]}|| |<   t          |           D ]1}t          j         |d          }||                     |          | |<   2| S )zNormalizes option names in the options dictionary by converting them to
    their internally-used names.

    :Parameters:
        - `options`: Instance of _CaseInsensitiveDictionary containing
          MongoDB URI options.
    ra   N)ri   rj   rs   r   ru   )rZ   ra   rl   rv   intnames        r$   _normalize_optionsr~     s~     ++m,,K- 	' 	'C&GCLL== 4 4.27DAA&{{733GGNr&   FMapping[str, Any]rY   MutableMapping[str, Any]c                "    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   )rM   rY   s     r$   validate_optionsr   4  s     !t,,,r&   Tvalidate	normalizec                   |                      d          }|                      d          }	 |dk    r|dk    rt          d          |dk    rt          | d          }nH|dk    rt          | d          }n1|                      d          dk    rt          | d          }nt          n# t          $ r t          d          dw xY wt	          |          }t          |          }|rt          |          }|rKt          t          t          ||                    }|
                    d	          d
k    rt          d          |S )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.rQ   r9   Nz(MongoDB URI options are key=value pairs.
authsource z1the authSource database cannot be an empty string)r;   r   r_   r<   ro   r{   r~   r   r   r   ri   )rM   r   rY   r   and_idxsemi_idxrZ   s          r$   split_optionsr   D  sY    iinnGyy~~HOa<<HMMMNNN\\$T3//GG]]$T3//GGYYs^^r!!$T400GG O O OCDD$NO 'w//G)'22G .$W-- R13CGT3R3RSS;;|$$**PQQQNs   A:B' 'Chostslist[_Address]c                    g }|                      d          D ]O}|st          d          |}|                    d          rd}|                    t	          ||                     P|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)rB   r   rA   rW   rI   )r   r4   nodesr3   rH   s        r$   split_hostsr   r  s~     E++c"" / / 	R$%PQQQ??7## 	DZ--....Lr&   r?   z/ "$r8   )r   
authSource
replicaset
replicaSetloadbalancedloadBalancedr   r	   Nonec                v   t          |           dk    r$|                    d          rt          d          |                    d          rjt          |           dk    rt          d          |                    d          rt          d          |                    d          rt          d          d S d S )	Nr,   directconnectionz8Cannot specify multiple hosts with directConnection=truer   z4Cannot specify multiple hosts with loadBalanced=truez;Cannot specify directConnection=true with loadBalanced=truer   z0Cannot specify replicaSet with loadBalanced=true)r!   ri   r   )r   rZ   s     r$   _check_optionsr     s    
5zzA~~'++&899~ ![\\\{{>"" Yu::>>$%[\\\;;)** 	d$%bccc;;|$$ 	Y$%WXXXY Y
	Y 	Yr&   uriconnect_timeoutOptional[float]srv_service_namesrv_max_hostsdict[str, Any]c                V   |                      t                    rd}| t          d         }	ns|                      t                    r9t          s t
          j        pd}
t          d|
z            d}| t          d         }	n t          dt           dt           d          |	st          d	          d}d}d}d}t                      }|	                    d
          \  }}}|s|}d}|r|                    d          \  }}}n|                    d          \  }}}|rYt          |          }d|v r|                    dd          \  }}t                              |          rt          d|z            nd}|r%|                    t#          ||||                     ||                    dt&                    }d|v r,|                    d          \  }}}t+          |          \  }}n|}d
|v rt          d|z            t          |          }d}|p|                    d          }|r|                    d          rt          dt           d          t-          |d          }t/          |          dk    rt          t           d          |d         \  }}|t          t           d          |p|                    d          }t1          ||||          }|                                }|                                }|r[t#          ||||          }t7          |          t8          z
  rt          d          |                                D ]\  }}||vr|||<   |                    d          r|rt          d          |                    d          r|rt          d           d!|vrd"|vr	|rdnd#|d!<   nJ|s$|                    d          t          d$          |s|rt          d%          t-          ||          }t=          ||           |||||||d&S )'aw  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.
        - `srv_service_name` (optional): A custom SRV service name

    .. versionchanged:: 4.6
       The delimiting slash (``/``) between hosts and connection options is now optional.
       For example, "mongodb://example.com?tls=true" is now a valid URI.

    .. versionchanged:: 4.0
       To better follow RFC 3986, unquoted percent signs ("%") are no longer
       supported.

    .. 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.
    FNpythonzThe "dnspython" module must be installed to use mongodb+srv:// URIs. To fix this error install pymongo again:
 %s -m pip install pymongo>=4.3Tz)Invalid URI scheme: URI must begin with 'z' or ''z)Must provide at least one hostname or IP./r   ?.r,   zBad database name "%s"srvServiceNamer*   z;Any '/' in a unix domain socket must be percent-encoded: %ssrvMaxHostsdirectConnectionz*Cannot specify directConnection=true with z URIs)r4   z. URIs must include one, and only one, hostnamer   z$ URIs must not include a port numberconnectTimeoutMSzDOnly authSource, replicaSet, and loadBalanced are supported from DNSr   z0You cannot specify loadBalanced with srvMaxHostsr   z.You cannot specify replicaSet with srvMaxHostsrd   rc   rf   zDThe srvServiceName option is only allowed with 'mongodb+srv://' URIszAThe srvMaxHosts option is only allowed with 'mongodb+srv://' URIs)nodelistusernamepassworddatabase
collectionrZ   fqdn)
startswithSCHEME
SCHEME_LEN
SRV_SCHEMEr   sys
executabler   SRV_SCHEME_LENr   r   r.   r   rB   _BAD_DB_CHARSsearchupdater   ri   r   
rpartitionr2   r   r!   r   	get_hostsget_optionsset_ALLOWED_TXT_OPTSitemsr   )r   r4   r   rY   r   r   r   r   is_srvscheme_freepython_pathr/   r1   dbaser   rZ   	host_partr0   	path_partrM   r'   r   r   r   rH   dns_resolverdns_optionsparsed_dns_optionsrl   r^   s                                 r$   	parse_urir     s   @ ~~f b*++&	
	#	# b 	.4HK$1 5@A   .//*`V``S]```aaa FDEEEDFEJ(**G)33C88Iq) 		 6",,S11q$$ '0055	1d U##%<< %C 3 3E:&& 	?5=>>>	?  G}T8T9EEFFF";;'79IJJ
i&11#66!U%h//ff
e||VYbbcccED!?W[[%?%?M (>;;)** 	e$%cR\%c%c%cdddE555u::??
ZZZ[[[1X
d
PPPQQQ *LW[[9K-L-L#D/;K][[&&(("..00 	'!.{HdI!V!V%&&):: (Z   /4466 ' 'Sg%%#&GCL;;~&& 	Q= 	QOPPP;;|$$ 	O 	OMNNNE$8$8%-9TT6GEN 	>$455A R
 
 	
  > > O
 
 	
 E===5'"""    r&   kms_tls_optionsOptional[Mapping[str, Any]]dict[str, SSLContext]c                P   | si S t          | t                    st          d          i }|                                 D ]\  }}t          |t                    st          d| d          |                    dd           t          |          }t          |          }t          |          }t          t
          t          |                    }t          |          \  }}|t          d          |rt          d          d	D ]}||v rt          d
|           |||<   |S )z!Parse KMS TLS connection options.zkms_tls_options must be a dictzkms_tls_options["z"] must be a dictrd   TNz!TLS is required for KMS providerszInsecure TLS options prohibited)tlsInsecuretlsAllowInvalidCertificatestlsAllowInvalidHostnames$tlsDisableCertificateRevocationCheckz!Insecure TLS options prohibited: )rC   dict	TypeErrorr   rV   r   ro   r~   r   r   r   r   )r   contextsproviderrZ   rM   ssl_contextallow_invalid_hostnamesns           r$   _parse_kms_tls_optionsr   W  sd    	ot,, :8999H,2244 - -''4(( 	MKKKKLLL5$''')'22'--!$''.0@0F0FGG/A$/G/G,,$%HIII" 	H$%FGGG
 	- 	-A Dyy()PQ)P)PQQQ!,HX	- Or&   __main__r,   )r   r   r   r   )r'   r   r   r(   )r3   r   r4   r5   r   r6   )r3   r   r4   r5   r   r   )rM   r   rN   rO   r   r   )rZ   r   r   r   )F)rM   r   rY   r   r   r   )TFT)
rM   r   r   r   rY   r   r   r   r   r   )r   r   r4   r5   r   r   )r   r	   rZ   r   r   r   )r   r   r4   r5   r   r   rY   r   r   r   r   r   r   rO   r   r5   r   r   )r   r   r   r   )C__doc__
__future__r   rer   rX   typingr   r   r   r   r   r	   r
   r   urllib.parser   pymongo.client_optionsr   pymongo.commonr   r   r   r   r   pymongo.errorsr   r   pymongo.srv_resolverr   r   pymongo.typingsr   pymongo.pyopenssl_contextr   r   r!   r   r   r   DEFAULT_PORTr%   r2   r=   rI   rj   r_   ro   r{   r~   r   r   r   compileescaper   	frozensetr   r   r   r   __name__pprintargvexcprintexit r&   r$   <module>r      s    1 0 " " " " " " 				 



 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 & % % % % % 5 5 5 5 5 5              : 9 9 9 9 9 9 9 > > > > > > > > $ $ $ $ $ $ 5444444	S[[

Z   "4 4 4 42( ( ( (0 ;G $ $ $ $ $P      ,3 3 3 3l% % % %P   .- - - - -" MQ+ + + + +\ ;G     6 
37!3!33c9::I\\\  
Y Y Y Y  #/'+&*#'r r r r rj   B zMMMii,,----   c







CHQKKKKK s   $D) )E.D>>E