o Sb [@sdZddlZddlZddlZddlmZmZmZmZm Z m Z m Z m Z ddl mZddlmZddlmZmZmZmZmZddlmZmZddlmZmZdd lmZd Ze eZ!d Z"e e"Z#d Z$d dZ%de&de e&e&ffddZ'de&de e(de e&e e e&e(fffddZ)e$fde&de e(defddZ*hdZ+ddZ,ddZ-ddZ.d d!Z/d?d#ee&efd$e0de e&effd%d&Z1 'd@d#e&d(e0d$e0d)e0de e&eff d*d+Z2e$fd,e&de e(deefd-d.Z3e4d/e5d0d1Z6e7gd2Z8d3d4Z9e$d'd"d'dddfd5e&de e(d(e0d$e0d)e0d6e e:d7e e&d8e e(dee&effd9d:Z;d;d<ZZ>z e>>e;ej?d>WneyVZ@z eAe@WYdZ@[@ndZ@[@wweBddSdS)Az*Tools to parse and validate a MongoDB URI.N)AnyDictListMappingMutableMappingOptionalTupleUnion) unquote_plus)_parse_ssl_options)INTERNAL_URI_OPTION_NAME_MAPSRV_SERVICE_NAMEURI_OPTIONS_DEPRECATION_MAP_CaseInsensitiveDictionaryget_validated_options)ConfigurationError InvalidURI)_HAVE_DNSPYTHON _SrvResolver)_Addressz mongodb://zmongodb+srv://iicCsDtt|D]}||dkr|||d}t||krdSqdS)zCheck for unescaped percent signs. :Paramaters: - `s`: A string. `s` can have things like '%25', '%2525', and '%E2%85%A8' but cannot have unquoted percent like '%foo'. %TF)rangelenr )sisubr9/tmp/pip-target-onvjaxws/lib/python/pymongo/uri_parser.py_unquoted_percent*s  ruserinforeturncCsRd|vs|ddkst|rtd|d\}}}|s!tdt|t|fS)alValidates 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. :Paramaters: - `userinfo`: A string of the form : @:zXUsername and password must be escaped according to RFC 3986, use urllib.parse.quote_plusz'The empty string is not valid username.)countrr partitionr )r user_passwdrrrparse_userinfo;s r*entity default_portcCsT|ddkr td|d}|dkr|dd|fS|d|||ddfS)aValidates 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)r+r,rrrrparse_ipv6_literal_hostTs r2cCs|}|}|ddkrt||\}}n#|dr||fS|ddkr5|ddkr-td|dd\}}t|trU|rJt |dksJt |dkrQtd |ft |}| |fS) aValidates 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.iz/Port must be an integer between 0 and 65535: %r) r2endswithr0r%r1split isinstancestrisdigitintlower)r+r,hostportrrr parse_hostls"      r>>ZtlsallowinvalidhostnamestlsallowinvalidcertificatestlsdisableocspendpointcheckcCst}||D]6}|d\}}|dkr!||g|q||vr-td|f|dkr6|}nt|}|||<q|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.=ZreadpreferencetagszDuplicate URI option '%s'.Zauthmechanismproperties)rr6r; setdefaultappendwarningswarnr )optsdelimoptionsZurioptkeyvaluevalrrr_parse_optionss   rLcCs|d}|dur"tD]}||vr!d}t||d||fq |d}|durDd|vr.truth_valuez=Can not specify conflicting values for URI options %s and %s.)get_IMPLICIT_TLSINSECURE_OPTSr cased_key)rHrMopterr_msgZtlsallowinvalidcertsrNrTrrr_handle_security_optionssB    rZcCst|D]W}|tvr[t|\}}|dkrF|}||vr4d}tj|||||ftdd||qd}tj||||ftddq|dkr[d}tj||||ftddq|S)aMIssue 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. Zrenamedz0Deprecated option '%s' ignored in favor of '%s'.r/) stacklevelz,Option '%s' is deprecated, use '%s' instead.removedzOption '%s' is deprecated. %s.)listrrDrErWDeprecationWarningpop)rHoptnamemodemessageZ newoptnameZwarn_msgrrr_handle_option_deprecationss:   rccCsX|d}|durtD]}|||<q t|D]}t|d}|dur)||||<q|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. rMN)rUrVr]r r_)rHrMrXr`Zintnamerrr_normalize_optionss    rdFrFrEcCs t||S)aValidates 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)rFrErrrvalidate_options%s reTvalidate normalizecCs|d}|d}z1|dkr|dkrtd|dkr!t|d}n|dkr+t|d}n|ddkr8t|d}ntWn tyFtdwt|}t|}|rUt|}|rgt||}|d d krgtd |S) aTakes 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. &;rz.Can not mix '&' and ';' for option separators.rAr.Nz(MongoDB URI options are key=value pairs. authsourcez1the authSource database cannot be an empty string) r0rrLr1rZrcrdrerU)rFrfrErgZand_idxZsemi_idxrHrrr split_options5s2       rlhostscCsFg}|dD]}|std|}|drd}|t||q|S)aTakes 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).r4N)r6rr5rCr>)rmr,nodesr+r=rrr split_hostscs  rpr3z/ "$r-)rjZ authSource replicaset replicaSet loadbalanced loadBalancedcCsht|dkr|drtd|dr0t|dkrtd|dr'td|dr2tddSdS) Nr$Zdirectconnectionz8Cannot specify multiple hosts with directConnection=truersz4Cannot specify multiple hosts with loadBalanced=truez;Cannot specify directConnection=true with loadBalanced=truerqz0Cannot specify replicaSet with loadBalanced=true)rrUr)rorHrrr_check_optionss    ruuriconnect_timeoutsrv_service_name srv_max_hostscCs&|trd}|td} n#|tr)ts tjpd} td| d}|td} nt dttf| s7t dd} d} d} d}t }| d\}}}|sP|}d }|sZd |vrZt d |r| d \} }}| rt | } d | vrv| d d \} }t| rt d| nd} |r|t|||||dur|dt}d|vr|d\}}}t|\} } n|}d|vrt d|t |}d}|p|d}|re|drtdtft|dd}t|d krt dtf|d\}}|durt dtf|p|d}t||||}|}|}|r7t||||}t|tr$td|D]\}}||vr5|||<q(|drD|rDt d|drQ|rQt dd|vrdd |vrd|r`dnd!|d<n|st|ddurttd"|s~|r~td#t||d}t|||| | | |||d$S)%aParse and validate a MongoDB URI. Returns a dict of the form:: { 'nodelist': , 'username': or None, 'password': or None, 'database': or None, 'collection': or None, 'options': , 'fqdn': 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.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. FNpythonzThe "dnspython" module must be installed to use mongodb+srv:// URIs. To fix this error install pymongo with the srv extra: %s -m pip install "pymongo[srv]"Tz4Invalid URI scheme: URI must begin with '%s' or '%s'z)Must provide at least one hostname or IP./rk?z8A '/' is required between the host list and any options..r$zBad database name "%s"ZsrvServiceNamer"z;Any '/' in a unix domain socket must be percent-encoded: %sZ srvMaxHostsZdirectConnectionz1Cannot specify directConnection=true with %s URIs)r,z0%s URIs must include one, and only one, hostnamerz&%s URIs must not include a port numberZconnectTimeoutMSzDOnly authSource, replicaSet, and loadBalanced are supported from DNSrtz0You cannot specify loadBalanced with srvMaxHostsrrz.You cannot specify replicaSet with srvMaxHostsrPrOrQzDThe srvServiceName option is only allowed with 'mongodb+srv://' URIszAThe srvMaxHosts option is only allowed with 'mongodb+srv://' URIs)ZnodelistusernamepasswordZdatabase collectionrHfqdn) startswithSCHEME SCHEME_LEN SRV_SCHEMErsys executablerSRV_SCHEME_LENrrr&r r6 _BAD_DB_CHARSsearchupdaterlrUr rpartitionr*rprrZ get_hostsZ get_optionsset_ALLOWED_TXT_OPTSitemsru)rvr,rfrErgrwrxryZis_srvZ scheme_freeZ python_pathr'r)ZdbaserrHZ host_partr(Z path_partrFr rmrror=Z dns_resolverZ dns_optionsZparsed_dns_optionsrXrKrrr parse_uris <                rcCs|siSt|ts tdi}|D]O\}}t|ts$td|d|ddt|}t|}t|}t|}t |\}}|durHt d|rNt dd D]}||vr]t d ||||<qPq|S) z!Parse KMS TLS connection options.zkms_tls_options must be a dictzkms_tls_options["z"] must be a dictrPTNz!TLS is required for KMS providerszInsecure TLS options prohibited)Z tlsInsecureZtlsAllowInvalidCertificatesZtlsAllowInvalidHostnamesZtlsDisableOCSPEndpointCheckZ$tlsDisableCertificateRevocationCheckz!Insecure TLS options prohibited: ) r7dict TypeErrorrrBrrZrdrer r)Zkms_tls_optionsZcontextsproviderrF ssl_contextZallow_invalid_hostnamesnrrr_parse_kms_tls_optionsGs0      r__main__r$)F)TFT)C__doc__rerrDtypingrrrrrrrr urllib.parser Zpymongo.client_optionsr Zpymongo.commonr r rrrZpymongo.errorsrrZpymongo.srv_resolverrrZpymongo.typingsrrrrrrZ DEFAULT_PORTrr8r*r:r2r>rVrLrZrcrdrSrerlrpcompileescaper frozensetrrufloatrr__name__pprintargvexcprintexitrrrrs(    (6((  ". 5 "