Модуль | Имя | Версия | Лицензия | Источник | Языки | Платформы | Тип | Автор | Описание |
---|---|---|---|---|---|---|---|---|---|
HTTP | HTTP-реализация | 3.10 | GPL2 | prot_HTTP.so | en,uk,ru,de | x86,x86_64,ARM | Протокол | Роман Савоченко | Предоставляет поддержку протокола HTTP для WWW-основанных пользовательских интерфейсов.
|
Модуль транспортного протокола HTTP предназначен для реализации поддержки сетевого протокола HTTP(Hypertext Transfer Protocol) в OpenSCADA.
HTTP protocol is used to transfer the WWW content. For example, via HTTP the following types of documents are transmitted: html, xhtml, png, javascript, and many others. Support HTTP in OpenSCADA together with the transport Sockets and SSL allows to implement various user functions based on the WWW interface. The module initially implements two main methods of the HTTP protocol "GET", "POST", and currently any HTTP method. The module provides control of the integrity of HTTP-queries and, jointly with Sockets and SSL transport, allows to "collect" whole requests from their fragments, as well as hold of the connection "alive" (Keep-Alive).
Для гибкого подключения пользовательских интерфейсов к данному модулю, используется модульный механизм в рамках самого этого модуля. В роли модулей используются модули подсистемы "Пользовательские интерфейсы" с дополнительным информационным полем "SubType", имеющим значение "WWW".
В запросах к Web ресурсам принято использовать URL(Universal Resource Locator). Следовательно, URL передаётся как основной параметр через HTTP. Первый элемент запрашиваемого URL используется для идентификации модуля UI. Например, URL "http://localhost:10002/WebCfg" означает обращение к модулю "WebCfg" на хосте "http://localhost:10002". В случае ошибочного указания идентификатора модуля, или при обращении вообще без идентификатора, модуль генерирует информационный диалог о входе и выбор одного из доступных пользовательских интерфейсов. Пример диалога показан на рисунке 1.
Модулем поддерживается многоязычность, которая включается динамическим переводом сообщений OpenSCADA.
Язык конечного пользователя интерфейса определяется путём и в последовательности:
- URL параметр "lang".
- Язык пользователя, который вошёл.
- Язык Web-браузера из HTTP свойства "Accept-Language".
- Общий язык процесса OpenSCADA.
Gotten in the way language used for building interfaces of the module and passes to the WWW sub-modules into the HTTP property "oscd_lang" of the argument "vars" of the generic, "GET" and "POST" functions.
To configure and control this module, you have the configuration page of the OpenSCADA control interface (Fig.3) where you can perform:
- Control for the active authentication sessions.
- Configuring:
- Rules of accessing for deny and allow. Any line of the rules of accessing is a different rule and you can use here templates, like to "*/WebVision/*"), or regular expressions, like to "/[^/]+/WebVision/.+/". Useful entries for:
- Deny:
- "*/WebCfgD/*" — the module WebCfgD completely;
- "*/WebVision/*tmplSO/*" — the VCA project "tmplSO" of the module WebVision.
- Allow:
- "*" — all, excluding the deny;
- "/^[^/]+/[^/]*$/" — pages of the module with all their resources;
- "*/login/*" — the login page;
- "/^[^/]+/WebVision/[^/]*($|\?)/" — the WebVision module main page without the VCA projects accessing;
- "/^[^/]+/WebVision/.+_aviariesOril\d*/.*/" — the VCA project "aviariesOril" of the module WebVision;
- "/^[^/]+/WebVision/Archive/.*/" — accessing archive data of the Protocol primitive for all WebVision projects.
- Deny:
- HTML-template of the user interface and user main-page. In the HTML-template's fields you must specify an address of the file HTML/XHTML, which will be used for formation of the internal-service and main-page interfaces. Internal-service interfaces for example, it's the WEB-modules selection, the login page and like ones of the WEB-modules. From the template required correct XHTML, allowing parse the file by XML-parser, and the presence of the tag "#####CONTEXT#####" at the location of the dynamic content, for internal-service interfaces it's necessarily. Resource files of the templates represented by images, CSS and JavaScript files and their are searching from the directory in which located the specified template file and from the current directory. If errors are found in the template there will be use a standard builtin interface. For different, to the language, template file you can add the language suffix to the file end like "{My template}_{lang}.html" but select the generic-base template file "{My template}.html" into these configuration fields. For the templates example you can see to the most used templates:
- Internal-service and main-page interfaces template, includes the modules index.
- Main-page's template with a direct link to the AGLKS main interface by UI.WebVision and without the WEB-modules index.
- Main-page's template with a strong redirection to the AGLKS main interface by UI.WebVision.
- DB of the active authentication sessions provides an external table of the active authentication sessions — "HTTP_AuthSessions", which is enabled for not empty value and provides a possibility of sharing the authentication between different OpenSCADA stations and its short storing at the station shut down time.
- Authentication UID generation space, accessible with the common authentication sessions table to guaranty the cookie difference for different OpenSCADA processes.
- Lifetime of the authentication and set up of the automatic login.
- Rules of accessing for deny and allow. Any line of the rules of accessing is a different rule and you can use here templates, like to "*/WebVision/*"), or regular expressions, like to "/[^/]+/WebVision/.+/". Useful entries for:
Contents
1 Аутентификация
Модулем поддерживается аутентификация в OpenSCADA при предоставлении доступа к модулям WEB-интерфейсов (рис.2).
Аутентификация этим модулем осуществляется "печеньем" (cookies) с динамическим названием и пространством ИД пользователя, где название "печенья" (cookie) "oscd_UID" и используется пространство ИД пользователя в работе с совместной таблицей сеансов аутентификации, и название "oscd_UID_{PrjNm}" в роботі без неё.
Для облегчения работы с Web-интерфейсами модуль предусматривает возможность автоматического входа от имени указанного пользователя. Конфигурация автоматического входа осуществляется на странице настройки модуля (рис.3). Автоматический вход осуществляется по совпадению адреса, указанного в колонке "Адреса", и от имени пользователя, указанного в колонке "Пользователь".
Для большей безопасности Вы можете определить только Web-пользователей, в перечне пользователей разрешённых к аутентификации.
2 Modules of the WEB-interface
Modules of the user interface (UI) designed to work with the HTTP module, should indicate the information field "SubType" in the value "WWW" and "Auth" field in the value "1", if the module requires an authentication at login. For communication of the HTTP module and the UI modules an advanced communication mechanism is used. This mechanism involves export of interface functions. In this case, the UI modules must export only one generic function for all methods:
- void HTTP(const string &meth, const string &uri, string &page, vector<string> &vars, const string &user, TProtocolIn *iprt);:
- meth — method of the request;
- uri — local address of the request;
- page — page with the answer;
- sender — address of the sender;
- vars — variables of the request;
- user — user, can contain previous user in the second line;
- iprt — pointer to an input part object of the protocol.
Or following different functions separately for GET and POST methods:
- void HTTP_GET(const string &uri, string &page, vector<string> &vars, const string &user, TProtocolIn *iprt); OR
- void HttpGet( const string &uri, string &page, const string &sender, vector<string> &vars, const string &user ); — GET method with the parameters:
- uri — local address of the request;
- page — page with the answer;
- sender — address of the sender;
- vars — variables of the request;
- user — user, can contain previous user in the second line;
- iprt — pointer to an input part object of the protocol.
- void HTTP_POST(const string &uri, string &page, vector<string> &vars, const string &user, TProtocolIn *iprt); OR
- void HttpPost( const string &uri, string &page, const string &sender, vector<string> &vars, const string &user ); — POST method with the parameters:
- uri — local address of the request;
- page — page with the answer and with the content of the body of the POST request;
- sender — address of the sender;
- vars — variables of the request;
- user — user, can contain previous user in the second line;
- iprt — pointer to an input part object of the protocol.
Then, in the case of the HTTP "GET" request, the function "HTTP_GET" or "HttpGet" will be called, and in the case of the "POST" request, the function "HTTP_POST" or "HttpPost" will be called in the appropriate UI module, or the function "HTTP" for any method.
3 Функция выходных запросов пользовательского API
Функция исходящих запросов messIO() оперирует обменом содержимым HTTP-запросов, завёрнутыми в XML-пакеты. Структура запроса имеет вид:
<req Host="host" URI="uri">
<prm id="pId">pVal</prm>
<cnt name="cName" filename="cFileName">
<prm id="cpId">cpVal</prm>
cVal
</cnt>
reqVal
</req>
- Где:
- req — метод запроса, поддерживаются методы "GET" и "POST".
- host — адрес узла http-сервера в формате {HostAddr}:{HostIp}. Если данное поле опущено то используется адрес узла, указанный в поле адреса транспорта.
- uri — адрес ресурса на http-сервере, обычно файл или директория.
- pId, pVal — идентификатор и значение дополнительного http-параметра. Http-параметров может быть указано множество, отдельными prm тегами.
- cName, cFileName, cVal — имя, имя-файла и значение элемента содержимого POST-запроса. Элементов содержимого может быть указано множество, отдельными cnt тегами.
- cpId, cpVal — идентификатор и значение дополнительного параметра содержимого. Параметров содержимого может быть указано множество, отдельными prm тегами;
- reqVal — одиночное содержимое POST запроса.
Результатом запроса является ответ со структурой:
<req Host="host" URI="uri" err="err" Protocol="prt" RezCod="rCod" RezStr="rStr">
<prm id="pId">pVal</prm>
respVal
</req>
- Где:
- req — метод запроса.
- host — адрес узла http-сервера.
- uri — адрес ресурса.
- err — ошибка, возникшая во время запроса. В случае успешного запроса это поле пустое.
- RezCod, RezStr — результат запроса в виде кода и текста.
- pId, pVal — идентификатор и значение дополнительного http-параметра ответа. Http-параметров может быть множество, определённые отдельными prm тегами.
- respVal — содержимое ответа.
Приведём формирование GET и POST запросов на языке JavaLikeCalc.JavaScript, в качестве примера использования данной функции в пользовательских процедурах:
//GET запрос HTML страницы
req = SYS.XMLNode("GET");
req.setAttr("URI","/");
SYS.Transport.Sockets.out_testHTTP.messIO(req,"HTTP");
test = req.text();
//GET запрос и сохранение файла
req = SYS.XMLNode("GET");
req.setAttr("URI","/oscadaArch/Work/openscada-0.9-r2188.tar.lzma");
SYS.Transport.Sockets.out_testHTTP.messIO(req,"HTTP");
if(!req.attr("err").length) SYS.fileWrite("/var/tmp/recvFile.tmp", req.text());
//POST запрос
req = SYS.XMLNode("POST");
req.setAttr("URI","/WebUser/FlowTec.txt");
cntNode = req.childAdd("cnt").setAttr("name","pole0").setAttr("filename","Object2-k001-100309-17.txt");
cntNode.childAdd("prm").setAttr("id","Content-Type").setText("text/plain");
cntText = "Object2-k001\r\n";
cntText += "\r\n";
cntText += "v002\r\n";
cntText += " n1\r\n";
cntText += " 09.03.10 16 Polnyj 7155.25 216.0 32.000 17.5\r\n";
cntText += "v005\r\n";
cntText += " n1\r\n";
cntText += " 09.03.10 16 Polnyj 188.81 350.0 4.000 40.0\r\n";
cntText += "\r\n";
cntNode.setText(cntText);
SYS.Transport.Sockets.out_testHTTP.messIO(req,"HTTP");
//POST запрос с одиночным содержимым
req = SYS.XMLNode("POST");
req.setAttr("URI","/WebUser/FlowTec.txt");
req.childAdd("prm").setAttr("id","Content-Type").setText("text/plain");
cntText = "Object2-k001\r\n";
cntText += "\r\n";
cntText += "v002\r\n";
cntText += " n1\r\n";
cntText += " 09.03.10 16 Polnyj 7155.25 216.0 32.000 17.5\r\n";
cntText += "v005\r\n";
cntText += " n1\r\n";
cntText += " 09.03.10 16 Polnyj 188.81 350.0 4.000 40.0\r\n";
cntText += "\r\n";
req.setText(cntText);
SYS.Transport.Sockets.out_testHTTP.messIO(req,"HTTP");
4 API пользовательского программирования
Входная часть объекта модуля (SYS.Protocol.HTTP.{In})
- bool setUser( string user ) — меняет пользователя связанного с идентификатором сеанса аутентификации.
- user — пользователя для смены.
- bool pgAccess(string URL) — проверяет доступность страницы, определённой в URL.
- URL — URL страницы, которая проверяется.
- string pgCreator(string cnt, string rcode = "", string httpattrs = "Content-Type: text/html;charset={SYS}", string htmlHeadEls = "", string forceTmplFile = "") — формирует страницу или ресурс из содержимого cnt, обёрнутого в HTTP с результатом rcode, с дополнительными атрибутами HTTP httpattrs, дополнительным элементом заголовка HTML htmlHeadEls и использованием файла шаблона forceTmplFile.
- cnt — содержимое страницы или ресурса (изображения, XML, CSS, JavaScript, ...);
- rcode — результирующий код HTTP, вроде "200 OK"; пустое значение выключает добавление HTTP заголовка;
- httpattrs — дополнительные атрибуты HTTP, в основном это "Content-Type" со значением по умолчанию "text/html;charset={SYS}"; только для "Content-Type: text/html" будет осуществляться заворачивание во внутренний/сервисный, или определённый forceTmplFile, HTML-шаблон;
- htmlHeadEls — дополнительный тег заголовка HTML, в основном это META с "Refresh" для указанного URL;
- forceTmplFile — файл прямо определённого шаблона для перекрытия внутреннего/сервисного или главной страницы.