We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Using a docker/config.json file causes "TypeError: string indices must be integers"
Using a ~/.docker/config.json file causes docker-compose to output a Python error. @dnephin in https://github.com/docker/compose/issues/2697#issuecomment-172936366 suggests that this is an issue to be raised with the docker-py project instead of the compose project.

So here's a simple config.json file, and a dummy docker-compose.yml file which demonstrate the issue:

```
$ cat ~/.docker/config.json 
{
  "detachKeys": "ctrl-q,ctrl-u,ctrl-i,ctrl-t"
}
$ cat docker-compose.yml 
version: '2'
services:
  s1:
    image: ubuntu
$ docker-compose ps
Traceback (most recent call last):
  File "<string>", line 3, in <module>
  File "/compose/compose/cli/main.py", line 55, in main
  File "/compose/compose/cli/docopt_command.py", line 23, in sys_dispatch
  File "/compose/compose/cli/docopt_command.py", line 26, in dispatch
  File "/compose/compose/cli/main.py", line 172, in perform_command
  File "/compose/compose/cli/command.py", line 52, in project_from_options
  File "/compose/compose/cli/command.py", line 85, in get_project
  File "/compose/compose/cli/command.py", line 66, in get_client
  File "/compose/compose/cli/docker_client.py", line 37, in docker_client
  File "/compose/venv/lib/python2.7/site-packages/docker/client.py", line 56, in __init__
  File "/compose/venv/lib/python2.7/site-packages/docker/auth/auth.py", line 182, in load_config
  File "/compose/venv/lib/python2.7/site-packages/docker/auth/auth.py", line 118, in parse_auth
TypeError: string indices must be integers
docker-compose returned -1
```

And if we delete the config and try again:

```
$ rm ~/.docker/config.json 
$ docker-compose ps
Name   Command   State   Ports 
------------------------------
```

I'm using Docker Toolbox 1.10.0 on OSX 10.11.3. The docker container is being run on a VirtualBox VM managed by docker-machine. Here are some more version numbers:

