/* * QEMU readline utility * * Copyright (c) 2003-2004 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "vl.h" #define TERM_CMD_BUF_SIZE 4095 #define TERM_MAX_CMDS 64 #define NB_COMPLETIONS_MAX 256 #define IS_NORM 0 #define IS_ESC 1 #define IS_CSI 2 #define printf do_not_use_printf static char term_cmd_buf[TERM_CMD_BUF_SIZE + 1]; static int term_cmd_buf_index; static int term_cmd_buf_size; static char term_last_cmd_buf[TERM_CMD_BUF_SIZE + 1]; static int term_last_cmd_buf_index; static int term_last_cmd_buf_size; static int term_esc_state; static int term_esc_param; static char *term_history[TERM_MAX_CMDS]; static int term_hist_entry = -1; static int nb_completions; int completion_index; static char *completions[NB_COMPLETIONS_MAX]; static ReadLineFunc *term_readline_func; static int term_is_password; static char term_prompt[256]; static void *term_readline_opaque; static void term_show_prompt2(void) { term_printf("%s", term_prompt); term_flush(); term_last_cmd_buf_index = 0; term_last_cmd_buf_size = 0; term_esc_state = IS_NORM; } static void term_show_prompt(void) { term_show_prompt2(); term_cmd_buf_index = 0; term_cmd_buf_size = 0; } /* update the displayed command line */ static void term_update(void) { int i, delta, len; if (term_cmd_buf_size != term_last_cmd_buf_size || memcmp(term_cmd_buf, term_last_cmd_buf, term_cmd_buf_size) != 0) { for(i = 0; i < term_last_cmd_buf_index; i++) { term_printf("\033[D"); } term_cmd_buf[term_cmd_buf_size] = '\0'; if (term_is_password) { len = strlen(term_cmd_buf); for(i = 0; i < len; i++) term_printf("*"); } else { term_printf("%s", term_cmd_buf); } term_printf("\033[K"); memcpy(term_last_cmd_buf, term_cmd_buf, term_cmd_buf_size); term_last_cmd_buf_size = term_cmd_buf_size; term_last_cmd_buf_index = term_cmd_buf_size; } if (term_cmd_buf_index != term_last_cmd_buf_index) { delta = term_cmd_buf_index - term_last_cmd_buf_index; if (delta > 0) { for(i = 0;i < delta; i++) { term_printf("\033[C"); } } else { delta = -delta; for(i = 0;i < delta; i++) { term_printf("\033[D"); } } term_last_cmd_buf_index = term_cmd_buf_index; } term_flush(); } static void term_insert_char(int ch) { if (term_cmd_buf_index < TERM_CMD_BUF_SIZE) { memmove(term_cmd_buf + term_cmd_buf_index + 1, term_cmd_buf + term_cmd_buf_index, term_cmd_buf_size - term_cmd_buf_index); term_cmd_buf[term_cmd_buf_index] = ch; term_cmd_buf_size++; term_cmd_buf_index++; } } static void term_backward_char(void) { if (term_cmd_buf_index > 0) { term_cmd_buf_index--; } } static void term_forward_char(void) { if (term_cmd_buf_index < term_cmd_buf_size) { term_cmd_buf_index++; } } static void term_delete_char(void) { if (term_cmd_buf_index < term_cmd_buf_size) { memmove(term_cmd_buf + term_cmd_buf_index, term_cmd_buf + term_cmd_buf_index + 1, term_cmd_buf_size - term_cmd_buf_index - 1); term_cmd_buf_size--; } } static void term_backspace(void) { if (term_cmd_buf_index > 0) { term_backward_char(); term_delete_char(); } } static void term_bol(void) { term_cmd_buf_index = 0; } static void term_eol(void) { term_cmd_buf_index = term_cmd_buf_size; } static void term_up_char(void) { int idx; if (term_hist_entry == 0) return; if (term_hist_entry == -1) { /* Find latest entry */ for (idx = 0; idx < TERM_MAX_CMDS; idx++) { if (term_history[idx] == NULL) break; } term_hist_entry = idx; } term_hist_entry--; if (term_hist_entry >= 0) { pstrcpy(term_cmd_buf, sizeof(term_cmd_buf), term_history[term_hist_entry]); term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf); } } static void term_down_char(void) { if (term_hist_entry == TERM_MAX_CMDS - 1 || term_hist_entry == -1) return; if (term_history[++term_hist_entry] != NULL) { pstrcpy(term_cmd_buf, sizeof(term_cmd_buf), term_history[term_hist_entry]); } else { term_hist_entry = -1; } term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf); } static void term_hist_add(const char *cmdline) { char *hist_entry, *new_entry; int idx; if (cmdline[0] == '\0') return; new_entry = NULL; if (term_hist_entry != -1) { /* We were editing an existing history entry: replace it */ hist_entry = term_history[term_hist_entry]; idx = term_hist_entry; if (strcmp(hist_entry, cmdline) == 0) { goto same_entry; } } /* Search cmdline in history buffers */ for (idx = 0; idx < TERM_MAX_CMDS; idx++) { hist_entry = term_history[idx]; if (hist_entry == NULL) break; if (strcmp(hist_entry, cmdline) == 0) { same_entry: new_entry = hist_entry; /* Put this entry at the end of history */ memmove(&term_history[idx], &term_history[idx + 1], &term_history[TERM_MAX_CMDS] - &term_history[idx + 1]); term_history[TERM_MAX_CMDS - 1] = NULL; for (; idx < TERM_MAX_CMDS; idx++) { if (term_history[idx] == NULL) break; } break; } } if (idx == TERM_MAX_CMDS) { /* Need to get one free slot */ free(term_history[0]); memcpy(term_history, &term_history[1], &term_history[TERM_MAX_CMDS] - &term_history[1]); term_history[TERM_MAX_CMDS - 1] = NULL; idx = TERM_MAX_CMDS - 1; } if (new_entry == NULL) new_entry = strdup(cmdline); term_history[idx] = new_entry; term_hist_entry = -1; } /* completion support */ void add_completion(const char *str) { if (nb_completions < NB_COMPLETIONS_MAX) { completions[nb_completions++] = qemu_strdup(str); } } static void term_completion(void) { int len, i, j, max_width, nb_cols; char *cmdline; nb_completions = 0; cmdline = qemu_malloc(term_cmd_buf_index + 1); if (!cmdline) return; memcpy(cmdline, term_cmd_buf, term_cmd_buf_index); cmdline[term_cmd_buf_index] = '\0'; readline_find_completion(cmdline); qemu_free(cmdline); /* no completion found */ if (nb_completions <= 0) return; if (nb_completions == 1) { len = strlen(completions[0]); for(i = completion_index; i < len; i++) { term_insert_char(completions[0][i]); } /* extra space for next argument. XXX: make it more generic */ if (len > 0 && completions[0][len - 1] != '/') term_insert_char(' '); } else { term_printf("\n"); max_width = 0; for(i = 0; i < nb_completions; i++) { len = strlen(completions[i]); if (len > max_width) max_width = len; } max_width += 2; if (max_width < 10) max_width = 10; else if (max_width > 80) max_width = 80; nb_cols = 80 / max_width; j = 0; for(i = 0; i < nb_completions; i++) { term_printf("%-*s", max_width, completions[i]); if (++j == nb_cols || i == (nb_completions - 1)) { term_printf("\n"); j = 0; } } term_show_prompt2(); } } /* return true if command handled */ void readline_handle_byte(int ch) { switch(term_esc_state) { case IS_NORM: switch(ch) { case 1: term_bol(); break; case 4: term_delete_char(); break; case 5: term_eol(); break; case 9: term_completion(); break; case 10: case 13: term_cmd_buf[term_cmd_buf_size] = '\0'; if (!term_is_password) term_hist_add(term_cmd_buf); term_printf("\n"); /* NOTE: readline_start can be called here */ term_readline_func(term_readline_opaque, term_cmd_buf); break; case 27: term_esc_state = IS_ESC; break; case 127: case 8: term_backspace(); break; case 155: term_esc_state = IS_CSI; break; default: if (ch >= 32) { term_insert_char(ch); } break; } break; case IS_ESC: if (ch == '[') { term_esc_state = IS_CSI; term_esc_param = 0; } else { term_esc_state = IS_NORM; } break; case IS_CSI: switch(ch) { case 'A': case 'F': term_up_char(); break; case 'B': case 'E': term_down_char(); break; case 'D': term_backward_char(); break; case 'C': term_forward_char(); break; case '0' ... '9': term_esc_param = term_esc_param * 10 + (ch - '0'); goto the_end; case '~': switch(term_esc_param) { case 1: term_bol(); break; case 3: term_delete_char(); break; case 4: term_eol(); break; } break; default: break; } term_esc_state = IS_NORM; the_end: break; } term_update(); } void readline_start(const char *prompt, int is_password, ReadLineFunc *readline_func, void *opaque) { pstrcpy(term_prompt, sizeof(term_prompt), prompt); term_readline_func = readline_func; term_readline_opaque = opaque; term_is_password = is_password; term_show_prompt(); } const char *readline_get_history(unsigned int index) { if (index >= TERM_MAX_CMDS) return NULL; return term_history[index]; } n241'>241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
import collections
import email.utils
import re
import time

