Перекодировка в Proftpd
Добавлено: 2008-03-23 15:04:45
Слушаем-с Samm.
Мастер-класс. (Если он таки не откажется)
Мастер-класс. (Если он таки не откажется)
Сталина давно нэт. Чтоби спасти Россию, ищитэ его внутри сэбя...
https://forum.lissyara.su/
Ты бы сам повежливей был. А так чему удивляешься?Samm писал(а):1) Никакого мастер класса не будет. Патч я сделал, исключительно для тех, кто считает что чарсет в фтп нужен (зачем??) и кто при этом хоть немного вежливее админа этого сайта.
2) Патч был написан на коленке, тестровался минут 5, вроде работает. Никаких гарантий. По идее его можно допилить и отправить автору proftpd, я этим заниматься не хочу и не буду, так как считаю, что данное решение - кривое и неправильное. Есть множество протоколов с нормальной поддержкой кодировки в стандарте, юзайте их и будет вам счастье. Лицензия - BSD, т.е. делайте что хотите и не е..те мозг.
3) Протокол ftp говно.
Теперь об использовании - наложите патч, пересоберите proftpd, после чего добавляем в конфиг:
LocalCharset koi8-r
ClientCharset windows-1251
или любой другой на ваш вкус. По идее - многобайтные кодировки должны работать, так как длинна строки пересчитывается, но я не проверял.
Сеттинг можно указывать как в глобальном конфиге, так и в виртуалхосте (тоже не проверял). Вопросы - принимаются на мыло.
Ах, да, сам говнопатч: http://samm.kiev.ua/proftpd-iconv.diff
Дай сцылку почитать, я не слышал про такой тестSamm писал(а):Кстати, скорость у nginx была выше, за счёт sendfile(). На гигабите при тестах было заметно.
Это я смотрел и читал.Samm писал(а):тест я проводил, результаты не выкладывал
http://www.opennet.ru/base/net/tune_freebsd.txt.html - вот про sendfile и не только.
Код: Выделить всё
LocalCharset koi8-r
ClientCharset cp1251Пасиб, щас срач на серваке разгребу, snort настрою и буду тестить.Samm писал(а):А, ну да, нифига при configure не подцепилось. Щас поправим патч.
UPD: патч для порта @ http://samm.kiev.ua/proftpd.patch
Hello.
First of all i want to thank all of the developers for the great work - as for me proftpd is one of the best ftp servers. I`m using it on most of my servers and very happy with it.
Latest version of the proftp includes some basic UTF-8 support. Unicode support is a very important for any countries with non-latin alphabets, but also in some countries non-unicode characters are still widely used. Also i found a bugs in the current implementation, so i decided to extend recoding support in the proftpd webserver. Now the patch is ready and tested, and I hope that it is possible to integrate it in the baseline, because this is a "must have" feature for countries like Japan, Russia or Ukraine. Here is a brief description of the patch:
1) It will fix current recoding (wrong arguments order in the iconv_open)
2) 2 new optional configuration settings added LocalCharset and ClientCharset.
LocalCharset allow us to override server charset (nl_langinfo is not reliable way in many cases)
ClientCharset allow us to use other than Unicode charset in the server output.
If ClientCharset is used and is not UTF-8, UTF8 will be removed from the FEAT output to avoid problems with RFC2460 compatible clients.
Also patch will fix some minor issues with utf8_init() trace, which was broken because this function was used before configuration file was processed.
More details and the patch itself are at http://bugs.proftpd.org/show_bug.cgi?id=3056 . I am ready to support this patch and i hope that it will be included in the feature releases of the ProFTPD.
With best regards,
Alex Samorukov
При чём тут телнет, если мы говорим о FTP, спросите вы? А очень просто. RFC959 (FTP) чётко говорит о том, чтоAll TELNET commands consist of at least a two byte sequence: the
"Interpret as Command" (IAC) escape character followed by the code
for the command. The commands dealing with option negotiation are
three byte sequences, the third byte being the code for the option
referenced. This format was chosen so that as more comprehensive use
of the "data space" is made -- by negotiations from the basic NVT, of
course -- collisions of data bytes with reserved command values will
be minimized, all such collisions requiring the inconvenience, and
inefficiency, of "escaping" the data bytes into the stream. With the
current set-up, only the IAC need be doubled to be sent as data, and
the other 255 codes may be passed transparently.
и там жеThe File Transfer Protocol follows the specifications of the Telnet
protocol for all communications over the control connection. Since
the language used for Telnet communication may be a negotiated
option, all references in the next two sections will be to the
"Telnet language" and the corresponding "Telnet end-of-line code".
Currently, one may take these to mean NVT-ASCII and <CRLF>. No other
specifications of the Telnet protocol will be cited.
Теперь, зачем же proftpd потребовался код IAC? Он его использует очень забавно - для того, чтобы сообщить что его имплементация телнета - ничего не умеет и ничего делать не будет, т.е. максимально тупой терминал. А именно - на все запросы типа WILL/WONT отвечает DONT и на DO/DONT - WONT. Ни 1 из известных мне ftp клиентов не пытается делать escape для 0xff и таким образом мы имеем то, что следующий за "я" символ воспринимается как как команда и благополучно глотается. Думаю, что этот кусок кода с WILL/WONT был сделан для каких-то очень старых и глючных терминалов или ftp клиентов. По крайне мере я таких не видел. Полагаю, что будет вполне уместно сделать setting вроде TelnetEmuDisable или как-то так, который позволит вырубать кусок кода связанного с IAC.The Relationship between FTP and Telnet:
The FTP uses the Telnet protocol on the control connection.
This can be achieved in two ways: first, the user-PI or the
server-PI may implement the rules of the Telnet Protocol
directly in their own procedures; or, second, the user-PI or
the server-PI may make use of the existing Telnet module in the
system.
Ease of implementaion, sharing code, and modular programming
argue for the second approach. Efficiency and independence
argue for the first approach. In practice, FTP relies on very
little of the Telnet Protocol, so the first approach does not
necessarily involve a large amount of code.
Теперь перейдём от теории к практике. Я испытал 2 клиента для того на предмет обработки злосчастного символа 0xFF. Первым был FileZilla. Есть мнение, что всем известным ftp клиентам вообще наплевать на обработку IAC. По крайне мере ни FileZilla ни mc не посылают 0xFF два раза вместо одного. Более того, получая 1 0xFF они честно отрисовывают его как "я", а вовсе не переходят в режим control, как того требует telnet rfc. Причём в профтпд без cyrfix патча обработка символа 0xff соотв. RFC, т.е. два символа воспринимаются как 1. Хотя в отдаваемой им информации он тоже не ескейпит этот символ, таким образом также нарушая станарт.4.1.2.12 Connections: RFC-959 Section 5.2
The words "and the port used" in the second paragraph of
this section of RFC-959 are erroneous (historical), and they
should be ignored.
On a multihomed server host, the default data transfer port
(L-1) MUST be associated with the same local IP address as
the corresponding control connection to port L.
A user-FTP MUST NOT send any Telnet controls other than
SYNCH and IP on an FTP control connection. In particular, it
MUST NOT attempt to negotiate Telnet options on the control
connection. However, a server-FTP MUST be capable of
accepting and refusing Telnet negotiations (i.e., sending
DONT/WONT).
DISCUSSION:
Although the RFC says: "Server- and User- processes
should follow the conventions for the Telnet
protocol...[on the control connection]", it is not the
intent that Telnet option negotiation is to be
employed.
Также была решена проблем с некорректной обработкой файлов содержащих русскую букву "я" в кодовой странице cp1251.UseEncoding
Syntax: UseEncoding on|off|local-charset client-charset
Default: None
Context: "server config", <VirtualHost>, <Global>
Module: mod_lang
Compatibility: 1.3.2rc1
The UseEncoding directive is used to explicit configure which character sets should be used for encoding. By default, the mod_lang will automatically discover the local character set, and will use UTF8 for the client character set. The module will also allow the use of UTF8 encoding to be changed by clients using the OPTS UTF8 command (as per RFC2640). However, if the UseEncoding directive is explicitly used to indicate the character sets to use (or not use), then any OPTS UTF8 commands used by clients will be refused.
For example, to disable all use of encoding, use the following in your proftpd.conf:
UseEncoding off
Similarly, to enable use of UTF8 encoding and to not allow clients to change the use of UTF8, you would use:
UseEncoding on
In addition to the on|off parameters, the UseEncoding directive allows administrators to specify exactly which character sets to use locally (i.e. for paths on local disks) and for dealing with clients. One such usage this way might look like:
UseEncoding koi8-r cp1251
For a full list of the character sets which are supported, use:
$ iconv --list
P.S. От начала работы (2008-03-23) до сегодняшнего дня прошло куча времени и изначальный багрепорт превратился в 4- Bug 3064 - Better handling of 0xFF character for Cyrillic, non-UTF8 charsets.
These character sets use the same value as the Telnet IAC character in
the alphabet. RFC959 states that FTP control messages must support Telnet
characters; this requirement causes problems for the character sets.
This the RFC959 requirement is relaxed if --enable-nls is used, and if
one of the problematic character sets is configured.