```
$ docker version
Client:
 Version:      1.10.0
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   590d5108
 Built:        Thu Feb  4 18:18:11 2016
 OS/Arch:      darwin/amd64

Server:
 Version:      1.10.0
 API version:  1.22
 Go version:   go1.5.3
 Git commit:   590d5108
 Built:        Thu Feb  4 19:55:25 2016
 OS/Arch:      linux/amd64
$ docker-compose version
docker-compose version 1.6.0, build d99cad6
docker-py version: 1.7.0
CPython version: 2.7.9
OpenSSL version: OpenSSL 1.0.1j 15 Oct 2014
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docker/auth/auth.py`
Content:
```
1 # Copyright 2013 dotCloud inc.
2 
3 #    Licensed under the Apache License, Version 2.0 (the "License");
4 #    you may not use this file except in compliance with the License.
5 #    You may obtain a copy of the License at
6 
7 #        http://www.apache.org/licenses/LICENSE-2.0
8 
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS,
11 #    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #    See the License for the specific language governing permissions and
13 #    limitations under the License.
14 
15 import base64
16 import json
17 import logging
18 import os
19 
20 import six
21 
22 from .. import errors
23 
24 INDEX_NAME = 'docker.io'
25 INDEX_URL = 'https://{0}/v1/'.format(INDEX_NAME)
26 DOCKER_CONFIG_FILENAME = os.path.join('.docker', 'config.json')
27 LEGACY_DOCKER_CONFIG_FILENAME = '.dockercfg'
28 
29 log = logging.getLogger(__name__)
30 
31 
32 def resolve_repository_name(repo_name):
33     if '://' in repo_name:
34         raise errors.InvalidRepository(
35             'Repository name cannot contain a scheme ({0})'.format(repo_name)
36         )
37 
38     index_name, remote_name = split_repo_name(repo_name)
39     if index_name[0] == '-' or index_name[-1] == '-':
40         raise errors.InvalidRepository(
41             'Invalid index name ({0}). Cannot begin or end with a'
42             ' hyphen.'.format(index_name)
43         )
44     return resolve_index_name(index_name), remote_name
45 
46 
47 def resolve_index_name(index_name):
48     index_name = convert_to_hostname(index_name)
49     if index_name == 'index.'+INDEX_NAME:
50         index_name = INDEX_NAME
51     return index_name
52 
53 
54 def split_repo_name(repo_name):
55     parts = repo_name.split('/', 1)
56     if len(parts) == 1 or (
57         '.' not in parts[0] and ':' not in parts[0] and parts[0] != 'localhost'
58     ):
59         # This is a docker index repo (ex: username/foobar or ubuntu)
60         return INDEX_NAME, repo_name
61     return tuple(parts)
62 
63 
64 def resolve_authconfig(authconfig, registry=None):
65     """
66     Returns the authentication data from the given auth configuration for a
67     specific registry. As with the Docker client, legacy entries in the config
68     with full URLs are stripped down to hostnames before checking for a match.
69     Returns None if no match was found.
70     """
71     # Default to the public index server
72     registry = resolve_index_name(registry) if registry else INDEX_NAME
73     log.debug("Looking for auth entry for {0}".format(repr(registry)))
74 
75     if registry in authconfig:
76         log.debug("Found {0}".format(repr(registry)))
77         return authconfig[registry]
78 
79     for key, config in six.iteritems(authconfig):
80         if resolve_index_name(key) == registry:
81             log.debug("Found {0}".format(repr(key)))
82             return config
83 
84     log.debug("No entry found")
85     return None
86 
87 
88 def convert_to_hostname(url):
89     return url.replace('http://', '').replace('https://', '').split('/', 1)[0]
90 
91 
92 def decode_auth(auth):
93     if isinstance(auth, six.string_types):
94         auth = auth.encode('ascii')
95     s = base64.b64decode(auth)
96     login, pwd = s.split(b':', 1)
97     return login.decode('utf8'), pwd.decode('utf8')
98 
99 
100 def encode_header(auth):
101     auth_json = json.dumps(auth).encode('ascii')
102     return base64.urlsafe_b64encode(auth_json)
103 
104 
105 def parse_auth(entries):
106     """
107     Parses authentication entries
108 
109     Args:
110       entries: Dict of authentication entries.
111 
112     Returns:
113       Authentication registry.
114     """
115 
116     conf = {}
117     for registry, entry in six.iteritems(entries):
118         username, password = decode_auth(entry['auth'])
119         log.debug(
120             'Found entry (registry={0}, username={1})'
121             .format(repr(registry), repr(username))
122         )
123         conf[registry] = {
124             'username': username,
125             'password': password,
126             'email': entry.get('email'),
127             'serveraddress': registry,
128         }
129     return conf
130 
131 
132 def find_config_file(config_path=None):
133     environment_path = os.path.join(
134         os.environ.get('DOCKER_CONFIG'),
135         os.path.basename(DOCKER_CONFIG_FILENAME)
136     ) if os.environ.get('DOCKER_CONFIG') else None
137 
138     paths = [
139         config_path,  # 1
140         environment_path,  # 2
141         os.path.join(os.path.expanduser('~'), DOCKER_CONFIG_FILENAME),  # 3
142         os.path.join(
143             os.path.expanduser('~'), LEGACY_DOCKER_CONFIG_FILENAME
144         )  # 4
145     ]
146 
147     for path in paths:
148         if path and os.path.exists(path):
149             return path
150     return None
151 
152 
153 def load_config(config_path=None):
154     """
155     Loads authentication data from a Docker configuration file in the given
156     root directory or if config_path is passed use given path.
157     Lookup priority:
158         explicit config_path parameter > DOCKER_CONFIG environment variable >
159         ~/.docker/config.json > ~/.dockercfg
160     """
161     config_file = find_config_file(config_path)
162 
163     if not config_file:
164         log.debug("File doesn't exist")
165         return {}
166 
167     try:
168         with open(config_file) as f:
169             data = json.load(f)
170             res = {}
171             if data.get('auths'):
172                 log.debug("Found 'auths' section")
173                 res.update(parse_auth(data['auths']))
174             if data.get('HttpHeaders'):
175                 log.debug("Found 'HttpHeaders' section")
176                 res.update({'HttpHeaders': data['HttpHeaders']})
177             if res:
178                 return res
179             else:
180                 log.debug("Couldn't find 'auths' or 'HttpHeaders' sections")
181                 f.seek(0)
182                 return parse_auth(json.load(f))
183     except (IOError, KeyError, ValueError) as e:
184         # Likely missing new Docker config file or it's in an
185         # unknown format, continue to attempt to read old location
186         # and format.
187         log.debug(e)
188 
189     log.debug("Attempting to parse legacy auth file format")
190     try:
191         data = []
192         with open(config_file) as f:
193             for line in f.readlines():
194                 data.append(line.strip().split(' = ')[1])
195             if len(data) < 2:
196                 # Not enough data
197                 raise errors.InvalidConfigFile(
198                     'Invalid or empty configuration file!'
199                 )
200 
201         username, password = decode_auth(data[0])
202         return {
203             INDEX_NAME: {
204                 'username': username,
205                 'password': password,
206                 'email': data[1],
207                 'serveraddress': INDEX_URL,
208             }
209         }
210     except Exception as e:
211         log.debug(e)
212         pass
213 
214     log.debug("All parsing attempts failed - returning empty config")
215     return {}
216
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/docker/auth/auth.py b/docker/auth/auth.py
--- a/docker/auth/auth.py
+++ b/docker/auth/auth.py
@@ -46,7 +46,7 @@
 
 def resolve_index_name(index_name):
     index_name = convert_to_hostname(index_name)
-    if index_name == 'index.'+INDEX_NAME:
+    if index_name == 'index.' + INDEX_NAME:
         index_name = INDEX_NAME
     return index_name
 
@@ -102,12 +102,14 @@
     return base64.urlsafe_b64encode(auth_json)
 
 
-def parse_auth(entries):
+def parse_auth(entries, raise_on_error=False):
     """
     Parses authentication entries
 
     Args:
-      entries: Dict of authentication entries.
+      entries:        Dict of authentication entries.
+      raise_on_error: If set to true, an invalid format will raise
+                      InvalidConfigFile
 
     Returns:
       Authentication registry.
@@ -115,6 +117,19 @@
 
     conf = {}
     for registry, entry in six.iteritems(entries):
+        if not (isinstance(entry, dict) and 'auth' in entry):
+            log.debug(
+                'Config entry for key {0} is not auth config'.format(registry)
+            )
+            # We sometimes fall back to parsing the whole config as if it was
+            # the auth config by itself, for legacy purposes. In that case, we
+            # fail silently and return an empty conf if any of the keys is not
+            # formatted properly.
+            if raise_on_error:
+                raise errors.InvalidConfigFile(
+                    'Invalid configuration for registry {0}'.format(registry)
+                )
+            return {}
         username, password = decode_auth(entry['auth'])
         log.debug(
             'Found entry (registry={0}, username={1})'
@@ -170,7 +185,7 @@
             res = {}
             if data.get('auths'):
                 log.debug("Found 'auths' section")
-                res.update(parse_auth(data['auths']))
+                res.update(parse_auth(data['auths'], raise_on_error=True))
             if data.get('HttpHeaders'):
                 log.debug("Found 'HttpHeaders' section")
                 res.update({'HttpHeaders': data['HttpHeaders']})

{"golden_diff": "diff --git a/docker/auth/auth.py b/docker/auth/auth.py\n--- a/docker/auth/auth.py\n+++ b/docker/auth/auth.py\n@@ -46,7 +46,7 @@\n \n def resolve_index_name(index_name):\n     index_name = convert_to_hostname(index_name)\n-    if index_name == 'index.'+INDEX_NAME:\n+    if index_name == 'index.' + INDEX_NAME:\n         index_name = INDEX_NAME\n     return index_name\n \n@@ -102,12 +102,14 @@\n     return base64.urlsafe_b64encode(auth_json)\n \n \n-def parse_auth(entries):\n+def parse_auth(entries, raise_on_error=False):\n     \"\"\"\n     Parses authentication entries\n \n     Args:\n-      entries: Dict of authentication entries.\n+      entries:        Dict of authentication entries.\n+      raise_on_error: If set to true, an invalid format will raise\n+                      InvalidConfigFile\n \n     Returns:\n       Authentication registry.\n@@ -115,6 +117,19 @@\n \n     conf = {}\n     for registry, entry in six.iteritems(entries):\n+        if not (isinstance(entry, dict) and 'auth' in entry):\n+            log.debug(\n+                'Config entry for key {0} is not auth config'.format(registry)\n+            )\n+            # We sometimes fall back to parsing the whole config as if it was\n+            # the auth config by itself, for legacy purposes. In that case, we\n+            # fail silently and return an empty conf if any of the keys is not\n+            # formatted properly.\n+            if raise_on_error:\n+                raise errors.InvalidConfigFile(\n+                    'Invalid configuration for registry {0}'.format(registry)\n+                )\n+            return {}\n         username, password = decode_auth(entry['auth'])\n         log.debug(\n             'Found entry (registry={0}, username={1})'\n@@ -170,7 +185,7 @@\n             res = {}\n             if data.get('auths'):\n                 log.debug(\"Found 'auths' section\")\n-                res.update(parse_auth(data['auths']))\n+                res.update(parse_auth(data['auths'], raise_on_error=True))\n             if data.get('HttpHeaders'):\n                 log.debug(\"Found 'HttpHeaders' section\")\n                 res.update({'HttpHeaders': data['HttpHeaders']})\n", "issue": "Using a docker/config.json file causes \"TypeError: string indices must be integers\"\nUsing a ~/.docker/config.json file causes docker-compose to output a Python error. @dnephin in https://github.com/docker/compose/issues/2697#issuecomment-172936366 suggests that this is an issue to be raised with the docker-py project instead of the compose project.\n\nSo here's a simple config.json file, and a dummy docker-compose.yml file which demonstrate the issue:\n\n```\n$ cat ~/.docker/config.json \n{\n  \"detachKeys\": \"ctrl-q,ctrl-u,ctrl-i,ctrl-t\"\n}\n$ cat docker-compose.yml \nversion: '2'\nservices:\n  s1:\n    image: ubuntu\n$ docker-compose ps\nTraceback (most recent call last):\n  File \"<string>\", line 3, in <module>\n  File \"/compose/compose/cli/main.py\", line 55, in main\n  File \"/compose/compose/cli/docopt_command.py\", line 23, in sys_dispatch\n  File \"/compose/compose/cli/docopt_command.py\", line 26, in dispatch\n  File \"/compose/compose/cli/main.py\", line 172, in perform_command\n  File \"/compose/compose/cli/command.py\", line 52, in project_from_options\n  File \"/compose/compose/cli/command.py\", line 85, in get_project\n  File \"/compose/compose/cli/command.py\", line 66, in get_client\n  File \"/compose/compose/cli/docker_client.py\", line 37, in docker_client\n  File \"/compose/venv/lib/python2.7/site-packages/docker/client.py\", line 56, in __init__\n  File \"/compose/venv/lib/python2.7/site-packages/docker/auth/auth.py\", line 182, in load_config\n  File \"/compose/venv/lib/python2.7/site-packages/docker/auth/auth.py\", line 118, in parse_auth\nTypeError: string indices must be integers\ndocker-compose returned -1\n```\n\nAnd if we delete the config and try again:\n\n```\n$ rm ~/.docker/config.json \n$ docker-compose ps\nName   Command   State   Ports \n------------------------------\n```\n\nI'm using Docker Toolbox 1.10.0 on OSX 10.11.3. The docker container is being run on a VirtualBox VM managed by docker-machine. Here are some more version numbers:\n\n```\n$ docker version\nClient:\n Version:      1.10.0\n API version:  1.22\n Go version:   go1.5.3\n Git commit:   590d5108\n Built:        Thu Feb  4 18:18:11 2016\n OS/Arch:      darwin/amd64\n\nServer:\n Version:      1.10.0\n API version:  1.22\n Go version:   go1.5.3\n Git commit:   590d5108\n Built:        Thu Feb  4 19:55:25 2016\n OS/Arch:      linux/amd64\n$ docker-compose version\ndocker-compose version 1.6.0, build d99cad6\ndocker-py version: 1.7.0\nCPython version: 2.7.9\nOpenSSL version: OpenSSL 1.0.1j 15 Oct 2014\n```\n\n", "before_files": [{"content": "# Copyright 2013 dotCloud inc.\n\n#    Licensed under the Apache License, Version 2.0 (the \"License\");\n#    you may not use this file except in compliance with the License.\n#    You may obtain a copy of the License at\n\n#        http://www.apache.org/licenses/LICENSE-2.0\n\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#    See the License for the specific language governing permissions and\n#    limitations under the License.\n\nimport base64\nimport json\nimport logging\nimport os\n\nimport six\n\nfrom .. import errors\n\nINDEX_NAME = 'docker.io'\nINDEX_URL = 'https://{0}/v1/'.format(INDEX_NAME)\nDOCKER_CONFIG_FILENAME = os.path.join('.docker', 'config.json')\nLEGACY_DOCKER_CONFIG_FILENAME = '.dockercfg'\n\nlog = logging.getLogger(__name__)\n\n\ndef resolve_repository_name(repo_name):\n    if '://' in repo_name:\n        raise errors.InvalidRepository(\n            'Repository name cannot contain a scheme ({0})'.format(repo_name)\n        )\n\n    index_name, remote_name = split_repo_name(repo_name)\n    if index_name[0] == '-' or index_name[-1] == '-':\n        raise errors.InvalidRepository(\n            'Invalid index name ({0}). Cannot begin or end with a'\n            ' hyphen.'.format(index_name)\n        )\n    return resolve_index_name(index_name), remote_name\n\n\ndef resolve_index_name(index_name):\n    index_name = convert_to_hostname(index_name)\n    if index_name == 'index.'+INDEX_NAME:\n        index_name = INDEX_NAME\n    return index_name\n\n\ndef split_repo_name(repo_name):\n    parts = repo_name.split('/', 1)\n    if len(parts) == 1 or (\n        '.' not in parts[0] and ':' not in parts[0] and parts[0] != 'localhost'\n    ):\n        # This is a docker index repo (ex: username/foobar or ubuntu)\n        return INDEX_NAME, repo_name\n    return tuple(parts)\n\n\ndef resolve_authconfig(authconfig, registry=None):\n    \"\"\"\n    Returns the authentication data from the given auth configuration for a\n    specific registry. As with the Docker client, legacy entries in the config\n    with full URLs are stripped down to hostnames before checking for a match.\n    Returns None if no match was found.\n    \"\"\"\n    # Default to the public index server\n    registry = resolve_index_name(registry) if registry else INDEX_NAME\n    log.debug(\"Looking for auth entry for {0}\".format(repr(registry)))\n\n    if registry in authconfig:\n        log.debug(\"Found {0}\".format(repr(registry)))\n        return authconfig[registry]\n\n    for key, config in six.iteritems(authconfig):\n        if resolve_index_name(key) == registry:\n            log.debug(\"Found {0}\".format(repr(key)))\n            return config\n\n    log.debug(\"No entry found\")\n    return None\n\n\ndef convert_to_hostname(url):\n    return url.replace('http://', '').replace('https://', '').split('/', 1)[0]\n\n\ndef decode_auth(auth):\n    if isinstance(auth, six.string_types):\n        auth = auth.encode('ascii')\n    s = base64.b64decode(auth)\n    login, pwd = s.split(b':', 1)\n    return login.decode('utf8'), pwd.decode('utf8')\n\n\ndef encode_header(auth):\n    auth_json = json.dumps(auth).encode('ascii')\n    return base64.urlsafe_b64encode(auth_json)\n\n\ndef parse_auth(entries):\n    \"\"\"\n    Parses authentication entries\n\n    Args:\n      entries: Dict of authentication entries.\n\n    Returns:\n      Authentication registry.\n    \"\"\"\n\n    conf = {}\n    for registry, entry in six.iteritems(entries):\n        username, password = decode_auth(entry['auth'])\n        log.debug(\n            'Found entry (registry={0}, username={1})'\n            .format(repr(registry), repr(username))\n        )\n        conf[registry] = {\n            'username': username,\n            'password': password,\n            'email': entry.get('email'),\n            'serveraddress': registry,\n        }\n    return conf\n\n\ndef find_config_file(config_path=None):\n    environment_path = os.path.join(\n        os.environ.get('DOCKER_CONFIG'),\n        os.path.basename(DOCKER_CONFIG_FILENAME)\n    ) if os.environ.get('DOCKER_CONFIG') else None\n\n    paths = [\n        config_path,  # 1\n        environment_path,  # 2\n        os.path.join(os.path.expanduser('~'), DOCKER_CONFIG_FILENAME),  # 3\n        os.path.join(\n            os.path.expanduser('~'), LEGACY_DOCKER_CONFIG_FILENAME\n        )  # 4\n    ]\n\n    for path in paths:\n        if path and os.path.exists(path):\n            return path\n    return None\n\n\ndef load_config(config_path=None):\n    \"\"\"\n    Loads authentication data from a Docker configuration file in the given\n    root directory or if config_path is passed use given path.\n    Lookup priority:\n        explicit config_path parameter > DOCKER_CONFIG environment variable >\n        ~/.docker/config.json > ~/.dockercfg\n    \"\"\"\n    config_file = find_config_file(config_path)\n\n    if not config_file:\n        log.debug(\"File doesn't exist\")\n        return {}\n\n    try:\n        with open(config_file) as f:\n            data = json.load(f)\n            res = {}\n            if data.get('auths'):\n                log.debug(\"Found 'auths' section\")\n                res.update(parse_auth(data['auths']))\n            if data.get('HttpHeaders'):\n                log.debug(\"Found 'HttpHeaders' section\")\n                res.update({'HttpHeaders': data['HttpHeaders']})\n            if res:\n                return res\n            else:\n                log.debug(\"Couldn't find 'auths' or 'HttpHeaders' sections\")\n                f.seek(0)\n                return parse_auth(json.load(f))\n    except (IOError, KeyError, ValueError) as e:\n        # Likely missing new Docker config file or it's in an\n        # unknown format, continue to attempt to read old location\n        # and format.\n        log.debug(e)\n\n    log.debug(\"Attempting to parse legacy auth file format\")\n    try:\n        data = []\n        with open(config_file) as f:\n            for line in f.readlines():\n                data.append(line.strip().split(' = ')[1])\n            if len(data) < 2:\n                # Not enough data\n                raise errors.InvalidConfigFile(\n                    'Invalid or empty configuration file!'\n                )\n\n        username, password = decode_auth(data[0])\n        return {\n            INDEX_NAME: {\n                'username': username,\n                'password': password,\n                'email': data[1],\n                'serveraddress': INDEX_URL,\n            }\n        }\n    except Exception as e:\n        log.debug(e)\n        pass\n\n    log.debug(\"All parsing attempts failed - returning empty config\")\n    return {}\n", "path": "docker/auth/auth.py"}], "after_files": [{"content": "# Copyright 2013 dotCloud inc.\n\n#    Licensed under the Apache License, Version 2.0 (the \"License\");\n#    you may not use this file except in compliance with the License.\n#    You may obtain a copy of the License at\n\n#        http://www.apache.org/licenses/LICENSE-2.0\n\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#    See the License for the specific language governing permissions and\n#    limitations under the License.\n\nimport base64\nimport json\nimport logging\nimport os\n\nimport six\n\nfrom .. import errors\n\nINDEX_NAME = 'docker.io'\nINDEX_URL = 'https://{0}/v1/'.format(INDEX_NAME)\nDOCKER_CONFIG_FILENAME = os.path.join('.docker', 'config.json')\nLEGACY_DOCKER_CONFIG_FILENAME = '.dockercfg'\n\nlog = logging.getLogger(__name__)\n\n\ndef resolve_repository_name(repo_name):\n    if '://' in repo_name:\n        raise errors.InvalidRepository(\n            'Repository name cannot contain a scheme ({0})'.format(repo_name)\n        )\n\n    index_name, remote_name = split_repo_name(repo_name)\n    if index_name[0] == '-' or index_name[-1] == '-':\n        raise errors.InvalidRepository(\n            'Invalid index name ({0}). Cannot begin or end with a'\n            ' hyphen.'.format(index_name)\n        )\n    return resolve_index_name(index_name), remote_name\n\n\ndef resolve_index_name(index_name):\n    index_name = convert_to_hostname(index_name)\n    if index_name == 'index.' + INDEX_NAME:\n        index_name = INDEX_NAME\n    return index_name\n\n\ndef split_repo_name(repo_name):\n    parts = repo_name.split('/', 1)\n    if len(parts) == 1 or (\n        '.' not in parts[0] and ':' not in parts[0] and parts[0] != 'localhost'\n    ):\n        # This is a docker index repo (ex: username/foobar or ubuntu)\n        return INDEX_NAME, repo_name\n    return tuple(parts)\n\n\ndef resolve_authconfig(authconfig, registry=None):\n    \"\"\"\n    Returns the authentication data from the given auth configuration for a\n    specific registry. As with the Docker client, legacy entries in the config\n    with full URLs are stripped down to hostnames before checking for a match.\n    Returns None if no match was found.\n    \"\"\"\n    # Default to the public index server\n    registry = resolve_index_name(registry) if registry else INDEX_NAME\n    log.debug(\"Looking for auth entry for {0}\".format(repr(registry)))\n\n    if registry in authconfig:\n        log.debug(\"Found {0}\".format(repr(registry)))\n        return authconfig[registry]\n\n    for key, config in six.iteritems(authconfig):\n        if resolve_index_name(key) == registry:\n            log.debug(\"Found {0}\".format(repr(key)))\n            return config\n\n    log.debug(\"No entry found\")\n    return None\n\n\ndef convert_to_hostname(url):\n    return url.replace('http://', '').replace('https://', '').split('/', 1)[0]\n\n\ndef decode_auth(auth):\n    if isinstance(auth, six.string_types):\n        auth = auth.encode('ascii')\n    s = base64.b64decode(auth)\n    login, pwd = s.split(b':', 1)\n    return login.decode('utf8'), pwd.decode('utf8')\n\n\ndef encode_header(auth):\n    auth_json = json.dumps(auth).encode('ascii')\n    return base64.urlsafe_b64encode(auth_json)\n\n\ndef parse_auth(entries, raise_on_error=False):\n    \"\"\"\n    Parses authentication entries\n\n    Args:\n      entries:        Dict of authentication entries.\n      raise_on_error: If set to true, an invalid format will raise\n                      InvalidConfigFile\n\n    Returns:\n      Authentication registry.\n    \"\"\"\n\n    conf = {}\n    for registry, entry in six.iteritems(entries):\n        if not (isinstance(entry, dict) and 'auth' in entry):\n            log.debug(\n                'Config entry for key {0} is not auth config'.format(registry)\n            )\n            # We sometimes fall back to parsing the whole config as if it was\n            # the auth config by itself, for legacy purposes. In that case, we\n            # fail silently and return an empty conf if any of the keys is not\n            # formatted properly.\n            if raise_on_error:\n                raise errors.InvalidConfigFile(\n                    'Invalid configuration for registry {0}'.format(registry)\n                )\n            return {}\n        username, password = decode_auth(entry['auth'])\n        log.debug(\n            'Found entry (registry={0}, username={1})'\n            .format(repr(registry), repr(username))\n        )\n        conf[registry] = {\n            'username': username,\n            'password': password,\n            'email': entry.get('email'),\n            'serveraddress': registry,\n        }\n    return conf\n\n\ndef find_config_file(config_path=None):\n    environment_path = os.path.join(\n        os.environ.get('DOCKER_CONFIG'),\n        os.path.basename(DOCKER_CONFIG_FILENAME)\n    ) if os.environ.get('DOCKER_CONFIG') else None\n\n    paths = [\n        config_path,  # 1\n        environment_path,  # 2\n        os.path.join(os.path.expanduser('~'), DOCKER_CONFIG_FILENAME),  # 3\n        os.path.join(\n            os.path.expanduser('~'), LEGACY_DOCKER_CONFIG_FILENAME\n        )  # 4\n    ]\n\n    for path in paths:\n        if path and os.path.exists(path):\n            return path\n    return None\n\n\ndef load_config(config_path=None):\n    \"\"\"\n    Loads authentication data from a Docker configuration file in the given\n    root directory or if config_path is passed use given path.\n    Lookup priority:\n        explicit config_path parameter > DOCKER_CONFIG environment variable >\n        ~/.docker/config.json > ~/.dockercfg\n    \"\"\"\n    config_file = find_config_file(config_path)\n\n    if not config_file:\n        log.debug(\"File doesn't exist\")\n        return {}\n\n    try:\n        with open(config_file) as f:\n            data = json.load(f)\n            res = {}\n            if data.get('auths'):\n                log.debug(\"Found 'auths' section\")\n                res.update(parse_auth(data['auths'], raise_on_error=True))\n            if data.get('HttpHeaders'):\n                log.debug(\"Found 'HttpHeaders' section\")\n                res.update({'HttpHeaders': data['HttpHeaders']})\n            if res:\n                return res\n            else:\n                log.debug(\"Couldn't find 'auths' or 'HttpHeaders' sections\")\n                f.seek(0)\n                return parse_auth(json.load(f))\n    except (IOError, KeyError, ValueError) as e:\n        # Likely missing new Docker config file or it's in an\n        # unknown format, continue to attempt to read old location\n        # and format.\n        log.debug(e)\n\n    log.debug(\"Attempting to parse legacy auth file format\")\n    try:\n        data = []\n        with open(config_file) as f:\n            for line in f.readlines():\n                data.append(line.strip().split(' = ')[1])\n            if len(data) < 2:\n                # Not enough data\n                raise errors.InvalidConfigFile(\n                    'Invalid or empty configuration file!'\n                )\n\n        username, password = decode_auth(data[0])\n        return {\n            INDEX_NAME: {\n                'username': username,\n                'password': password,\n                'email': data[1],\n                'serveraddress': INDEX_URL,\n            }\n        }\n    except Exception as e:\n        log.debug(e)\n        pass\n\n    log.debug(\"All parsing attempts failed - returning empty config\")\n    return {}\n", "path": "docker/auth/auth.py"}]}