from netlib import multidict

"""
A flexible module for cookie parsing and manipulation.

This module differs from usual standards-compliant cookie modules in a number
of ways. We try to be as permissive as possible, and to retain even mal-formed
information. Duplicate cookies are preserved in parsing, and can be set in
formatting. We do attempt to escape and quote values where needed, but will not
reject data that violate the specs.

Parsing accepts the formats in RFC6265 and partially RFC2109 and RFC2965. We do
not parse the comma-separated variant of Set-Cookie that allows multiple
cookies to be set in a single header. Technically this should be feasible, but
it turns out that violations of RFC6265 that makes the parsing problem
indeterminate are much more common than genuine occurences of the multi-cookie
variants. Serialization follows RFC6265.

    http://tools.ietf.org/html/rfc6265
    http://tools.ietf.org/html/rfc2109
    http://tools.ietf.org/html/rfc2965
"""

_cookie_params = set((
    'expires', 'path', 'comment', 'max-age',
    'secure', 'httponly', 'version',
))


# TODO: Disallow LHS-only Cookie values


def _read_until(s, start, term):
    """
        Read until one of the characters in term is reached.
    """
    if start == len(s):
        return "", start + 1
    for i in range(start, len(s)):
        if s[i] in term:
            return s[start:i], i
    return s[start:i + 1], i + 1


