# Path: dput/exceptions.py
# class UploadException(DputError):
#     """
#     Thrown when there's an error uploading, or creating an uploader. Usually
#     thrown by a subclass of the :class:`dput.uploader.AbstractUploader`
#     """
#     pass
# 
# Path: dput/uploader.py
# class AbstractUploader(object):
#     """
#     Abstract base class for all concrete uploader implementations.
#     """
# 
#     __metaclass__ = abc.ABCMeta
# 
#     def __init__(self, profile):
#         self._config = profile
#         interface = 'cli'
#         if 'interface' in profile:
#             interface = profile['interface']
#         logger.trace("Using interface %s" % (interface))
#         interface_obj = get_obj('interfaces', interface)
#         if interface_obj is None:
#             raise DputConfigurationError("No such interface: `%s'" % (
#                 interface
#             ))
#         self.interface = interface_obj()
#         self.interface.initialize()
# 
#     def _pre_hook(self):
#         self._run_hook("pre_upload_command")
# 
#     def _post_hook(self):
#         self._run_hook("post_upload_command")
# 
#     def _run_hook(self, hook):
#         if hook in self._config and self._config[hook] != "":
#             cmd = self._config[hook]
#             (output, stderr, ret) = run_command(cmd)
#             if ret == -1:
#                 if not os.path.exists(cmd):
#                     logger.warning(
#                         "Error: You've set a hook (%s) to run (`%s`), "
#                         "but it can't be found (and doesn't appear to exist)."
#                         " Please verify the path and correct it." % (
#                             hook,
#                             self._config[hook]
#                         )
#                     )
#                     return
# 
#             sys.stdout.write(output)  # XXX: Fixme
#             sys.stdout.flush()
#             if ret != 0:
#                 raise DputError(
#                     "Command `%s' returned an error: %s [err=%d]" % (
#                         self._config[hook],
#                         stderr,
#                         ret
#                     )
#                 )
# 
#     def __del__(self):
#         self.interface.shutdown()
# 
#     def upload_write_error(self, e):
#         """
#         .. warning::
#            don't call this.
# 
#         please don't call this
#         """
#         # XXX: Refactor this, please god, refactor this.
#         logger.warning("""Upload permissions error
# 
# You either don't have the rights to upload a file, or, if this is on
# ftp-master, you may have tried to overwrite a file already on the server.
# 
# Continuing anyway in case you want to recover from an incomplete upload.
# No file was uploaded, however.""")
# 
#     @abc.abstractmethod
#     def initialize(self, **kwargs):
#         """
#         Setup the things needed to upload a file. Usually this means creating
#         a network connection & authenticating.
#         """
#         pass
# 
#     @abc.abstractmethod
#     def upload_file(self, filename, upload_filename=None):
#         """
#         Upload a single file (``filename``) to the server.
#         """
#         pass
# 
#     @abc.abstractmethod
#     def shutdown(self):
#         """
#         Disconnect and shutdown.
#         """
#         pass
# 
# Path: dput/core.py
# CONFIG_LOCATIONS = {
#     "/usr/share/dput-ng/": 30,
#     "/etc/dput.d/": 20,
#     os.path.expanduser("~/.dput.d"): 10,
#     "skel/": 100
# }
# DPUT_CONFIG_LOCATIONS = {
#     "/etc/dput.cf": 15,
#     os.path.expanduser("~/.dput.cf"): 5
# }
# SCHEMA_DIRS = [
#     "/usr/share/dput-ng/schemas",
#     "skel/schemas"
# ]
# def _write_upload_log(logfile, full_log):
# def _enable_debugging(level):
# def mangle_sys():
# def maybe_print_traceback(debug_level, stack):
# def get_local_username():


from dput.exceptions import UploadException
from dput.uploader import AbstractUploader
from dput.core import logger
import mmap
import urllib.parse
import urllib.request
import os.path
import mimetypes
        mmaped_fh = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
        req = urllib.request.Request(
            url=upload_filename,
            data=fh.read(),
            method='PUT',
        )
        if mime_type is not None:
            req.add_header("Content-Type", mime_type)

        if self._username is not None:
            try:
                password_mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
                password_mgr.add_password(None, self._baseurl, self._username, self._password, is_authenticated=True)
            except AttributeError:
                password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
                password_mgr.add_password(None, self._baseurl, self._username, self._password)
            handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
            opener = urllib.request.build_opener(handler)
        else:
            opener = urllib.request.build_opener()

        try:
            opener.open(req)
        except urllib.error.HTTPError as e:
            error_message = e.read().decode(
                e.headers.get_content_charset(failobj='utf-8'))
            if error_message:
                error_message = error_message.strip()
                if "\n" in error_message:
                    error_message = "\n\t" + "\n\t".join(error_message.splitlines())

