|
1 | | -# Infinite backtracking problem |
| 1 | +# Проблема поиска с вечным возвратом |
2 | 2 |
|
3 | | -Some regular expressions are looking simple, but can execute veeeeeery long time, and even "hang" the JavaScript engine. |
| 3 | +Некоторые регулярные выражения выглядят просто, но могут выполняться оооочень долго, и даже "подвешивать" движок JavaScript. |
4 | 4 |
|
5 | | -Sooner or later most developers occasionally face such behavior. |
| 5 | +Рано или поздно большинство разработчиков с этим сталкиваются. |
6 | 6 |
|
7 | | -The typical situation -- a regular expression works fine sometimes, but for certain strings it "hangs" consuming 100% of CPU. |
| 7 | +Типичная ситуация: регулярное выражение работает нормально, но иногда, с некоторыми строками, зависает и потребляет 100% CPU. |
8 | 8 |
|
9 | | -In a web-browser it kills the page. Not a good thing for sure. |
| 9 | +В веб-браузере такой случай убивает страницу. Явно плохая ситуация. |
10 | 10 |
|
11 | | -For server-side Javascript it may become a vulnerability, and it uses regular expressions to process user data. Bad input will make the process hang, causing denial of service. The author personally saw and reported such vulnerabilities even for very well-known and widely used programs. |
| 11 | +Такой код, выполняемый на стороне сервера, может стать уязвимостью, а он использует регулярные выражения для обработки пользовательских данных. Некорректный ввод данных приведет к зависанию процесса и, как следствие, отказу сервиса. Автор(?) лично видел и сообщал о таких уязвимостях даже для очень известных и широко используемых программ. |
12 | 12 |
|
13 | | -So the problem is definitely worth to deal with. |
| 13 | +Так что проблема, несомненно, достойна рассмотрения. |
14 | 14 |
|
15 | | -## Introduction |
| 15 | +## Вступление |
16 | 16 |
|
17 | | -The plan will be like this: |
| 17 | +План будет следующим: |
18 | 18 |
|
19 | | -1. First we see the problem how it may occur. |
20 | | -2. Then we simplify the situation and see why it occurs. |
21 | | -3. Then we fix it. |
| 19 | +1. Сперва мы рассмотрим проблему так, как она может произойти. |
| 20 | +2. Затем мы упростим ситуацию и разберемся почему так происходит. |
| 21 | +3. И, на конец, исправим её. |
22 | 22 |
|
23 | | -For instance let's consider searching tags in HTML. |
| 23 | +Например, давайте рассмотрим поиск тегов в HTML. |
24 | 24 |
|
25 | | -We want to find all tags, with or without attributes -- like `subject:<a href="..." class="doc" ...>`. We need the regexp to work reliably, because HTML comes from the internet and can be messy. |
| 25 | +Мы хотим найти все теги с (или без) атрибутами, типа: `subject:<a href="..." class="doc" ...>`. Нужно чтобы регулярное выражение работало надёжно, так как HTML приходит из Интернета и может быть запутанным. |
26 | 26 |
|
27 | | -In particular, we need it to match tags like `<a test="<>" href="#">` -- with `<` and `>` in attributes. That's allowed by [HTML standard](https://html.spec.whatwg.org/multipage/syntax.html#syntax-attributes). |
| 27 | +В частности, нам нужно, чтобы оно соответствовало тегам типа: `<a test="<>" href="#">` -- т.е. с символами `<` и `>` в атрибутах, так как это поддерживается [стандартом HTML](https://html.spec.whatwg.org/multipage/syntax.html#syntax-attributes). |
28 | 28 |
|
29 | | -Now we can see that a simple regexp like `pattern:<[^>]+>` doesn't work, because it stops at the first `>`, and we need to ignore `<>` if inside an attribute. |
| 29 | +Как мы видим, простое регулярное выражение `pattern:<[^>]+>` не работает, потому что оно останавливает поиск на первом `>`, а нам нужно игнорировать `<>` если они являются частью атрибута. |
30 | 30 |
|
31 | 31 | ```js run |
32 | | -// the match doesn't reach the end of the tag - wrong! |
| 32 | +// поиск не достигает конца тега - неверно! |
33 | 33 | alert( '<a test="<>" href="#">'.match(/<[^>]+>/) ); // <a test="<> |
34 | 34 | ``` |
35 | 35 |
|
36 | | -To correctly handle such situations we need a more complex regular expression. It will have the form `pattern:<tag (key=value)*>`. |
| 36 | +Чтобы поддерживать такие случаи корректно To correctly handle such situations we need a more complex regular expression. It will have the form `pattern:<tag (key=value)*>`. |
37 | 37 |
|
38 | 38 | 1. For the `tag` name: `pattern:\w+`, |
39 | 39 | 2. For the `key` name: `pattern:\w+`, |
|
0 commit comments