def _read_token(s, start):
    """
        Read a token - the LHS of a token/value pair in a cookie.
    """
    return _read_until(s, start, ";=")


def _read_quoted_string(s, start):
    """
        start: offset to the first quote of the string to be read

        A sort of loose super-set of the various quoted string specifications.

        RFC6265 disallows backslashes or double quotes within quoted strings.
        Prior RFCs use backslashes to escape. This leaves us free to apply
        backslash escaping by default and be compatible with everything.
    """
    escaping = False
    ret = []
    # Skip the first quote
    i = start  # initialize in case the loop doesn't run.
    for i in range(start + 1, len(s)):
        if escaping:
            ret.append(s[i])
            escaping = False
        elif s[i] == '"':
            break
        elif s[i] == "\\":
            escaping = True
        else:
            ret.append(s[i])
    return "".join(ret), i + 1


def _read_value(s, start, delims):
    """
        Reads a value - the RHS of a token/value pair in a cookie.

        special: If the value is special, commas are premitted. Else comma
        terminates. This helps us support old and new style values.
    """
    if start >= len(s):
        return "", start
    elif s[start] == '"':
        return _read_quoted_string(s, start)
    else:
        return _read_until(s, start, delims)


def _read_pairs(s, off=0):
    """
        Read pairs of lhs=rhs values.

        off: start offset
        specials: a lower-cased list of keys that may contain commas
    """
    vals = []
    while True:
        lhs, off = _read_token(s, off)
        lhs = lhs.lstrip()
        if lhs:
            rhs = None
            if off < len(s):
                if s[off] == "=":
                    rhs, off = _read_value(s, off + 1, ";")
            vals.append([lhs, rhs])
        off += 1
        if not off < len(s):
            break
    return vals, off


def _has_special(s):
    for i in s:
        if i in '",;\\':
            return True
        o = ord(i)
        if o < 0x21 or o > 0x7e:
            return True
    return False


ESCAPE = re.compile(r"([\"\\])")


def _format_pairs(lst, specials=(), sep="; "):
    """
        specials: A lower-cased list of keys that will not be quoted.
    """
    vals = []
    for k, v in lst:
        if v is None:
            vals.append(k)
        else:
            if k.lower() not in specials and _has_special(v):
                v = ESCAPE.sub(r"\\\1", v)
                v = '"%s"' % v
            vals.append("%s=%s" % (k, v))
    return sep.join(vals)


def _format_set_cookie_pairs(lst):
    return _format_pairs(
        lst,
        specials=("expires", "path")
    )


def _parse_set_cookie_pairs(s):
    """
        For Set-Cookie, we support multiple cookies as described in RFC2109.
        This function therefore returns a list of lists.
    """
    pairs, off_ = _read_pairs(s)
    return pairs


