def parse_headers(fp):
    """
    Parses HTTP-like headers into a dictionary until an empty line
    is found. Invalid headers are ignored and if a header is found
    twice, it won't overwrite its previous value. Header-keys are
    converted to lower-case and stripped of whitespace at both ends.
    """

    headers = {}
    while True:
        line = fp.readline().strip()
        if not line: break

        key, _, value = line.partition(':')
        key = key.rstrip().lower()
        if key not in headers:
            headers[key] = value.lstrip()

    return headers