repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_bracketed_uri_scheme | def _parse_bracketed_uri_scheme(self):
"""Parse the URI scheme of a bracket-enclosed external link."""
self._push(contexts.EXT_LINK_URI)
if self._read() == self._read(1) == "/":
self._emit_text("//")
self._head += 2
else:
valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-"
all_valid = lambda: all(char in valid for char in self._read())
scheme = ""
while self._read() is not self.END and all_valid():
scheme += self._read()
self._emit_text(self._read())
self._head += 1
if self._read() != ":":
self._fail_route()
self._emit_text(":")
self._head += 1
slashes = self._read() == self._read(1) == "/"
if slashes:
self._emit_text("//")
self._head += 2
if not is_scheme(scheme, slashes):
self._fail_route() | python | def _parse_bracketed_uri_scheme(self):
"""Parse the URI scheme of a bracket-enclosed external link."""
self._push(contexts.EXT_LINK_URI)
if self._read() == self._read(1) == "/":
self._emit_text("//")
self._head += 2
else:
valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-"
all_valid = lambda: all(char in valid for char in self._read())
scheme = ""
while self._read() is not self.END and all_valid():
scheme += self._read()
self._emit_text(self._read())
self._head += 1
if self._read() != ":":
self._fail_route()
self._emit_text(":")
self._head += 1
slashes = self._read() == self._read(1) == "/"
if slashes:
self._emit_text("//")
self._head += 2
if not is_scheme(scheme, slashes):
self._fail_route() | [
"def",
"_parse_bracketed_uri_scheme",
"(",
"self",
")",
":",
"self",
".",
"_push",
"(",
"contexts",
".",
"EXT_LINK_URI",
")",
"if",
"self",
".",
"_read",
"(",
")",
"==",
"self",
".",
"_read",
"(",
"1",
")",
"==",
"\"/\"",
":",
"self",
".",
"_emit_text",
"(",
"\"//\"",
")",
"self",
".",
"_head",
"+=",
"2",
"else",
":",
"valid",
"=",
"\"abcdefghijklmnopqrstuvwxyz0123456789+.-\"",
"all_valid",
"=",
"lambda",
":",
"all",
"(",
"char",
"in",
"valid",
"for",
"char",
"in",
"self",
".",
"_read",
"(",
")",
")",
"scheme",
"=",
"\"\"",
"while",
"self",
".",
"_read",
"(",
")",
"is",
"not",
"self",
".",
"END",
"and",
"all_valid",
"(",
")",
":",
"scheme",
"+=",
"self",
".",
"_read",
"(",
")",
"self",
".",
"_emit_text",
"(",
"self",
".",
"_read",
"(",
")",
")",
"self",
".",
"_head",
"+=",
"1",
"if",
"self",
".",
"_read",
"(",
")",
"!=",
"\":\"",
":",
"self",
".",
"_fail_route",
"(",
")",
"self",
".",
"_emit_text",
"(",
"\":\"",
")",
"self",
".",
"_head",
"+=",
"1",
"slashes",
"=",
"self",
".",
"_read",
"(",
")",
"==",
"self",
".",
"_read",
"(",
"1",
")",
"==",
"\"/\"",
"if",
"slashes",
":",
"self",
".",
"_emit_text",
"(",
"\"//\"",
")",
"self",
".",
"_head",
"+=",
"2",
"if",
"not",
"is_scheme",
"(",
"scheme",
",",
"slashes",
")",
":",
"self",
".",
"_fail_route",
"(",
")"
]
| Parse the URI scheme of a bracket-enclosed external link. | [
"Parse",
"the",
"URI",
"scheme",
"of",
"a",
"bracket",
"-",
"enclosed",
"external",
"link",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L364-L387 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_free_link_text | def _handle_free_link_text(self, punct, tail, this):
"""Handle text in a free ext link, including trailing punctuation."""
if "(" in this and ")" in punct:
punct = punct[:-1] # ')' is not longer valid punctuation
if this.endswith(punct):
for i in range(len(this) - 1, 0, -1):
if this[i - 1] not in punct:
break
else:
i = 0
stripped = this[:i]
if stripped and tail:
self._emit_text(tail)
tail = ""
tail += this[i:]
this = stripped
elif tail:
self._emit_text(tail)
tail = ""
self._emit_text(this)
return punct, tail | python | def _handle_free_link_text(self, punct, tail, this):
"""Handle text in a free ext link, including trailing punctuation."""
if "(" in this and ")" in punct:
punct = punct[:-1] # ')' is not longer valid punctuation
if this.endswith(punct):
for i in range(len(this) - 1, 0, -1):
if this[i - 1] not in punct:
break
else:
i = 0
stripped = this[:i]
if stripped and tail:
self._emit_text(tail)
tail = ""
tail += this[i:]
this = stripped
elif tail:
self._emit_text(tail)
tail = ""
self._emit_text(this)
return punct, tail | [
"def",
"_handle_free_link_text",
"(",
"self",
",",
"punct",
",",
"tail",
",",
"this",
")",
":",
"if",
"\"(\"",
"in",
"this",
"and",
"\")\"",
"in",
"punct",
":",
"punct",
"=",
"punct",
"[",
":",
"-",
"1",
"]",
"# ')' is not longer valid punctuation",
"if",
"this",
".",
"endswith",
"(",
"punct",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"this",
")",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"if",
"this",
"[",
"i",
"-",
"1",
"]",
"not",
"in",
"punct",
":",
"break",
"else",
":",
"i",
"=",
"0",
"stripped",
"=",
"this",
"[",
":",
"i",
"]",
"if",
"stripped",
"and",
"tail",
":",
"self",
".",
"_emit_text",
"(",
"tail",
")",
"tail",
"=",
"\"\"",
"tail",
"+=",
"this",
"[",
"i",
":",
"]",
"this",
"=",
"stripped",
"elif",
"tail",
":",
"self",
".",
"_emit_text",
"(",
"tail",
")",
"tail",
"=",
"\"\"",
"self",
".",
"_emit_text",
"(",
"this",
")",
"return",
"punct",
",",
"tail"
]
| Handle text in a free ext link, including trailing punctuation. | [
"Handle",
"text",
"in",
"a",
"free",
"ext",
"link",
"including",
"trailing",
"punctuation",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L416-L436 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._is_free_link_end | def _is_free_link_end(self, this, next):
"""Return whether the current head is the end of a free link."""
# Built from _parse()'s end sentinels:
after, ctx = self._read(2), self._context
equal_sign_contexts = contexts.TEMPLATE_PARAM_KEY | contexts.HEADING
return (this in (self.END, "\n", "[", "]", "<", ">") or
this == next == "'" or
(this == "|" and ctx & contexts.TEMPLATE) or
(this == "=" and ctx & equal_sign_contexts) or
(this == next == "}" and ctx & contexts.TEMPLATE) or
(this == next == after == "}" and ctx & contexts.ARGUMENT)) | python | def _is_free_link_end(self, this, next):
"""Return whether the current head is the end of a free link."""
# Built from _parse()'s end sentinels:
after, ctx = self._read(2), self._context
equal_sign_contexts = contexts.TEMPLATE_PARAM_KEY | contexts.HEADING
return (this in (self.END, "\n", "[", "]", "<", ">") or
this == next == "'" or
(this == "|" and ctx & contexts.TEMPLATE) or
(this == "=" and ctx & equal_sign_contexts) or
(this == next == "}" and ctx & contexts.TEMPLATE) or
(this == next == after == "}" and ctx & contexts.ARGUMENT)) | [
"def",
"_is_free_link_end",
"(",
"self",
",",
"this",
",",
"next",
")",
":",
"# Built from _parse()'s end sentinels:",
"after",
",",
"ctx",
"=",
"self",
".",
"_read",
"(",
"2",
")",
",",
"self",
".",
"_context",
"equal_sign_contexts",
"=",
"contexts",
".",
"TEMPLATE_PARAM_KEY",
"|",
"contexts",
".",
"HEADING",
"return",
"(",
"this",
"in",
"(",
"self",
".",
"END",
",",
"\"\\n\"",
",",
"\"[\"",
",",
"\"]\"",
",",
"\"<\"",
",",
"\">\"",
")",
"or",
"this",
"==",
"next",
"==",
"\"'\"",
"or",
"(",
"this",
"==",
"\"|\"",
"and",
"ctx",
"&",
"contexts",
".",
"TEMPLATE",
")",
"or",
"(",
"this",
"==",
"\"=\"",
"and",
"ctx",
"&",
"equal_sign_contexts",
")",
"or",
"(",
"this",
"==",
"next",
"==",
"\"}\"",
"and",
"ctx",
"&",
"contexts",
".",
"TEMPLATE",
")",
"or",
"(",
"this",
"==",
"next",
"==",
"after",
"==",
"\"}\"",
"and",
"ctx",
"&",
"contexts",
".",
"ARGUMENT",
")",
")"
]
| Return whether the current head is the end of a free link. | [
"Return",
"whether",
"the",
"current",
"head",
"is",
"the",
"end",
"of",
"a",
"free",
"link",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L438-L448 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._really_parse_external_link | def _really_parse_external_link(self, brackets):
"""Really parse an external link."""
if brackets:
self._parse_bracketed_uri_scheme()
invalid = ("\n", " ", "]")
else:
self._parse_free_uri_scheme()
invalid = ("\n", " ", "[", "]")
punct = tuple(",;\\.:!?)")
if self._read() is self.END or self._read()[0] in invalid:
self._fail_route()
tail = ""
while True:
this, next = self._read(), self._read(1)
if this == "&":
if tail:
self._emit_text(tail)
tail = ""
self._parse_entity()
elif (this == "<" and next == "!" and self._read(2) ==
self._read(3) == "-"):
if tail:
self._emit_text(tail)
tail = ""
self._parse_comment()
elif not brackets and self._is_free_link_end(this, next):
return self._pop(), tail, -1
elif this is self.END or this == "\n":
self._fail_route()
elif this == next == "{" and self._can_recurse():
if tail:
self._emit_text(tail)
tail = ""
self._parse_template_or_argument()
elif this == "]":
return self._pop(), tail, 0
elif " " in this:
before, after = this.split(" ", 1)
if brackets:
self._emit_text(before)
self._emit(tokens.ExternalLinkSeparator())
if after:
self._emit_text(after)
self._context ^= contexts.EXT_LINK_URI
self._context |= contexts.EXT_LINK_TITLE
self._head += 1
return self._parse(push=False), None, 0
punct, tail = self._handle_free_link_text(punct, tail, before)
return self._pop(), tail + " " + after, 0
elif not brackets:
punct, tail = self._handle_free_link_text(punct, tail, this)
else:
self._emit_text(this)
self._head += 1 | python | def _really_parse_external_link(self, brackets):
"""Really parse an external link."""
if brackets:
self._parse_bracketed_uri_scheme()
invalid = ("\n", " ", "]")
else:
self._parse_free_uri_scheme()
invalid = ("\n", " ", "[", "]")
punct = tuple(",;\\.:!?)")
if self._read() is self.END or self._read()[0] in invalid:
self._fail_route()
tail = ""
while True:
this, next = self._read(), self._read(1)
if this == "&":
if tail:
self._emit_text(tail)
tail = ""
self._parse_entity()
elif (this == "<" and next == "!" and self._read(2) ==
self._read(3) == "-"):
if tail:
self._emit_text(tail)
tail = ""
self._parse_comment()
elif not brackets and self._is_free_link_end(this, next):
return self._pop(), tail, -1
elif this is self.END or this == "\n":
self._fail_route()
elif this == next == "{" and self._can_recurse():
if tail:
self._emit_text(tail)
tail = ""
self._parse_template_or_argument()
elif this == "]":
return self._pop(), tail, 0
elif " " in this:
before, after = this.split(" ", 1)
if brackets:
self._emit_text(before)
self._emit(tokens.ExternalLinkSeparator())
if after:
self._emit_text(after)
self._context ^= contexts.EXT_LINK_URI
self._context |= contexts.EXT_LINK_TITLE
self._head += 1
return self._parse(push=False), None, 0
punct, tail = self._handle_free_link_text(punct, tail, before)
return self._pop(), tail + " " + after, 0
elif not brackets:
punct, tail = self._handle_free_link_text(punct, tail, this)
else:
self._emit_text(this)
self._head += 1 | [
"def",
"_really_parse_external_link",
"(",
"self",
",",
"brackets",
")",
":",
"if",
"brackets",
":",
"self",
".",
"_parse_bracketed_uri_scheme",
"(",
")",
"invalid",
"=",
"(",
"\"\\n\"",
",",
"\" \"",
",",
"\"]\"",
")",
"else",
":",
"self",
".",
"_parse_free_uri_scheme",
"(",
")",
"invalid",
"=",
"(",
"\"\\n\"",
",",
"\" \"",
",",
"\"[\"",
",",
"\"]\"",
")",
"punct",
"=",
"tuple",
"(",
"\",;\\\\.:!?)\"",
")",
"if",
"self",
".",
"_read",
"(",
")",
"is",
"self",
".",
"END",
"or",
"self",
".",
"_read",
"(",
")",
"[",
"0",
"]",
"in",
"invalid",
":",
"self",
".",
"_fail_route",
"(",
")",
"tail",
"=",
"\"\"",
"while",
"True",
":",
"this",
",",
"next",
"=",
"self",
".",
"_read",
"(",
")",
",",
"self",
".",
"_read",
"(",
"1",
")",
"if",
"this",
"==",
"\"&\"",
":",
"if",
"tail",
":",
"self",
".",
"_emit_text",
"(",
"tail",
")",
"tail",
"=",
"\"\"",
"self",
".",
"_parse_entity",
"(",
")",
"elif",
"(",
"this",
"==",
"\"<\"",
"and",
"next",
"==",
"\"!\"",
"and",
"self",
".",
"_read",
"(",
"2",
")",
"==",
"self",
".",
"_read",
"(",
"3",
")",
"==",
"\"-\"",
")",
":",
"if",
"tail",
":",
"self",
".",
"_emit_text",
"(",
"tail",
")",
"tail",
"=",
"\"\"",
"self",
".",
"_parse_comment",
"(",
")",
"elif",
"not",
"brackets",
"and",
"self",
".",
"_is_free_link_end",
"(",
"this",
",",
"next",
")",
":",
"return",
"self",
".",
"_pop",
"(",
")",
",",
"tail",
",",
"-",
"1",
"elif",
"this",
"is",
"self",
".",
"END",
"or",
"this",
"==",
"\"\\n\"",
":",
"self",
".",
"_fail_route",
"(",
")",
"elif",
"this",
"==",
"next",
"==",
"\"{\"",
"and",
"self",
".",
"_can_recurse",
"(",
")",
":",
"if",
"tail",
":",
"self",
".",
"_emit_text",
"(",
"tail",
")",
"tail",
"=",
"\"\"",
"self",
".",
"_parse_template_or_argument",
"(",
")",
"elif",
"this",
"==",
"\"]\"",
":",
"return",
"self",
".",
"_pop",
"(",
")",
",",
"tail",
",",
"0",
"elif",
"\" \"",
"in",
"this",
":",
"before",
",",
"after",
"=",
"this",
".",
"split",
"(",
"\" \"",
",",
"1",
")",
"if",
"brackets",
":",
"self",
".",
"_emit_text",
"(",
"before",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ExternalLinkSeparator",
"(",
")",
")",
"if",
"after",
":",
"self",
".",
"_emit_text",
"(",
"after",
")",
"self",
".",
"_context",
"^=",
"contexts",
".",
"EXT_LINK_URI",
"self",
".",
"_context",
"|=",
"contexts",
".",
"EXT_LINK_TITLE",
"self",
".",
"_head",
"+=",
"1",
"return",
"self",
".",
"_parse",
"(",
"push",
"=",
"False",
")",
",",
"None",
",",
"0",
"punct",
",",
"tail",
"=",
"self",
".",
"_handle_free_link_text",
"(",
"punct",
",",
"tail",
",",
"before",
")",
"return",
"self",
".",
"_pop",
"(",
")",
",",
"tail",
"+",
"\" \"",
"+",
"after",
",",
"0",
"elif",
"not",
"brackets",
":",
"punct",
",",
"tail",
"=",
"self",
".",
"_handle_free_link_text",
"(",
"punct",
",",
"tail",
",",
"this",
")",
"else",
":",
"self",
".",
"_emit_text",
"(",
"this",
")",
"self",
".",
"_head",
"+=",
"1"
]
| Really parse an external link. | [
"Really",
"parse",
"an",
"external",
"link",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L450-L503 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._remove_uri_scheme_from_textbuffer | def _remove_uri_scheme_from_textbuffer(self, scheme):
"""Remove the URI scheme of a new external link from the textbuffer."""
length = len(scheme)
while length:
if length < len(self._textbuffer[-1]):
self._textbuffer[-1] = self._textbuffer[-1][:-length]
break
length -= len(self._textbuffer[-1])
self._textbuffer.pop() | python | def _remove_uri_scheme_from_textbuffer(self, scheme):
"""Remove the URI scheme of a new external link from the textbuffer."""
length = len(scheme)
while length:
if length < len(self._textbuffer[-1]):
self._textbuffer[-1] = self._textbuffer[-1][:-length]
break
length -= len(self._textbuffer[-1])
self._textbuffer.pop() | [
"def",
"_remove_uri_scheme_from_textbuffer",
"(",
"self",
",",
"scheme",
")",
":",
"length",
"=",
"len",
"(",
"scheme",
")",
"while",
"length",
":",
"if",
"length",
"<",
"len",
"(",
"self",
".",
"_textbuffer",
"[",
"-",
"1",
"]",
")",
":",
"self",
".",
"_textbuffer",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"_textbuffer",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"length",
"]",
"break",
"length",
"-=",
"len",
"(",
"self",
".",
"_textbuffer",
"[",
"-",
"1",
"]",
")",
"self",
".",
"_textbuffer",
".",
"pop",
"(",
")"
]
| Remove the URI scheme of a new external link from the textbuffer. | [
"Remove",
"the",
"URI",
"scheme",
"of",
"a",
"new",
"external",
"link",
"from",
"the",
"textbuffer",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L505-L513 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_external_link | def _parse_external_link(self, brackets):
"""Parse an external link at the head of the wikicode string."""
if self._context & contexts.NO_EXT_LINKS or not self._can_recurse():
if not brackets and self._context & contexts.DL_TERM:
self._handle_dl_term()
else:
self._emit_text(self._read())
return
reset = self._head
self._head += 1
try:
link, extra, delta = self._really_parse_external_link(brackets)
except BadRoute:
self._head = reset
if not brackets and self._context & contexts.DL_TERM:
self._handle_dl_term()
else:
self._emit_text(self._read())
else:
if not brackets:
scheme = link[0].text.split(":", 1)[0]
self._remove_uri_scheme_from_textbuffer(scheme)
self._emit(tokens.ExternalLinkOpen(brackets=brackets))
self._emit_all(link)
self._emit(tokens.ExternalLinkClose())
self._head += delta
if extra:
self._emit_text(extra) | python | def _parse_external_link(self, brackets):
"""Parse an external link at the head of the wikicode string."""
if self._context & contexts.NO_EXT_LINKS or not self._can_recurse():
if not brackets and self._context & contexts.DL_TERM:
self._handle_dl_term()
else:
self._emit_text(self._read())
return
reset = self._head
self._head += 1
try:
link, extra, delta = self._really_parse_external_link(brackets)
except BadRoute:
self._head = reset
if not brackets and self._context & contexts.DL_TERM:
self._handle_dl_term()
else:
self._emit_text(self._read())
else:
if not brackets:
scheme = link[0].text.split(":", 1)[0]
self._remove_uri_scheme_from_textbuffer(scheme)
self._emit(tokens.ExternalLinkOpen(brackets=brackets))
self._emit_all(link)
self._emit(tokens.ExternalLinkClose())
self._head += delta
if extra:
self._emit_text(extra) | [
"def",
"_parse_external_link",
"(",
"self",
",",
"brackets",
")",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"NO_EXT_LINKS",
"or",
"not",
"self",
".",
"_can_recurse",
"(",
")",
":",
"if",
"not",
"brackets",
"and",
"self",
".",
"_context",
"&",
"contexts",
".",
"DL_TERM",
":",
"self",
".",
"_handle_dl_term",
"(",
")",
"else",
":",
"self",
".",
"_emit_text",
"(",
"self",
".",
"_read",
"(",
")",
")",
"return",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"1",
"try",
":",
"link",
",",
"extra",
",",
"delta",
"=",
"self",
".",
"_really_parse_external_link",
"(",
"brackets",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"if",
"not",
"brackets",
"and",
"self",
".",
"_context",
"&",
"contexts",
".",
"DL_TERM",
":",
"self",
".",
"_handle_dl_term",
"(",
")",
"else",
":",
"self",
".",
"_emit_text",
"(",
"self",
".",
"_read",
"(",
")",
")",
"else",
":",
"if",
"not",
"brackets",
":",
"scheme",
"=",
"link",
"[",
"0",
"]",
".",
"text",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"[",
"0",
"]",
"self",
".",
"_remove_uri_scheme_from_textbuffer",
"(",
"scheme",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ExternalLinkOpen",
"(",
"brackets",
"=",
"brackets",
")",
")",
"self",
".",
"_emit_all",
"(",
"link",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ExternalLinkClose",
"(",
")",
")",
"self",
".",
"_head",
"+=",
"delta",
"if",
"extra",
":",
"self",
".",
"_emit_text",
"(",
"extra",
")"
]
| Parse an external link at the head of the wikicode string. | [
"Parse",
"an",
"external",
"link",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L515-L543 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_heading | def _parse_heading(self):
"""Parse a section heading at the head of the wikicode string."""
self._global |= contexts.GL_HEADING
reset = self._head
self._head += 1
best = 1
while self._read() == "=":
best += 1
self._head += 1
context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
try:
title, level = self._parse(context)
except BadRoute:
self._head = reset + best - 1
self._emit_text("=" * best)
else:
self._emit(tokens.HeadingStart(level=level))
if level < best:
self._emit_text("=" * (best - level))
self._emit_all(title)
self._emit(tokens.HeadingEnd())
finally:
self._global ^= contexts.GL_HEADING | python | def _parse_heading(self):
"""Parse a section heading at the head of the wikicode string."""
self._global |= contexts.GL_HEADING
reset = self._head
self._head += 1
best = 1
while self._read() == "=":
best += 1
self._head += 1
context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
try:
title, level = self._parse(context)
except BadRoute:
self._head = reset + best - 1
self._emit_text("=" * best)
else:
self._emit(tokens.HeadingStart(level=level))
if level < best:
self._emit_text("=" * (best - level))
self._emit_all(title)
self._emit(tokens.HeadingEnd())
finally:
self._global ^= contexts.GL_HEADING | [
"def",
"_parse_heading",
"(",
"self",
")",
":",
"self",
".",
"_global",
"|=",
"contexts",
".",
"GL_HEADING",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"1",
"best",
"=",
"1",
"while",
"self",
".",
"_read",
"(",
")",
"==",
"\"=\"",
":",
"best",
"+=",
"1",
"self",
".",
"_head",
"+=",
"1",
"context",
"=",
"contexts",
".",
"HEADING_LEVEL_1",
"<<",
"min",
"(",
"best",
"-",
"1",
",",
"5",
")",
"try",
":",
"title",
",",
"level",
"=",
"self",
".",
"_parse",
"(",
"context",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"+",
"best",
"-",
"1",
"self",
".",
"_emit_text",
"(",
"\"=\"",
"*",
"best",
")",
"else",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"HeadingStart",
"(",
"level",
"=",
"level",
")",
")",
"if",
"level",
"<",
"best",
":",
"self",
".",
"_emit_text",
"(",
"\"=\"",
"*",
"(",
"best",
"-",
"level",
")",
")",
"self",
".",
"_emit_all",
"(",
"title",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"HeadingEnd",
"(",
")",
")",
"finally",
":",
"self",
".",
"_global",
"^=",
"contexts",
".",
"GL_HEADING"
]
| Parse a section heading at the head of the wikicode string. | [
"Parse",
"a",
"section",
"heading",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L545-L568 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_heading_end | def _handle_heading_end(self):
"""Handle the end of a section heading at the head of the string."""
reset = self._head
self._head += 1
best = 1
while self._read() == "=":
best += 1
self._head += 1
current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
level = min(current, min(best, 6))
try: # Try to check for a heading closure after this one
after, after_level = self._parse(self._context)
except BadRoute:
if level < best:
self._emit_text("=" * (best - level))
self._head = reset + best - 1
return self._pop(), level
else: # Found another closure
self._emit_text("=" * best)
self._emit_all(after)
return self._pop(), after_level | python | def _handle_heading_end(self):
"""Handle the end of a section heading at the head of the string."""
reset = self._head
self._head += 1
best = 1
while self._read() == "=":
best += 1
self._head += 1
current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
level = min(current, min(best, 6))
try: # Try to check for a heading closure after this one
after, after_level = self._parse(self._context)
except BadRoute:
if level < best:
self._emit_text("=" * (best - level))
self._head = reset + best - 1
return self._pop(), level
else: # Found another closure
self._emit_text("=" * best)
self._emit_all(after)
return self._pop(), after_level | [
"def",
"_handle_heading_end",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"1",
"best",
"=",
"1",
"while",
"self",
".",
"_read",
"(",
")",
"==",
"\"=\"",
":",
"best",
"+=",
"1",
"self",
".",
"_head",
"+=",
"1",
"current",
"=",
"int",
"(",
"log",
"(",
"self",
".",
"_context",
"/",
"contexts",
".",
"HEADING_LEVEL_1",
",",
"2",
")",
")",
"+",
"1",
"level",
"=",
"min",
"(",
"current",
",",
"min",
"(",
"best",
",",
"6",
")",
")",
"try",
":",
"# Try to check for a heading closure after this one",
"after",
",",
"after_level",
"=",
"self",
".",
"_parse",
"(",
"self",
".",
"_context",
")",
"except",
"BadRoute",
":",
"if",
"level",
"<",
"best",
":",
"self",
".",
"_emit_text",
"(",
"\"=\"",
"*",
"(",
"best",
"-",
"level",
")",
")",
"self",
".",
"_head",
"=",
"reset",
"+",
"best",
"-",
"1",
"return",
"self",
".",
"_pop",
"(",
")",
",",
"level",
"else",
":",
"# Found another closure",
"self",
".",
"_emit_text",
"(",
"\"=\"",
"*",
"best",
")",
"self",
".",
"_emit_all",
"(",
"after",
")",
"return",
"self",
".",
"_pop",
"(",
")",
",",
"after_level"
]
| Handle the end of a section heading at the head of the string. | [
"Handle",
"the",
"end",
"of",
"a",
"section",
"heading",
"at",
"the",
"head",
"of",
"the",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L570-L591 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._really_parse_entity | def _really_parse_entity(self):
"""Actually parse an HTML entity and ensure that it is valid."""
self._emit(tokens.HTMLEntityStart())
self._head += 1
this = self._read(strict=True)
if this == "#":
numeric = True
self._emit(tokens.HTMLEntityNumeric())
self._head += 1
this = self._read(strict=True)
if this[0].lower() == "x":
hexadecimal = True
self._emit(tokens.HTMLEntityHex(char=this[0]))
this = this[1:]
if not this:
self._fail_route()
else:
hexadecimal = False
else:
numeric = hexadecimal = False
valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
if not numeric and not hexadecimal:
valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if not all([char in valid for char in this]):
self._fail_route()
self._head += 1
if self._read() != ";":
self._fail_route()
if numeric:
test = int(this, 16) if hexadecimal else int(this)
if test < 1 or test > 0x10FFFF:
self._fail_route()
else:
if this not in htmlentities.entitydefs:
self._fail_route()
self._emit(tokens.Text(text=this))
self._emit(tokens.HTMLEntityEnd()) | python | def _really_parse_entity(self):
"""Actually parse an HTML entity and ensure that it is valid."""
self._emit(tokens.HTMLEntityStart())
self._head += 1
this = self._read(strict=True)
if this == "#":
numeric = True
self._emit(tokens.HTMLEntityNumeric())
self._head += 1
this = self._read(strict=True)
if this[0].lower() == "x":
hexadecimal = True
self._emit(tokens.HTMLEntityHex(char=this[0]))
this = this[1:]
if not this:
self._fail_route()
else:
hexadecimal = False
else:
numeric = hexadecimal = False
valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
if not numeric and not hexadecimal:
valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if not all([char in valid for char in this]):
self._fail_route()
self._head += 1
if self._read() != ";":
self._fail_route()
if numeric:
test = int(this, 16) if hexadecimal else int(this)
if test < 1 or test > 0x10FFFF:
self._fail_route()
else:
if this not in htmlentities.entitydefs:
self._fail_route()
self._emit(tokens.Text(text=this))
self._emit(tokens.HTMLEntityEnd()) | [
"def",
"_really_parse_entity",
"(",
"self",
")",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"HTMLEntityStart",
"(",
")",
")",
"self",
".",
"_head",
"+=",
"1",
"this",
"=",
"self",
".",
"_read",
"(",
"strict",
"=",
"True",
")",
"if",
"this",
"==",
"\"#\"",
":",
"numeric",
"=",
"True",
"self",
".",
"_emit",
"(",
"tokens",
".",
"HTMLEntityNumeric",
"(",
")",
")",
"self",
".",
"_head",
"+=",
"1",
"this",
"=",
"self",
".",
"_read",
"(",
"strict",
"=",
"True",
")",
"if",
"this",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"\"x\"",
":",
"hexadecimal",
"=",
"True",
"self",
".",
"_emit",
"(",
"tokens",
".",
"HTMLEntityHex",
"(",
"char",
"=",
"this",
"[",
"0",
"]",
")",
")",
"this",
"=",
"this",
"[",
"1",
":",
"]",
"if",
"not",
"this",
":",
"self",
".",
"_fail_route",
"(",
")",
"else",
":",
"hexadecimal",
"=",
"False",
"else",
":",
"numeric",
"=",
"hexadecimal",
"=",
"False",
"valid",
"=",
"\"0123456789abcdefABCDEF\"",
"if",
"hexadecimal",
"else",
"\"0123456789\"",
"if",
"not",
"numeric",
"and",
"not",
"hexadecimal",
":",
"valid",
"+=",
"\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"if",
"not",
"all",
"(",
"[",
"char",
"in",
"valid",
"for",
"char",
"in",
"this",
"]",
")",
":",
"self",
".",
"_fail_route",
"(",
")",
"self",
".",
"_head",
"+=",
"1",
"if",
"self",
".",
"_read",
"(",
")",
"!=",
"\";\"",
":",
"self",
".",
"_fail_route",
"(",
")",
"if",
"numeric",
":",
"test",
"=",
"int",
"(",
"this",
",",
"16",
")",
"if",
"hexadecimal",
"else",
"int",
"(",
"this",
")",
"if",
"test",
"<",
"1",
"or",
"test",
">",
"0x10FFFF",
":",
"self",
".",
"_fail_route",
"(",
")",
"else",
":",
"if",
"this",
"not",
"in",
"htmlentities",
".",
"entitydefs",
":",
"self",
".",
"_fail_route",
"(",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"Text",
"(",
"text",
"=",
"this",
")",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"HTMLEntityEnd",
"(",
")",
")"
]
| Actually parse an HTML entity and ensure that it is valid. | [
"Actually",
"parse",
"an",
"HTML",
"entity",
"and",
"ensure",
"that",
"it",
"is",
"valid",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L593-L633 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_entity | def _parse_entity(self):
"""Parse an HTML entity at the head of the wikicode string."""
reset = self._head
try:
self._push(contexts.HTML_ENTITY)
self._really_parse_entity()
except BadRoute:
self._head = reset
self._emit_text(self._read())
else:
self._emit_all(self._pop()) | python | def _parse_entity(self):
"""Parse an HTML entity at the head of the wikicode string."""
reset = self._head
try:
self._push(contexts.HTML_ENTITY)
self._really_parse_entity()
except BadRoute:
self._head = reset
self._emit_text(self._read())
else:
self._emit_all(self._pop()) | [
"def",
"_parse_entity",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"try",
":",
"self",
".",
"_push",
"(",
"contexts",
".",
"HTML_ENTITY",
")",
"self",
".",
"_really_parse_entity",
"(",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"self",
".",
"_read",
"(",
")",
")",
"else",
":",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")"
]
| Parse an HTML entity at the head of the wikicode string. | [
"Parse",
"an",
"HTML",
"entity",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L635-L645 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_comment | def _parse_comment(self):
"""Parse an HTML comment at the head of the wikicode string."""
self._head += 4
reset = self._head - 1
self._push()
while True:
this = self._read()
if this == self.END:
self._pop()
self._head = reset
self._emit_text("<!--")
return
if this == self._read(1) == "-" and self._read(2) == ">":
self._emit_first(tokens.CommentStart())
self._emit(tokens.CommentEnd())
self._emit_all(self._pop())
self._head += 2
if self._context & contexts.FAIL_NEXT:
# _verify_safe() sets this flag while parsing a template
# or link when it encounters what might be a comment -- we
# must unset it to let _verify_safe() know it was correct:
self._context ^= contexts.FAIL_NEXT
return
self._emit_text(this)
self._head += 1 | python | def _parse_comment(self):
"""Parse an HTML comment at the head of the wikicode string."""
self._head += 4
reset = self._head - 1
self._push()
while True:
this = self._read()
if this == self.END:
self._pop()
self._head = reset
self._emit_text("<!--")
return
if this == self._read(1) == "-" and self._read(2) == ">":
self._emit_first(tokens.CommentStart())
self._emit(tokens.CommentEnd())
self._emit_all(self._pop())
self._head += 2
if self._context & contexts.FAIL_NEXT:
# _verify_safe() sets this flag while parsing a template
# or link when it encounters what might be a comment -- we
# must unset it to let _verify_safe() know it was correct:
self._context ^= contexts.FAIL_NEXT
return
self._emit_text(this)
self._head += 1 | [
"def",
"_parse_comment",
"(",
"self",
")",
":",
"self",
".",
"_head",
"+=",
"4",
"reset",
"=",
"self",
".",
"_head",
"-",
"1",
"self",
".",
"_push",
"(",
")",
"while",
"True",
":",
"this",
"=",
"self",
".",
"_read",
"(",
")",
"if",
"this",
"==",
"self",
".",
"END",
":",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"\"<!--\"",
")",
"return",
"if",
"this",
"==",
"self",
".",
"_read",
"(",
"1",
")",
"==",
"\"-\"",
"and",
"self",
".",
"_read",
"(",
"2",
")",
"==",
"\">\"",
":",
"self",
".",
"_emit_first",
"(",
"tokens",
".",
"CommentStart",
"(",
")",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"CommentEnd",
"(",
")",
")",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"self",
".",
"_head",
"+=",
"2",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"FAIL_NEXT",
":",
"# _verify_safe() sets this flag while parsing a template",
"# or link when it encounters what might be a comment -- we",
"# must unset it to let _verify_safe() know it was correct:",
"self",
".",
"_context",
"^=",
"contexts",
".",
"FAIL_NEXT",
"return",
"self",
".",
"_emit_text",
"(",
"this",
")",
"self",
".",
"_head",
"+=",
"1"
]
| Parse an HTML comment at the head of the wikicode string. | [
"Parse",
"an",
"HTML",
"comment",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L647-L671 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_blacklisted_tag | def _handle_blacklisted_tag(self):
"""Handle the body of an HTML tag that is parser-blacklisted."""
strip = lambda text: text.rstrip().lower()
while True:
this, next = self._read(), self._read(1)
if this is self.END:
self._fail_route()
elif this == "<" and next == "/":
self._head += 3
if self._read() != ">" or (strip(self._read(-1)) !=
strip(self._stack[1].text)):
self._head -= 1
self._emit_text("</")
continue
self._emit(tokens.TagOpenClose())
self._emit_text(self._read(-1))
self._emit(tokens.TagCloseClose())
return self._pop()
elif this == "&":
self._parse_entity()
else:
self._emit_text(this)
self._head += 1 | python | def _handle_blacklisted_tag(self):
"""Handle the body of an HTML tag that is parser-blacklisted."""
strip = lambda text: text.rstrip().lower()
while True:
this, next = self._read(), self._read(1)
if this is self.END:
self._fail_route()
elif this == "<" and next == "/":
self._head += 3
if self._read() != ">" or (strip(self._read(-1)) !=
strip(self._stack[1].text)):
self._head -= 1
self._emit_text("</")
continue
self._emit(tokens.TagOpenClose())
self._emit_text(self._read(-1))
self._emit(tokens.TagCloseClose())
return self._pop()
elif this == "&":
self._parse_entity()
else:
self._emit_text(this)
self._head += 1 | [
"def",
"_handle_blacklisted_tag",
"(",
"self",
")",
":",
"strip",
"=",
"lambda",
"text",
":",
"text",
".",
"rstrip",
"(",
")",
".",
"lower",
"(",
")",
"while",
"True",
":",
"this",
",",
"next",
"=",
"self",
".",
"_read",
"(",
")",
",",
"self",
".",
"_read",
"(",
"1",
")",
"if",
"this",
"is",
"self",
".",
"END",
":",
"self",
".",
"_fail_route",
"(",
")",
"elif",
"this",
"==",
"\"<\"",
"and",
"next",
"==",
"\"/\"",
":",
"self",
".",
"_head",
"+=",
"3",
"if",
"self",
".",
"_read",
"(",
")",
"!=",
"\">\"",
"or",
"(",
"strip",
"(",
"self",
".",
"_read",
"(",
"-",
"1",
")",
")",
"!=",
"strip",
"(",
"self",
".",
"_stack",
"[",
"1",
"]",
".",
"text",
")",
")",
":",
"self",
".",
"_head",
"-=",
"1",
"self",
".",
"_emit_text",
"(",
"\"</\"",
")",
"continue",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagOpenClose",
"(",
")",
")",
"self",
".",
"_emit_text",
"(",
"self",
".",
"_read",
"(",
"-",
"1",
")",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseClose",
"(",
")",
")",
"return",
"self",
".",
"_pop",
"(",
")",
"elif",
"this",
"==",
"\"&\"",
":",
"self",
".",
"_parse_entity",
"(",
")",
"else",
":",
"self",
".",
"_emit_text",
"(",
"this",
")",
"self",
".",
"_head",
"+=",
"1"
]
| Handle the body of an HTML tag that is parser-blacklisted. | [
"Handle",
"the",
"body",
"of",
"an",
"HTML",
"tag",
"that",
"is",
"parser",
"-",
"blacklisted",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L797-L819 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_single_only_tag_end | def _handle_single_only_tag_end(self):
"""Handle the end of an implicitly closing single-only HTML tag."""
padding = self._stack.pop().padding
self._emit(tokens.TagCloseSelfclose(padding=padding, implicit=True))
self._head -= 1 # Offset displacement done by _handle_tag_close_open
return self._pop() | python | def _handle_single_only_tag_end(self):
"""Handle the end of an implicitly closing single-only HTML tag."""
padding = self._stack.pop().padding
self._emit(tokens.TagCloseSelfclose(padding=padding, implicit=True))
self._head -= 1 # Offset displacement done by _handle_tag_close_open
return self._pop() | [
"def",
"_handle_single_only_tag_end",
"(",
"self",
")",
":",
"padding",
"=",
"self",
".",
"_stack",
".",
"pop",
"(",
")",
".",
"padding",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseSelfclose",
"(",
"padding",
"=",
"padding",
",",
"implicit",
"=",
"True",
")",
")",
"self",
".",
"_head",
"-=",
"1",
"# Offset displacement done by _handle_tag_close_open",
"return",
"self",
".",
"_pop",
"(",
")"
]
| Handle the end of an implicitly closing single-only HTML tag. | [
"Handle",
"the",
"end",
"of",
"an",
"implicitly",
"closing",
"single",
"-",
"only",
"HTML",
"tag",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L821-L826 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_single_tag_end | def _handle_single_tag_end(self):
"""Handle the stream end when inside a single-supporting HTML tag."""
stack = self._stack
# We need to find the index of the TagCloseOpen token corresponding to
# the TagOpenOpen token located at index 0:
depth = 1
for index, token in enumerate(stack[2:], 2):
if isinstance(token, tokens.TagOpenOpen):
depth += 1
elif isinstance(token, tokens.TagCloseOpen):
depth -= 1
if depth == 0:
break
elif isinstance(token, tokens.TagCloseSelfclose):
depth -= 1
if depth == 0: # pragma: no cover (untestable/exceptional)
raise ParserError(
"_handle_single_tag_end() got an unexpected "
"TagCloseSelfclose")
else: # pragma: no cover (untestable/exceptional case)
raise ParserError("_handle_single_tag_end() missed a TagCloseOpen")
padding = stack[index].padding
stack[index] = tokens.TagCloseSelfclose(padding=padding, implicit=True)
return self._pop() | python | def _handle_single_tag_end(self):
"""Handle the stream end when inside a single-supporting HTML tag."""
stack = self._stack
# We need to find the index of the TagCloseOpen token corresponding to
# the TagOpenOpen token located at index 0:
depth = 1
for index, token in enumerate(stack[2:], 2):
if isinstance(token, tokens.TagOpenOpen):
depth += 1
elif isinstance(token, tokens.TagCloseOpen):
depth -= 1
if depth == 0:
break
elif isinstance(token, tokens.TagCloseSelfclose):
depth -= 1
if depth == 0: # pragma: no cover (untestable/exceptional)
raise ParserError(
"_handle_single_tag_end() got an unexpected "
"TagCloseSelfclose")
else: # pragma: no cover (untestable/exceptional case)
raise ParserError("_handle_single_tag_end() missed a TagCloseOpen")
padding = stack[index].padding
stack[index] = tokens.TagCloseSelfclose(padding=padding, implicit=True)
return self._pop() | [
"def",
"_handle_single_tag_end",
"(",
"self",
")",
":",
"stack",
"=",
"self",
".",
"_stack",
"# We need to find the index of the TagCloseOpen token corresponding to",
"# the TagOpenOpen token located at index 0:",
"depth",
"=",
"1",
"for",
"index",
",",
"token",
"in",
"enumerate",
"(",
"stack",
"[",
"2",
":",
"]",
",",
"2",
")",
":",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagOpenOpen",
")",
":",
"depth",
"+=",
"1",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagCloseOpen",
")",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"break",
"elif",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"TagCloseSelfclose",
")",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"# pragma: no cover (untestable/exceptional)",
"raise",
"ParserError",
"(",
"\"_handle_single_tag_end() got an unexpected \"",
"\"TagCloseSelfclose\"",
")",
"else",
":",
"# pragma: no cover (untestable/exceptional case)",
"raise",
"ParserError",
"(",
"\"_handle_single_tag_end() missed a TagCloseOpen\"",
")",
"padding",
"=",
"stack",
"[",
"index",
"]",
".",
"padding",
"stack",
"[",
"index",
"]",
"=",
"tokens",
".",
"TagCloseSelfclose",
"(",
"padding",
"=",
"padding",
",",
"implicit",
"=",
"True",
")",
"return",
"self",
".",
"_pop",
"(",
")"
]
| Handle the stream end when inside a single-supporting HTML tag. | [
"Handle",
"the",
"stream",
"end",
"when",
"inside",
"a",
"single",
"-",
"supporting",
"HTML",
"tag",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L828-L851 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_tag | def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._emit_all(tag) | python | def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._emit_all(tag) | [
"def",
"_parse_tag",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"1",
"try",
":",
"tag",
"=",
"self",
".",
"_really_parse_tag",
"(",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"\"<\"",
")",
"else",
":",
"self",
".",
"_emit_all",
"(",
"tag",
")"
]
| Parse an HTML tag at the head of the wikicode string. | [
"Parse",
"an",
"HTML",
"tag",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L903-L913 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._emit_style_tag | def _emit_style_tag(self, tag, markup, body):
"""Write the body of a tag and the tokens that should surround it."""
self._emit(tokens.TagOpenOpen(wiki_markup=markup))
self._emit_text(tag)
self._emit(tokens.TagCloseOpen())
self._emit_all(body)
self._emit(tokens.TagOpenClose())
self._emit_text(tag)
self._emit(tokens.TagCloseClose()) | python | def _emit_style_tag(self, tag, markup, body):
"""Write the body of a tag and the tokens that should surround it."""
self._emit(tokens.TagOpenOpen(wiki_markup=markup))
self._emit_text(tag)
self._emit(tokens.TagCloseOpen())
self._emit_all(body)
self._emit(tokens.TagOpenClose())
self._emit_text(tag)
self._emit(tokens.TagCloseClose()) | [
"def",
"_emit_style_tag",
"(",
"self",
",",
"tag",
",",
"markup",
",",
"body",
")",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagOpenOpen",
"(",
"wiki_markup",
"=",
"markup",
")",
")",
"self",
".",
"_emit_text",
"(",
"tag",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseOpen",
"(",
")",
")",
"self",
".",
"_emit_all",
"(",
"body",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagOpenClose",
"(",
")",
")",
"self",
".",
"_emit_text",
"(",
"tag",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseClose",
"(",
")",
")"
]
| Write the body of a tag and the tokens that should surround it. | [
"Write",
"the",
"body",
"of",
"a",
"tag",
"and",
"the",
"tokens",
"that",
"should",
"surround",
"it",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L915-L923 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_italics | def _parse_italics(self):
"""Parse wiki-style italics."""
reset = self._head
try:
stack = self._parse(contexts.STYLE_ITALICS)
except BadRoute as route:
self._head = reset
if route.context & contexts.STYLE_PASS_AGAIN:
new_ctx = contexts.STYLE_ITALICS | contexts.STYLE_SECOND_PASS
stack = self._parse(new_ctx)
else:
return self._emit_text("''")
self._emit_style_tag("i", "''", stack) | python | def _parse_italics(self):
"""Parse wiki-style italics."""
reset = self._head
try:
stack = self._parse(contexts.STYLE_ITALICS)
except BadRoute as route:
self._head = reset
if route.context & contexts.STYLE_PASS_AGAIN:
new_ctx = contexts.STYLE_ITALICS | contexts.STYLE_SECOND_PASS
stack = self._parse(new_ctx)
else:
return self._emit_text("''")
self._emit_style_tag("i", "''", stack) | [
"def",
"_parse_italics",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"try",
":",
"stack",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"STYLE_ITALICS",
")",
"except",
"BadRoute",
"as",
"route",
":",
"self",
".",
"_head",
"=",
"reset",
"if",
"route",
".",
"context",
"&",
"contexts",
".",
"STYLE_PASS_AGAIN",
":",
"new_ctx",
"=",
"contexts",
".",
"STYLE_ITALICS",
"|",
"contexts",
".",
"STYLE_SECOND_PASS",
"stack",
"=",
"self",
".",
"_parse",
"(",
"new_ctx",
")",
"else",
":",
"return",
"self",
".",
"_emit_text",
"(",
"\"''\"",
")",
"self",
".",
"_emit_style_tag",
"(",
"\"i\"",
",",
"\"''\"",
",",
"stack",
")"
]
| Parse wiki-style italics. | [
"Parse",
"wiki",
"-",
"style",
"italics",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L925-L937 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_bold | def _parse_bold(self):
"""Parse wiki-style bold."""
reset = self._head
try:
stack = self._parse(contexts.STYLE_BOLD)
except BadRoute:
self._head = reset
if self._context & contexts.STYLE_SECOND_PASS:
self._emit_text("'")
return True
elif self._context & contexts.STYLE_ITALICS:
self._context |= contexts.STYLE_PASS_AGAIN
self._emit_text("'''")
else:
self._emit_text("'")
self._parse_italics()
else:
self._emit_style_tag("b", "'''", stack) | python | def _parse_bold(self):
"""Parse wiki-style bold."""
reset = self._head
try:
stack = self._parse(contexts.STYLE_BOLD)
except BadRoute:
self._head = reset
if self._context & contexts.STYLE_SECOND_PASS:
self._emit_text("'")
return True
elif self._context & contexts.STYLE_ITALICS:
self._context |= contexts.STYLE_PASS_AGAIN
self._emit_text("'''")
else:
self._emit_text("'")
self._parse_italics()
else:
self._emit_style_tag("b", "'''", stack) | [
"def",
"_parse_bold",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"try",
":",
"stack",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"STYLE_BOLD",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"STYLE_SECOND_PASS",
":",
"self",
".",
"_emit_text",
"(",
"\"'\"",
")",
"return",
"True",
"elif",
"self",
".",
"_context",
"&",
"contexts",
".",
"STYLE_ITALICS",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"STYLE_PASS_AGAIN",
"self",
".",
"_emit_text",
"(",
"\"'''\"",
")",
"else",
":",
"self",
".",
"_emit_text",
"(",
"\"'\"",
")",
"self",
".",
"_parse_italics",
"(",
")",
"else",
":",
"self",
".",
"_emit_style_tag",
"(",
"\"b\"",
",",
"\"'''\"",
",",
"stack",
")"
]
| Parse wiki-style bold. | [
"Parse",
"wiki",
"-",
"style",
"bold",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L939-L956 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._emit_table_tag | def _emit_table_tag(self, open_open_markup, tag, style, padding,
close_open_markup, contents, open_close_markup):
"""Emit a table tag."""
self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
self._emit_text(tag)
if style:
self._emit_all(style)
if close_open_markup:
self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,
padding=padding))
else:
self._emit(tokens.TagCloseOpen(padding=padding))
if contents:
self._emit_all(contents)
self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))
self._emit_text(tag)
self._emit(tokens.TagCloseClose()) | python | def _emit_table_tag(self, open_open_markup, tag, style, padding,
close_open_markup, contents, open_close_markup):
"""Emit a table tag."""
self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
self._emit_text(tag)
if style:
self._emit_all(style)
if close_open_markup:
self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,
padding=padding))
else:
self._emit(tokens.TagCloseOpen(padding=padding))
if contents:
self._emit_all(contents)
self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))
self._emit_text(tag)
self._emit(tokens.TagCloseClose()) | [
"def",
"_emit_table_tag",
"(",
"self",
",",
"open_open_markup",
",",
"tag",
",",
"style",
",",
"padding",
",",
"close_open_markup",
",",
"contents",
",",
"open_close_markup",
")",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagOpenOpen",
"(",
"wiki_markup",
"=",
"open_open_markup",
")",
")",
"self",
".",
"_emit_text",
"(",
"tag",
")",
"if",
"style",
":",
"self",
".",
"_emit_all",
"(",
"style",
")",
"if",
"close_open_markup",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseOpen",
"(",
"wiki_markup",
"=",
"close_open_markup",
",",
"padding",
"=",
"padding",
")",
")",
"else",
":",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseOpen",
"(",
"padding",
"=",
"padding",
")",
")",
"if",
"contents",
":",
"self",
".",
"_emit_all",
"(",
"contents",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagOpenClose",
"(",
"wiki_markup",
"=",
"open_close_markup",
")",
")",
"self",
".",
"_emit_text",
"(",
"tag",
")",
"self",
".",
"_emit",
"(",
"tokens",
".",
"TagCloseClose",
"(",
")",
")"
]
| Emit a table tag. | [
"Emit",
"a",
"table",
"tag",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1070-L1086 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_table_style | def _handle_table_style(self, end_token):
"""Handle style attributes for a table until ``end_token``."""
data = _TagOpenData()
data.context = _TagOpenData.CX_ATTR_READY
while True:
this = self._read()
can_exit = (not data.context & data.CX_QUOTED or
data.context & data.CX_NOTE_SPACE)
if this == end_token and can_exit:
if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
self._push_tag_buffer(data)
if this.isspace():
data.padding_buffer["first"] += this
return data.padding_buffer["first"]
elif this is self.END or this == end_token:
if self._context & contexts.TAG_ATTR:
if data.context & data.CX_QUOTED:
# Unclosed attribute quote: reset, don't die
data.context = data.CX_ATTR_VALUE
self._memoize_bad_route()
self._pop()
self._head = data.reset
continue
self._pop()
self._fail_route()
else:
self._handle_tag_data(data, this)
self._head += 1 | python | def _handle_table_style(self, end_token):
"""Handle style attributes for a table until ``end_token``."""
data = _TagOpenData()
data.context = _TagOpenData.CX_ATTR_READY
while True:
this = self._read()
can_exit = (not data.context & data.CX_QUOTED or
data.context & data.CX_NOTE_SPACE)
if this == end_token and can_exit:
if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
self._push_tag_buffer(data)
if this.isspace():
data.padding_buffer["first"] += this
return data.padding_buffer["first"]
elif this is self.END or this == end_token:
if self._context & contexts.TAG_ATTR:
if data.context & data.CX_QUOTED:
# Unclosed attribute quote: reset, don't die
data.context = data.CX_ATTR_VALUE
self._memoize_bad_route()
self._pop()
self._head = data.reset
continue
self._pop()
self._fail_route()
else:
self._handle_tag_data(data, this)
self._head += 1 | [
"def",
"_handle_table_style",
"(",
"self",
",",
"end_token",
")",
":",
"data",
"=",
"_TagOpenData",
"(",
")",
"data",
".",
"context",
"=",
"_TagOpenData",
".",
"CX_ATTR_READY",
"while",
"True",
":",
"this",
"=",
"self",
".",
"_read",
"(",
")",
"can_exit",
"=",
"(",
"not",
"data",
".",
"context",
"&",
"data",
".",
"CX_QUOTED",
"or",
"data",
".",
"context",
"&",
"data",
".",
"CX_NOTE_SPACE",
")",
"if",
"this",
"==",
"end_token",
"and",
"can_exit",
":",
"if",
"data",
".",
"context",
"&",
"(",
"data",
".",
"CX_ATTR_NAME",
"|",
"data",
".",
"CX_ATTR_VALUE",
")",
":",
"self",
".",
"_push_tag_buffer",
"(",
"data",
")",
"if",
"this",
".",
"isspace",
"(",
")",
":",
"data",
".",
"padding_buffer",
"[",
"\"first\"",
"]",
"+=",
"this",
"return",
"data",
".",
"padding_buffer",
"[",
"\"first\"",
"]",
"elif",
"this",
"is",
"self",
".",
"END",
"or",
"this",
"==",
"end_token",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TAG_ATTR",
":",
"if",
"data",
".",
"context",
"&",
"data",
".",
"CX_QUOTED",
":",
"# Unclosed attribute quote: reset, don't die",
"data",
".",
"context",
"=",
"data",
".",
"CX_ATTR_VALUE",
"self",
".",
"_memoize_bad_route",
"(",
")",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_head",
"=",
"data",
".",
"reset",
"continue",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_fail_route",
"(",
")",
"else",
":",
"self",
".",
"_handle_tag_data",
"(",
"data",
",",
"this",
")",
"self",
".",
"_head",
"+=",
"1"
]
| Handle style attributes for a table until ``end_token``. | [
"Handle",
"style",
"attributes",
"for",
"a",
"table",
"until",
"end_token",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1088-L1115 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_table | def _parse_table(self):
"""Parse a wikicode table by starting with the first line."""
reset = self._head
self._head += 2
try:
self._push(contexts.TABLE_OPEN)
padding = self._handle_table_style("\n")
except BadRoute:
self._head = reset
self._emit_text("{")
return
style = self._pop()
self._head += 1
restore_point = self._stack_ident
try:
table = self._parse(contexts.TABLE_OPEN)
except BadRoute:
while self._stack_ident != restore_point:
self._memoize_bad_route()
self._pop()
self._head = reset
self._emit_text("{")
return
self._emit_table_tag("{|", "table", style, padding, None, table, "|}")
# Offset displacement done by _parse():
self._head -= 1 | python | def _parse_table(self):
"""Parse a wikicode table by starting with the first line."""
reset = self._head
self._head += 2
try:
self._push(contexts.TABLE_OPEN)
padding = self._handle_table_style("\n")
except BadRoute:
self._head = reset
self._emit_text("{")
return
style = self._pop()
self._head += 1
restore_point = self._stack_ident
try:
table = self._parse(contexts.TABLE_OPEN)
except BadRoute:
while self._stack_ident != restore_point:
self._memoize_bad_route()
self._pop()
self._head = reset
self._emit_text("{")
return
self._emit_table_tag("{|", "table", style, padding, None, table, "|}")
# Offset displacement done by _parse():
self._head -= 1 | [
"def",
"_parse_table",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"2",
"try",
":",
"self",
".",
"_push",
"(",
"contexts",
".",
"TABLE_OPEN",
")",
"padding",
"=",
"self",
".",
"_handle_table_style",
"(",
"\"\\n\"",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"\"{\"",
")",
"return",
"style",
"=",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_head",
"+=",
"1",
"restore_point",
"=",
"self",
".",
"_stack_ident",
"try",
":",
"table",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"TABLE_OPEN",
")",
"except",
"BadRoute",
":",
"while",
"self",
".",
"_stack_ident",
"!=",
"restore_point",
":",
"self",
".",
"_memoize_bad_route",
"(",
")",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_emit_text",
"(",
"\"{\"",
")",
"return",
"self",
".",
"_emit_table_tag",
"(",
"\"{|\"",
",",
"\"table\"",
",",
"style",
",",
"padding",
",",
"None",
",",
"table",
",",
"\"|}\"",
")",
"# Offset displacement done by _parse():",
"self",
".",
"_head",
"-=",
"1"
]
| Parse a wikicode table by starting with the first line. | [
"Parse",
"a",
"wikicode",
"table",
"by",
"starting",
"with",
"the",
"first",
"line",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1117-L1144 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_table_row | def _handle_table_row(self):
"""Parse as style until end of the line, then continue."""
self._head += 2
if not self._can_recurse():
self._emit_text("|-")
self._head -= 1
return
self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
padding = self._handle_table_style("\n")
style = self._pop()
# Don't parse the style separator:
self._head += 1
row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
self._emit_table_tag("|-", "tr", style, padding, None, row, "")
# Offset displacement done by parse():
self._head -= 1 | python | def _handle_table_row(self):
"""Parse as style until end of the line, then continue."""
self._head += 2
if not self._can_recurse():
self._emit_text("|-")
self._head -= 1
return
self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
padding = self._handle_table_style("\n")
style = self._pop()
# Don't parse the style separator:
self._head += 1
row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
self._emit_table_tag("|-", "tr", style, padding, None, row, "")
# Offset displacement done by parse():
self._head -= 1 | [
"def",
"_handle_table_row",
"(",
"self",
")",
":",
"self",
".",
"_head",
"+=",
"2",
"if",
"not",
"self",
".",
"_can_recurse",
"(",
")",
":",
"self",
".",
"_emit_text",
"(",
"\"|-\"",
")",
"self",
".",
"_head",
"-=",
"1",
"return",
"self",
".",
"_push",
"(",
"contexts",
".",
"TABLE_OPEN",
"|",
"contexts",
".",
"TABLE_ROW_OPEN",
")",
"padding",
"=",
"self",
".",
"_handle_table_style",
"(",
"\"\\n\"",
")",
"style",
"=",
"self",
".",
"_pop",
"(",
")",
"# Don't parse the style separator:",
"self",
".",
"_head",
"+=",
"1",
"row",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"TABLE_OPEN",
"|",
"contexts",
".",
"TABLE_ROW_OPEN",
")",
"self",
".",
"_emit_table_tag",
"(",
"\"|-\"",
",",
"\"tr\"",
",",
"style",
",",
"padding",
",",
"None",
",",
"row",
",",
"\"\"",
")",
"# Offset displacement done by parse():",
"self",
".",
"_head",
"-=",
"1"
]
| Parse as style until end of the line, then continue. | [
"Parse",
"as",
"style",
"until",
"end",
"of",
"the",
"line",
"then",
"continue",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1146-L1164 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_table_cell | def _handle_table_cell(self, markup, tag, line_context):
"""Parse as normal syntax unless we hit a style marker, then parse
style as HTML attributes and the remainder as normal syntax."""
old_context = self._context
padding, style = "", None
self._head += len(markup)
reset = self._head
if not self._can_recurse():
self._emit_text(markup)
self._head -= 1
return
cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
line_context | contexts.TABLE_CELL_STYLE)
cell_context = self._context
self._context = old_context
reset_for_style = cell_context & contexts.TABLE_CELL_STYLE
if reset_for_style:
self._head = reset
self._push(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
line_context)
padding = self._handle_table_style("|")
style = self._pop()
# Don't parse the style separator:
self._head += 1
cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
line_context)
cell_context = self._context
self._context = old_context
close_open_markup = "|" if reset_for_style else None
self._emit_table_tag(markup, tag, style, padding, close_open_markup,
cell, "")
# Keep header/cell line contexts:
self._context |= cell_context & (contexts.TABLE_TH_LINE |
contexts.TABLE_TD_LINE)
# Offset displacement done by parse():
self._head -= 1 | python | def _handle_table_cell(self, markup, tag, line_context):
"""Parse as normal syntax unless we hit a style marker, then parse
style as HTML attributes and the remainder as normal syntax."""
old_context = self._context
padding, style = "", None
self._head += len(markup)
reset = self._head
if not self._can_recurse():
self._emit_text(markup)
self._head -= 1
return
cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
line_context | contexts.TABLE_CELL_STYLE)
cell_context = self._context
self._context = old_context
reset_for_style = cell_context & contexts.TABLE_CELL_STYLE
if reset_for_style:
self._head = reset
self._push(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
line_context)
padding = self._handle_table_style("|")
style = self._pop()
# Don't parse the style separator:
self._head += 1
cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
line_context)
cell_context = self._context
self._context = old_context
close_open_markup = "|" if reset_for_style else None
self._emit_table_tag(markup, tag, style, padding, close_open_markup,
cell, "")
# Keep header/cell line contexts:
self._context |= cell_context & (contexts.TABLE_TH_LINE |
contexts.TABLE_TD_LINE)
# Offset displacement done by parse():
self._head -= 1 | [
"def",
"_handle_table_cell",
"(",
"self",
",",
"markup",
",",
"tag",
",",
"line_context",
")",
":",
"old_context",
"=",
"self",
".",
"_context",
"padding",
",",
"style",
"=",
"\"\"",
",",
"None",
"self",
".",
"_head",
"+=",
"len",
"(",
"markup",
")",
"reset",
"=",
"self",
".",
"_head",
"if",
"not",
"self",
".",
"_can_recurse",
"(",
")",
":",
"self",
".",
"_emit_text",
"(",
"markup",
")",
"self",
".",
"_head",
"-=",
"1",
"return",
"cell",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"TABLE_OPEN",
"|",
"contexts",
".",
"TABLE_CELL_OPEN",
"|",
"line_context",
"|",
"contexts",
".",
"TABLE_CELL_STYLE",
")",
"cell_context",
"=",
"self",
".",
"_context",
"self",
".",
"_context",
"=",
"old_context",
"reset_for_style",
"=",
"cell_context",
"&",
"contexts",
".",
"TABLE_CELL_STYLE",
"if",
"reset_for_style",
":",
"self",
".",
"_head",
"=",
"reset",
"self",
".",
"_push",
"(",
"contexts",
".",
"TABLE_OPEN",
"|",
"contexts",
".",
"TABLE_CELL_OPEN",
"|",
"line_context",
")",
"padding",
"=",
"self",
".",
"_handle_table_style",
"(",
"\"|\"",
")",
"style",
"=",
"self",
".",
"_pop",
"(",
")",
"# Don't parse the style separator:",
"self",
".",
"_head",
"+=",
"1",
"cell",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"TABLE_OPEN",
"|",
"contexts",
".",
"TABLE_CELL_OPEN",
"|",
"line_context",
")",
"cell_context",
"=",
"self",
".",
"_context",
"self",
".",
"_context",
"=",
"old_context",
"close_open_markup",
"=",
"\"|\"",
"if",
"reset_for_style",
"else",
"None",
"self",
".",
"_emit_table_tag",
"(",
"markup",
",",
"tag",
",",
"style",
",",
"padding",
",",
"close_open_markup",
",",
"cell",
",",
"\"\"",
")",
"# Keep header/cell line contexts:",
"self",
".",
"_context",
"|=",
"cell_context",
"&",
"(",
"contexts",
".",
"TABLE_TH_LINE",
"|",
"contexts",
".",
"TABLE_TD_LINE",
")",
"# Offset displacement done by parse():",
"self",
".",
"_head",
"-=",
"1"
]
| Parse as normal syntax unless we hit a style marker, then parse
style as HTML attributes and the remainder as normal syntax. | [
"Parse",
"as",
"normal",
"syntax",
"unless",
"we",
"hit",
"a",
"style",
"marker",
"then",
"parse",
"style",
"as",
"HTML",
"attributes",
"and",
"the",
"remainder",
"as",
"normal",
"syntax",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1166-L1203 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_table_cell_end | def _handle_table_cell_end(self, reset_for_style=False):
"""Returns the current context, with the TABLE_CELL_STYLE flag set if
it is necessary to reset and parse style attributes."""
if reset_for_style:
self._context |= contexts.TABLE_CELL_STYLE
else:
self._context &= ~contexts.TABLE_CELL_STYLE
return self._pop(keep_context=True) | python | def _handle_table_cell_end(self, reset_for_style=False):
"""Returns the current context, with the TABLE_CELL_STYLE flag set if
it is necessary to reset and parse style attributes."""
if reset_for_style:
self._context |= contexts.TABLE_CELL_STYLE
else:
self._context &= ~contexts.TABLE_CELL_STYLE
return self._pop(keep_context=True) | [
"def",
"_handle_table_cell_end",
"(",
"self",
",",
"reset_for_style",
"=",
"False",
")",
":",
"if",
"reset_for_style",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"TABLE_CELL_STYLE",
"else",
":",
"self",
".",
"_context",
"&=",
"~",
"contexts",
".",
"TABLE_CELL_STYLE",
"return",
"self",
".",
"_pop",
"(",
"keep_context",
"=",
"True",
")"
]
| Returns the current context, with the TABLE_CELL_STYLE flag set if
it is necessary to reset and parse style attributes. | [
"Returns",
"the",
"current",
"context",
"with",
"the",
"TABLE_CELL_STYLE",
"flag",
"set",
"if",
"it",
"is",
"necessary",
"to",
"reset",
"and",
"parse",
"style",
"attributes",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1205-L1212 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_end | def _handle_end(self):
"""Handle the end of the stream of wikitext."""
if self._context & contexts.FAIL:
if self._context & contexts.TAG_BODY:
if is_single(self._stack[1].text):
return self._handle_single_tag_end()
if self._context & contexts.TABLE_CELL_OPEN:
self._pop()
if self._context & contexts.DOUBLE:
self._pop()
self._fail_route()
return self._pop() | python | def _handle_end(self):
"""Handle the end of the stream of wikitext."""
if self._context & contexts.FAIL:
if self._context & contexts.TAG_BODY:
if is_single(self._stack[1].text):
return self._handle_single_tag_end()
if self._context & contexts.TABLE_CELL_OPEN:
self._pop()
if self._context & contexts.DOUBLE:
self._pop()
self._fail_route()
return self._pop() | [
"def",
"_handle_end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"FAIL",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TAG_BODY",
":",
"if",
"is_single",
"(",
"self",
".",
"_stack",
"[",
"1",
"]",
".",
"text",
")",
":",
"return",
"self",
".",
"_handle_single_tag_end",
"(",
")",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TABLE_CELL_OPEN",
":",
"self",
".",
"_pop",
"(",
")",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"DOUBLE",
":",
"self",
".",
"_pop",
"(",
")",
"self",
".",
"_fail_route",
"(",
")",
"return",
"self",
".",
"_pop",
"(",
")"
]
| Handle the end of the stream of wikitext. | [
"Handle",
"the",
"end",
"of",
"the",
"stream",
"of",
"wikitext",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1223-L1234 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._verify_safe | def _verify_safe(self, this):
"""Make sure we are not trying to write an invalid character."""
context = self._context
if context & contexts.FAIL_NEXT:
return False
if context & contexts.WIKILINK_TITLE:
if this == "]" or this == "{":
self._context |= contexts.FAIL_NEXT
elif this == "\n" or this == "[" or this == "}" or this == ">":
return False
elif this == "<":
if self._read(1) == "!":
self._context |= contexts.FAIL_NEXT
else:
return False
return True
elif context & contexts.EXT_LINK_TITLE:
return this != "\n"
elif context & contexts.TEMPLATE_NAME:
if this == "{":
self._context |= contexts.HAS_TEMPLATE | contexts.FAIL_NEXT
return True
if this == "}" or (this == "<" and self._read(1) == "!"):
self._context |= contexts.FAIL_NEXT
return True
if this == "[" or this == "]" or this == "<" or this == ">":
return False
if this == "|":
return True
if context & contexts.HAS_TEXT:
if context & contexts.FAIL_ON_TEXT:
if this is self.END or not this.isspace():
return False
elif this == "\n":
self._context |= contexts.FAIL_ON_TEXT
elif this is self.END or not this.isspace():
self._context |= contexts.HAS_TEXT
return True
elif context & contexts.TAG_CLOSE:
return this != "<"
else:
if context & contexts.FAIL_ON_EQUALS:
if this == "=":
return False
elif context & contexts.FAIL_ON_LBRACE:
if this == "{" or (self._read(-1) == self._read(-2) == "{"):
if context & contexts.TEMPLATE:
self._context |= contexts.FAIL_ON_EQUALS
else:
self._context |= contexts.FAIL_NEXT
return True
self._context ^= contexts.FAIL_ON_LBRACE
elif context & contexts.FAIL_ON_RBRACE:
if this == "}":
self._context |= contexts.FAIL_NEXT
return True
self._context ^= contexts.FAIL_ON_RBRACE
elif this == "{":
self._context |= contexts.FAIL_ON_LBRACE
elif this == "}":
self._context |= contexts.FAIL_ON_RBRACE
return True | python | def _verify_safe(self, this):
"""Make sure we are not trying to write an invalid character."""
context = self._context
if context & contexts.FAIL_NEXT:
return False
if context & contexts.WIKILINK_TITLE:
if this == "]" or this == "{":
self._context |= contexts.FAIL_NEXT
elif this == "\n" or this == "[" or this == "}" or this == ">":
return False
elif this == "<":
if self._read(1) == "!":
self._context |= contexts.FAIL_NEXT
else:
return False
return True
elif context & contexts.EXT_LINK_TITLE:
return this != "\n"
elif context & contexts.TEMPLATE_NAME:
if this == "{":
self._context |= contexts.HAS_TEMPLATE | contexts.FAIL_NEXT
return True
if this == "}" or (this == "<" and self._read(1) == "!"):
self._context |= contexts.FAIL_NEXT
return True
if this == "[" or this == "]" or this == "<" or this == ">":
return False
if this == "|":
return True
if context & contexts.HAS_TEXT:
if context & contexts.FAIL_ON_TEXT:
if this is self.END or not this.isspace():
return False
elif this == "\n":
self._context |= contexts.FAIL_ON_TEXT
elif this is self.END or not this.isspace():
self._context |= contexts.HAS_TEXT
return True
elif context & contexts.TAG_CLOSE:
return this != "<"
else:
if context & contexts.FAIL_ON_EQUALS:
if this == "=":
return False
elif context & contexts.FAIL_ON_LBRACE:
if this == "{" or (self._read(-1) == self._read(-2) == "{"):
if context & contexts.TEMPLATE:
self._context |= contexts.FAIL_ON_EQUALS
else:
self._context |= contexts.FAIL_NEXT
return True
self._context ^= contexts.FAIL_ON_LBRACE
elif context & contexts.FAIL_ON_RBRACE:
if this == "}":
self._context |= contexts.FAIL_NEXT
return True
self._context ^= contexts.FAIL_ON_RBRACE
elif this == "{":
self._context |= contexts.FAIL_ON_LBRACE
elif this == "}":
self._context |= contexts.FAIL_ON_RBRACE
return True | [
"def",
"_verify_safe",
"(",
"self",
",",
"this",
")",
":",
"context",
"=",
"self",
".",
"_context",
"if",
"context",
"&",
"contexts",
".",
"FAIL_NEXT",
":",
"return",
"False",
"if",
"context",
"&",
"contexts",
".",
"WIKILINK_TITLE",
":",
"if",
"this",
"==",
"\"]\"",
"or",
"this",
"==",
"\"{\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_NEXT",
"elif",
"this",
"==",
"\"\\n\"",
"or",
"this",
"==",
"\"[\"",
"or",
"this",
"==",
"\"}\"",
"or",
"this",
"==",
"\">\"",
":",
"return",
"False",
"elif",
"this",
"==",
"\"<\"",
":",
"if",
"self",
".",
"_read",
"(",
"1",
")",
"==",
"\"!\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_NEXT",
"else",
":",
"return",
"False",
"return",
"True",
"elif",
"context",
"&",
"contexts",
".",
"EXT_LINK_TITLE",
":",
"return",
"this",
"!=",
"\"\\n\"",
"elif",
"context",
"&",
"contexts",
".",
"TEMPLATE_NAME",
":",
"if",
"this",
"==",
"\"{\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"HAS_TEMPLATE",
"|",
"contexts",
".",
"FAIL_NEXT",
"return",
"True",
"if",
"this",
"==",
"\"}\"",
"or",
"(",
"this",
"==",
"\"<\"",
"and",
"self",
".",
"_read",
"(",
"1",
")",
"==",
"\"!\"",
")",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_NEXT",
"return",
"True",
"if",
"this",
"==",
"\"[\"",
"or",
"this",
"==",
"\"]\"",
"or",
"this",
"==",
"\"<\"",
"or",
"this",
"==",
"\">\"",
":",
"return",
"False",
"if",
"this",
"==",
"\"|\"",
":",
"return",
"True",
"if",
"context",
"&",
"contexts",
".",
"HAS_TEXT",
":",
"if",
"context",
"&",
"contexts",
".",
"FAIL_ON_TEXT",
":",
"if",
"this",
"is",
"self",
".",
"END",
"or",
"not",
"this",
".",
"isspace",
"(",
")",
":",
"return",
"False",
"elif",
"this",
"==",
"\"\\n\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_ON_TEXT",
"elif",
"this",
"is",
"self",
".",
"END",
"or",
"not",
"this",
".",
"isspace",
"(",
")",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"HAS_TEXT",
"return",
"True",
"elif",
"context",
"&",
"contexts",
".",
"TAG_CLOSE",
":",
"return",
"this",
"!=",
"\"<\"",
"else",
":",
"if",
"context",
"&",
"contexts",
".",
"FAIL_ON_EQUALS",
":",
"if",
"this",
"==",
"\"=\"",
":",
"return",
"False",
"elif",
"context",
"&",
"contexts",
".",
"FAIL_ON_LBRACE",
":",
"if",
"this",
"==",
"\"{\"",
"or",
"(",
"self",
".",
"_read",
"(",
"-",
"1",
")",
"==",
"self",
".",
"_read",
"(",
"-",
"2",
")",
"==",
"\"{\"",
")",
":",
"if",
"context",
"&",
"contexts",
".",
"TEMPLATE",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_ON_EQUALS",
"else",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_NEXT",
"return",
"True",
"self",
".",
"_context",
"^=",
"contexts",
".",
"FAIL_ON_LBRACE",
"elif",
"context",
"&",
"contexts",
".",
"FAIL_ON_RBRACE",
":",
"if",
"this",
"==",
"\"}\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_NEXT",
"return",
"True",
"self",
".",
"_context",
"^=",
"contexts",
".",
"FAIL_ON_RBRACE",
"elif",
"this",
"==",
"\"{\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_ON_LBRACE",
"elif",
"this",
"==",
"\"}\"",
":",
"self",
".",
"_context",
"|=",
"contexts",
".",
"FAIL_ON_RBRACE",
"return",
"True"
]
| Make sure we are not trying to write an invalid character. | [
"Make",
"sure",
"we",
"are",
"not",
"trying",
"to",
"write",
"an",
"invalid",
"character",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1236-L1297 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer.tokenize | def tokenize(self, text, context=0, skip_style_tags=False):
"""Build a list of tokens from a string of wikicode and return it."""
split = self.regex.split(text)
self._text = [segment for segment in split if segment]
self._head = self._global = self._depth = 0
self._bad_routes = set()
self._skip_style_tags = skip_style_tags
try:
tokens = self._parse(context)
except BadRoute: # pragma: no cover (untestable/exceptional case)
raise ParserError("Python tokenizer exited with BadRoute")
if self._stacks: # pragma: no cover (untestable/exceptional case)
err = "Python tokenizer exited with non-empty token stack"
raise ParserError(err)
return tokens | python | def tokenize(self, text, context=0, skip_style_tags=False):
"""Build a list of tokens from a string of wikicode and return it."""
split = self.regex.split(text)
self._text = [segment for segment in split if segment]
self._head = self._global = self._depth = 0
self._bad_routes = set()
self._skip_style_tags = skip_style_tags
try:
tokens = self._parse(context)
except BadRoute: # pragma: no cover (untestable/exceptional case)
raise ParserError("Python tokenizer exited with BadRoute")
if self._stacks: # pragma: no cover (untestable/exceptional case)
err = "Python tokenizer exited with non-empty token stack"
raise ParserError(err)
return tokens | [
"def",
"tokenize",
"(",
"self",
",",
"text",
",",
"context",
"=",
"0",
",",
"skip_style_tags",
"=",
"False",
")",
":",
"split",
"=",
"self",
".",
"regex",
".",
"split",
"(",
"text",
")",
"self",
".",
"_text",
"=",
"[",
"segment",
"for",
"segment",
"in",
"split",
"if",
"segment",
"]",
"self",
".",
"_head",
"=",
"self",
".",
"_global",
"=",
"self",
".",
"_depth",
"=",
"0",
"self",
".",
"_bad_routes",
"=",
"set",
"(",
")",
"self",
".",
"_skip_style_tags",
"=",
"skip_style_tags",
"try",
":",
"tokens",
"=",
"self",
".",
"_parse",
"(",
"context",
")",
"except",
"BadRoute",
":",
"# pragma: no cover (untestable/exceptional case)",
"raise",
"ParserError",
"(",
"\"Python tokenizer exited with BadRoute\"",
")",
"if",
"self",
".",
"_stacks",
":",
"# pragma: no cover (untestable/exceptional case)",
"err",
"=",
"\"Python tokenizer exited with non-empty token stack\"",
"raise",
"ParserError",
"(",
"err",
")",
"return",
"tokens"
]
| Build a list of tokens from a string of wikicode and return it. | [
"Build",
"a",
"list",
"of",
"tokens",
"from",
"a",
"string",
"of",
"wikicode",
"and",
"return",
"it",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1450-L1465 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/extras/attribute.py | Attribute._value_needs_quotes | def _value_needs_quotes(val):
"""Return valid quotes for the given value, or None if unneeded."""
if not val:
return None
val = "".join(str(node) for node in val.filter_text(recursive=False))
if not any(char.isspace() for char in val):
return None
if "'" in val and '"' not in val:
return '"'
if '"' in val and "'" not in val:
return "'"
return "\"'" | python | def _value_needs_quotes(val):
"""Return valid quotes for the given value, or None if unneeded."""
if not val:
return None
val = "".join(str(node) for node in val.filter_text(recursive=False))
if not any(char.isspace() for char in val):
return None
if "'" in val and '"' not in val:
return '"'
if '"' in val and "'" not in val:
return "'"
return "\"'" | [
"def",
"_value_needs_quotes",
"(",
"val",
")",
":",
"if",
"not",
"val",
":",
"return",
"None",
"val",
"=",
"\"\"",
".",
"join",
"(",
"str",
"(",
"node",
")",
"for",
"node",
"in",
"val",
".",
"filter_text",
"(",
"recursive",
"=",
"False",
")",
")",
"if",
"not",
"any",
"(",
"char",
".",
"isspace",
"(",
")",
"for",
"char",
"in",
"val",
")",
":",
"return",
"None",
"if",
"\"'\"",
"in",
"val",
"and",
"'\"'",
"not",
"in",
"val",
":",
"return",
"'\"'",
"if",
"'\"'",
"in",
"val",
"and",
"\"'\"",
"not",
"in",
"val",
":",
"return",
"\"'\"",
"return",
"\"\\\"'\""
]
| Return valid quotes for the given value, or None if unneeded. | [
"Return",
"valid",
"quotes",
"for",
"the",
"given",
"value",
"or",
"None",
"if",
"unneeded",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/extras/attribute.py#L60-L71 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/extras/attribute.py | Attribute._set_padding | def _set_padding(self, attr, value):
"""Setter for the value of a padding attribute."""
if not value:
setattr(self, attr, "")
else:
value = str(value)
if not value.isspace():
raise ValueError("padding must be entirely whitespace")
setattr(self, attr, value) | python | def _set_padding(self, attr, value):
"""Setter for the value of a padding attribute."""
if not value:
setattr(self, attr, "")
else:
value = str(value)
if not value.isspace():
raise ValueError("padding must be entirely whitespace")
setattr(self, attr, value) | [
"def",
"_set_padding",
"(",
"self",
",",
"attr",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"\"\"",
")",
"else",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"not",
"value",
".",
"isspace",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"padding must be entirely whitespace\"",
")",
"setattr",
"(",
"self",
",",
"attr",
",",
"value",
")"
]
| Setter for the value of a padding attribute. | [
"Setter",
"for",
"the",
"value",
"of",
"a",
"padding",
"attribute",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/extras/attribute.py#L73-L81 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/extras/attribute.py | Attribute.coerce_quotes | def coerce_quotes(quotes):
"""Coerce a quote type into an acceptable value, or raise an error."""
orig, quotes = quotes, str(quotes) if quotes else None
if quotes not in [None, '"', "'"]:
raise ValueError("{!r} is not a valid quote type".format(orig))
return quotes | python | def coerce_quotes(quotes):
"""Coerce a quote type into an acceptable value, or raise an error."""
orig, quotes = quotes, str(quotes) if quotes else None
if quotes not in [None, '"', "'"]:
raise ValueError("{!r} is not a valid quote type".format(orig))
return quotes | [
"def",
"coerce_quotes",
"(",
"quotes",
")",
":",
"orig",
",",
"quotes",
"=",
"quotes",
",",
"str",
"(",
"quotes",
")",
"if",
"quotes",
"else",
"None",
"if",
"quotes",
"not",
"in",
"[",
"None",
",",
"'\"'",
",",
"\"'\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"{!r} is not a valid quote type\"",
".",
"format",
"(",
"orig",
")",
")",
"return",
"quotes"
]
| Coerce a quote type into an acceptable value, or raise an error. | [
"Coerce",
"a",
"quote",
"type",
"into",
"an",
"acceptable",
"value",
"or",
"raise",
"an",
"error",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/extras/attribute.py#L84-L89 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode._indexed_ifilter | def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes and their corresponding indices in the node list.
The arguments are interpreted as for :meth:`ifilter`. For each tuple
``(i, node)`` yielded by this method, ``self.index(node) == i``. Note
that if *recursive* is ``True``, ``self.nodes[i]`` might not be the
node itself, but will still contain it.
"""
match = self._build_matcher(matches, flags)
if recursive:
restrict = forcetype if recursive == self.RECURSE_OTHERS else None
def getter(i, node):
for ch in self._get_children(node, restrict=restrict):
yield (i, ch)
inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
else:
inodes = enumerate(self.nodes)
for i, node in inodes:
if (not forcetype or isinstance(node, forcetype)) and match(node):
yield (i, node) | python | def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes and their corresponding indices in the node list.
The arguments are interpreted as for :meth:`ifilter`. For each tuple
``(i, node)`` yielded by this method, ``self.index(node) == i``. Note
that if *recursive* is ``True``, ``self.nodes[i]`` might not be the
node itself, but will still contain it.
"""
match = self._build_matcher(matches, flags)
if recursive:
restrict = forcetype if recursive == self.RECURSE_OTHERS else None
def getter(i, node):
for ch in self._get_children(node, restrict=restrict):
yield (i, ch)
inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
else:
inodes = enumerate(self.nodes)
for i, node in inodes:
if (not forcetype or isinstance(node, forcetype)) and match(node):
yield (i, node) | [
"def",
"_indexed_ifilter",
"(",
"self",
",",
"recursive",
"=",
"True",
",",
"matches",
"=",
"None",
",",
"flags",
"=",
"FLAGS",
",",
"forcetype",
"=",
"None",
")",
":",
"match",
"=",
"self",
".",
"_build_matcher",
"(",
"matches",
",",
"flags",
")",
"if",
"recursive",
":",
"restrict",
"=",
"forcetype",
"if",
"recursive",
"==",
"self",
".",
"RECURSE_OTHERS",
"else",
"None",
"def",
"getter",
"(",
"i",
",",
"node",
")",
":",
"for",
"ch",
"in",
"self",
".",
"_get_children",
"(",
"node",
",",
"restrict",
"=",
"restrict",
")",
":",
"yield",
"(",
"i",
",",
"ch",
")",
"inodes",
"=",
"chain",
"(",
"*",
"(",
"getter",
"(",
"i",
",",
"n",
")",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"self",
".",
"nodes",
")",
")",
")",
"else",
":",
"inodes",
"=",
"enumerate",
"(",
"self",
".",
"nodes",
")",
"for",
"i",
",",
"node",
"in",
"inodes",
":",
"if",
"(",
"not",
"forcetype",
"or",
"isinstance",
"(",
"node",
",",
"forcetype",
")",
")",
"and",
"match",
"(",
"node",
")",
":",
"yield",
"(",
"i",
",",
"node",
")"
]
| Iterate over nodes and their corresponding indices in the node list.
The arguments are interpreted as for :meth:`ifilter`. For each tuple
``(i, node)`` yielded by this method, ``self.index(node) == i``. Note
that if *recursive* is ``True``, ``self.nodes[i]`` might not be the
node itself, but will still contain it. | [
"Iterate",
"over",
"nodes",
"and",
"their",
"corresponding",
"indices",
"in",
"the",
"node",
"list",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L90-L110 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode._get_tree | def _get_tree(self, code, lines, marker, indent):
"""Build a tree to illustrate the way the Wikicode object was parsed.
The method that builds the actual tree is ``__showtree__`` of ``Node``
objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
is the list to append the tree to, which is returned at the end of the
method. *marker* is some object to be used to indicate that the builder
should continue on from the last line instead of starting a new one; it
should be any object that can be tested for with ``is``. *indent* is
the starting indentation.
"""
def write(*args):
"""Write a new line following the proper indentation rules."""
if lines and lines[-1] is marker: # Continue from the last line
lines.pop() # Remove the marker
last = lines.pop()
lines.append(last + " ".join(args))
else:
lines.append(" " * 6 * indent + " ".join(args))
get = lambda code: self._get_tree(code, lines, marker, indent + 1)
mark = lambda: lines.append(marker)
for node in code.nodes:
node.__showtree__(write, get, mark)
return lines | python | def _get_tree(self, code, lines, marker, indent):
"""Build a tree to illustrate the way the Wikicode object was parsed.
The method that builds the actual tree is ``__showtree__`` of ``Node``
objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
is the list to append the tree to, which is returned at the end of the
method. *marker* is some object to be used to indicate that the builder
should continue on from the last line instead of starting a new one; it
should be any object that can be tested for with ``is``. *indent* is
the starting indentation.
"""
def write(*args):
"""Write a new line following the proper indentation rules."""
if lines and lines[-1] is marker: # Continue from the last line
lines.pop() # Remove the marker
last = lines.pop()
lines.append(last + " ".join(args))
else:
lines.append(" " * 6 * indent + " ".join(args))
get = lambda code: self._get_tree(code, lines, marker, indent + 1)
mark = lambda: lines.append(marker)
for node in code.nodes:
node.__showtree__(write, get, mark)
return lines | [
"def",
"_get_tree",
"(",
"self",
",",
"code",
",",
"lines",
",",
"marker",
",",
"indent",
")",
":",
"def",
"write",
"(",
"*",
"args",
")",
":",
"\"\"\"Write a new line following the proper indentation rules.\"\"\"",
"if",
"lines",
"and",
"lines",
"[",
"-",
"1",
"]",
"is",
"marker",
":",
"# Continue from the last line",
"lines",
".",
"pop",
"(",
")",
"# Remove the marker",
"last",
"=",
"lines",
".",
"pop",
"(",
")",
"lines",
".",
"append",
"(",
"last",
"+",
"\" \"",
".",
"join",
"(",
"args",
")",
")",
"else",
":",
"lines",
".",
"append",
"(",
"\" \"",
"*",
"6",
"*",
"indent",
"+",
"\" \"",
".",
"join",
"(",
"args",
")",
")",
"get",
"=",
"lambda",
"code",
":",
"self",
".",
"_get_tree",
"(",
"code",
",",
"lines",
",",
"marker",
",",
"indent",
"+",
"1",
")",
"mark",
"=",
"lambda",
":",
"lines",
".",
"append",
"(",
"marker",
")",
"for",
"node",
"in",
"code",
".",
"nodes",
":",
"node",
".",
"__showtree__",
"(",
"write",
",",
"get",
",",
"mark",
")",
"return",
"lines"
]
| Build a tree to illustrate the way the Wikicode object was parsed.
The method that builds the actual tree is ``__showtree__`` of ``Node``
objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
is the list to append the tree to, which is returned at the end of the
method. *marker* is some object to be used to indicate that the builder
should continue on from the last line instead of starting a new one; it
should be any object that can be tested for with ``is``. *indent* is
the starting indentation. | [
"Build",
"a",
"tree",
"to",
"illustrate",
"the",
"way",
"the",
"Wikicode",
"object",
"was",
"parsed",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L207-L231 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode._build_filter_methods | def _build_filter_methods(cls, **meths):
"""Given Node types, build the corresponding i?filter shortcuts.
The should be given as keys storing the method's base name paired with
values storing the corresponding :class:`.Node` type. For example, the
dict may contain the pair ``("templates", Template)``, which will
produce the methods :meth:`ifilter_templates` and
:meth:`filter_templates`, which are shortcuts for
:meth:`ifilter(forcetype=Template) <ifilter>` and
:meth:`filter(forcetype=Template) <filter>`, respectively. These
shortcuts are added to the class itself, with an appropriate docstring.
"""
doc = """Iterate over {0}.
This is equivalent to :meth:`{1}` with *forcetype* set to
:class:`~{2.__module__}.{2.__name__}`.
"""
make_ifilter = lambda ftype: (lambda self, *a, **kw:
self.ifilter(forcetype=ftype, *a, **kw))
make_filter = lambda ftype: (lambda self, *a, **kw:
self.filter(forcetype=ftype, *a, **kw))
for name, ftype in (meths.items() if py3k else meths.iteritems()):
ifilter = make_ifilter(ftype)
filter = make_filter(ftype)
ifilter.__doc__ = doc.format(name, "ifilter", ftype)
filter.__doc__ = doc.format(name, "filter", ftype)
setattr(cls, "ifilter_" + name, ifilter)
setattr(cls, "filter_" + name, filter) | python | def _build_filter_methods(cls, **meths):
"""Given Node types, build the corresponding i?filter shortcuts.
The should be given as keys storing the method's base name paired with
values storing the corresponding :class:`.Node` type. For example, the
dict may contain the pair ``("templates", Template)``, which will
produce the methods :meth:`ifilter_templates` and
:meth:`filter_templates`, which are shortcuts for
:meth:`ifilter(forcetype=Template) <ifilter>` and
:meth:`filter(forcetype=Template) <filter>`, respectively. These
shortcuts are added to the class itself, with an appropriate docstring.
"""
doc = """Iterate over {0}.
This is equivalent to :meth:`{1}` with *forcetype* set to
:class:`~{2.__module__}.{2.__name__}`.
"""
make_ifilter = lambda ftype: (lambda self, *a, **kw:
self.ifilter(forcetype=ftype, *a, **kw))
make_filter = lambda ftype: (lambda self, *a, **kw:
self.filter(forcetype=ftype, *a, **kw))
for name, ftype in (meths.items() if py3k else meths.iteritems()):
ifilter = make_ifilter(ftype)
filter = make_filter(ftype)
ifilter.__doc__ = doc.format(name, "ifilter", ftype)
filter.__doc__ = doc.format(name, "filter", ftype)
setattr(cls, "ifilter_" + name, ifilter)
setattr(cls, "filter_" + name, filter) | [
"def",
"_build_filter_methods",
"(",
"cls",
",",
"*",
"*",
"meths",
")",
":",
"doc",
"=",
"\"\"\"Iterate over {0}.\n\n This is equivalent to :meth:`{1}` with *forcetype* set to\n :class:`~{2.__module__}.{2.__name__}`.\n \"\"\"",
"make_ifilter",
"=",
"lambda",
"ftype",
":",
"(",
"lambda",
"self",
",",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"self",
".",
"ifilter",
"(",
"forcetype",
"=",
"ftype",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
")",
"make_filter",
"=",
"lambda",
"ftype",
":",
"(",
"lambda",
"self",
",",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"self",
".",
"filter",
"(",
"forcetype",
"=",
"ftype",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
")",
"for",
"name",
",",
"ftype",
"in",
"(",
"meths",
".",
"items",
"(",
")",
"if",
"py3k",
"else",
"meths",
".",
"iteritems",
"(",
")",
")",
":",
"ifilter",
"=",
"make_ifilter",
"(",
"ftype",
")",
"filter",
"=",
"make_filter",
"(",
"ftype",
")",
"ifilter",
".",
"__doc__",
"=",
"doc",
".",
"format",
"(",
"name",
",",
"\"ifilter\"",
",",
"ftype",
")",
"filter",
".",
"__doc__",
"=",
"doc",
".",
"format",
"(",
"name",
",",
"\"filter\"",
",",
"ftype",
")",
"setattr",
"(",
"cls",
",",
"\"ifilter_\"",
"+",
"name",
",",
"ifilter",
")",
"setattr",
"(",
"cls",
",",
"\"filter_\"",
"+",
"name",
",",
"filter",
")"
]
| Given Node types, build the corresponding i?filter shortcuts.
The should be given as keys storing the method's base name paired with
values storing the corresponding :class:`.Node` type. For example, the
dict may contain the pair ``("templates", Template)``, which will
produce the methods :meth:`ifilter_templates` and
:meth:`filter_templates`, which are shortcuts for
:meth:`ifilter(forcetype=Template) <ifilter>` and
:meth:`filter(forcetype=Template) <filter>`, respectively. These
shortcuts are added to the class itself, with an appropriate docstring. | [
"Given",
"Node",
"types",
"build",
"the",
"corresponding",
"i?filter",
"shortcuts",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L234-L261 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode.matches | def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and the first
letter's case is normalized. Typical usage is
``if template.name.matches("stub"): ...``.
"""
cmp = lambda a, b: (a[0].upper() + a[1:] == b[0].upper() + b[1:]
if a and b else a == b)
this = self.strip_code().strip()
if isinstance(other, (str, bytes, Wikicode, Node)):
that = parse_anything(other).strip_code().strip()
return cmp(this, that)
for obj in other:
that = parse_anything(obj).strip_code().strip()
if cmp(this, that):
return True
return False | python | def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and the first
letter's case is normalized. Typical usage is
``if template.name.matches("stub"): ...``.
"""
cmp = lambda a, b: (a[0].upper() + a[1:] == b[0].upper() + b[1:]
if a and b else a == b)
this = self.strip_code().strip()
if isinstance(other, (str, bytes, Wikicode, Node)):
that = parse_anything(other).strip_code().strip()
return cmp(this, that)
for obj in other:
that = parse_anything(obj).strip_code().strip()
if cmp(this, that):
return True
return False | [
"def",
"matches",
"(",
"self",
",",
"other",
")",
":",
"cmp",
"=",
"lambda",
"a",
",",
"b",
":",
"(",
"a",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"a",
"[",
"1",
":",
"]",
"==",
"b",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"b",
"[",
"1",
":",
"]",
"if",
"a",
"and",
"b",
"else",
"a",
"==",
"b",
")",
"this",
"=",
"self",
".",
"strip_code",
"(",
")",
".",
"strip",
"(",
")",
"if",
"isinstance",
"(",
"other",
",",
"(",
"str",
",",
"bytes",
",",
"Wikicode",
",",
"Node",
")",
")",
":",
"that",
"=",
"parse_anything",
"(",
"other",
")",
".",
"strip_code",
"(",
")",
".",
"strip",
"(",
")",
"return",
"cmp",
"(",
"this",
",",
"that",
")",
"for",
"obj",
"in",
"other",
":",
"that",
"=",
"parse_anything",
"(",
"obj",
")",
".",
"strip_code",
"(",
")",
".",
"strip",
"(",
")",
"if",
"cmp",
"(",
"this",
",",
"that",
")",
":",
"return",
"True",
"return",
"False"
]
| Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and the first
letter's case is normalized. Typical usage is
``if template.name.matches("stub"): ...``. | [
"Do",
"a",
"loose",
"equivalency",
"test",
"suitable",
"for",
"comparing",
"page",
"names",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L495-L515 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode.ifilter | def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
iterate over all children and their descendants. ``RECURSE_OTHERS``
will only iterate over children that are not the instances of
*forcetype*. ``False`` will only iterate over immediate children.
``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,
even if they are inside of HTML tags, like so:
>>> code = mwparserfromhell.parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
>>> code.filter_templates(code.RECURSE_OTHERS)
["{{foo}}", "{{foo|{{bar}}}}"]
*matches* can be used to further restrict the nodes, either as a
function (taking a single :class:`.Node` and returning a boolean) or a
regular expression (matched against the node's string representation
with :func:`re.search`). If *matches* is a regex, the flags passed to
:func:`re.search` are :const:`re.IGNORECASE`, :const:`re.DOTALL`, and
:const:`re.UNICODE`, but custom flags can be specified by passing
*flags*.
"""
gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
return (node for i, node in gen) | python | def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
iterate over all children and their descendants. ``RECURSE_OTHERS``
will only iterate over children that are not the instances of
*forcetype*. ``False`` will only iterate over immediate children.
``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,
even if they are inside of HTML tags, like so:
>>> code = mwparserfromhell.parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
>>> code.filter_templates(code.RECURSE_OTHERS)
["{{foo}}", "{{foo|{{bar}}}}"]
*matches* can be used to further restrict the nodes, either as a
function (taking a single :class:`.Node` and returning a boolean) or a
regular expression (matched against the node's string representation
with :func:`re.search`). If *matches* is a regex, the flags passed to
:func:`re.search` are :const:`re.IGNORECASE`, :const:`re.DOTALL`, and
:const:`re.UNICODE`, but custom flags can be specified by passing
*flags*.
"""
gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
return (node for i, node in gen) | [
"def",
"ifilter",
"(",
"self",
",",
"recursive",
"=",
"True",
",",
"matches",
"=",
"None",
",",
"flags",
"=",
"FLAGS",
",",
"forcetype",
"=",
"None",
")",
":",
"gen",
"=",
"self",
".",
"_indexed_ifilter",
"(",
"recursive",
",",
"matches",
",",
"flags",
",",
"forcetype",
")",
"return",
"(",
"node",
"for",
"i",
",",
"node",
"in",
"gen",
")"
]
| Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
iterate over all children and their descendants. ``RECURSE_OTHERS``
will only iterate over children that are not the instances of
*forcetype*. ``False`` will only iterate over immediate children.
``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,
even if they are inside of HTML tags, like so:
>>> code = mwparserfromhell.parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
>>> code.filter_templates(code.RECURSE_OTHERS)
["{{foo}}", "{{foo|{{bar}}}}"]
*matches* can be used to further restrict the nodes, either as a
function (taking a single :class:`.Node` and returning a boolean) or a
regular expression (matched against the node's string representation
with :func:`re.search`). If *matches* is a regex, the flags passed to
:func:`re.search` are :const:`re.IGNORECASE`, :const:`re.DOTALL`, and
:const:`re.UNICODE`, but custom flags can be specified by passing
*flags*. | [
"Iterate",
"over",
"nodes",
"in",
"our",
"list",
"matching",
"certain",
"conditions",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L517-L543 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode.get_sections | def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
include_lead=None, include_headings=True):
"""Return a list of sections within the page.
Sections are returned as :class:`.Wikicode` objects with a shared node
list (implemented using :class:`.SmartList`) so that changes to
sections are reflected in the parent Wikicode object.
Each section contains all of its subsections, unless *flat* is
``True``. If *levels* is given, it should be a iterable of integers;
only sections whose heading levels are within it will be returned. If
*matches* is given, it should be either a function or a regex; only
sections whose headings match it (without the surrounding equal signs)
will be included. *flags* can be used to override the default regex
flags (see :meth:`ifilter`) if a regex *matches* is used.
If *include_lead* is ``True``, the first, lead section (without a
heading) will be included in the list; ``False`` will not include it;
the default will include it only if no specific *levels* were given. If
*include_headings* is ``True``, the section's beginning
:class:`.Heading` object will be included; otherwise, this is skipped.
"""
title_matcher = self._build_matcher(matches, flags)
matcher = lambda heading: (title_matcher(heading.title) and
(not levels or heading.level in levels))
iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
sections = [] # Tuples of (index_of_first_node, section)
open_headings = [] # Tuples of (index, heading), where index and
# heading.level are both monotonically increasing
# Add the lead section if appropriate:
if include_lead or not (include_lead is not None or matches or levels):
itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
try:
first = next(itr)[0]
sections.append((0, Wikicode(self.nodes[:first])))
except StopIteration: # No headings in page
sections.append((0, Wikicode(self.nodes[:])))
# Iterate over headings, adding sections to the list as they end:
for i, heading in iheadings:
if flat: # With flat, all sections close at the next heading
newly_closed, open_headings = open_headings, []
else: # Otherwise, figure out which sections have closed, if any
closed_start_index = len(open_headings)
for j, (start, last_heading) in enumerate(open_headings):
if heading.level <= last_heading.level:
closed_start_index = j
break
newly_closed = open_headings[closed_start_index:]
del open_headings[closed_start_index:]
for start, closed_heading in newly_closed:
if matcher(closed_heading):
sections.append((start, Wikicode(self.nodes[start:i])))
start = i if include_headings else (i + 1)
open_headings.append((start, heading))
# Add any remaining open headings to the list of sections:
for start, heading in open_headings:
if matcher(heading):
sections.append((start, Wikicode(self.nodes[start:])))
# Ensure that earlier sections are earlier in the returned list:
return [section for i, section in sorted(sections)] | python | def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
include_lead=None, include_headings=True):
"""Return a list of sections within the page.
Sections are returned as :class:`.Wikicode` objects with a shared node
list (implemented using :class:`.SmartList`) so that changes to
sections are reflected in the parent Wikicode object.
Each section contains all of its subsections, unless *flat* is
``True``. If *levels* is given, it should be a iterable of integers;
only sections whose heading levels are within it will be returned. If
*matches* is given, it should be either a function or a regex; only
sections whose headings match it (without the surrounding equal signs)
will be included. *flags* can be used to override the default regex
flags (see :meth:`ifilter`) if a regex *matches* is used.
If *include_lead* is ``True``, the first, lead section (without a
heading) will be included in the list; ``False`` will not include it;
the default will include it only if no specific *levels* were given. If
*include_headings* is ``True``, the section's beginning
:class:`.Heading` object will be included; otherwise, this is skipped.
"""
title_matcher = self._build_matcher(matches, flags)
matcher = lambda heading: (title_matcher(heading.title) and
(not levels or heading.level in levels))
iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
sections = [] # Tuples of (index_of_first_node, section)
open_headings = [] # Tuples of (index, heading), where index and
# heading.level are both monotonically increasing
# Add the lead section if appropriate:
if include_lead or not (include_lead is not None or matches or levels):
itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
try:
first = next(itr)[0]
sections.append((0, Wikicode(self.nodes[:first])))
except StopIteration: # No headings in page
sections.append((0, Wikicode(self.nodes[:])))
# Iterate over headings, adding sections to the list as they end:
for i, heading in iheadings:
if flat: # With flat, all sections close at the next heading
newly_closed, open_headings = open_headings, []
else: # Otherwise, figure out which sections have closed, if any
closed_start_index = len(open_headings)
for j, (start, last_heading) in enumerate(open_headings):
if heading.level <= last_heading.level:
closed_start_index = j
break
newly_closed = open_headings[closed_start_index:]
del open_headings[closed_start_index:]
for start, closed_heading in newly_closed:
if matcher(closed_heading):
sections.append((start, Wikicode(self.nodes[start:i])))
start = i if include_headings else (i + 1)
open_headings.append((start, heading))
# Add any remaining open headings to the list of sections:
for start, heading in open_headings:
if matcher(heading):
sections.append((start, Wikicode(self.nodes[start:])))
# Ensure that earlier sections are earlier in the returned list:
return [section for i, section in sorted(sections)] | [
"def",
"get_sections",
"(",
"self",
",",
"levels",
"=",
"None",
",",
"matches",
"=",
"None",
",",
"flags",
"=",
"FLAGS",
",",
"flat",
"=",
"False",
",",
"include_lead",
"=",
"None",
",",
"include_headings",
"=",
"True",
")",
":",
"title_matcher",
"=",
"self",
".",
"_build_matcher",
"(",
"matches",
",",
"flags",
")",
"matcher",
"=",
"lambda",
"heading",
":",
"(",
"title_matcher",
"(",
"heading",
".",
"title",
")",
"and",
"(",
"not",
"levels",
"or",
"heading",
".",
"level",
"in",
"levels",
")",
")",
"iheadings",
"=",
"self",
".",
"_indexed_ifilter",
"(",
"recursive",
"=",
"False",
",",
"forcetype",
"=",
"Heading",
")",
"sections",
"=",
"[",
"]",
"# Tuples of (index_of_first_node, section)",
"open_headings",
"=",
"[",
"]",
"# Tuples of (index, heading), where index and",
"# heading.level are both monotonically increasing",
"# Add the lead section if appropriate:",
"if",
"include_lead",
"or",
"not",
"(",
"include_lead",
"is",
"not",
"None",
"or",
"matches",
"or",
"levels",
")",
":",
"itr",
"=",
"self",
".",
"_indexed_ifilter",
"(",
"recursive",
"=",
"False",
",",
"forcetype",
"=",
"Heading",
")",
"try",
":",
"first",
"=",
"next",
"(",
"itr",
")",
"[",
"0",
"]",
"sections",
".",
"append",
"(",
"(",
"0",
",",
"Wikicode",
"(",
"self",
".",
"nodes",
"[",
":",
"first",
"]",
")",
")",
")",
"except",
"StopIteration",
":",
"# No headings in page",
"sections",
".",
"append",
"(",
"(",
"0",
",",
"Wikicode",
"(",
"self",
".",
"nodes",
"[",
":",
"]",
")",
")",
")",
"# Iterate over headings, adding sections to the list as they end:",
"for",
"i",
",",
"heading",
"in",
"iheadings",
":",
"if",
"flat",
":",
"# With flat, all sections close at the next heading",
"newly_closed",
",",
"open_headings",
"=",
"open_headings",
",",
"[",
"]",
"else",
":",
"# Otherwise, figure out which sections have closed, if any",
"closed_start_index",
"=",
"len",
"(",
"open_headings",
")",
"for",
"j",
",",
"(",
"start",
",",
"last_heading",
")",
"in",
"enumerate",
"(",
"open_headings",
")",
":",
"if",
"heading",
".",
"level",
"<=",
"last_heading",
".",
"level",
":",
"closed_start_index",
"=",
"j",
"break",
"newly_closed",
"=",
"open_headings",
"[",
"closed_start_index",
":",
"]",
"del",
"open_headings",
"[",
"closed_start_index",
":",
"]",
"for",
"start",
",",
"closed_heading",
"in",
"newly_closed",
":",
"if",
"matcher",
"(",
"closed_heading",
")",
":",
"sections",
".",
"append",
"(",
"(",
"start",
",",
"Wikicode",
"(",
"self",
".",
"nodes",
"[",
"start",
":",
"i",
"]",
")",
")",
")",
"start",
"=",
"i",
"if",
"include_headings",
"else",
"(",
"i",
"+",
"1",
")",
"open_headings",
".",
"append",
"(",
"(",
"start",
",",
"heading",
")",
")",
"# Add any remaining open headings to the list of sections:",
"for",
"start",
",",
"heading",
"in",
"open_headings",
":",
"if",
"matcher",
"(",
"heading",
")",
":",
"sections",
".",
"append",
"(",
"(",
"start",
",",
"Wikicode",
"(",
"self",
".",
"nodes",
"[",
"start",
":",
"]",
")",
")",
")",
"# Ensure that earlier sections are earlier in the returned list:",
"return",
"[",
"section",
"for",
"i",
",",
"section",
"in",
"sorted",
"(",
"sections",
")",
"]"
]
| Return a list of sections within the page.
Sections are returned as :class:`.Wikicode` objects with a shared node
list (implemented using :class:`.SmartList`) so that changes to
sections are reflected in the parent Wikicode object.
Each section contains all of its subsections, unless *flat* is
``True``. If *levels* is given, it should be a iterable of integers;
only sections whose heading levels are within it will be returned. If
*matches* is given, it should be either a function or a regex; only
sections whose headings match it (without the surrounding equal signs)
will be included. *flags* can be used to override the default regex
flags (see :meth:`ifilter`) if a regex *matches* is used.
If *include_lead* is ``True``, the first, lead section (without a
heading) will be included in the list; ``False`` will not include it;
the default will include it only if no specific *levels* were given. If
*include_headings* is ``True``, the section's beginning
:class:`.Heading` object will be included; otherwise, this is skipped. | [
"Return",
"a",
"list",
"of",
"sections",
"within",
"the",
"page",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L552-L615 | train |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | Wikicode.strip_code | def strip_code(self, normalize=True, collapse=True,
keep_template_params=False):
"""Return a rendered string without unprintable code such as templates.
The way a node is stripped is handled by the
:meth:`~.Node.__strip__` method of :class:`.Node` objects, which
generally return a subset of their nodes or ``None``. For example,
templates and tags are removed completely, links are stripped to just
their display part, headings are stripped to just their title.
If *normalize* is ``True``, various things may be done to strip code
further, such as converting HTML entities like ``Σ``, ``Σ``,
and ``Σ`` to ``Σ``. If *collapse* is ``True``, we will try to
remove excess whitespace as well (three or more newlines are converted
to two, for example). If *keep_template_params* is ``True``, then
template parameters will be preserved in the output (normally, they are
removed completely).
"""
kwargs = {
"normalize": normalize,
"collapse": collapse,
"keep_template_params": keep_template_params
}
nodes = []
for node in self.nodes:
stripped = node.__strip__(**kwargs)
if stripped:
nodes.append(str(stripped))
if collapse:
stripped = "".join(nodes).strip("\n")
while "\n\n\n" in stripped:
stripped = stripped.replace("\n\n\n", "\n\n")
return stripped
else:
return "".join(nodes) | python | def strip_code(self, normalize=True, collapse=True,
keep_template_params=False):
"""Return a rendered string without unprintable code such as templates.
The way a node is stripped is handled by the
:meth:`~.Node.__strip__` method of :class:`.Node` objects, which
generally return a subset of their nodes or ``None``. For example,
templates and tags are removed completely, links are stripped to just
their display part, headings are stripped to just their title.
If *normalize* is ``True``, various things may be done to strip code
further, such as converting HTML entities like ``Σ``, ``Σ``,
and ``Σ`` to ``Σ``. If *collapse* is ``True``, we will try to
remove excess whitespace as well (three or more newlines are converted
to two, for example). If *keep_template_params* is ``True``, then
template parameters will be preserved in the output (normally, they are
removed completely).
"""
kwargs = {
"normalize": normalize,
"collapse": collapse,
"keep_template_params": keep_template_params
}
nodes = []
for node in self.nodes:
stripped = node.__strip__(**kwargs)
if stripped:
nodes.append(str(stripped))
if collapse:
stripped = "".join(nodes).strip("\n")
while "\n\n\n" in stripped:
stripped = stripped.replace("\n\n\n", "\n\n")
return stripped
else:
return "".join(nodes) | [
"def",
"strip_code",
"(",
"self",
",",
"normalize",
"=",
"True",
",",
"collapse",
"=",
"True",
",",
"keep_template_params",
"=",
"False",
")",
":",
"kwargs",
"=",
"{",
"\"normalize\"",
":",
"normalize",
",",
"\"collapse\"",
":",
"collapse",
",",
"\"keep_template_params\"",
":",
"keep_template_params",
"}",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"stripped",
"=",
"node",
".",
"__strip__",
"(",
"*",
"*",
"kwargs",
")",
"if",
"stripped",
":",
"nodes",
".",
"append",
"(",
"str",
"(",
"stripped",
")",
")",
"if",
"collapse",
":",
"stripped",
"=",
"\"\"",
".",
"join",
"(",
"nodes",
")",
".",
"strip",
"(",
"\"\\n\"",
")",
"while",
"\"\\n\\n\\n\"",
"in",
"stripped",
":",
"stripped",
"=",
"stripped",
".",
"replace",
"(",
"\"\\n\\n\\n\"",
",",
"\"\\n\\n\"",
")",
"return",
"stripped",
"else",
":",
"return",
"\"\"",
".",
"join",
"(",
"nodes",
")"
]
| Return a rendered string without unprintable code such as templates.
The way a node is stripped is handled by the
:meth:`~.Node.__strip__` method of :class:`.Node` objects, which
generally return a subset of their nodes or ``None``. For example,
templates and tags are removed completely, links are stripped to just
their display part, headings are stripped to just their title.
If *normalize* is ``True``, various things may be done to strip code
further, such as converting HTML entities like ``Σ``, ``Σ``,
and ``Σ`` to ``Σ``. If *collapse* is ``True``, we will try to
remove excess whitespace as well (three or more newlines are converted
to two, for example). If *keep_template_params* is ``True``, then
template parameters will be preserved in the output (normally, they are
removed completely). | [
"Return",
"a",
"rendered",
"string",
"without",
"unprintable",
"code",
"such",
"as",
"templates",
"."
]
| 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L617-L653 | train |
Yubico/python-pyhsm | pyhsm/stick_daemon.py | write_pid_file | def write_pid_file(fn):
""" Create a file with our PID. """
if not fn:
return None
if fn == '' or fn == "''":
# work around argument passings in init-scripts
return None
f = open(fn, "w")
f.write("%s\n" % (os.getpid()))
f.close() | python | def write_pid_file(fn):
""" Create a file with our PID. """
if not fn:
return None
if fn == '' or fn == "''":
# work around argument passings in init-scripts
return None
f = open(fn, "w")
f.write("%s\n" % (os.getpid()))
f.close() | [
"def",
"write_pid_file",
"(",
"fn",
")",
":",
"if",
"not",
"fn",
":",
"return",
"None",
"if",
"fn",
"==",
"''",
"or",
"fn",
"==",
"\"''\"",
":",
"# work around argument passings in init-scripts",
"return",
"None",
"f",
"=",
"open",
"(",
"fn",
",",
"\"w\"",
")",
"f",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"(",
"os",
".",
"getpid",
"(",
")",
")",
")",
"f",
".",
"close",
"(",
")"
]
| Create a file with our PID. | [
"Create",
"a",
"file",
"with",
"our",
"PID",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/stick_daemon.py#L54-L63 | train |
Yubico/python-pyhsm | pyhsm/util.py | input_validate_str | def input_validate_str(string, name, max_len=None, exact_len=None):
""" Input validation for strings. """
if type(string) is not str:
raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string))
if max_len != None and len(string) > max_len:
raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string))
if exact_len != None and len(string) != exact_len:
raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string))
return string | python | def input_validate_str(string, name, max_len=None, exact_len=None):
""" Input validation for strings. """
if type(string) is not str:
raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string))
if max_len != None and len(string) > max_len:
raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string))
if exact_len != None and len(string) != exact_len:
raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string))
return string | [
"def",
"input_validate_str",
"(",
"string",
",",
"name",
",",
"max_len",
"=",
"None",
",",
"exact_len",
"=",
"None",
")",
":",
"if",
"type",
"(",
"string",
")",
"is",
"not",
"str",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputType",
"(",
"name",
",",
"str",
",",
"type",
"(",
"string",
")",
")",
"if",
"max_len",
"!=",
"None",
"and",
"len",
"(",
"string",
")",
">",
"max_len",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_InputTooLong",
"(",
"name",
",",
"max_len",
",",
"len",
"(",
"string",
")",
")",
"if",
"exact_len",
"!=",
"None",
"and",
"len",
"(",
"string",
")",
"!=",
"exact_len",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputSize",
"(",
"name",
",",
"exact_len",
",",
"len",
"(",
"string",
")",
")",
"return",
"string"
]
| Input validation for strings. | [
"Input",
"validation",
"for",
"strings",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L57-L65 | train |
Yubico/python-pyhsm | pyhsm/util.py | input_validate_int | def input_validate_int(value, name, max_value=None):
""" Input validation for integers. """
if type(value) is not int:
raise pyhsm.exception.YHSM_WrongInputType(name, int, type(value))
if max_value != None and value > max_value:
raise pyhsm.exception.YHSM_WrongInputSize(name, max_value, value)
return value | python | def input_validate_int(value, name, max_value=None):
""" Input validation for integers. """
if type(value) is not int:
raise pyhsm.exception.YHSM_WrongInputType(name, int, type(value))
if max_value != None and value > max_value:
raise pyhsm.exception.YHSM_WrongInputSize(name, max_value, value)
return value | [
"def",
"input_validate_int",
"(",
"value",
",",
"name",
",",
"max_value",
"=",
"None",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"not",
"int",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputType",
"(",
"name",
",",
"int",
",",
"type",
"(",
"value",
")",
")",
"if",
"max_value",
"!=",
"None",
"and",
"value",
">",
"max_value",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputSize",
"(",
"name",
",",
"max_value",
",",
"value",
")",
"return",
"value"
]
| Input validation for integers. | [
"Input",
"validation",
"for",
"integers",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L67-L73 | train |
Yubico/python-pyhsm | pyhsm/util.py | input_validate_nonce | def input_validate_nonce(nonce, name='nonce', pad = False):
""" Input validation for nonces. """
if type(nonce) is not str:
raise pyhsm.exception.YHSM_WrongInputType( \
name, str, type(nonce))
if len(nonce) > pyhsm.defines.YSM_AEAD_NONCE_SIZE:
raise pyhsm.exception.YHSM_InputTooLong(
name, pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(nonce))
if pad:
return nonce.ljust(pyhsm.defines.YSM_AEAD_NONCE_SIZE, chr(0x0))
else:
return nonce | python | def input_validate_nonce(nonce, name='nonce', pad = False):
""" Input validation for nonces. """
if type(nonce) is not str:
raise pyhsm.exception.YHSM_WrongInputType( \
name, str, type(nonce))
if len(nonce) > pyhsm.defines.YSM_AEAD_NONCE_SIZE:
raise pyhsm.exception.YHSM_InputTooLong(
name, pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(nonce))
if pad:
return nonce.ljust(pyhsm.defines.YSM_AEAD_NONCE_SIZE, chr(0x0))
else:
return nonce | [
"def",
"input_validate_nonce",
"(",
"nonce",
",",
"name",
"=",
"'nonce'",
",",
"pad",
"=",
"False",
")",
":",
"if",
"type",
"(",
"nonce",
")",
"is",
"not",
"str",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputType",
"(",
"name",
",",
"str",
",",
"type",
"(",
"nonce",
")",
")",
"if",
"len",
"(",
"nonce",
")",
">",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_InputTooLong",
"(",
"name",
",",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
",",
"len",
"(",
"nonce",
")",
")",
"if",
"pad",
":",
"return",
"nonce",
".",
"ljust",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
",",
"chr",
"(",
"0x0",
")",
")",
"else",
":",
"return",
"nonce"
]
| Input validation for nonces. | [
"Input",
"validation",
"for",
"nonces",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L75-L86 | train |
Yubico/python-pyhsm | pyhsm/util.py | input_validate_key_handle | def input_validate_key_handle(key_handle, name='key_handle'):
""" Input validation for key_handles. """
if type(key_handle) is not int:
try:
return key_handle_to_int(key_handle)
except pyhsm.exception.YHSM_Error:
raise pyhsm.exception.YHSM_WrongInputType(name, int, type(key_handle))
return key_handle | python | def input_validate_key_handle(key_handle, name='key_handle'):
""" Input validation for key_handles. """
if type(key_handle) is not int:
try:
return key_handle_to_int(key_handle)
except pyhsm.exception.YHSM_Error:
raise pyhsm.exception.YHSM_WrongInputType(name, int, type(key_handle))
return key_handle | [
"def",
"input_validate_key_handle",
"(",
"key_handle",
",",
"name",
"=",
"'key_handle'",
")",
":",
"if",
"type",
"(",
"key_handle",
")",
"is",
"not",
"int",
":",
"try",
":",
"return",
"key_handle_to_int",
"(",
"key_handle",
")",
"except",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputType",
"(",
"name",
",",
"int",
",",
"type",
"(",
"key_handle",
")",
")",
"return",
"key_handle"
]
| Input validation for key_handles. | [
"Input",
"validation",
"for",
"key_handles",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L88-L95 | train |
Yubico/python-pyhsm | pyhsm/util.py | input_validate_yubikey_secret | def input_validate_yubikey_secret(data, name='data'):
""" Input validation for YHSM_YubiKeySecret or string. """
if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret):
data = data.pack()
return input_validate_str(data, name) | python | def input_validate_yubikey_secret(data, name='data'):
""" Input validation for YHSM_YubiKeySecret or string. """
if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret):
data = data.pack()
return input_validate_str(data, name) | [
"def",
"input_validate_yubikey_secret",
"(",
"data",
",",
"name",
"=",
"'data'",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
")",
":",
"data",
"=",
"data",
".",
"pack",
"(",
")",
"return",
"input_validate_str",
"(",
"data",
",",
"name",
")"
]
| Input validation for YHSM_YubiKeySecret or string. | [
"Input",
"validation",
"for",
"YHSM_YubiKeySecret",
"or",
"string",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L97-L101 | train |
Yubico/python-pyhsm | pyhsm/util.py | input_validate_aead | def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE):
""" Input validation for YHSM_GeneratedAEAD or string. """
if isinstance(aead, pyhsm.aead_cmd.YHSM_GeneratedAEAD):
aead = aead.data
if expected_len != None:
return input_validate_str(aead, name, exact_len = expected_len)
else:
return input_validate_str(aead, name, max_len=max_aead_len) | python | def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE):
""" Input validation for YHSM_GeneratedAEAD or string. """
if isinstance(aead, pyhsm.aead_cmd.YHSM_GeneratedAEAD):
aead = aead.data
if expected_len != None:
return input_validate_str(aead, name, exact_len = expected_len)
else:
return input_validate_str(aead, name, max_len=max_aead_len) | [
"def",
"input_validate_aead",
"(",
"aead",
",",
"name",
"=",
"'aead'",
",",
"expected_len",
"=",
"None",
",",
"max_aead_len",
"=",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_MAX_SIZE",
")",
":",
"if",
"isinstance",
"(",
"aead",
",",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_GeneratedAEAD",
")",
":",
"aead",
"=",
"aead",
".",
"data",
"if",
"expected_len",
"!=",
"None",
":",
"return",
"input_validate_str",
"(",
"aead",
",",
"name",
",",
"exact_len",
"=",
"expected_len",
")",
"else",
":",
"return",
"input_validate_str",
"(",
"aead",
",",
"name",
",",
"max_len",
"=",
"max_aead_len",
")"
]
| Input validation for YHSM_GeneratedAEAD or string. | [
"Input",
"validation",
"for",
"YHSM_GeneratedAEAD",
"or",
"string",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L103-L110 | train |
Yubico/python-pyhsm | pyhsm/util.py | validate_cmd_response_nonce | def validate_cmd_response_nonce(got, used):
"""
Check that the returned nonce matches nonce used in request.
A request nonce of 000000000000 means the HSM should generate a nonce internally though,
so if 'used' is all zeros we actually check that 'got' does NOT match 'used'.
"""
if used == '000000000000'.decode('hex'):
if got == used:
raise(pyhsm.exception.YHSM_Error("Bad nonce in response (got %s, expected HSM generated nonce)" \
% (got.encode('hex'))))
return got
return validate_cmd_response_str('nonce', got, used) | python | def validate_cmd_response_nonce(got, used):
"""
Check that the returned nonce matches nonce used in request.
A request nonce of 000000000000 means the HSM should generate a nonce internally though,
so if 'used' is all zeros we actually check that 'got' does NOT match 'used'.
"""
if used == '000000000000'.decode('hex'):
if got == used:
raise(pyhsm.exception.YHSM_Error("Bad nonce in response (got %s, expected HSM generated nonce)" \
% (got.encode('hex'))))
return got
return validate_cmd_response_str('nonce', got, used) | [
"def",
"validate_cmd_response_nonce",
"(",
"got",
",",
"used",
")",
":",
"if",
"used",
"==",
"'000000000000'",
".",
"decode",
"(",
"'hex'",
")",
":",
"if",
"got",
"==",
"used",
":",
"raise",
"(",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"\"Bad nonce in response (got %s, expected HSM generated nonce)\"",
"%",
"(",
"got",
".",
"encode",
"(",
"'hex'",
")",
")",
")",
")",
"return",
"got",
"return",
"validate_cmd_response_str",
"(",
"'nonce'",
",",
"got",
",",
"used",
")"
]
| Check that the returned nonce matches nonce used in request.
A request nonce of 000000000000 means the HSM should generate a nonce internally though,
so if 'used' is all zeros we actually check that 'got' does NOT match 'used'. | [
"Check",
"that",
"the",
"returned",
"nonce",
"matches",
"nonce",
"used",
"in",
"request",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L152-L164 | train |
Yubico/python-pyhsm | pyhsm/hmac_cmd.py | _raw_pack | def _raw_pack(key_handle, flags, data):
"""
Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command.
"""
# #define YHSM_HMAC_RESET 0x01 // Flag to indicate reset at first packet
# #define YHSM_HMAC_FINAL 0x02 // Flag to indicate that the hash shall be calculated
# typedef struct {
# uint32_t keyHandle; // Key handle
# uint8_t flags; // Flags
# uint8_t numBytes; // Number of bytes in data packet
# uint8_t data[YHSM_MAX_PKT_SIZE - 6]; // Data to be written
# } YHSM_HMAC_SHA1_GENERATE_REQ;
return struct.pack('<IBB', key_handle, flags, len(data)) + data | python | def _raw_pack(key_handle, flags, data):
"""
Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command.
"""
# #define YHSM_HMAC_RESET 0x01 // Flag to indicate reset at first packet
# #define YHSM_HMAC_FINAL 0x02 // Flag to indicate that the hash shall be calculated
# typedef struct {
# uint32_t keyHandle; // Key handle
# uint8_t flags; // Flags
# uint8_t numBytes; // Number of bytes in data packet
# uint8_t data[YHSM_MAX_PKT_SIZE - 6]; // Data to be written
# } YHSM_HMAC_SHA1_GENERATE_REQ;
return struct.pack('<IBB', key_handle, flags, len(data)) + data | [
"def",
"_raw_pack",
"(",
"key_handle",
",",
"flags",
",",
"data",
")",
":",
"# #define YHSM_HMAC_RESET 0x01 // Flag to indicate reset at first packet",
"# #define YHSM_HMAC_FINAL 0x02 // Flag to indicate that the hash shall be calculated",
"# typedef struct {",
"# uint32_t keyHandle; // Key handle",
"# uint8_t flags; // Flags",
"# uint8_t numBytes; // Number of bytes in data packet",
"# uint8_t data[YHSM_MAX_PKT_SIZE - 6]; // Data to be written",
"# } YHSM_HMAC_SHA1_GENERATE_REQ;",
"return",
"struct",
".",
"pack",
"(",
"'<IBB'",
",",
"key_handle",
",",
"flags",
",",
"len",
"(",
"data",
")",
")",
"+",
"data"
]
| Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command. | [
"Common",
"code",
"for",
"packing",
"payload",
"to",
"YHSM_HMAC_SHA1_GENERATE",
"command",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/hmac_cmd.py#L110-L122 | train |
Yubico/python-pyhsm | pyhsm/hmac_cmd.py | YHSM_Cmd_HMAC_SHA1_Write.next | def next(self, data, final = False, to_buffer = False):
"""
Add more input to the HMAC SHA1.
"""
if final:
self.flags = pyhsm.defines.YSM_HMAC_SHA1_FINAL
else:
self.flags = 0x0
if to_buffer:
self.flags |= pyhsm.defines.YSM_HMAC_SHA1_TO_BUFFER
self.payload = _raw_pack(self.key_handle, self.flags, data)
self.final = final
return self | python | def next(self, data, final = False, to_buffer = False):
"""
Add more input to the HMAC SHA1.
"""
if final:
self.flags = pyhsm.defines.YSM_HMAC_SHA1_FINAL
else:
self.flags = 0x0
if to_buffer:
self.flags |= pyhsm.defines.YSM_HMAC_SHA1_TO_BUFFER
self.payload = _raw_pack(self.key_handle, self.flags, data)
self.final = final
return self | [
"def",
"next",
"(",
"self",
",",
"data",
",",
"final",
"=",
"False",
",",
"to_buffer",
"=",
"False",
")",
":",
"if",
"final",
":",
"self",
".",
"flags",
"=",
"pyhsm",
".",
"defines",
".",
"YSM_HMAC_SHA1_FINAL",
"else",
":",
"self",
".",
"flags",
"=",
"0x0",
"if",
"to_buffer",
":",
"self",
".",
"flags",
"|=",
"pyhsm",
".",
"defines",
".",
"YSM_HMAC_SHA1_TO_BUFFER",
"self",
".",
"payload",
"=",
"_raw_pack",
"(",
"self",
".",
"key_handle",
",",
"self",
".",
"flags",
",",
"data",
")",
"self",
".",
"final",
"=",
"final",
"return",
"self"
]
| Add more input to the HMAC SHA1. | [
"Add",
"more",
"input",
"to",
"the",
"HMAC",
"SHA1",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/hmac_cmd.py#L53-L65 | train |
Yubico/python-pyhsm | pyhsm/hmac_cmd.py | YHSM_Cmd_HMAC_SHA1_Write.get_hash | def get_hash(self):
"""
Get the HMAC-SHA1 that has been calculated this far.
"""
if not self.executed:
raise pyhsm.exception.YHSM_Error("HMAC-SHA1 hash not available, before execute().")
return self.result.hash_result | python | def get_hash(self):
"""
Get the HMAC-SHA1 that has been calculated this far.
"""
if not self.executed:
raise pyhsm.exception.YHSM_Error("HMAC-SHA1 hash not available, before execute().")
return self.result.hash_result | [
"def",
"get_hash",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"executed",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"\"HMAC-SHA1 hash not available, before execute().\"",
")",
"return",
"self",
".",
"result",
".",
"hash_result"
]
| Get the HMAC-SHA1 that has been calculated this far. | [
"Get",
"the",
"HMAC",
"-",
"SHA1",
"that",
"has",
"been",
"calculated",
"this",
"far",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/hmac_cmd.py#L67-L73 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | check_signature | def check_signature(params):
"""
Verify the signature of the parameters in an OTP v2.0 verify request.
Returns ValResultBool, Key
"""
if 'id' in params:
try:
id_int = int(params['id'][0])
except:
my_log_message(args, syslog.LOG_INFO, "Non-numerical client id (%s) in request." % (params['id'][0]))
return False, None
key = client_ids.get(id_int)
if key:
if 'h' in params:
sig = params['h'][0]
good_sig = make_signature(params, key)
if sig == good_sig:
#my_log_message(args, syslog.LOG_DEBUG, "Good signature (client id '%i')" % id_int)
return True, key
else:
my_log_message(args, syslog.LOG_INFO, "Bad signature from client id '%i' (%s, expected %s)." \
% (id_int, sig, good_sig))
else:
my_log_message(args, syslog.LOG_INFO, "Client id (%i) but no HMAC in request." % (id_int))
return False, key
else:
my_log_message(args, syslog.LOG_INFO, "Unknown client id '%i'" % (id_int))
return False, None
return True, None | python | def check_signature(params):
"""
Verify the signature of the parameters in an OTP v2.0 verify request.
Returns ValResultBool, Key
"""
if 'id' in params:
try:
id_int = int(params['id'][0])
except:
my_log_message(args, syslog.LOG_INFO, "Non-numerical client id (%s) in request." % (params['id'][0]))
return False, None
key = client_ids.get(id_int)
if key:
if 'h' in params:
sig = params['h'][0]
good_sig = make_signature(params, key)
if sig == good_sig:
#my_log_message(args, syslog.LOG_DEBUG, "Good signature (client id '%i')" % id_int)
return True, key
else:
my_log_message(args, syslog.LOG_INFO, "Bad signature from client id '%i' (%s, expected %s)." \
% (id_int, sig, good_sig))
else:
my_log_message(args, syslog.LOG_INFO, "Client id (%i) but no HMAC in request." % (id_int))
return False, key
else:
my_log_message(args, syslog.LOG_INFO, "Unknown client id '%i'" % (id_int))
return False, None
return True, None | [
"def",
"check_signature",
"(",
"params",
")",
":",
"if",
"'id'",
"in",
"params",
":",
"try",
":",
"id_int",
"=",
"int",
"(",
"params",
"[",
"'id'",
"]",
"[",
"0",
"]",
")",
"except",
":",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Non-numerical client id (%s) in request.\"",
"%",
"(",
"params",
"[",
"'id'",
"]",
"[",
"0",
"]",
")",
")",
"return",
"False",
",",
"None",
"key",
"=",
"client_ids",
".",
"get",
"(",
"id_int",
")",
"if",
"key",
":",
"if",
"'h'",
"in",
"params",
":",
"sig",
"=",
"params",
"[",
"'h'",
"]",
"[",
"0",
"]",
"good_sig",
"=",
"make_signature",
"(",
"params",
",",
"key",
")",
"if",
"sig",
"==",
"good_sig",
":",
"#my_log_message(args, syslog.LOG_DEBUG, \"Good signature (client id '%i')\" % id_int)",
"return",
"True",
",",
"key",
"else",
":",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Bad signature from client id '%i' (%s, expected %s).\"",
"%",
"(",
"id_int",
",",
"sig",
",",
"good_sig",
")",
")",
"else",
":",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Client id (%i) but no HMAC in request.\"",
"%",
"(",
"id_int",
")",
")",
"return",
"False",
",",
"key",
"else",
":",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Unknown client id '%i'\"",
"%",
"(",
"id_int",
")",
")",
"return",
"False",
",",
"None",
"return",
"True",
",",
"None"
]
| Verify the signature of the parameters in an OTP v2.0 verify request.
Returns ValResultBool, Key | [
"Verify",
"the",
"signature",
"of",
"the",
"parameters",
"in",
"an",
"OTP",
"v2",
".",
"0",
"verify",
"request",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L297-L326 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | validate_oath_hotp | def validate_oath_hotp(self, params):
"""
Validate OATH-HOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database.
"""
from_key = params["hotp"][0]
if not re.match(hotp_valid_input, from_key):
self.log_error("IN: %s, Invalid OATH-HOTP OTP" % (params))
return "ERR Invalid OATH-HOTP OTP"
uid, otp, = get_oath_hotp_bits(params)
if not uid or not otp:
self.log_error("IN: %s, could not get UID/OTP ('%s'/'%s')" % (params, uid, otp))
return "ERR Invalid OATH-HOTP input"
if args.debug:
print "OATH-HOTP uid %s, OTP %s" % (uid, otp)
# Fetch counter value for `uid' from database
try:
db = ValOathDb(args.db_file)
entry = db.get(uid)
except Exception, e:
self.log_error("IN: %s, database error : '%s'" % (params, e))
return "ERR Internal error"
# Check for correct OATH-HOTP OTP
nonce = entry.data["nonce"].decode('hex')
aead = entry.data["aead"].decode('hex')
new_counter = pyhsm.oath_hotp.search_for_oath_code(hsm, entry.data["key_handle"], nonce, aead, \
entry.data["oath_c"], otp, args.look_ahead)
if args.debug:
print "OATH-HOTP %i..%i -> new C == %s" \
% (entry.data["oath_c"], entry.data["oath_c"] + args.look_ahead, new_counter)
if type(new_counter) != int:
# XXX increase 'throttling parameter' to make brute forcing harder/impossible
return "ERR Could not validate OATH-HOTP OTP"
try:
# Must successfully store new_counter before we return OK
if db.update_oath_hotp_c(entry, new_counter):
return "OK counter=%04x" % (new_counter)
else:
return "ERR replayed OATH-HOTP"
except Exception, e:
self.log_error("IN: %s, database error updating counter : %s" % (params, e))
return "ERR Internal error" | python | def validate_oath_hotp(self, params):
"""
Validate OATH-HOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database.
"""
from_key = params["hotp"][0]
if not re.match(hotp_valid_input, from_key):
self.log_error("IN: %s, Invalid OATH-HOTP OTP" % (params))
return "ERR Invalid OATH-HOTP OTP"
uid, otp, = get_oath_hotp_bits(params)
if not uid or not otp:
self.log_error("IN: %s, could not get UID/OTP ('%s'/'%s')" % (params, uid, otp))
return "ERR Invalid OATH-HOTP input"
if args.debug:
print "OATH-HOTP uid %s, OTP %s" % (uid, otp)
# Fetch counter value for `uid' from database
try:
db = ValOathDb(args.db_file)
entry = db.get(uid)
except Exception, e:
self.log_error("IN: %s, database error : '%s'" % (params, e))
return "ERR Internal error"
# Check for correct OATH-HOTP OTP
nonce = entry.data["nonce"].decode('hex')
aead = entry.data["aead"].decode('hex')
new_counter = pyhsm.oath_hotp.search_for_oath_code(hsm, entry.data["key_handle"], nonce, aead, \
entry.data["oath_c"], otp, args.look_ahead)
if args.debug:
print "OATH-HOTP %i..%i -> new C == %s" \
% (entry.data["oath_c"], entry.data["oath_c"] + args.look_ahead, new_counter)
if type(new_counter) != int:
# XXX increase 'throttling parameter' to make brute forcing harder/impossible
return "ERR Could not validate OATH-HOTP OTP"
try:
# Must successfully store new_counter before we return OK
if db.update_oath_hotp_c(entry, new_counter):
return "OK counter=%04x" % (new_counter)
else:
return "ERR replayed OATH-HOTP"
except Exception, e:
self.log_error("IN: %s, database error updating counter : %s" % (params, e))
return "ERR Internal error" | [
"def",
"validate_oath_hotp",
"(",
"self",
",",
"params",
")",
":",
"from_key",
"=",
"params",
"[",
"\"hotp\"",
"]",
"[",
"0",
"]",
"if",
"not",
"re",
".",
"match",
"(",
"hotp_valid_input",
",",
"from_key",
")",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, Invalid OATH-HOTP OTP\"",
"%",
"(",
"params",
")",
")",
"return",
"\"ERR Invalid OATH-HOTP OTP\"",
"uid",
",",
"otp",
",",
"=",
"get_oath_hotp_bits",
"(",
"params",
")",
"if",
"not",
"uid",
"or",
"not",
"otp",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, could not get UID/OTP ('%s'/'%s')\"",
"%",
"(",
"params",
",",
"uid",
",",
"otp",
")",
")",
"return",
"\"ERR Invalid OATH-HOTP input\"",
"if",
"args",
".",
"debug",
":",
"print",
"\"OATH-HOTP uid %s, OTP %s\"",
"%",
"(",
"uid",
",",
"otp",
")",
"# Fetch counter value for `uid' from database",
"try",
":",
"db",
"=",
"ValOathDb",
"(",
"args",
".",
"db_file",
")",
"entry",
"=",
"db",
".",
"get",
"(",
"uid",
")",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, database error : '%s'\"",
"%",
"(",
"params",
",",
"e",
")",
")",
"return",
"\"ERR Internal error\"",
"# Check for correct OATH-HOTP OTP",
"nonce",
"=",
"entry",
".",
"data",
"[",
"\"nonce\"",
"]",
".",
"decode",
"(",
"'hex'",
")",
"aead",
"=",
"entry",
".",
"data",
"[",
"\"aead\"",
"]",
".",
"decode",
"(",
"'hex'",
")",
"new_counter",
"=",
"pyhsm",
".",
"oath_hotp",
".",
"search_for_oath_code",
"(",
"hsm",
",",
"entry",
".",
"data",
"[",
"\"key_handle\"",
"]",
",",
"nonce",
",",
"aead",
",",
"entry",
".",
"data",
"[",
"\"oath_c\"",
"]",
",",
"otp",
",",
"args",
".",
"look_ahead",
")",
"if",
"args",
".",
"debug",
":",
"print",
"\"OATH-HOTP %i..%i -> new C == %s\"",
"%",
"(",
"entry",
".",
"data",
"[",
"\"oath_c\"",
"]",
",",
"entry",
".",
"data",
"[",
"\"oath_c\"",
"]",
"+",
"args",
".",
"look_ahead",
",",
"new_counter",
")",
"if",
"type",
"(",
"new_counter",
")",
"!=",
"int",
":",
"# XXX increase 'throttling parameter' to make brute forcing harder/impossible",
"return",
"\"ERR Could not validate OATH-HOTP OTP\"",
"try",
":",
"# Must successfully store new_counter before we return OK",
"if",
"db",
".",
"update_oath_hotp_c",
"(",
"entry",
",",
"new_counter",
")",
":",
"return",
"\"OK counter=%04x\"",
"%",
"(",
"new_counter",
")",
"else",
":",
"return",
"\"ERR replayed OATH-HOTP\"",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, database error updating counter : %s\"",
"%",
"(",
"params",
",",
"e",
")",
")",
"return",
"\"ERR Internal error\""
]
| Validate OATH-HOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database. | [
"Validate",
"OATH",
"-",
"HOTP",
"code",
"using",
"YubiHSM",
"HMAC",
"-",
"SHA1",
"hashing",
"with",
"token",
"keys",
"secured",
"in",
"AEAD",
"s",
"that",
"we",
"have",
"stored",
"in",
"an",
"SQLite3",
"database",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L339-L382 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | validate_oath_totp | def validate_oath_totp(self, params):
"""
Validate OATH-TOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database.
"""
from_key = params["totp"][0]
if not re.match(totp_valid_input, from_key):
self.log_error("IN: %s, Invalid OATH-TOTP OTP" % (params))
return "ERR Invalid OATH-TOTP OTP"
uid, otp, = get_oath_totp_bits(params)
if not uid or not otp:
self.log_error("IN: %s, could not get UID/OTP ('%s'/'%s')" % (params, uid, otp))
return "ERR Invalid OATH-TOTP input"
if args.debug:
print "OATH-TOTP uid %s, OTP %s" % (uid, otp)
# Fetch counter value for `uid' from database
try:
db = ValOathDb(args.db_file)
entry = db.get(uid)
except Exception, e:
self.log_error("IN: %s, database error : '%s'" % (params, e))
return "ERR Internal error"
# Check for correct OATH-TOTP OTP
nonce = entry.data["nonce"].decode('hex')
aead = entry.data["aead"].decode('hex')
new_timecounter = pyhsm.oath_totp.search_for_oath_code(
hsm, entry.data["key_handle"], nonce, aead, otp, args.interval, args.tolerance)
if args.debug:
print "OATH-TOTP counter: %i, interval: %i -> new timecounter == %s" \
% (entry.data["oath_c"], args.interval, new_timecounter)
if type(new_timecounter) != int:
return "ERR Could not validate OATH-TOTP OTP"
try:
# Must successfully store new_timecounter before we return OK
# Can use existing hotp function since it would be identical
if db.update_oath_hotp_c(entry, new_timecounter):
return "OK timecounter=%04x" % (new_timecounter)
else:
return "ERR replayed OATH-TOTP"
except Exception, e:
self.log_error("IN: %s, database error updating counter : %s" % (params, e))
return "ERR Internal error" | python | def validate_oath_totp(self, params):
"""
Validate OATH-TOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database.
"""
from_key = params["totp"][0]
if not re.match(totp_valid_input, from_key):
self.log_error("IN: %s, Invalid OATH-TOTP OTP" % (params))
return "ERR Invalid OATH-TOTP OTP"
uid, otp, = get_oath_totp_bits(params)
if not uid or not otp:
self.log_error("IN: %s, could not get UID/OTP ('%s'/'%s')" % (params, uid, otp))
return "ERR Invalid OATH-TOTP input"
if args.debug:
print "OATH-TOTP uid %s, OTP %s" % (uid, otp)
# Fetch counter value for `uid' from database
try:
db = ValOathDb(args.db_file)
entry = db.get(uid)
except Exception, e:
self.log_error("IN: %s, database error : '%s'" % (params, e))
return "ERR Internal error"
# Check for correct OATH-TOTP OTP
nonce = entry.data["nonce"].decode('hex')
aead = entry.data["aead"].decode('hex')
new_timecounter = pyhsm.oath_totp.search_for_oath_code(
hsm, entry.data["key_handle"], nonce, aead, otp, args.interval, args.tolerance)
if args.debug:
print "OATH-TOTP counter: %i, interval: %i -> new timecounter == %s" \
% (entry.data["oath_c"], args.interval, new_timecounter)
if type(new_timecounter) != int:
return "ERR Could not validate OATH-TOTP OTP"
try:
# Must successfully store new_timecounter before we return OK
# Can use existing hotp function since it would be identical
if db.update_oath_hotp_c(entry, new_timecounter):
return "OK timecounter=%04x" % (new_timecounter)
else:
return "ERR replayed OATH-TOTP"
except Exception, e:
self.log_error("IN: %s, database error updating counter : %s" % (params, e))
return "ERR Internal error" | [
"def",
"validate_oath_totp",
"(",
"self",
",",
"params",
")",
":",
"from_key",
"=",
"params",
"[",
"\"totp\"",
"]",
"[",
"0",
"]",
"if",
"not",
"re",
".",
"match",
"(",
"totp_valid_input",
",",
"from_key",
")",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, Invalid OATH-TOTP OTP\"",
"%",
"(",
"params",
")",
")",
"return",
"\"ERR Invalid OATH-TOTP OTP\"",
"uid",
",",
"otp",
",",
"=",
"get_oath_totp_bits",
"(",
"params",
")",
"if",
"not",
"uid",
"or",
"not",
"otp",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, could not get UID/OTP ('%s'/'%s')\"",
"%",
"(",
"params",
",",
"uid",
",",
"otp",
")",
")",
"return",
"\"ERR Invalid OATH-TOTP input\"",
"if",
"args",
".",
"debug",
":",
"print",
"\"OATH-TOTP uid %s, OTP %s\"",
"%",
"(",
"uid",
",",
"otp",
")",
"# Fetch counter value for `uid' from database",
"try",
":",
"db",
"=",
"ValOathDb",
"(",
"args",
".",
"db_file",
")",
"entry",
"=",
"db",
".",
"get",
"(",
"uid",
")",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, database error : '%s'\"",
"%",
"(",
"params",
",",
"e",
")",
")",
"return",
"\"ERR Internal error\"",
"# Check for correct OATH-TOTP OTP",
"nonce",
"=",
"entry",
".",
"data",
"[",
"\"nonce\"",
"]",
".",
"decode",
"(",
"'hex'",
")",
"aead",
"=",
"entry",
".",
"data",
"[",
"\"aead\"",
"]",
".",
"decode",
"(",
"'hex'",
")",
"new_timecounter",
"=",
"pyhsm",
".",
"oath_totp",
".",
"search_for_oath_code",
"(",
"hsm",
",",
"entry",
".",
"data",
"[",
"\"key_handle\"",
"]",
",",
"nonce",
",",
"aead",
",",
"otp",
",",
"args",
".",
"interval",
",",
"args",
".",
"tolerance",
")",
"if",
"args",
".",
"debug",
":",
"print",
"\"OATH-TOTP counter: %i, interval: %i -> new timecounter == %s\"",
"%",
"(",
"entry",
".",
"data",
"[",
"\"oath_c\"",
"]",
",",
"args",
".",
"interval",
",",
"new_timecounter",
")",
"if",
"type",
"(",
"new_timecounter",
")",
"!=",
"int",
":",
"return",
"\"ERR Could not validate OATH-TOTP OTP\"",
"try",
":",
"# Must successfully store new_timecounter before we return OK",
"# Can use existing hotp function since it would be identical",
"if",
"db",
".",
"update_oath_hotp_c",
"(",
"entry",
",",
"new_timecounter",
")",
":",
"return",
"\"OK timecounter=%04x\"",
"%",
"(",
"new_timecounter",
")",
"else",
":",
"return",
"\"ERR replayed OATH-TOTP\"",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log_error",
"(",
"\"IN: %s, database error updating counter : %s\"",
"%",
"(",
"params",
",",
"e",
")",
")",
"return",
"\"ERR Internal error\""
]
| Validate OATH-TOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database. | [
"Validate",
"OATH",
"-",
"TOTP",
"code",
"using",
"YubiHSM",
"HMAC",
"-",
"SHA1",
"hashing",
"with",
"token",
"keys",
"secured",
"in",
"AEAD",
"s",
"that",
"we",
"have",
"stored",
"in",
"an",
"SQLite3",
"database",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L384-L428 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | validate_pwhash | def validate_pwhash(_self, params):
"""
Validate password hash using YubiHSM.
"""
pwhash, nonce, aead, key_handle = get_pwhash_bits(params)
d_aead = aead.decode('hex')
plaintext_len = len(d_aead) - pyhsm.defines.YSM_AEAD_MAC_SIZE
pw = pwhash.ljust(plaintext_len, chr(0x0))
if hsm.validate_aead(nonce.decode('hex'), key_handle, d_aead, pw):
return "OK pwhash validated"
return "ERR Could not validate pwhash" | python | def validate_pwhash(_self, params):
"""
Validate password hash using YubiHSM.
"""
pwhash, nonce, aead, key_handle = get_pwhash_bits(params)
d_aead = aead.decode('hex')
plaintext_len = len(d_aead) - pyhsm.defines.YSM_AEAD_MAC_SIZE
pw = pwhash.ljust(plaintext_len, chr(0x0))
if hsm.validate_aead(nonce.decode('hex'), key_handle, d_aead, pw):
return "OK pwhash validated"
return "ERR Could not validate pwhash" | [
"def",
"validate_pwhash",
"(",
"_self",
",",
"params",
")",
":",
"pwhash",
",",
"nonce",
",",
"aead",
",",
"key_handle",
"=",
"get_pwhash_bits",
"(",
"params",
")",
"d_aead",
"=",
"aead",
".",
"decode",
"(",
"'hex'",
")",
"plaintext_len",
"=",
"len",
"(",
"d_aead",
")",
"-",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_MAC_SIZE",
"pw",
"=",
"pwhash",
".",
"ljust",
"(",
"plaintext_len",
",",
"chr",
"(",
"0x0",
")",
")",
"if",
"hsm",
".",
"validate_aead",
"(",
"nonce",
".",
"decode",
"(",
"'hex'",
")",
",",
"key_handle",
",",
"d_aead",
",",
"pw",
")",
":",
"return",
"\"OK pwhash validated\"",
"return",
"\"ERR Could not validate pwhash\""
]
| Validate password hash using YubiHSM. | [
"Validate",
"password",
"hash",
"using",
"YubiHSM",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L430-L440 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | get_pwhash_bits | def get_pwhash_bits(params):
""" Extract bits for password hash validation from params. """
if not "pwhash" in params or \
not "nonce" in params or \
not "aead" in params or \
not "kh" in params:
raise Exception("Missing required parameter in request (pwhash, nonce, aead or kh)")
pwhash = params["pwhash"][0]
nonce = params["nonce"][0]
aead = params["aead"][0]
key_handle = pyhsm.util.key_handle_to_int(params["kh"][0])
return pwhash, nonce, aead, key_handle | python | def get_pwhash_bits(params):
""" Extract bits for password hash validation from params. """
if not "pwhash" in params or \
not "nonce" in params or \
not "aead" in params or \
not "kh" in params:
raise Exception("Missing required parameter in request (pwhash, nonce, aead or kh)")
pwhash = params["pwhash"][0]
nonce = params["nonce"][0]
aead = params["aead"][0]
key_handle = pyhsm.util.key_handle_to_int(params["kh"][0])
return pwhash, nonce, aead, key_handle | [
"def",
"get_pwhash_bits",
"(",
"params",
")",
":",
"if",
"not",
"\"pwhash\"",
"in",
"params",
"or",
"not",
"\"nonce\"",
"in",
"params",
"or",
"not",
"\"aead\"",
"in",
"params",
"or",
"not",
"\"kh\"",
"in",
"params",
":",
"raise",
"Exception",
"(",
"\"Missing required parameter in request (pwhash, nonce, aead or kh)\"",
")",
"pwhash",
"=",
"params",
"[",
"\"pwhash\"",
"]",
"[",
"0",
"]",
"nonce",
"=",
"params",
"[",
"\"nonce\"",
"]",
"[",
"0",
"]",
"aead",
"=",
"params",
"[",
"\"aead\"",
"]",
"[",
"0",
"]",
"key_handle",
"=",
"pyhsm",
".",
"util",
".",
"key_handle_to_int",
"(",
"params",
"[",
"\"kh\"",
"]",
"[",
"0",
"]",
")",
"return",
"pwhash",
",",
"nonce",
",",
"aead",
",",
"key_handle"
]
| Extract bits for password hash validation from params. | [
"Extract",
"bits",
"for",
"password",
"hash",
"validation",
"from",
"params",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L442-L453 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | get_oath_hotp_bits | def get_oath_hotp_bits(params):
""" Extract the OATH-HOTP uid and OTP from params. """
if "uid" in params:
return params["uid"][0], int(params["hotp"][0])
m = re.match("^([cbdefghijklnrtuv]*)([0-9]{6,8})", params["hotp"][0])
uid, otp, = m.groups()
return uid, int(otp), | python | def get_oath_hotp_bits(params):
""" Extract the OATH-HOTP uid and OTP from params. """
if "uid" in params:
return params["uid"][0], int(params["hotp"][0])
m = re.match("^([cbdefghijklnrtuv]*)([0-9]{6,8})", params["hotp"][0])
uid, otp, = m.groups()
return uid, int(otp), | [
"def",
"get_oath_hotp_bits",
"(",
"params",
")",
":",
"if",
"\"uid\"",
"in",
"params",
":",
"return",
"params",
"[",
"\"uid\"",
"]",
"[",
"0",
"]",
",",
"int",
"(",
"params",
"[",
"\"hotp\"",
"]",
"[",
"0",
"]",
")",
"m",
"=",
"re",
".",
"match",
"(",
"\"^([cbdefghijklnrtuv]*)([0-9]{6,8})\"",
",",
"params",
"[",
"\"hotp\"",
"]",
"[",
"0",
"]",
")",
"uid",
",",
"otp",
",",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"uid",
",",
"int",
"(",
"otp",
")",
","
]
| Extract the OATH-HOTP uid and OTP from params. | [
"Extract",
"the",
"OATH",
"-",
"HOTP",
"uid",
"and",
"OTP",
"from",
"params",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L455-L461 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | load_clients_file | def load_clients_file(filename):
"""
Load a list of base64 encoded shared secrets for numerical client ids.
Returns a dict.
Format of file is expected to be
# This is a comment. Blank lines are OK.
123,c2hhcmVkIHNlY3JldA==
456,MTIzNDU2Nzg5MDEyMw==
"""
res = {}
content = []
try:
fhandle = file(filename)
content = fhandle.readlines()
fhandle.close()
except IOError:
return None
linenum = 0
for line in content:
linenum += 1
while line.endswith("\r") or line.endswith("\n"):
line = line[:-1]
if re.match("(^\s*#|^\s*$)", line):
# skip comments and empty lines
continue
parts = [x.strip() for x in line.split(',')]
try:
if len(parts) != 2:
raise Exception()
id_num = int(parts[0])
key = base64.b64decode(parts[1])
res[id_num] = key
except:
my_log_message(args, syslog.LOG_ERR, 'Bad data on line %i of clients file "%s" : "%s"' % (linenum, filename, line))
return None
return res | python | def load_clients_file(filename):
"""
Load a list of base64 encoded shared secrets for numerical client ids.
Returns a dict.
Format of file is expected to be
# This is a comment. Blank lines are OK.
123,c2hhcmVkIHNlY3JldA==
456,MTIzNDU2Nzg5MDEyMw==
"""
res = {}
content = []
try:
fhandle = file(filename)
content = fhandle.readlines()
fhandle.close()
except IOError:
return None
linenum = 0
for line in content:
linenum += 1
while line.endswith("\r") or line.endswith("\n"):
line = line[:-1]
if re.match("(^\s*#|^\s*$)", line):
# skip comments and empty lines
continue
parts = [x.strip() for x in line.split(',')]
try:
if len(parts) != 2:
raise Exception()
id_num = int(parts[0])
key = base64.b64decode(parts[1])
res[id_num] = key
except:
my_log_message(args, syslog.LOG_ERR, 'Bad data on line %i of clients file "%s" : "%s"' % (linenum, filename, line))
return None
return res | [
"def",
"load_clients_file",
"(",
"filename",
")",
":",
"res",
"=",
"{",
"}",
"content",
"=",
"[",
"]",
"try",
":",
"fhandle",
"=",
"file",
"(",
"filename",
")",
"content",
"=",
"fhandle",
".",
"readlines",
"(",
")",
"fhandle",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"return",
"None",
"linenum",
"=",
"0",
"for",
"line",
"in",
"content",
":",
"linenum",
"+=",
"1",
"while",
"line",
".",
"endswith",
"(",
"\"\\r\"",
")",
"or",
"line",
".",
"endswith",
"(",
"\"\\n\"",
")",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"if",
"re",
".",
"match",
"(",
"\"(^\\s*#|^\\s*$)\"",
",",
"line",
")",
":",
"# skip comments and empty lines",
"continue",
"parts",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"line",
".",
"split",
"(",
"','",
")",
"]",
"try",
":",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
":",
"raise",
"Exception",
"(",
")",
"id_num",
"=",
"int",
"(",
"parts",
"[",
"0",
"]",
")",
"key",
"=",
"base64",
".",
"b64decode",
"(",
"parts",
"[",
"1",
"]",
")",
"res",
"[",
"id_num",
"]",
"=",
"key",
"except",
":",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_ERR",
",",
"'Bad data on line %i of clients file \"%s\" : \"%s\"'",
"%",
"(",
"linenum",
",",
"filename",
",",
"line",
")",
")",
"return",
"None",
"return",
"res"
]
| Load a list of base64 encoded shared secrets for numerical client ids.
Returns a dict.
Format of file is expected to be
# This is a comment. Blank lines are OK.
123,c2hhcmVkIHNlY3JldA==
456,MTIzNDU2Nzg5MDEyMw== | [
"Load",
"a",
"list",
"of",
"base64",
"encoded",
"shared",
"secrets",
"for",
"numerical",
"client",
"ids",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L657-L696 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | run | def run():
"""
Start the BaseHTTPServer and serve requests forever.
"""
server_address = (args.listen_addr, args.listen_port)
httpd = YHSM_VALServer(server_address, YHSM_VALRequestHandler)
my_log_message(args, syslog.LOG_INFO, "Serving requests to 'http://%s:%s%s' (YubiHSM: '%s')" \
% (args.listen_addr, args.listen_port, args.serve_url, args.device))
httpd.serve_forever() | python | def run():
"""
Start the BaseHTTPServer and serve requests forever.
"""
server_address = (args.listen_addr, args.listen_port)
httpd = YHSM_VALServer(server_address, YHSM_VALRequestHandler)
my_log_message(args, syslog.LOG_INFO, "Serving requests to 'http://%s:%s%s' (YubiHSM: '%s')" \
% (args.listen_addr, args.listen_port, args.serve_url, args.device))
httpd.serve_forever() | [
"def",
"run",
"(",
")",
":",
"server_address",
"=",
"(",
"args",
".",
"listen_addr",
",",
"args",
".",
"listen_port",
")",
"httpd",
"=",
"YHSM_VALServer",
"(",
"server_address",
",",
"YHSM_VALRequestHandler",
")",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Serving requests to 'http://%s:%s%s' (YubiHSM: '%s')\"",
"%",
"(",
"args",
".",
"listen_addr",
",",
"args",
".",
"listen_port",
",",
"args",
".",
"serve_url",
",",
"args",
".",
"device",
")",
")",
"httpd",
".",
"serve_forever",
"(",
")"
]
| Start the BaseHTTPServer and serve requests forever. | [
"Start",
"the",
"BaseHTTPServer",
"and",
"serve",
"requests",
"forever",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L709-L717 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | main | def main():
"""
The main function that will be executed when running this as a stand alone script.
"""
my_name = os.path.basename(sys.argv[0])
if not my_name:
my_name = "yhsm-validation-server"
syslog.openlog(my_name, syslog.LOG_PID, syslog.LOG_LOCAL0)
global args
args = parse_args()
args_fixup()
global hsm
try:
hsm = pyhsm.YHSM(device = args.device, debug = args.debug)
except serial.SerialException, e:
my_log_message(args, syslog.LOG_ERR, 'Failed opening YubiHSM device "%s" : %s' %(args.device, e))
return 1
write_pid_file(args.pid_file)
try:
run()
except KeyboardInterrupt:
print ""
print "Shutting down"
print "" | python | def main():
"""
The main function that will be executed when running this as a stand alone script.
"""
my_name = os.path.basename(sys.argv[0])
if not my_name:
my_name = "yhsm-validation-server"
syslog.openlog(my_name, syslog.LOG_PID, syslog.LOG_LOCAL0)
global args
args = parse_args()
args_fixup()
global hsm
try:
hsm = pyhsm.YHSM(device = args.device, debug = args.debug)
except serial.SerialException, e:
my_log_message(args, syslog.LOG_ERR, 'Failed opening YubiHSM device "%s" : %s' %(args.device, e))
return 1
write_pid_file(args.pid_file)
try:
run()
except KeyboardInterrupt:
print ""
print "Shutting down"
print "" | [
"def",
"main",
"(",
")",
":",
"my_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"not",
"my_name",
":",
"my_name",
"=",
"\"yhsm-validation-server\"",
"syslog",
".",
"openlog",
"(",
"my_name",
",",
"syslog",
".",
"LOG_PID",
",",
"syslog",
".",
"LOG_LOCAL0",
")",
"global",
"args",
"args",
"=",
"parse_args",
"(",
")",
"args_fixup",
"(",
")",
"global",
"hsm",
"try",
":",
"hsm",
"=",
"pyhsm",
".",
"YHSM",
"(",
"device",
"=",
"args",
".",
"device",
",",
"debug",
"=",
"args",
".",
"debug",
")",
"except",
"serial",
".",
"SerialException",
",",
"e",
":",
"my_log_message",
"(",
"args",
",",
"syslog",
".",
"LOG_ERR",
",",
"'Failed opening YubiHSM device \"%s\" : %s'",
"%",
"(",
"args",
".",
"device",
",",
"e",
")",
")",
"return",
"1",
"write_pid_file",
"(",
"args",
".",
"pid_file",
")",
"try",
":",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"\"\"",
"print",
"\"Shutting down\"",
"print",
"\"\""
]
| The main function that will be executed when running this as a stand alone script. | [
"The",
"main",
"function",
"that",
"will",
"be",
"executed",
"when",
"running",
"this",
"as",
"a",
"stand",
"alone",
"script",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L727-L754 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | YHSM_VALRequestHandler.do_GET | def do_GET(self):
"""
Process validation GET requests.
All modes of validation (OTP, OATH and PWHASH) must be explicitly
enabled in `args' to be allowed.
"""
if self.path.startswith(args.serve_url):
res = None
log_res = None
mode = None
params = urlparse.parse_qs(self.path[len(args.serve_url):])
if "otp" in params:
if args.mode_short_otp:
# YubiKey internal db OTP in KSM mode
mode = 'YubiKey OTP (short)'
res = validate_yubikey_otp_short(self, params)
elif args.mode_otp:
# YubiKey internal db OTP validation 2.0
mode = 'YubiKey OTP'
res = validate_yubikey_otp(self, params)
#status = [x for x in res.split('\n') if x.startswith("status=")]
#if len(status) == 1:
# res = status[0][7:]
log_res = '&'.join(res.split('\n'))
else:
res = "ERR 'otp/otp2' disabled"
elif "hotp" in params:
if args.mode_hotp:
mode = 'OATH-HOTP'
res = validate_oath_hotp(self, params)
else:
res = "ERR 'hotp' disabled"
elif "totp" in params:
if args.mode_totp:
mode = 'OATH-TOTP'
res = validate_oath_totp(self, params)
else:
res = "ERR 'totp' disabled"
elif "pwhash" in params:
if args.mode_pwhash:
mode = 'Password hash'
res = validate_pwhash(self, params)
else:
res = "ERR 'pwhash' disabled"
if not log_res:
log_res = res
self.log_message("%s validation result: %s -> %s", mode, self.path, log_res)
if res != None:
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(res)
self.wfile.write("\n")
else:
self.log_error ("No validation result to '%s' (responding 403)" % (self.path))
self.send_response(403, 'Forbidden')
self.end_headers()
else:
self.log_error ("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, args.serve_url))
self.send_response(403, 'Forbidden')
self.end_headers() | python | def do_GET(self):
"""
Process validation GET requests.
All modes of validation (OTP, OATH and PWHASH) must be explicitly
enabled in `args' to be allowed.
"""
if self.path.startswith(args.serve_url):
res = None
log_res = None
mode = None
params = urlparse.parse_qs(self.path[len(args.serve_url):])
if "otp" in params:
if args.mode_short_otp:
# YubiKey internal db OTP in KSM mode
mode = 'YubiKey OTP (short)'
res = validate_yubikey_otp_short(self, params)
elif args.mode_otp:
# YubiKey internal db OTP validation 2.0
mode = 'YubiKey OTP'
res = validate_yubikey_otp(self, params)
#status = [x for x in res.split('\n') if x.startswith("status=")]
#if len(status) == 1:
# res = status[0][7:]
log_res = '&'.join(res.split('\n'))
else:
res = "ERR 'otp/otp2' disabled"
elif "hotp" in params:
if args.mode_hotp:
mode = 'OATH-HOTP'
res = validate_oath_hotp(self, params)
else:
res = "ERR 'hotp' disabled"
elif "totp" in params:
if args.mode_totp:
mode = 'OATH-TOTP'
res = validate_oath_totp(self, params)
else:
res = "ERR 'totp' disabled"
elif "pwhash" in params:
if args.mode_pwhash:
mode = 'Password hash'
res = validate_pwhash(self, params)
else:
res = "ERR 'pwhash' disabled"
if not log_res:
log_res = res
self.log_message("%s validation result: %s -> %s", mode, self.path, log_res)
if res != None:
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(res)
self.wfile.write("\n")
else:
self.log_error ("No validation result to '%s' (responding 403)" % (self.path))
self.send_response(403, 'Forbidden')
self.end_headers()
else:
self.log_error ("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, args.serve_url))
self.send_response(403, 'Forbidden')
self.end_headers() | [
"def",
"do_GET",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
".",
"startswith",
"(",
"args",
".",
"serve_url",
")",
":",
"res",
"=",
"None",
"log_res",
"=",
"None",
"mode",
"=",
"None",
"params",
"=",
"urlparse",
".",
"parse_qs",
"(",
"self",
".",
"path",
"[",
"len",
"(",
"args",
".",
"serve_url",
")",
":",
"]",
")",
"if",
"\"otp\"",
"in",
"params",
":",
"if",
"args",
".",
"mode_short_otp",
":",
"# YubiKey internal db OTP in KSM mode",
"mode",
"=",
"'YubiKey OTP (short)'",
"res",
"=",
"validate_yubikey_otp_short",
"(",
"self",
",",
"params",
")",
"elif",
"args",
".",
"mode_otp",
":",
"# YubiKey internal db OTP validation 2.0",
"mode",
"=",
"'YubiKey OTP'",
"res",
"=",
"validate_yubikey_otp",
"(",
"self",
",",
"params",
")",
"#status = [x for x in res.split('\\n') if x.startswith(\"status=\")]",
"#if len(status) == 1:",
"# res = status[0][7:]",
"log_res",
"=",
"'&'",
".",
"join",
"(",
"res",
".",
"split",
"(",
"'\\n'",
")",
")",
"else",
":",
"res",
"=",
"\"ERR 'otp/otp2' disabled\"",
"elif",
"\"hotp\"",
"in",
"params",
":",
"if",
"args",
".",
"mode_hotp",
":",
"mode",
"=",
"'OATH-HOTP'",
"res",
"=",
"validate_oath_hotp",
"(",
"self",
",",
"params",
")",
"else",
":",
"res",
"=",
"\"ERR 'hotp' disabled\"",
"elif",
"\"totp\"",
"in",
"params",
":",
"if",
"args",
".",
"mode_totp",
":",
"mode",
"=",
"'OATH-TOTP'",
"res",
"=",
"validate_oath_totp",
"(",
"self",
",",
"params",
")",
"else",
":",
"res",
"=",
"\"ERR 'totp' disabled\"",
"elif",
"\"pwhash\"",
"in",
"params",
":",
"if",
"args",
".",
"mode_pwhash",
":",
"mode",
"=",
"'Password hash'",
"res",
"=",
"validate_pwhash",
"(",
"self",
",",
"params",
")",
"else",
":",
"res",
"=",
"\"ERR 'pwhash' disabled\"",
"if",
"not",
"log_res",
":",
"log_res",
"=",
"res",
"self",
".",
"log_message",
"(",
"\"%s validation result: %s -> %s\"",
",",
"mode",
",",
"self",
".",
"path",
",",
"log_res",
")",
"if",
"res",
"!=",
"None",
":",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"'Content-type'",
",",
"'text/plain'",
")",
"self",
".",
"end_headers",
"(",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"res",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"\"\\n\"",
")",
"else",
":",
"self",
".",
"log_error",
"(",
"\"No validation result to '%s' (responding 403)\"",
"%",
"(",
"self",
".",
"path",
")",
")",
"self",
".",
"send_response",
"(",
"403",
",",
"'Forbidden'",
")",
"self",
".",
"end_headers",
"(",
")",
"else",
":",
"self",
".",
"log_error",
"(",
"\"Bad URL '%s' - I'm serving '%s' (responding 403)\"",
"%",
"(",
"self",
".",
"path",
",",
"args",
".",
"serve_url",
")",
")",
"self",
".",
"send_response",
"(",
"403",
",",
"'Forbidden'",
")",
"self",
".",
"end_headers",
"(",
")"
]
| Process validation GET requests.
All modes of validation (OTP, OATH and PWHASH) must be explicitly
enabled in `args' to be allowed. | [
"Process",
"validation",
"GET",
"requests",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L122-L186 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | ValOathDb.get | def get(self, key):
""" Fetch entry from database. """
c = self.conn.cursor()
for row in c.execute("SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?", (key,)):
return ValOathEntry(row)
raise Exception("OATH token for '%s' not found in database (%s)" % (key, self.filename)) | python | def get(self, key):
""" Fetch entry from database. """
c = self.conn.cursor()
for row in c.execute("SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?", (key,)):
return ValOathEntry(row)
raise Exception("OATH token for '%s' not found in database (%s)" % (key, self.filename)) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"for",
"row",
"in",
"c",
".",
"execute",
"(",
"\"SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?\"",
",",
"(",
"key",
",",
")",
")",
":",
"return",
"ValOathEntry",
"(",
"row",
")",
"raise",
"Exception",
"(",
"\"OATH token for '%s' not found in database (%s)\"",
"%",
"(",
"key",
",",
"self",
".",
"filename",
")",
")"
]
| Fetch entry from database. | [
"Fetch",
"entry",
"from",
"database",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L479-L484 | train |
Yubico/python-pyhsm | pyhsm/val/validation_server.py | ValOathDb.update_oath_hotp_c | def update_oath_hotp_c(self, entry, new_c):
"""
Update the OATH-HOTP counter value for `entry' in the database.
Use SQL statement to ensure we only ever increase the counter.
"""
key = entry.data["key"]
c = self.conn.cursor()
c.execute("UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c",
(new_c, key, new_c,))
self.conn.commit()
return c.rowcount == 1 | python | def update_oath_hotp_c(self, entry, new_c):
"""
Update the OATH-HOTP counter value for `entry' in the database.
Use SQL statement to ensure we only ever increase the counter.
"""
key = entry.data["key"]
c = self.conn.cursor()
c.execute("UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c",
(new_c, key, new_c,))
self.conn.commit()
return c.rowcount == 1 | [
"def",
"update_oath_hotp_c",
"(",
"self",
",",
"entry",
",",
"new_c",
")",
":",
"key",
"=",
"entry",
".",
"data",
"[",
"\"key\"",
"]",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c\"",
",",
"(",
"new_c",
",",
"key",
",",
"new_c",
",",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"c",
".",
"rowcount",
"==",
"1"
]
| Update the OATH-HOTP counter value for `entry' in the database.
Use SQL statement to ensure we only ever increase the counter. | [
"Update",
"the",
"OATH",
"-",
"HOTP",
"counter",
"value",
"for",
"entry",
"in",
"the",
"database",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L486-L497 | train |
Yubico/python-pyhsm | examples/yhsm-password-auth.py | generate_aead | def generate_aead(hsm, args, password):
"""
Generate an AEAD using the YubiHSM.
"""
try:
pw = password.ljust(args.min_len, chr(0x0))
return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw)
except pyhsm.exception.YHSM_CommandFailed, e:
if e.status_str == 'YHSM_FUNCTION_DISABLED':
print "ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE." % (args.key_handle)
return None
else:
print "ERROR: %s" % (e.reason) | python | def generate_aead(hsm, args, password):
"""
Generate an AEAD using the YubiHSM.
"""
try:
pw = password.ljust(args.min_len, chr(0x0))
return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw)
except pyhsm.exception.YHSM_CommandFailed, e:
if e.status_str == 'YHSM_FUNCTION_DISABLED':
print "ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE." % (args.key_handle)
return None
else:
print "ERROR: %s" % (e.reason) | [
"def",
"generate_aead",
"(",
"hsm",
",",
"args",
",",
"password",
")",
":",
"try",
":",
"pw",
"=",
"password",
".",
"ljust",
"(",
"args",
".",
"min_len",
",",
"chr",
"(",
"0x0",
")",
")",
"return",
"hsm",
".",
"generate_aead_simple",
"(",
"args",
".",
"nonce",
".",
"decode",
"(",
"'hex'",
")",
",",
"args",
".",
"key_handle",
",",
"pw",
")",
"except",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
",",
"e",
":",
"if",
"e",
".",
"status_str",
"==",
"'YHSM_FUNCTION_DISABLED'",
":",
"print",
"\"ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE.\"",
"%",
"(",
"args",
".",
"key_handle",
")",
"return",
"None",
"else",
":",
"print",
"\"ERROR: %s\"",
"%",
"(",
"e",
".",
"reason",
")"
]
| Generate an AEAD using the YubiHSM. | [
"Generate",
"an",
"AEAD",
"using",
"the",
"YubiHSM",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/examples/yhsm-password-auth.py#L108-L120 | train |
Yubico/python-pyhsm | pyhsm/tools/decrypt_aead.py | aead_filename | def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id,
and create any missing directorys.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id) | python | def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id,
and create any missing directorys.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id) | [
"def",
"aead_filename",
"(",
"aead_dir",
",",
"key_handle",
",",
"public_id",
")",
":",
"parts",
"=",
"[",
"aead_dir",
",",
"key_handle",
"]",
"+",
"pyhsm",
".",
"util",
".",
"group",
"(",
"public_id",
",",
"2",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"public_id",
")"
]
| Return the filename of the AEAD for this public_id,
and create any missing directorys. | [
"Return",
"the",
"filename",
"of",
"the",
"AEAD",
"for",
"this",
"public_id",
"and",
"create",
"any",
"missing",
"directorys",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L234-L245 | train |
Yubico/python-pyhsm | pyhsm/tools/decrypt_aead.py | safe_process_files | def safe_process_files(path, files, args, state):
"""
Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going.
"""
for fn in files:
full_fn = os.path.join(path, fn)
try:
if not process_file(path, fn, args, state):
return False
except Exception, e:
sys.stderr.write("error: %s\n%s\n" % (os.path.join(path, fn), traceback.format_exc()))
state.log_failed(full_fn)
if state.should_quit():
return False
return True | python | def safe_process_files(path, files, args, state):
"""
Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going.
"""
for fn in files:
full_fn = os.path.join(path, fn)
try:
if not process_file(path, fn, args, state):
return False
except Exception, e:
sys.stderr.write("error: %s\n%s\n" % (os.path.join(path, fn), traceback.format_exc()))
state.log_failed(full_fn)
if state.should_quit():
return False
return True | [
"def",
"safe_process_files",
"(",
"path",
",",
"files",
",",
"args",
",",
"state",
")",
":",
"for",
"fn",
"in",
"files",
":",
"full_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fn",
")",
"try",
":",
"if",
"not",
"process_file",
"(",
"path",
",",
"fn",
",",
"args",
",",
"state",
")",
":",
"return",
"False",
"except",
"Exception",
",",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error: %s\\n%s\\n\"",
"%",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fn",
")",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
")",
"state",
".",
"log_failed",
"(",
"full_fn",
")",
"if",
"state",
".",
"should_quit",
"(",
")",
":",
"return",
"False",
"return",
"True"
]
| Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going. | [
"Process",
"a",
"number",
"of",
"files",
"in",
"a",
"directory",
".",
"Catches",
"any",
"exception",
"from",
"the",
"processing",
"and",
"checks",
"if",
"we",
"should",
"fail",
"directly",
"or",
"keep",
"going",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L247-L262 | train |
Yubico/python-pyhsm | pyhsm/tools/decrypt_aead.py | walk_dir | def walk_dir(path, args, state):
"""
Check all files in `path' to see if there is any requests that
we should send out on the bus.
"""
if args.debug:
sys.stderr.write("Walking %s\n" % path)
for root, _dirs, files in os.walk(path):
if not safe_process_files(root, files, args, state):
return False
if state.should_quit():
return False
return True | python | def walk_dir(path, args, state):
"""
Check all files in `path' to see if there is any requests that
we should send out on the bus.
"""
if args.debug:
sys.stderr.write("Walking %s\n" % path)
for root, _dirs, files in os.walk(path):
if not safe_process_files(root, files, args, state):
return False
if state.should_quit():
return False
return True | [
"def",
"walk_dir",
"(",
"path",
",",
"args",
",",
"state",
")",
":",
"if",
"args",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Walking %s\\n\"",
"%",
"path",
")",
"for",
"root",
",",
"_dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
"not",
"safe_process_files",
"(",
"root",
",",
"files",
",",
"args",
",",
"state",
")",
":",
"return",
"False",
"if",
"state",
".",
"should_quit",
"(",
")",
":",
"return",
"False",
"return",
"True"
]
| Check all files in `path' to see if there is any requests that
we should send out on the bus. | [
"Check",
"all",
"files",
"in",
"path",
"to",
"see",
"if",
"there",
"is",
"any",
"requests",
"that",
"we",
"should",
"send",
"out",
"on",
"the",
"bus",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L264-L277 | train |
Yubico/python-pyhsm | pyhsm/tools/decrypt_aead.py | main | def main():
""" Main function when running as a program. """
global args
args = parse_args()
if not args:
return 1
state = MyState(args)
for path in args.paths:
if os.path.isdir(path):
walk_dir(path, args, state)
else:
safe_process_files(os.path.dirname(path), [os.path.basename(path)], args, state)
if state.should_quit():
break
if state.failed_files:
sys.stderr.write("error: %i/%i AEADs failed\n" % (len(state.failed_files), state.file_count))
return 1
if args.debug:
sys.stderr.write("Successfully processed %i AEADs\n" % (state.file_count)) | python | def main():
""" Main function when running as a program. """
global args
args = parse_args()
if not args:
return 1
state = MyState(args)
for path in args.paths:
if os.path.isdir(path):
walk_dir(path, args, state)
else:
safe_process_files(os.path.dirname(path), [os.path.basename(path)], args, state)
if state.should_quit():
break
if state.failed_files:
sys.stderr.write("error: %i/%i AEADs failed\n" % (len(state.failed_files), state.file_count))
return 1
if args.debug:
sys.stderr.write("Successfully processed %i AEADs\n" % (state.file_count)) | [
"def",
"main",
"(",
")",
":",
"global",
"args",
"args",
"=",
"parse_args",
"(",
")",
"if",
"not",
"args",
":",
"return",
"1",
"state",
"=",
"MyState",
"(",
"args",
")",
"for",
"path",
"in",
"args",
".",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"walk_dir",
"(",
"path",
",",
"args",
",",
"state",
")",
"else",
":",
"safe_process_files",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"]",
",",
"args",
",",
"state",
")",
"if",
"state",
".",
"should_quit",
"(",
")",
":",
"break",
"if",
"state",
".",
"failed_files",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error: %i/%i AEADs failed\\n\"",
"%",
"(",
"len",
"(",
"state",
".",
"failed_files",
")",
",",
"state",
".",
"file_count",
")",
")",
"return",
"1",
"if",
"args",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Successfully processed %i AEADs\\n\"",
"%",
"(",
"state",
".",
"file_count",
")",
")"
]
| Main function when running as a program. | [
"Main",
"function",
"when",
"running",
"as",
"a",
"program",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L279-L300 | train |
Yubico/python-pyhsm | pyhsm/oath_hotp.py | search_for_oath_code | def search_for_oath_code(hsm, key_handle, nonce, aead, counter, user_code, look_ahead=1):
"""
Try to validate an OATH HOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns next counter value on successful auth, and None otherwise.
"""
key_handle = pyhsm.util.input_validate_key_handle(key_handle)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = False)
aead = pyhsm.util.input_validate_aead(aead)
counter = pyhsm.util.input_validate_int(counter, 'counter')
user_code = pyhsm.util.input_validate_int(user_code, 'user_code')
hsm.load_temp_key(nonce, key_handle, aead)
# User might have produced codes never sent to us, so we support trying look_ahead
# codes to see if we find the user's current code.
for j in xrange(look_ahead):
this_counter = counter + j
secret = struct.pack("> Q", this_counter)
hmac_result = hsm.hmac_sha1(pyhsm.defines.YSM_TEMP_KEY_HANDLE, secret).get_hash()
this_code = truncate(hmac_result)
if this_code == user_code:
return this_counter + 1
return None | python | def search_for_oath_code(hsm, key_handle, nonce, aead, counter, user_code, look_ahead=1):
"""
Try to validate an OATH HOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns next counter value on successful auth, and None otherwise.
"""
key_handle = pyhsm.util.input_validate_key_handle(key_handle)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = False)
aead = pyhsm.util.input_validate_aead(aead)
counter = pyhsm.util.input_validate_int(counter, 'counter')
user_code = pyhsm.util.input_validate_int(user_code, 'user_code')
hsm.load_temp_key(nonce, key_handle, aead)
# User might have produced codes never sent to us, so we support trying look_ahead
# codes to see if we find the user's current code.
for j in xrange(look_ahead):
this_counter = counter + j
secret = struct.pack("> Q", this_counter)
hmac_result = hsm.hmac_sha1(pyhsm.defines.YSM_TEMP_KEY_HANDLE, secret).get_hash()
this_code = truncate(hmac_result)
if this_code == user_code:
return this_counter + 1
return None | [
"def",
"search_for_oath_code",
"(",
"hsm",
",",
"key_handle",
",",
"nonce",
",",
"aead",
",",
"counter",
",",
"user_code",
",",
"look_ahead",
"=",
"1",
")",
":",
"key_handle",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_key_handle",
"(",
"key_handle",
")",
"nonce",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_nonce",
"(",
"nonce",
",",
"pad",
"=",
"False",
")",
"aead",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_aead",
"(",
"aead",
")",
"counter",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_int",
"(",
"counter",
",",
"'counter'",
")",
"user_code",
"=",
"pyhsm",
".",
"util",
".",
"input_validate_int",
"(",
"user_code",
",",
"'user_code'",
")",
"hsm",
".",
"load_temp_key",
"(",
"nonce",
",",
"key_handle",
",",
"aead",
")",
"# User might have produced codes never sent to us, so we support trying look_ahead",
"# codes to see if we find the user's current code.",
"for",
"j",
"in",
"xrange",
"(",
"look_ahead",
")",
":",
"this_counter",
"=",
"counter",
"+",
"j",
"secret",
"=",
"struct",
".",
"pack",
"(",
"\"> Q\"",
",",
"this_counter",
")",
"hmac_result",
"=",
"hsm",
".",
"hmac_sha1",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_TEMP_KEY_HANDLE",
",",
"secret",
")",
".",
"get_hash",
"(",
")",
"this_code",
"=",
"truncate",
"(",
"hmac_result",
")",
"if",
"this_code",
"==",
"user_code",
":",
"return",
"this_counter",
"+",
"1",
"return",
"None"
]
| Try to validate an OATH HOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.
Returns next counter value on successful auth, and None otherwise. | [
"Try",
"to",
"validate",
"an",
"OATH",
"HOTP",
"OTP",
"generated",
"by",
"a",
"token",
"whose",
"secret",
"key",
"is",
"available",
"to",
"the",
"YubiHSM",
"through",
"the",
"AEAD",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_hotp.py#L20-L44 | train |
Yubico/python-pyhsm | pyhsm/oath_hotp.py | truncate | def truncate(hmac_result, length=6):
""" Perform the truncating. """
assert(len(hmac_result) == 20)
offset = ord(hmac_result[19]) & 0xf
bin_code = (ord(hmac_result[offset]) & 0x7f) << 24 \
| (ord(hmac_result[offset+1]) & 0xff) << 16 \
| (ord(hmac_result[offset+2]) & 0xff) << 8 \
| (ord(hmac_result[offset+3]) & 0xff)
return bin_code % (10 ** length) | python | def truncate(hmac_result, length=6):
""" Perform the truncating. """
assert(len(hmac_result) == 20)
offset = ord(hmac_result[19]) & 0xf
bin_code = (ord(hmac_result[offset]) & 0x7f) << 24 \
| (ord(hmac_result[offset+1]) & 0xff) << 16 \
| (ord(hmac_result[offset+2]) & 0xff) << 8 \
| (ord(hmac_result[offset+3]) & 0xff)
return bin_code % (10 ** length) | [
"def",
"truncate",
"(",
"hmac_result",
",",
"length",
"=",
"6",
")",
":",
"assert",
"(",
"len",
"(",
"hmac_result",
")",
"==",
"20",
")",
"offset",
"=",
"ord",
"(",
"hmac_result",
"[",
"19",
"]",
")",
"&",
"0xf",
"bin_code",
"=",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"]",
")",
"&",
"0x7f",
")",
"<<",
"24",
"|",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"+",
"1",
"]",
")",
"&",
"0xff",
")",
"<<",
"16",
"|",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"+",
"2",
"]",
")",
"&",
"0xff",
")",
"<<",
"8",
"|",
"(",
"ord",
"(",
"hmac_result",
"[",
"offset",
"+",
"3",
"]",
")",
"&",
"0xff",
")",
"return",
"bin_code",
"%",
"(",
"10",
"**",
"length",
")"
]
| Perform the truncating. | [
"Perform",
"the",
"truncating",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_hotp.py#L46-L54 | train |
Yubico/python-pyhsm | pyhsm/stick.py | YHSM_Stick.flush | def flush(self):
"""
Flush input buffers.
"""
if self.debug:
sys.stderr.write("%s: FLUSH INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
self.ser.flushInput() | python | def flush(self):
"""
Flush input buffers.
"""
if self.debug:
sys.stderr.write("%s: FLUSH INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
self.ser.flushInput() | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s: FLUSH INPUT (%i bytes waiting)\\n\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"ser",
".",
"inWaiting",
"(",
")",
")",
")",
"self",
".",
"ser",
".",
"flushInput",
"(",
")"
]
| Flush input buffers. | [
"Flush",
"input",
"buffers",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/stick.py#L91-L100 | train |
Yubico/python-pyhsm | pyhsm/stick.py | YHSM_Stick.drain | def drain(self):
""" Drain input. """
if self.debug:
sys.stderr.write("%s: DRAIN INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
old_timeout = self.ser.timeout
self.ser.timeout = 0.1
data = self.ser.read(1)
while len(data):
if self.debug:
sys.stderr.write("%s: DRAINED 0x%x (%c)\n" %(self.__class__.__name__, ord(data[0]), data[0]))
data = self.ser.read(1)
self.ser.timeout = old_timeout
return True | python | def drain(self):
""" Drain input. """
if self.debug:
sys.stderr.write("%s: DRAIN INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
old_timeout = self.ser.timeout
self.ser.timeout = 0.1
data = self.ser.read(1)
while len(data):
if self.debug:
sys.stderr.write("%s: DRAINED 0x%x (%c)\n" %(self.__class__.__name__, ord(data[0]), data[0]))
data = self.ser.read(1)
self.ser.timeout = old_timeout
return True | [
"def",
"drain",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s: DRAIN INPUT (%i bytes waiting)\\n\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"ser",
".",
"inWaiting",
"(",
")",
")",
")",
"old_timeout",
"=",
"self",
".",
"ser",
".",
"timeout",
"self",
".",
"ser",
".",
"timeout",
"=",
"0.1",
"data",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"1",
")",
"while",
"len",
"(",
"data",
")",
":",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s: DRAINED 0x%x (%c)\\n\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"ord",
"(",
"data",
"[",
"0",
"]",
")",
",",
"data",
"[",
"0",
"]",
")",
")",
"data",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"1",
")",
"self",
".",
"ser",
".",
"timeout",
"=",
"old_timeout",
"return",
"True"
]
| Drain input. | [
"Drain",
"input",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/stick.py#L102-L117 | train |
Yubico/python-pyhsm | pyhsm/ksm/db_import.py | extract_keyhandle | def extract_keyhandle(path, filepath):
"""extract keyhandle value from the path"""
keyhandle = filepath.lstrip(path)
keyhandle = keyhandle.split("/")
return keyhandle[0] | python | def extract_keyhandle(path, filepath):
"""extract keyhandle value from the path"""
keyhandle = filepath.lstrip(path)
keyhandle = keyhandle.split("/")
return keyhandle[0] | [
"def",
"extract_keyhandle",
"(",
"path",
",",
"filepath",
")",
":",
"keyhandle",
"=",
"filepath",
".",
"lstrip",
"(",
"path",
")",
"keyhandle",
"=",
"keyhandle",
".",
"split",
"(",
"\"/\"",
")",
"return",
"keyhandle",
"[",
"0",
"]"
]
| extract keyhandle value from the path | [
"extract",
"keyhandle",
"value",
"from",
"the",
"path"
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/db_import.py#L19-L24 | train |
Yubico/python-pyhsm | pyhsm/ksm/db_import.py | insert_query | def insert_query(connection, publicId, aead, keyhandle, aeadobj):
"""this functions read the response fields and creates sql query. then
inserts everything inside the database"""
# turn the keyhandle into an integer
keyhandle = key_handle_to_int(keyhandle)
if not keyhandle == aead.key_handle:
print("WARNING: keyhandle does not match aead.key_handle")
return None
# creates the query object
try:
sql = aeadobj.insert().values(public_id=publicId, keyhandle=aead.key_handle, nonce=aead.nonce, aead=aead.data)
# insert the query
result = connection.execute(sql)
return result
except sqlalchemy.exc.IntegrityError:
pass
return None | python | def insert_query(connection, publicId, aead, keyhandle, aeadobj):
"""this functions read the response fields and creates sql query. then
inserts everything inside the database"""
# turn the keyhandle into an integer
keyhandle = key_handle_to_int(keyhandle)
if not keyhandle == aead.key_handle:
print("WARNING: keyhandle does not match aead.key_handle")
return None
# creates the query object
try:
sql = aeadobj.insert().values(public_id=publicId, keyhandle=aead.key_handle, nonce=aead.nonce, aead=aead.data)
# insert the query
result = connection.execute(sql)
return result
except sqlalchemy.exc.IntegrityError:
pass
return None | [
"def",
"insert_query",
"(",
"connection",
",",
"publicId",
",",
"aead",
",",
"keyhandle",
",",
"aeadobj",
")",
":",
"# turn the keyhandle into an integer",
"keyhandle",
"=",
"key_handle_to_int",
"(",
"keyhandle",
")",
"if",
"not",
"keyhandle",
"==",
"aead",
".",
"key_handle",
":",
"print",
"(",
"\"WARNING: keyhandle does not match aead.key_handle\"",
")",
"return",
"None",
"# creates the query object",
"try",
":",
"sql",
"=",
"aeadobj",
".",
"insert",
"(",
")",
".",
"values",
"(",
"public_id",
"=",
"publicId",
",",
"keyhandle",
"=",
"aead",
".",
"key_handle",
",",
"nonce",
"=",
"aead",
".",
"nonce",
",",
"aead",
"=",
"aead",
".",
"data",
")",
"# insert the query",
"result",
"=",
"connection",
".",
"execute",
"(",
"sql",
")",
"return",
"result",
"except",
"sqlalchemy",
".",
"exc",
".",
"IntegrityError",
":",
"pass",
"return",
"None"
]
| this functions read the response fields and creates sql query. then
inserts everything inside the database | [
"this",
"functions",
"read",
"the",
"response",
"fields",
"and",
"creates",
"sql",
"query",
".",
"then",
"inserts",
"everything",
"inside",
"the",
"database"
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/db_import.py#L27-L45 | train |
Yubico/python-pyhsm | pyhsm/ksm/import_keys.py | import_keys | def import_keys(hsm, args):
"""
The main stdin iteration loop.
"""
res = True
# ykksm 1
#123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,
for line in sys.stdin:
if line[0] == '#':
continue
l = line.split(',')
modhex_id = l[1]
uid = l[2].decode('hex')
key = l[3].decode('hex')
if modhex_id and uid and key:
public_id = pyhsm.yubikey.modhex_decode(modhex_id)
padded_id = modhex_id.rjust(args.public_id_chars, 'c')
if int(public_id, 16) == 0:
print "WARNING: Skipping import of key with public ID: %s" % (padded_id)
print "This public ID is unsupported by the YubiHSM.\n"
continue
if args.verbose:
print " %s" % (padded_id)
secret = pyhsm.aead_cmd.YHSM_YubiKeySecret(key, uid)
hsm.load_secret(secret)
for kh in args.key_handles.keys():
if(args.random_nonce):
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
if args.internal_db:
if not store_in_internal_db(
args, hsm, modhex_id, public_id, kh, aead):
res = False
continue
filename = output_filename(
args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
if res:
print "\nDone\n"
else:
print "\nDone (one or more entries rejected)"
return res | python | def import_keys(hsm, args):
"""
The main stdin iteration loop.
"""
res = True
# ykksm 1
#123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,
for line in sys.stdin:
if line[0] == '#':
continue
l = line.split(',')
modhex_id = l[1]
uid = l[2].decode('hex')
key = l[3].decode('hex')
if modhex_id and uid and key:
public_id = pyhsm.yubikey.modhex_decode(modhex_id)
padded_id = modhex_id.rjust(args.public_id_chars, 'c')
if int(public_id, 16) == 0:
print "WARNING: Skipping import of key with public ID: %s" % (padded_id)
print "This public ID is unsupported by the YubiHSM.\n"
continue
if args.verbose:
print " %s" % (padded_id)
secret = pyhsm.aead_cmd.YHSM_YubiKeySecret(key, uid)
hsm.load_secret(secret)
for kh in args.key_handles.keys():
if(args.random_nonce):
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
if args.internal_db:
if not store_in_internal_db(
args, hsm, modhex_id, public_id, kh, aead):
res = False
continue
filename = output_filename(
args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
if res:
print "\nDone\n"
else:
print "\nDone (one or more entries rejected)"
return res | [
"def",
"import_keys",
"(",
"hsm",
",",
"args",
")",
":",
"res",
"=",
"True",
"# ykksm 1",
"#123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,",
"for",
"line",
"in",
"sys",
".",
"stdin",
":",
"if",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"l",
"=",
"line",
".",
"split",
"(",
"','",
")",
"modhex_id",
"=",
"l",
"[",
"1",
"]",
"uid",
"=",
"l",
"[",
"2",
"]",
".",
"decode",
"(",
"'hex'",
")",
"key",
"=",
"l",
"[",
"3",
"]",
".",
"decode",
"(",
"'hex'",
")",
"if",
"modhex_id",
"and",
"uid",
"and",
"key",
":",
"public_id",
"=",
"pyhsm",
".",
"yubikey",
".",
"modhex_decode",
"(",
"modhex_id",
")",
"padded_id",
"=",
"modhex_id",
".",
"rjust",
"(",
"args",
".",
"public_id_chars",
",",
"'c'",
")",
"if",
"int",
"(",
"public_id",
",",
"16",
")",
"==",
"0",
":",
"print",
"\"WARNING: Skipping import of key with public ID: %s\"",
"%",
"(",
"padded_id",
")",
"print",
"\"This public ID is unsupported by the YubiHSM.\\n\"",
"continue",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %s\"",
"%",
"(",
"padded_id",
")",
"secret",
"=",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
"(",
"key",
",",
"uid",
")",
"hsm",
".",
"load_secret",
"(",
"secret",
")",
"for",
"kh",
"in",
"args",
".",
"key_handles",
".",
"keys",
"(",
")",
":",
"if",
"(",
"args",
".",
"random_nonce",
")",
":",
"nonce",
"=",
"\"\"",
"else",
":",
"nonce",
"=",
"public_id",
".",
"decode",
"(",
"'hex'",
")",
"aead",
"=",
"hsm",
".",
"generate_aead",
"(",
"nonce",
",",
"kh",
")",
"if",
"args",
".",
"internal_db",
":",
"if",
"not",
"store_in_internal_db",
"(",
"args",
",",
"hsm",
",",
"modhex_id",
",",
"public_id",
",",
"kh",
",",
"aead",
")",
":",
"res",
"=",
"False",
"continue",
"filename",
"=",
"output_filename",
"(",
"args",
".",
"output_dir",
",",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"padded_id",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %4s, %i bytes (%s) -> %s\"",
"%",
"(",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"len",
"(",
"aead",
".",
"data",
")",
",",
"shorten_aead",
"(",
"aead",
")",
",",
"filename",
")",
"aead",
".",
"save",
"(",
"filename",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\"\"",
"if",
"res",
":",
"print",
"\"\\nDone\\n\"",
"else",
":",
"print",
"\"\\nDone (one or more entries rejected)\"",
"return",
"res"
]
| The main stdin iteration loop. | [
"The",
"main",
"stdin",
"iteration",
"loop",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/import_keys.py#L142-L204 | train |
Yubico/python-pyhsm | pyhsm/ksm/import_keys.py | shorten_aead | def shorten_aead(aead):
""" Produce pretty-printable version of long AEAD. """
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (head, tail) | python | def shorten_aead(aead):
""" Produce pretty-printable version of long AEAD. """
head = aead.data[:4].encode('hex')
tail = aead.data[-4:].encode('hex')
return "%s...%s" % (head, tail) | [
"def",
"shorten_aead",
"(",
"aead",
")",
":",
"head",
"=",
"aead",
".",
"data",
"[",
":",
"4",
"]",
".",
"encode",
"(",
"'hex'",
")",
"tail",
"=",
"aead",
".",
"data",
"[",
"-",
"4",
":",
"]",
".",
"encode",
"(",
"'hex'",
")",
"return",
"\"%s...%s\"",
"%",
"(",
"head",
",",
"tail",
")"
]
| Produce pretty-printable version of long AEAD. | [
"Produce",
"pretty",
"-",
"printable",
"version",
"of",
"long",
"AEAD",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/import_keys.py#L225-L229 | train |
Yubico/python-pyhsm | pyhsm/ksm/import_keys.py | output_filename | def output_filename(output_dir, key_handle, public_id):
"""
Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage.
"""
parts = [output_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id) | python | def output_filename(output_dir, key_handle, public_id):
"""
Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage.
"""
parts = [output_dir, key_handle] + pyhsm.util.group(public_id, 2)
path = os.path.join(*parts)
if not os.path.isdir(path):
os.makedirs(path)
return os.path.join(path, public_id) | [
"def",
"output_filename",
"(",
"output_dir",
",",
"key_handle",
",",
"public_id",
")",
":",
"parts",
"=",
"[",
"output_dir",
",",
"key_handle",
"]",
"+",
"pyhsm",
".",
"util",
".",
"group",
"(",
"public_id",
",",
"2",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"public_id",
")"
]
| Return an output filename for a generated AEAD. Creates a hashed directory structure
using the last three bytes of the public id to get equal usage. | [
"Return",
"an",
"output",
"filename",
"for",
"a",
"generated",
"AEAD",
".",
"Creates",
"a",
"hashed",
"directory",
"structure",
"using",
"the",
"last",
"three",
"bytes",
"of",
"the",
"public",
"id",
"to",
"get",
"equal",
"usage",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/import_keys.py#L232-L243 | train |
Yubico/python-pyhsm | pyhsm/db_cmd.py | YHSM_Cmd_DB_YubiKey_Store.parse_result | def parse_result(self, data):
""" Return True if the AEAD was stored sucessfully. """
# typedef struct {
# uint8_t publicId[YSM_PUBLIC_ID_SIZE]; // Public id (nonce)
# uint32_t keyHandle; // Key handle
# YSM_STATUS status; // Validation status
# } YSM_DB_YUBIKEY_AEAD_STORE_RESP;
public_id, \
key_handle, \
self.status = struct.unpack("< %is I B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data)
pyhsm.util.validate_cmd_response_str('public_id', public_id, self.public_id)
pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)
if self.status == pyhsm.defines.YSM_STATUS_OK:
return True
else:
raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status) | python | def parse_result(self, data):
""" Return True if the AEAD was stored sucessfully. """
# typedef struct {
# uint8_t publicId[YSM_PUBLIC_ID_SIZE]; // Public id (nonce)
# uint32_t keyHandle; // Key handle
# YSM_STATUS status; // Validation status
# } YSM_DB_YUBIKEY_AEAD_STORE_RESP;
public_id, \
key_handle, \
self.status = struct.unpack("< %is I B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data)
pyhsm.util.validate_cmd_response_str('public_id', public_id, self.public_id)
pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)
if self.status == pyhsm.defines.YSM_STATUS_OK:
return True
else:
raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status) | [
"def",
"parse_result",
"(",
"self",
",",
"data",
")",
":",
"# typedef struct {",
"# uint8_t publicId[YSM_PUBLIC_ID_SIZE]; // Public id (nonce)",
"# uint32_t keyHandle; // Key handle",
"# YSM_STATUS status; // Validation status",
"# } YSM_DB_YUBIKEY_AEAD_STORE_RESP;",
"public_id",
",",
"key_handle",
",",
"self",
".",
"status",
"=",
"struct",
".",
"unpack",
"(",
"\"< %is I B\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_AEAD_NONCE_SIZE",
")",
",",
"data",
")",
"pyhsm",
".",
"util",
".",
"validate_cmd_response_str",
"(",
"'public_id'",
",",
"public_id",
",",
"self",
".",
"public_id",
")",
"pyhsm",
".",
"util",
".",
"validate_cmd_response_hex",
"(",
"'key_handle'",
",",
"key_handle",
",",
"self",
".",
"key_handle",
")",
"if",
"self",
".",
"status",
"==",
"pyhsm",
".",
"defines",
".",
"YSM_STATUS_OK",
":",
"return",
"True",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_CommandFailed",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"self",
".",
"command",
")",
",",
"self",
".",
"status",
")"
]
| Return True if the AEAD was stored sucessfully. | [
"Return",
"True",
"if",
"the",
"AEAD",
"was",
"stored",
"sucessfully",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/db_cmd.py#L64-L81 | train |
Yubico/python-pyhsm | pyhsm/tools/generate_keys.py | gen_keys | def gen_keys(hsm, args):
"""
The main key generating loop.
"""
if args.verbose:
print "Generating %i keys :\n" % (args.count)
else:
print "Generating %i keys" % (args.count)
for int_id in range(args.start_id, args.start_id + args.count):
public_id = ("%x" % int_id).rjust(args.public_id_chars, '0')
padded_id = pyhsm.yubikey.modhex_encode(public_id)
if args.verbose:
print " %s" % (padded_id)
num_bytes = len(pyhsm.aead_cmd.YHSM_YubiKeySecret('a' * 16, 'b' * 6).pack())
hsm.load_random(num_bytes)
for kh in args.key_handles.keys():
if args.random_nonce:
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
filename = output_filename(args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
print "\nDone\n" | python | def gen_keys(hsm, args):
"""
The main key generating loop.
"""
if args.verbose:
print "Generating %i keys :\n" % (args.count)
else:
print "Generating %i keys" % (args.count)
for int_id in range(args.start_id, args.start_id + args.count):
public_id = ("%x" % int_id).rjust(args.public_id_chars, '0')
padded_id = pyhsm.yubikey.modhex_encode(public_id)
if args.verbose:
print " %s" % (padded_id)
num_bytes = len(pyhsm.aead_cmd.YHSM_YubiKeySecret('a' * 16, 'b' * 6).pack())
hsm.load_random(num_bytes)
for kh in args.key_handles.keys():
if args.random_nonce:
nonce = ""
else:
nonce = public_id.decode('hex')
aead = hsm.generate_aead(nonce, kh)
filename = output_filename(args.output_dir, args.key_handles[kh], padded_id)
if args.verbose:
print " %4s, %i bytes (%s) -> %s" % \
(args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
aead.save(filename)
if args.verbose:
print ""
print "\nDone\n" | [
"def",
"gen_keys",
"(",
"hsm",
",",
"args",
")",
":",
"if",
"args",
".",
"verbose",
":",
"print",
"\"Generating %i keys :\\n\"",
"%",
"(",
"args",
".",
"count",
")",
"else",
":",
"print",
"\"Generating %i keys\"",
"%",
"(",
"args",
".",
"count",
")",
"for",
"int_id",
"in",
"range",
"(",
"args",
".",
"start_id",
",",
"args",
".",
"start_id",
"+",
"args",
".",
"count",
")",
":",
"public_id",
"=",
"(",
"\"%x\"",
"%",
"int_id",
")",
".",
"rjust",
"(",
"args",
".",
"public_id_chars",
",",
"'0'",
")",
"padded_id",
"=",
"pyhsm",
".",
"yubikey",
".",
"modhex_encode",
"(",
"public_id",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %s\"",
"%",
"(",
"padded_id",
")",
"num_bytes",
"=",
"len",
"(",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
"(",
"'a'",
"*",
"16",
",",
"'b'",
"*",
"6",
")",
".",
"pack",
"(",
")",
")",
"hsm",
".",
"load_random",
"(",
"num_bytes",
")",
"for",
"kh",
"in",
"args",
".",
"key_handles",
".",
"keys",
"(",
")",
":",
"if",
"args",
".",
"random_nonce",
":",
"nonce",
"=",
"\"\"",
"else",
":",
"nonce",
"=",
"public_id",
".",
"decode",
"(",
"'hex'",
")",
"aead",
"=",
"hsm",
".",
"generate_aead",
"(",
"nonce",
",",
"kh",
")",
"filename",
"=",
"output_filename",
"(",
"args",
".",
"output_dir",
",",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"padded_id",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\" %4s, %i bytes (%s) -> %s\"",
"%",
"(",
"args",
".",
"key_handles",
"[",
"kh",
"]",
",",
"len",
"(",
"aead",
".",
"data",
")",
",",
"shorten_aead",
"(",
"aead",
")",
",",
"filename",
")",
"aead",
".",
"save",
"(",
"filename",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"\"\"",
"print",
"\"\\nDone\\n\""
]
| The main key generating loop. | [
"The",
"main",
"key",
"generating",
"loop",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/generate_keys.py#L135-L171 | train |
Yubico/python-pyhsm | pyhsm/cmd.py | reset | def reset(stick):
"""
Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer.
"""
nulls = (pyhsm.defines.YSM_MAX_PKT_SIZE - 1) * '\x00'
res = YHSM_Cmd(stick, pyhsm.defines.YSM_NULL, payload = nulls).execute(read_response = False)
unlock = stick.acquire()
try:
stick.drain()
stick.flush()
finally:
unlock()
return res == 0 | python | def reset(stick):
"""
Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer.
"""
nulls = (pyhsm.defines.YSM_MAX_PKT_SIZE - 1) * '\x00'
res = YHSM_Cmd(stick, pyhsm.defines.YSM_NULL, payload = nulls).execute(read_response = False)
unlock = stick.acquire()
try:
stick.drain()
stick.flush()
finally:
unlock()
return res == 0 | [
"def",
"reset",
"(",
"stick",
")",
":",
"nulls",
"=",
"(",
"pyhsm",
".",
"defines",
".",
"YSM_MAX_PKT_SIZE",
"-",
"1",
")",
"*",
"'\\x00'",
"res",
"=",
"YHSM_Cmd",
"(",
"stick",
",",
"pyhsm",
".",
"defines",
".",
"YSM_NULL",
",",
"payload",
"=",
"nulls",
")",
".",
"execute",
"(",
"read_response",
"=",
"False",
")",
"unlock",
"=",
"stick",
".",
"acquire",
"(",
")",
"try",
":",
"stick",
".",
"drain",
"(",
")",
"stick",
".",
"flush",
"(",
")",
"finally",
":",
"unlock",
"(",
")",
"return",
"res",
"==",
"0"
]
| Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer. | [
"Send",
"a",
"bunch",
"of",
"zero",
"-",
"bytes",
"to",
"the",
"YubiHSM",
"and",
"flush",
"the",
"input",
"buffer",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/cmd.py#L149-L161 | train |
Yubico/python-pyhsm | pyhsm/cmd.py | YHSM_Cmd.execute | def execute(self, read_response=True):
"""
Write command to HSM and read response.
@param read_response: Whether to expect a response or not.
@type read_response: bool
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
if self.command != pyhsm.defines.YSM_NULL:
# YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt
cmd_buf = struct.pack('BB', len(self.payload) + 1, self.command)
else:
cmd_buf = chr(self.command)
cmd_buf += self.payload
debug_info = None
unlock = self.stick.acquire()
try:
if self.stick.debug:
debug_info = "%s (payload %i/0x%x)" % (pyhsm.defines.cmd2str(self.command), \
len(self.payload), len(self.payload))
self.stick.write(cmd_buf, debug_info)
if not read_response:
return None
return self._read_response()
finally:
unlock() | python | def execute(self, read_response=True):
"""
Write command to HSM and read response.
@param read_response: Whether to expect a response or not.
@type read_response: bool
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
if self.command != pyhsm.defines.YSM_NULL:
# YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt
cmd_buf = struct.pack('BB', len(self.payload) + 1, self.command)
else:
cmd_buf = chr(self.command)
cmd_buf += self.payload
debug_info = None
unlock = self.stick.acquire()
try:
if self.stick.debug:
debug_info = "%s (payload %i/0x%x)" % (pyhsm.defines.cmd2str(self.command), \
len(self.payload), len(self.payload))
self.stick.write(cmd_buf, debug_info)
if not read_response:
return None
return self._read_response()
finally:
unlock() | [
"def",
"execute",
"(",
"self",
",",
"read_response",
"=",
"True",
")",
":",
"# // Up- and downlink packet",
"# typedef struct {",
"# uint8_t bcnt; // Number of bytes (cmd + payload)",
"# uint8_t cmd; // YSM_xxx command",
"# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload",
"# } YSM_PKT;",
"if",
"self",
".",
"command",
"!=",
"pyhsm",
".",
"defines",
".",
"YSM_NULL",
":",
"# YSM_NULL is the exception to the rule - it should NOT be prefixed with YSM_PKT.bcnt",
"cmd_buf",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"len",
"(",
"self",
".",
"payload",
")",
"+",
"1",
",",
"self",
".",
"command",
")",
"else",
":",
"cmd_buf",
"=",
"chr",
"(",
"self",
".",
"command",
")",
"cmd_buf",
"+=",
"self",
".",
"payload",
"debug_info",
"=",
"None",
"unlock",
"=",
"self",
".",
"stick",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"stick",
".",
"debug",
":",
"debug_info",
"=",
"\"%s (payload %i/0x%x)\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"self",
".",
"command",
")",
",",
"len",
"(",
"self",
".",
"payload",
")",
",",
"len",
"(",
"self",
".",
"payload",
")",
")",
"self",
".",
"stick",
".",
"write",
"(",
"cmd_buf",
",",
"debug_info",
")",
"if",
"not",
"read_response",
":",
"return",
"None",
"return",
"self",
".",
"_read_response",
"(",
")",
"finally",
":",
"unlock",
"(",
")"
]
| Write command to HSM and read response.
@param read_response: Whether to expect a response or not.
@type read_response: bool | [
"Write",
"command",
"to",
"HSM",
"and",
"read",
"response",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/cmd.py#L47-L77 | train |
Yubico/python-pyhsm | pyhsm/cmd.py | YHSM_Cmd._read_response | def _read_response(self):
"""
After writing a command, read response.
@returns: Result of parse_data()
@raises pyhsm.exception.YHSM_Error: On failure to read a response to the
command we sent in a timely fashion.
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
# read YSM_PKT.bcnt and YSM_PKT.cmd
res = self.stick.read(2, 'response length + response status')
if len(res) != 2:
self._handle_invalid_read_response(res, 2)
response_len, response_status = struct.unpack('BB', res)
response_len -= 1 # the status byte has been read already
debug_info = None
if response_status & pyhsm.defines.YSM_RESPONSE:
debug_info = "%s response (%i/0x%x bytes)" \
% (pyhsm.defines.cmd2str(response_status - pyhsm.defines.YSM_RESPONSE), \
response_len, response_len)
# read YSM_PKT.payload
res = self.stick.read(response_len, debug_info)
if res:
if response_status == self.command | pyhsm.defines.YSM_RESPONSE:
self.executed = True
self.response_status = response_status
return self.parse_result(res)
else:
reset(self.stick)
raise pyhsm.exception.YHSM_Error('YubiHSM responded to wrong command')
else:
raise pyhsm.exception.YHSM_Error('YubiHSM did not respond') | python | def _read_response(self):
"""
After writing a command, read response.
@returns: Result of parse_data()
@raises pyhsm.exception.YHSM_Error: On failure to read a response to the
command we sent in a timely fashion.
"""
# // Up- and downlink packet
# typedef struct {
# uint8_t bcnt; // Number of bytes (cmd + payload)
# uint8_t cmd; // YSM_xxx command
# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload
# } YSM_PKT;
# read YSM_PKT.bcnt and YSM_PKT.cmd
res = self.stick.read(2, 'response length + response status')
if len(res) != 2:
self._handle_invalid_read_response(res, 2)
response_len, response_status = struct.unpack('BB', res)
response_len -= 1 # the status byte has been read already
debug_info = None
if response_status & pyhsm.defines.YSM_RESPONSE:
debug_info = "%s response (%i/0x%x bytes)" \
% (pyhsm.defines.cmd2str(response_status - pyhsm.defines.YSM_RESPONSE), \
response_len, response_len)
# read YSM_PKT.payload
res = self.stick.read(response_len, debug_info)
if res:
if response_status == self.command | pyhsm.defines.YSM_RESPONSE:
self.executed = True
self.response_status = response_status
return self.parse_result(res)
else:
reset(self.stick)
raise pyhsm.exception.YHSM_Error('YubiHSM responded to wrong command')
else:
raise pyhsm.exception.YHSM_Error('YubiHSM did not respond') | [
"def",
"_read_response",
"(",
"self",
")",
":",
"# // Up- and downlink packet",
"# typedef struct {",
"# uint8_t bcnt; // Number of bytes (cmd + payload)",
"# uint8_t cmd; // YSM_xxx command",
"# uint8_t payload[YSM_MAX_PKT_SIZE]; // Payload",
"# } YSM_PKT;",
"# read YSM_PKT.bcnt and YSM_PKT.cmd",
"res",
"=",
"self",
".",
"stick",
".",
"read",
"(",
"2",
",",
"'response length + response status'",
")",
"if",
"len",
"(",
"res",
")",
"!=",
"2",
":",
"self",
".",
"_handle_invalid_read_response",
"(",
"res",
",",
"2",
")",
"response_len",
",",
"response_status",
"=",
"struct",
".",
"unpack",
"(",
"'BB'",
",",
"res",
")",
"response_len",
"-=",
"1",
"# the status byte has been read already",
"debug_info",
"=",
"None",
"if",
"response_status",
"&",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
":",
"debug_info",
"=",
"\"%s response (%i/0x%x bytes)\"",
"%",
"(",
"pyhsm",
".",
"defines",
".",
"cmd2str",
"(",
"response_status",
"-",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
")",
",",
"response_len",
",",
"response_len",
")",
"# read YSM_PKT.payload",
"res",
"=",
"self",
".",
"stick",
".",
"read",
"(",
"response_len",
",",
"debug_info",
")",
"if",
"res",
":",
"if",
"response_status",
"==",
"self",
".",
"command",
"|",
"pyhsm",
".",
"defines",
".",
"YSM_RESPONSE",
":",
"self",
".",
"executed",
"=",
"True",
"self",
".",
"response_status",
"=",
"response_status",
"return",
"self",
".",
"parse_result",
"(",
"res",
")",
"else",
":",
"reset",
"(",
"self",
".",
"stick",
")",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"'YubiHSM responded to wrong command'",
")",
"else",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"'YubiHSM did not respond'",
")"
]
| After writing a command, read response.
@returns: Result of parse_data()
@raises pyhsm.exception.YHSM_Error: On failure to read a response to the
command we sent in a timely fashion. | [
"After",
"writing",
"a",
"command",
"read",
"response",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/cmd.py#L79-L117 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.reset | def reset(self, test_sync = True):
"""
Perform stream resynchronization.
@param test_sync: Verify sync with YubiHSM after reset
@type test_sync: bool
@return: True if successful
@rtype: bool
"""
pyhsm.cmd.reset(self.stick)
if test_sync:
# Now verify we are in sync
data = 'ekoeko'
echo = self.echo(data)
# XXX analyze 'echo' to see if we are in config mode, and produce a
# nice exception if we are.
return data == echo
else:
return True | python | def reset(self, test_sync = True):
"""
Perform stream resynchronization.
@param test_sync: Verify sync with YubiHSM after reset
@type test_sync: bool
@return: True if successful
@rtype: bool
"""
pyhsm.cmd.reset(self.stick)
if test_sync:
# Now verify we are in sync
data = 'ekoeko'
echo = self.echo(data)
# XXX analyze 'echo' to see if we are in config mode, and produce a
# nice exception if we are.
return data == echo
else:
return True | [
"def",
"reset",
"(",
"self",
",",
"test_sync",
"=",
"True",
")",
":",
"pyhsm",
".",
"cmd",
".",
"reset",
"(",
"self",
".",
"stick",
")",
"if",
"test_sync",
":",
"# Now verify we are in sync",
"data",
"=",
"'ekoeko'",
"echo",
"=",
"self",
".",
"echo",
"(",
"data",
")",
"# XXX analyze 'echo' to see if we are in config mode, and produce a",
"# nice exception if we are.",
"return",
"data",
"==",
"echo",
"else",
":",
"return",
"True"
]
| Perform stream resynchronization.
@param test_sync: Verify sync with YubiHSM after reset
@type test_sync: bool
@return: True if successful
@rtype: bool | [
"Perform",
"stream",
"resynchronization",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L91-L110 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.set_debug | def set_debug(self, new):
"""
Set debug mode.
@param new: new value
@type new: bool
@return: old value
@rtype: bool
"""
if type(new) is not bool:
raise pyhsm.exception.YHSM_WrongInputType(
'new', bool, type(new))
old = self.debug
self.debug = new
self.stick.set_debug(new)
return old | python | def set_debug(self, new):
"""
Set debug mode.
@param new: new value
@type new: bool
@return: old value
@rtype: bool
"""
if type(new) is not bool:
raise pyhsm.exception.YHSM_WrongInputType(
'new', bool, type(new))
old = self.debug
self.debug = new
self.stick.set_debug(new)
return old | [
"def",
"set_debug",
"(",
"self",
",",
"new",
")",
":",
"if",
"type",
"(",
"new",
")",
"is",
"not",
"bool",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_WrongInputType",
"(",
"'new'",
",",
"bool",
",",
"type",
"(",
"new",
")",
")",
"old",
"=",
"self",
".",
"debug",
"self",
".",
"debug",
"=",
"new",
"self",
".",
"stick",
".",
"set_debug",
"(",
"new",
")",
"return",
"old"
]
| Set debug mode.
@param new: new value
@type new: bool
@return: old value
@rtype: bool | [
"Set",
"debug",
"mode",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L112-L128 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.echo | def echo(self, data):
"""
Echo test.
@type data: string
@return: data read from YubiHSM -- should equal `data'
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Echo}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Echo(self.stick, data).execute() | python | def echo(self, data):
"""
Echo test.
@type data: string
@return: data read from YubiHSM -- should equal `data'
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Echo}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Echo(self.stick, data).execute() | [
"def",
"echo",
"(",
"self",
",",
"data",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Echo",
"(",
"self",
".",
"stick",
",",
"data",
")",
".",
"execute",
"(",
")"
]
| Echo test.
@type data: string
@return: data read from YubiHSM -- should equal `data'
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Echo} | [
"Echo",
"test",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L155-L165 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.random | def random(self, num_bytes):
"""
Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random(self.stick, num_bytes).execute() | python | def random(self, num_bytes):
"""
Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random(self.stick, num_bytes).execute() | [
"def",
"random",
"(",
"self",
",",
"num_bytes",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Random",
"(",
"self",
".",
"stick",
",",
"num_bytes",
")",
".",
"execute",
"(",
")"
]
| Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random} | [
"Get",
"random",
"bytes",
"from",
"YubiHSM",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L177-L191 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.random_reseed | def random_reseed(self, seed):
"""
Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed(self.stick, seed).execute() | python | def random_reseed(self, seed):
"""
Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed(self.stick, seed).execute() | [
"def",
"random_reseed",
"(",
"self",
",",
"seed",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Random_Reseed",
"(",
"self",
".",
"stick",
",",
"seed",
")",
".",
"execute",
"(",
")"
]
| Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed} | [
"Provide",
"YubiHSM",
"DRBG_CTR",
"with",
"a",
"new",
"seed",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L193-L205 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.get_nonce | def get_nonce(self, increment=1):
"""
Get current nonce from YubiHSM.
Use increment 0 to just fetch the value without incrementing it.
@keyword increment: requested increment (optional)
@return: nonce value _before_ increment
@rtype: L{YHSM_NonceResponse}
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get(self.stick, increment).execute() | python | def get_nonce(self, increment=1):
"""
Get current nonce from YubiHSM.
Use increment 0 to just fetch the value without incrementing it.
@keyword increment: requested increment (optional)
@return: nonce value _before_ increment
@rtype: L{YHSM_NonceResponse}
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get(self.stick, increment).execute() | [
"def",
"get_nonce",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Nonce_Get",
"(",
"self",
".",
"stick",
",",
"increment",
")",
".",
"execute",
"(",
")"
]
| Get current nonce from YubiHSM.
Use increment 0 to just fetch the value without incrementing it.
@keyword increment: requested increment (optional)
@return: nonce value _before_ increment
@rtype: L{YHSM_NonceResponse}
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Nonce_Get} | [
"Get",
"current",
"nonce",
"from",
"YubiHSM",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L207-L220 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.load_temp_key | def load_temp_key(self, nonce, key_handle, aead):
"""
Load the contents of an AEAD into the phantom key handle 0xffffffff.
@param nonce: The nonce used when creating the AEAD
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type nonce: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load(self.stick, nonce, key_handle, aead).execute() | python | def load_temp_key(self, nonce, key_handle, aead):
"""
Load the contents of an AEAD into the phantom key handle 0xffffffff.
@param nonce: The nonce used when creating the AEAD
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type nonce: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load}
"""
return pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load(self.stick, nonce, key_handle, aead).execute() | [
"def",
"load_temp_key",
"(",
"self",
",",
"nonce",
",",
"key_handle",
",",
"aead",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Temp_Key_Load",
"(",
"self",
".",
"stick",
",",
"nonce",
",",
"key_handle",
",",
"aead",
")",
".",
"execute",
"(",
")"
]
| Load the contents of an AEAD into the phantom key handle 0xffffffff.
@param nonce: The nonce used when creating the AEAD
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type nonce: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Temp_Key_Load} | [
"Load",
"the",
"contents",
"of",
"an",
"AEAD",
"into",
"the",
"phantom",
"key",
"handle",
"0xffffffff",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L222-L238 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.load_secret | def load_secret(self, secret):
"""
Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKey secret to load
@type secret: L{pyhsm.aead_cmd.YHSM_YubiKeySecret} or string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
if isinstance(secret, pyhsm.aead_cmd.YHSM_YubiKeySecret):
secret = secret.pack()
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, secret).execute() | python | def load_secret(self, secret):
"""
Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKey secret to load
@type secret: L{pyhsm.aead_cmd.YHSM_YubiKeySecret} or string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
if isinstance(secret, pyhsm.aead_cmd.YHSM_YubiKeySecret):
secret = secret.pack()
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, secret).execute() | [
"def",
"load_secret",
"(",
"self",
",",
"secret",
")",
":",
"if",
"isinstance",
"(",
"secret",
",",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_YubiKeySecret",
")",
":",
"secret",
"=",
"secret",
".",
"pack",
"(",
")",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
"YHSM_Cmd_Buffer_Load",
"(",
"self",
".",
"stick",
",",
"secret",
")",
".",
"execute",
"(",
")"
]
| Ask YubiHSM to load a pre-existing YubiKey secret.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param secret: YubiKey secret to load
@type secret: L{pyhsm.aead_cmd.YHSM_YubiKeySecret} or string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load} | [
"Ask",
"YubiHSM",
"to",
"load",
"a",
"pre",
"-",
"existing",
"YubiKey",
"secret",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L294-L312 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.load_data | def load_data(self, data, offset):
"""
Ask YubiHSM to load arbitrary data into it's internal buffer, at any offset.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
Load data to offset 0 to reset the buffer.
@param data: arbitrary data to load
@type data: string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, data, offset).execute() | python | def load_data(self, data, offset):
"""
Ask YubiHSM to load arbitrary data into it's internal buffer, at any offset.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
Load data to offset 0 to reset the buffer.
@param data: arbitrary data to load
@type data: string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load(self.stick, data, offset).execute() | [
"def",
"load_data",
"(",
"self",
",",
"data",
",",
"offset",
")",
":",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
"YHSM_Cmd_Buffer_Load",
"(",
"self",
".",
"stick",
",",
"data",
",",
"offset",
")",
".",
"execute",
"(",
")"
]
| Ask YubiHSM to load arbitrary data into it's internal buffer, at any offset.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
Load data to offset 0 to reset the buffer.
@param data: arbitrary data to load
@type data: string
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Load} | [
"Ask",
"YubiHSM",
"to",
"load",
"arbitrary",
"data",
"into",
"it",
"s",
"internal",
"buffer",
"at",
"any",
"offset",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L314-L332 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.load_random | def load_random(self, num_bytes, offset = 0):
"""
Ask YubiHSM to generate a number of random bytes to any offset of it's internal
buffer.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param num_bytes: Number of bytes to generate
@type num_bytes: integer
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load(self.stick, num_bytes, offset).execute() | python | def load_random(self, num_bytes, offset = 0):
"""
Ask YubiHSM to generate a number of random bytes to any offset of it's internal
buffer.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param num_bytes: Number of bytes to generate
@type num_bytes: integer
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load}
"""
return pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load(self.stick, num_bytes, offset).execute() | [
"def",
"load_random",
"(",
"self",
",",
"num_bytes",
",",
"offset",
"=",
"0",
")",
":",
"return",
"pyhsm",
".",
"buffer_cmd",
".",
"YHSM_Cmd_Buffer_Random_Load",
"(",
"self",
".",
"stick",
",",
"num_bytes",
",",
"offset",
")",
".",
"execute",
"(",
")"
]
| Ask YubiHSM to generate a number of random bytes to any offset of it's internal
buffer.
The data is stored internally in the YubiHSM in temporary memory -
this operation would typically be followed by one or more L{generate_aead}
commands to actually retreive the generated secret (in encrypted form).
@param num_bytes: Number of bytes to generate
@type num_bytes: integer
@returns: Number of bytes in YubiHSM internal buffer after load
@rtype: integer
@see: L{pyhsm.buffer_cmd.YHSM_Cmd_Buffer_Random_Load} | [
"Ask",
"YubiHSM",
"to",
"generate",
"a",
"number",
"of",
"random",
"bytes",
"to",
"any",
"offset",
"of",
"it",
"s",
"internal",
"buffer",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L334-L351 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.generate_aead_random | def generate_aead_random(self, nonce, key_handle, num_bytes):
"""
Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator.
To generate a secret for a YubiKey, use public_id as nonce.
@param nonce: The nonce to use when creating the AEAD
@param key_handle: The key handle that can encrypt the random data into an AEAD
@param num_bytes: Number of random data bytes to put inside the AEAD
@type nonce: string
@type key_handle: integer or string
@type num_bytes: integer
@returns: The generated AEAD on success.
@rtype: L{YHSM_GeneratedAEAD}
@see: L{pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate}
"""
return pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate(self.stick, nonce, key_handle, num_bytes).execute() | python | def generate_aead_random(self, nonce, key_handle, num_bytes):
"""
Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator.
To generate a secret for a YubiKey, use public_id as nonce.
@param nonce: The nonce to use when creating the AEAD
@param key_handle: The key handle that can encrypt the random data into an AEAD
@param num_bytes: Number of random data bytes to put inside the AEAD
@type nonce: string
@type key_handle: integer or string
@type num_bytes: integer
@returns: The generated AEAD on success.
@rtype: L{YHSM_GeneratedAEAD}
@see: L{pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate}
"""
return pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate(self.stick, nonce, key_handle, num_bytes).execute() | [
"def",
"generate_aead_random",
"(",
"self",
",",
"nonce",
",",
"key_handle",
",",
"num_bytes",
")",
":",
"return",
"pyhsm",
".",
"aead_cmd",
".",
"YHSM_Cmd_AEAD_Random_Generate",
"(",
"self",
".",
"stick",
",",
"nonce",
",",
"key_handle",
",",
"num_bytes",
")",
".",
"execute",
"(",
")"
]
| Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator.
To generate a secret for a YubiKey, use public_id as nonce.
@param nonce: The nonce to use when creating the AEAD
@param key_handle: The key handle that can encrypt the random data into an AEAD
@param num_bytes: Number of random data bytes to put inside the AEAD
@type nonce: string
@type key_handle: integer or string
@type num_bytes: integer
@returns: The generated AEAD on success.
@rtype: L{YHSM_GeneratedAEAD}
@see: L{pyhsm.aead_cmd.YHSM_Cmd_AEAD_Random_Generate} | [
"Generate",
"a",
"random",
"AEAD",
"block",
"using",
"the",
"YubiHSM",
"internal",
"DRBG_CTR",
"random",
"generator",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L372-L390 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.validate_aead_otp | def validate_aead_otp(self, public_id, otp, key_handle, aead):
"""
Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type public_id: string
@type otp: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP}
"""
if type(public_id) is not str:
assert()
if type(otp) is not str:
assert()
if type(key_handle) is not int:
assert()
if type(aead) is not str:
assert()
return pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP( \
self.stick, public_id, otp, key_handle, aead).execute() | python | def validate_aead_otp(self, public_id, otp, key_handle, aead):
"""
Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type public_id: string
@type otp: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP}
"""
if type(public_id) is not str:
assert()
if type(otp) is not str:
assert()
if type(key_handle) is not int:
assert()
if type(aead) is not str:
assert()
return pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP( \
self.stick, public_id, otp, key_handle, aead).execute() | [
"def",
"validate_aead_otp",
"(",
"self",
",",
"public_id",
",",
"otp",
",",
"key_handle",
",",
"aead",
")",
":",
"if",
"type",
"(",
"public_id",
")",
"is",
"not",
"str",
":",
"assert",
"(",
")",
"if",
"type",
"(",
"otp",
")",
"is",
"not",
"str",
":",
"assert",
"(",
")",
"if",
"type",
"(",
"key_handle",
")",
"is",
"not",
"int",
":",
"assert",
"(",
")",
"if",
"type",
"(",
"aead",
")",
"is",
"not",
"str",
":",
"assert",
"(",
")",
"return",
"pyhsm",
".",
"validate_cmd",
".",
"YHSM_Cmd_AEAD_Validate_OTP",
"(",
"self",
".",
"stick",
",",
"public_id",
",",
"otp",
",",
"key_handle",
",",
"aead",
")",
".",
"execute",
"(",
")"
]
| Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD containing the cryptographic key and permission flags
@type public_id: string
@type otp: string
@type key_handle: integer or string
@type aead: L{YHSM_GeneratedAEAD} or string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP} | [
"Ask",
"YubiHSM",
"to",
"validate",
"a",
"YubiKey",
"OTP",
"using",
"an",
"AEAD",
"and",
"a",
"key_handle",
"to",
"decrypt",
"the",
"AEAD",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L436-L464 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.aes_ecb_encrypt | def aes_ecb_encrypt(self, key_handle, plaintext):
"""
AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Ciphertext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt( \
self.stick, key_handle, plaintext).execute() | python | def aes_ecb_encrypt(self, key_handle, plaintext):
"""
AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Ciphertext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt( \
self.stick, key_handle, plaintext).execute() | [
"def",
"aes_ecb_encrypt",
"(",
"self",
",",
"key_handle",
",",
"plaintext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Encrypt",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"plaintext",
")",
".",
"execute",
"(",
")"
]
| AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Ciphertext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Encrypt} | [
"AES",
"ECB",
"encrypt",
"using",
"a",
"key",
"handle",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L505-L522 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.aes_ecb_decrypt | def aes_ecb_decrypt(self, key_handle, ciphertext):
"""
AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
@returns: Plaintext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt( \
self.stick, key_handle, ciphertext).execute() | python | def aes_ecb_decrypt(self, key_handle, ciphertext):
"""
AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
@returns: Plaintext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt( \
self.stick, key_handle, ciphertext).execute() | [
"def",
"aes_ecb_decrypt",
"(",
"self",
",",
"key_handle",
",",
"ciphertext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Decrypt",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"ciphertext",
")",
".",
"execute",
"(",
")"
]
| AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
@returns: Plaintext
@rtype: string
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt} | [
"AES",
"ECB",
"decrypt",
"using",
"a",
"key",
"handle",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L524-L541 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.aes_ecb_compare | def aes_ecb_compare(self, key_handle, ciphertext, plaintext):
"""
AES ECB decrypt and then compare using a key handle.
The comparison is done inside the YubiHSM so the plaintext is never exposed (well,
except indirectionally when the provided plaintext does match).
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param plaintext: Data to decrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Match result
@rtype: bool
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare( \
self.stick, key_handle, ciphertext, plaintext).execute() | python | def aes_ecb_compare(self, key_handle, ciphertext, plaintext):
"""
AES ECB decrypt and then compare using a key handle.
The comparison is done inside the YubiHSM so the plaintext is never exposed (well,
except indirectionally when the provided plaintext does match).
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param plaintext: Data to decrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Match result
@rtype: bool
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare}
"""
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare( \
self.stick, key_handle, ciphertext, plaintext).execute() | [
"def",
"aes_ecb_compare",
"(",
"self",
",",
"key_handle",
",",
"ciphertext",
",",
"plaintext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Compare",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"ciphertext",
",",
"plaintext",
")",
".",
"execute",
"(",
")"
]
| AES ECB decrypt and then compare using a key handle.
The comparison is done inside the YubiHSM so the plaintext is never exposed (well,
except indirectionally when the provided plaintext does match).
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param plaintext: Data to decrypt
@type key_handle: integer or string
@type plaintext: string
@returns: Match result
@rtype: bool
@see: L{pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Compare} | [
"AES",
"ECB",
"decrypt",
"and",
"then",
"compare",
"using",
"a",
"key",
"handle",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L543-L563 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.hmac_sha1 | def hmac_sha1(self, key_handle, data, flags = None, final = True, to_buffer = False):
"""
Have the YubiHSM generate a HMAC SHA1 of 'data' using a key handle.
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.next} to add more input (until
'final' has been set to True).
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.get_hash} to get the hash result
this far.
@param key_handle: Key handle to use when generating HMAC SHA1
@param data: what to calculate the HMAC SHA1 checksum of
@keyword flags: bit-flags, overrides 'final' and 'to_buffer'
@keyword final: True when there is no more data, False if there is more
@keyword to_buffer: Should the final result be stored in the YubiHSM internal buffer or not
@type key_handle: integer or string
@type data: string
@type flags: None or integer
@returns: HMAC-SHA1 instance
@rtype: L{YHSM_Cmd_HMAC_SHA1_Write}
@see: L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write}
"""
return pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write( \
self.stick, key_handle, data, flags = flags, final = final, to_buffer = to_buffer).execute() | python | def hmac_sha1(self, key_handle, data, flags = None, final = True, to_buffer = False):
"""
Have the YubiHSM generate a HMAC SHA1 of 'data' using a key handle.
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.next} to add more input (until
'final' has been set to True).
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.get_hash} to get the hash result
this far.
@param key_handle: Key handle to use when generating HMAC SHA1
@param data: what to calculate the HMAC SHA1 checksum of
@keyword flags: bit-flags, overrides 'final' and 'to_buffer'
@keyword final: True when there is no more data, False if there is more
@keyword to_buffer: Should the final result be stored in the YubiHSM internal buffer or not
@type key_handle: integer or string
@type data: string
@type flags: None or integer
@returns: HMAC-SHA1 instance
@rtype: L{YHSM_Cmd_HMAC_SHA1_Write}
@see: L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write}
"""
return pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write( \
self.stick, key_handle, data, flags = flags, final = final, to_buffer = to_buffer).execute() | [
"def",
"hmac_sha1",
"(",
"self",
",",
"key_handle",
",",
"data",
",",
"flags",
"=",
"None",
",",
"final",
"=",
"True",
",",
"to_buffer",
"=",
"False",
")",
":",
"return",
"pyhsm",
".",
"hmac_cmd",
".",
"YHSM_Cmd_HMAC_SHA1_Write",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"data",
",",
"flags",
"=",
"flags",
",",
"final",
"=",
"final",
",",
"to_buffer",
"=",
"to_buffer",
")",
".",
"execute",
"(",
")"
]
| Have the YubiHSM generate a HMAC SHA1 of 'data' using a key handle.
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.next} to add more input (until
'final' has been set to True).
Use the L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write.get_hash} to get the hash result
this far.
@param key_handle: Key handle to use when generating HMAC SHA1
@param data: what to calculate the HMAC SHA1 checksum of
@keyword flags: bit-flags, overrides 'final' and 'to_buffer'
@keyword final: True when there is no more data, False if there is more
@keyword to_buffer: Should the final result be stored in the YubiHSM internal buffer or not
@type key_handle: integer or string
@type data: string
@type flags: None or integer
@returns: HMAC-SHA1 instance
@rtype: L{YHSM_Cmd_HMAC_SHA1_Write}
@see: L{pyhsm.hmac_cmd.YHSM_Cmd_HMAC_SHA1_Write} | [
"Have",
"the",
"YubiHSM",
"generate",
"a",
"HMAC",
"SHA1",
"of",
"data",
"using",
"a",
"key",
"handle",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L568-L593 | train |
Yubico/python-pyhsm | pyhsm/base.py | YHSM.db_validate_yubikey_otp | def db_validate_yubikey_otp(self, public_id, otp):
"""
Request the YubiHSM to validate an OTP for a YubiKey stored
in the internal database.
@param public_id: The six bytes public id of the YubiKey
@param otp: The OTP from a YubiKey in binary form (16 bytes)
@type public_id: string
@type otp: string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP}
"""
return pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP( \
self.stick, public_id, otp).execute() | python | def db_validate_yubikey_otp(self, public_id, otp):
"""
Request the YubiHSM to validate an OTP for a YubiKey stored
in the internal database.
@param public_id: The six bytes public id of the YubiKey
@param otp: The OTP from a YubiKey in binary form (16 bytes)
@type public_id: string
@type otp: string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP}
"""
return pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP( \
self.stick, public_id, otp).execute() | [
"def",
"db_validate_yubikey_otp",
"(",
"self",
",",
"public_id",
",",
"otp",
")",
":",
"return",
"pyhsm",
".",
"db_cmd",
".",
"YHSM_Cmd_DB_Validate_OTP",
"(",
"self",
".",
"stick",
",",
"public_id",
",",
"otp",
")",
".",
"execute",
"(",
")"
]
| Request the YubiHSM to validate an OTP for a YubiKey stored
in the internal database.
@param public_id: The six bytes public id of the YubiKey
@param otp: The OTP from a YubiKey in binary form (16 bytes)
@type public_id: string
@type otp: string
@returns: validation response
@rtype: L{YHSM_ValidationResult}
@see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP} | [
"Request",
"the",
"YubiHSM",
"to",
"validate",
"an",
"OTP",
"for",
"a",
"YubiKey",
"stored",
"in",
"the",
"internal",
"database",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L626-L642 | train |
Yubico/python-pyhsm | pyhsm/ksm/yubikey_ksm.py | aead_filename | def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2) + [public_id]
return os.path.join(*parts) | python | def aead_filename(aead_dir, key_handle, public_id):
"""
Return the filename of the AEAD for this public_id.
"""
parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2) + [public_id]
return os.path.join(*parts) | [
"def",
"aead_filename",
"(",
"aead_dir",
",",
"key_handle",
",",
"public_id",
")",
":",
"parts",
"=",
"[",
"aead_dir",
",",
"key_handle",
"]",
"+",
"pyhsm",
".",
"util",
".",
"group",
"(",
"public_id",
",",
"2",
")",
"+",
"[",
"public_id",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")"
]
| Return the filename of the AEAD for this public_id. | [
"Return",
"the",
"filename",
"of",
"the",
"AEAD",
"for",
"this",
"public_id",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L249-L254 | train |
Yubico/python-pyhsm | pyhsm/ksm/yubikey_ksm.py | run | def run(hsm, aead_backend, args):
"""
Start a BaseHTTPServer.HTTPServer and serve requests forever.
"""
write_pid_file(args.pid_file)
server_address = (args.listen_addr, args.listen_port)
httpd = YHSM_KSMServer(server_address,
partial(YHSM_KSMRequestHandler, hsm, aead_backend, args))
my_log_message(args.debug or args.verbose, syslog.LOG_INFO,
"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')"
% (args.listen_addr, args.listen_port, args.serve_url, args.key_handles, args.device, args.aead_dir, args.db_url))
httpd.serve_forever() | python | def run(hsm, aead_backend, args):
"""
Start a BaseHTTPServer.HTTPServer and serve requests forever.
"""
write_pid_file(args.pid_file)
server_address = (args.listen_addr, args.listen_port)
httpd = YHSM_KSMServer(server_address,
partial(YHSM_KSMRequestHandler, hsm, aead_backend, args))
my_log_message(args.debug or args.verbose, syslog.LOG_INFO,
"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')"
% (args.listen_addr, args.listen_port, args.serve_url, args.key_handles, args.device, args.aead_dir, args.db_url))
httpd.serve_forever() | [
"def",
"run",
"(",
"hsm",
",",
"aead_backend",
",",
"args",
")",
":",
"write_pid_file",
"(",
"args",
".",
"pid_file",
")",
"server_address",
"=",
"(",
"args",
".",
"listen_addr",
",",
"args",
".",
"listen_port",
")",
"httpd",
"=",
"YHSM_KSMServer",
"(",
"server_address",
",",
"partial",
"(",
"YHSM_KSMRequestHandler",
",",
"hsm",
",",
"aead_backend",
",",
"args",
")",
")",
"my_log_message",
"(",
"args",
".",
"debug",
"or",
"args",
".",
"verbose",
",",
"syslog",
".",
"LOG_INFO",
",",
"\"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')\"",
"%",
"(",
"args",
".",
"listen_addr",
",",
"args",
".",
"listen_port",
",",
"args",
".",
"serve_url",
",",
"args",
".",
"key_handles",
",",
"args",
".",
"device",
",",
"args",
".",
"aead_dir",
",",
"args",
".",
"db_url",
")",
")",
"httpd",
".",
"serve_forever",
"(",
")"
]
| Start a BaseHTTPServer.HTTPServer and serve requests forever. | [
"Start",
"a",
"BaseHTTPServer",
".",
"HTTPServer",
"and",
"serve",
"requests",
"forever",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L394-L407 | train |
Yubico/python-pyhsm | pyhsm/ksm/yubikey_ksm.py | my_log_message | def my_log_message(verbose, prio, msg):
"""
Log to syslog, and possibly also to stderr.
"""
syslog.syslog(prio, msg)
if verbose or prio == syslog.LOG_ERR:
sys.stderr.write("%s\n" % (msg)) | python | def my_log_message(verbose, prio, msg):
"""
Log to syslog, and possibly also to stderr.
"""
syslog.syslog(prio, msg)
if verbose or prio == syslog.LOG_ERR:
sys.stderr.write("%s\n" % (msg)) | [
"def",
"my_log_message",
"(",
"verbose",
",",
"prio",
",",
"msg",
")",
":",
"syslog",
".",
"syslog",
"(",
"prio",
",",
"msg",
")",
"if",
"verbose",
"or",
"prio",
"==",
"syslog",
".",
"LOG_ERR",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"(",
"msg",
")",
")"
]
| Log to syslog, and possibly also to stderr. | [
"Log",
"to",
"syslog",
"and",
"possibly",
"also",
"to",
"stderr",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L410-L416 | train |
Yubico/python-pyhsm | pyhsm/ksm/yubikey_ksm.py | YHSM_KSMRequestHandler.do_GET | def do_GET(self):
""" Handle a HTTP GET request. """
# Example session:
# in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0
# out : OK counter=0004 low=f585 high=3e use=03
if self.path.startswith(self.serve_url):
from_key = self.path[len(self.serve_url):]
val_res = self.decrypt_yubikey_otp(from_key)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(val_res)
self.wfile.write("\n")
elif self.stats_url and self.path == self.stats_url:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
for key in stats:
self.wfile.write("%s %d\n" % (key, stats[key]))
else:
self.log_error("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, self.serve_url))
self.send_response(403, 'Forbidden')
self.end_headers() | python | def do_GET(self):
""" Handle a HTTP GET request. """
# Example session:
# in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0
# out : OK counter=0004 low=f585 high=3e use=03
if self.path.startswith(self.serve_url):
from_key = self.path[len(self.serve_url):]
val_res = self.decrypt_yubikey_otp(from_key)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(val_res)
self.wfile.write("\n")
elif self.stats_url and self.path == self.stats_url:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
for key in stats:
self.wfile.write("%s %d\n" % (key, stats[key]))
else:
self.log_error("Bad URL '%s' - I'm serving '%s' (responding 403)" % (self.path, self.serve_url))
self.send_response(403, 'Forbidden')
self.end_headers() | [
"def",
"do_GET",
"(",
"self",
")",
":",
"# Example session:",
"# in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0",
"# out : OK counter=0004 low=f585 high=3e use=03",
"if",
"self",
".",
"path",
".",
"startswith",
"(",
"self",
".",
"serve_url",
")",
":",
"from_key",
"=",
"self",
".",
"path",
"[",
"len",
"(",
"self",
".",
"serve_url",
")",
":",
"]",
"val_res",
"=",
"self",
".",
"decrypt_yubikey_otp",
"(",
"from_key",
")",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"'Content-type'",
",",
"'text/html'",
")",
"self",
".",
"end_headers",
"(",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"val_res",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"\"\\n\"",
")",
"elif",
"self",
".",
"stats_url",
"and",
"self",
".",
"path",
"==",
"self",
".",
"stats_url",
":",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"'Content-type'",
",",
"'text/html'",
")",
"self",
".",
"end_headers",
"(",
")",
"for",
"key",
"in",
"stats",
":",
"self",
".",
"wfile",
".",
"write",
"(",
"\"%s %d\\n\"",
"%",
"(",
"key",
",",
"stats",
"[",
"key",
"]",
")",
")",
"else",
":",
"self",
".",
"log_error",
"(",
"\"Bad URL '%s' - I'm serving '%s' (responding 403)\"",
"%",
"(",
"self",
".",
"path",
",",
"self",
".",
"serve_url",
")",
")",
"self",
".",
"send_response",
"(",
"403",
",",
"'Forbidden'",
")",
"self",
".",
"end_headers",
"(",
")"
]
| Handle a HTTP GET request. | [
"Handle",
"a",
"HTTP",
"GET",
"request",
"."
]
| b6e2744d1ea15c352a0fc1d6ebc5950026b71311 | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L92-L116 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.