def parse_set_cookie_headers(headers):
    ret = []
    for header in headers:
        v = parse_set_cookie_header(header)
        if v:
            name, value, attrs = v
            ret.append((name, SetCookie(value, attrs)))
    return ret


class CookieAttrs(multidict.ImmutableMultiDict):
    @staticmethod
    def _kconv(key):
        return key.lower()

    @staticmethod
    def _reduce_values(values):
        # See the StickyCookieTest for a weird cookie that only makes sense
        # if we take the last part.
        return values[-1]


SetCookie = collections.namedtuple("SetCookie", ["value", "attrs"])


def parse_set_cookie_header(line):
    """
        Parse a Set-Cookie header value

        Returns a (name, value, attrs) tuple, or None, where attrs is an
        CookieAttrs dict of attributes. No attempt is made to parse attribute
        values - they are treated purely as strings.
    """
    pairs = _parse_set_cookie_pairs(line)
    if pairs:
        return pairs[0][0], pairs[0][1], CookieAttrs(tuple(x) for x in pairs[1:])


def format_set_cookie_header(name, value, attrs):
    """
        Formats a Set-Cookie header value.
    """
    pairs = [(name, value)]
    pairs.extend(
        attrs.fields if hasattr(attrs, "fields") else attrs
    )
    return _format_set_cookie_pairs(pairs)


def parse_cookie_headers(cookie_headers):
    cookie_list = []
    for header in cookie_headers:
        cookie_list.extend(parse_cookie_header(header))
    return cookie_list


def parse_cookie_header(line):
    """
        Parse a Cookie header value.
        Returns a list of (lhs, rhs) tuples.
    """
    pairs, off_ = _read_pairs(line)
    return pairs


def format_cookie_header(lst):
    """
        Formats a Cookie header value.
    """
    return _format_pairs(lst)


def refresh_set_cookie_header(c, delta):
    """
    Args:
        c: A Set-Cookie string
        delta: Time delta in seconds
    Returns:
        A refreshed Set-Cookie string
    """

    name, value, attrs = parse_set_cookie_header(c)
    if not name or not value:
        raise ValueError("Invalid Cookie")

    if "expires" in attrs:
        e = email.utils.parsedate_tz(attrs["expires"])
        if e:
            f = email.utils.mktime_tz(e) + delta
            attrs = attrs.with_set_all("expires", [email.utils.formatdate(f)])
        else:
            # This can happen when the expires tag is invalid.
            # reddit.com sends a an expires tag like this: "Thu, 31 Dec
            # 2037 23:59:59 GMT", which is valid RFC 1123, but not
            # strictly correct according to the cookie spec. Browsers
            # appear to parse this tolerantly - maybe we should too.
            # For now, we just ignore this.
            attrs = attrs.with_delitem("expires")

    ret = format_set_cookie_header(name, value, attrs)
    if not ret:
        raise ValueError("Invalid Cookie")
    return ret


def get_expiration_ts(cookie_attrs):
    """
        Determines the time when the cookie will be expired.

        Considering both 'expires' and 'max-age' parameters.

        Returns: timestamp of when the cookie will expire.
                 None, if no expiration time is set.
    """
    if 'expires' in cookie_attrs:
        e = email.utils.parsedate_tz(cookie_attrs["expires"])
        if e:
            return email.utils.mktime_tz(e)

    elif 'max-age' in cookie_attrs:
        try:
            max_age = int(cookie_attrs['Max-Age'])
        except ValueError:
            pass
        else:
            now_ts = time.time()
            return now_ts + max_age

    return None


def is_expired(cookie_attrs):
    """
        Determines whether a cookie has expired.

        Returns: boolean
    """

    exp_ts = get_expiration_ts(cookie_attrs)
    now_ts = time.time()

    # If no expiration information was provided with the cookie
    if exp_ts is None:
        return False
    else:
        return exp_ts <= now_ts


def group_cookies(pairs):
    """
    Converts a list of pairs to a (name, value, attrs) for each cookie.
    """

    if not pairs:
        return []

    cookie_list = []

    # First pair is always a new cookie
    name, value = pairs[0]
    attrs = []

    for k, v in pairs[1:]:
        if k.lower() in _cookie_params:
            attrs.append((k, v))
        else:
            cookie_list.append((name, value, CookieAttrs(attrs)))
            name, value, attrs = k, v, []

    cookie_list.append((name, value, CookieAttrs(attrs)))
    return cookie_list