# Path: dput/exceptions.py
# class UploadException(DputError):
#     """
#     Thrown when there's an error uploading, or creating an uploader. Usually
#     thrown by a subclass of the :class:`dput.uploader.AbstractUploader`
#     """
#     pass
# 
# Path: dput/uploader.py
# class AbstractUploader(object):
#     """
#     Abstract base class for all concrete uploader implementations.
#     """
# 
#     __metaclass__ = abc.ABCMeta
# 
#     def __init__(self, profile):
#         self._config = profile
#         interface = 'cli'
#         if 'interface' in profile:
#             interface = profile['interface']
#         logger.trace("Using interface %s" % (interface))
#         interface_obj = get_obj('interfaces', interface)
#         if interface_obj is None:
#             raise DputConfigurationError("No such interface: `%s'" % (
#                 interface
#             ))
#         self.interface = interface_obj()
#         self.interface.initialize()
# 
#     def _pre_hook(self):
#         self._run_hook("pre_upload_command")
# 
#     def _post_hook(self):
#         self._run_hook("post_upload_command")
# 
#     def _run_hook(self, hook):
#         if hook in self._config and self._config[hook] != "":
#             cmd = self._config[hook]
#             (output, stderr, ret) = run_command(cmd)
#             if ret == -1:
#                 if not os.path.exists(cmd):
#                     logger.warning(
#                         "Error: You've set a hook (%s) to run (`%s`), "
#                         "but it can't be found (and doesn't appear to exist)."
#                         " Please verify the path and correct it." % (
#                             hook,
#                             self._config[hook]
#                         )
#                     )
#                     return
# 
#             sys.stdout.write(output)  # XXX: Fixme
#             sys.stdout.flush()
#             if ret != 0:
#                 raise DputError(
#                     "Command `%s' returned an error: %s [err=%d]" % (
#                         self._config[hook],
#                         stderr,
#                         ret
#                     )
#                 )
# 
#     def __del__(self):
#         self.interface.shutdown()
# 
#     def upload_write_error(self, e):
#         """
#         .. warning::
#            don't call this.
# 
#         please don't call this
#         """
#         # XXX: Refactor this, please god, refactor this.
#         logger.warning("""Upload permissions error
# 
# You either don't have the rights to upload a file, or, if this is on
# ftp-master, you may have tried to overwrite a file already on the server.
# 
# Continuing anyway in case you want to recover from an incomplete upload.
# No file was uploaded, however.""")
# 
#     @abc.abstractmethod
#     def initialize(self, **kwargs):
#         """
#         Setup the things needed to upload a file. Usually this means creating
#         a network connection & authenticating.
#         """
#         pass
# 
#     @abc.abstractmethod
#     def upload_file(self, filename, upload_filename=None):
#         """
#         Upload a single file (``filename``) to the server.
#         """
#         pass
# 
#     @abc.abstractmethod
#     def shutdown(self):
#         """
#         Disconnect and shutdown.
#         """
#         pass
# 
# Path: dput/core.py
# CONFIG_LOCATIONS = {
#     "/usr/share/dput-ng/": 30,
#     "/etc/dput.d/": 20,
#     os.path.expanduser("~/.dput.d"): 10,
#     "skel/": 100
# }
# DPUT_CONFIG_LOCATIONS = {
#     "/etc/dput.cf": 15,
#     os.path.expanduser("~/.dput.cf"): 5
# }
# SCHEMA_DIRS = [
#     "/usr/share/dput-ng/schemas",
#     "skel/schemas"
# ]
# def _write_upload_log(logfile, full_log):
# def _enable_debugging(level):
# def mangle_sys():
# def maybe_print_traceback(debug_level, stack):
# def get_local_username():


# Path: dput/uploaders/http.py
from dput.exceptions import UploadException
from dput.uploader import AbstractUploader
from dput.core import logger
import mmap
import urllib.parse
import urllib.request
import os.path
import mimetypes

        mmaped_fh = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
        req = urllib.request.Request(
            url=upload_filename,
            data=fh.read(),
            method='PUT',
        )
        if mime_type is not None:
            req.add_header("Content-Type", mime_type)

        if self._username is not None:
            try:
                password_mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
                password_mgr.add_password(None, self._baseurl, self._username, self._password, is_authenticated=True)
            except AttributeError:
                password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
                password_mgr.add_password(None, self._baseurl, self._username, self._password)
            handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
            opener = urllib.request.build_opener(handler)
        else:
            opener = urllib.request.build_opener()

        try:
            opener.open(req)
        except urllib.error.HTTPError as e:
            error_message = e.read().decode(
                e.headers.get_content_charset(failobj='utf-8'))
            if error_message:
                error_message = error_message.strip()
                if "\n" in error_message:
                    error_message = "\n\t" + "\n\t".join(error_message.splitlines())

                logger.warning("HTTP error message: %s" % error_message)