]> git.stg.codes - stg.git/commitdiff
Merge branch 'new-daily-fee'
authorMaxim Mamontov <faust.madf@gmail.com>
Mon, 6 Jan 2014 15:51:09 +0000 (17:51 +0200)
committerMaxim Mamontov <faust.madf@gmail.com>
Mon, 6 Jan 2014 15:51:09 +0000 (17:51 +0200)
Conflicts:
include/stg/tariff_conf.h
projects/stargazer/plugins/store/firebird/Makefile
projects/stargazer/plugins/store/firebird/firebird_store.cpp
projects/stargazer/plugins/store/firebird/firebird_store.h
projects/stargazer/plugins/store/mysql/Makefile
projects/stargazer/plugins/store/mysql/mysql_store.cpp
projects/stargazer/plugins/store/mysql/mysql_store.h
projects/stargazer/plugins/store/postgresql/Makefile
projects/stargazer/plugins/store/postgresql/postgresql_store.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store.h
projects/stargazer/plugins/store/postgresql/postgresql_store_tariffs.cpp

292 files changed:
ChangeLog
doc/xmlrpc/API-user.xml
include/stg/admin.h
include/stg/admin_conf.h
include/stg/const.h
include/stg/corp_conf.h
include/stg/corporations.h
include/stg/notifer.h
include/stg/os_int.h
include/stg/plugin.h
include/stg/raw_ip_packet.h
include/stg/resetable.h
include/stg/rs_packets.h
include/stg/service_conf.h
include/stg/services.h
include/stg/settings.h
include/stg/store.h
include/stg/tariff_conf.h
include/stg/tariffs.h
include/stg/user.h
include/stg/user_conf.h
include/stg/user_ips.h
include/stg/user_property.h
include/stg/user_stat.h
include/stg/user_traff.h
include/stg/users.h
include/stg/utime.h
include/stg/version.h
projects/convertor/Makefile [deleted file]
projects/convertor/build [deleted file]
projects/convertor/convertor.conf [deleted file]
projects/convertor/main.cpp [deleted file]
projects/convertor/settings_impl.cpp [deleted file]
projects/convertor/settings_impl.h [deleted file]
projects/rlm_stg/Makefile
projects/rlm_stg/build
projects/rlm_stg/build_check.c [deleted file]
projects/rlm_stg/conf.h [deleted file]
projects/rlm_stg/conffile.h [deleted file]
projects/rlm_stg/iface.cpp [new file with mode: 0644]
projects/rlm_stg/iface.h [new file with mode: 0644]
projects/rlm_stg/libradius.h [deleted file]
projects/rlm_stg/modules.h [deleted file]
projects/rlm_stg/radius.h [deleted file]
projects/rlm_stg/radiusd.h [deleted file]
projects/rlm_stg/rlm_stg.c [new file with mode: 0644]
projects/rlm_stg/rlm_stg.cpp [deleted file]
projects/rlm_stg/stats.h [deleted file]
projects/rlm_stg/stg_client.cpp
projects/rlm_stg/stg_client.h
projects/rlm_stg/stgpair.h [new file with mode: 0644]
projects/rlm_stg/token.h [deleted file]
projects/rscriptd/Makefile
projects/rscriptd/build
projects/rscriptd/listener.cpp
projects/rscriptd/listener.h
projects/rscriptd/rscriptd.conf
projects/sgauth/Makefile
projects/sgauth/build
projects/sgauth/main.cpp
projects/sgauth/settings_impl.cpp
projects/sgauth/settings_impl.h
projects/sgauth/sgauth.conf
projects/sgauthstress/build
projects/sgconf/Makefile
projects/sgconf/action.h [new file with mode: 0644]
projects/sgconf/actions.cpp [new file with mode: 0644]
projects/sgconf/actions.h [new file with mode: 0644]
projects/sgconf/build
projects/sgconf/common_sg.cpp
projects/sgconf/common_sg.h
projects/sgconf/config.h [new file with mode: 0644]
projects/sgconf/main.cpp
projects/sgconf/options.cpp [new file with mode: 0644]
projects/sgconf/options.h [new file with mode: 0644]
projects/sgconf/parser_state.h [new file with mode: 0644]
projects/sgconf/request.h
projects/sgconf_xml/Makefile
projects/sgconf_xml/build
projects/sgconv/Makefile [new file with mode: 0644]
projects/sgconv/build [new file with mode: 0755]
projects/sgconv/main.cpp [new file with mode: 0644]
projects/sgconv/settings_impl.cpp [new file with mode: 0644]
projects/sgconv/settings_impl.h [new file with mode: 0644]
projects/sgconv/sgconv.conf [new file with mode: 0644]
projects/stargazer/Makefile
projects/stargazer/actions.h
projects/stargazer/admin_impl.h
projects/stargazer/admins_impl.cpp
projects/stargazer/admins_impl.h
projects/stargazer/build
projects/stargazer/corps_impl.cpp
projects/stargazer/corps_impl.h
projects/stargazer/eventloop.h
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/mod_cap_divert.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/mod_cap_nf.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/mod_ia.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/mod_remote_script.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/mod_rpc.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/mod_smux.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/store_files.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/store_firebird.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/store_mysql.conf
projects/stargazer/inst/freebsd/etc/stargazer/conf-available.d/store_postgresql.conf
projects/stargazer/inst/linux/etc/init.d/stargazer.gentoo
projects/stargazer/inst/linux/etc/stargazer/OnChange
projects/stargazer/inst/linux/etc/stargazer/OnConnect
projects/stargazer/inst/linux/etc/stargazer/OnDisconnect
projects/stargazer/inst/linux/etc/stargazer/OnUserAdd
projects/stargazer/inst/linux/etc/stargazer/OnUserDel
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/mod_cap_nf.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/mod_ia.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/mod_remote_script.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/mod_rpc.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/mod_smux.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/store_files.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/store_firebird.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/store_mysql.conf
projects/stargazer/inst/linux/etc/stargazer/conf-available.d/store_postgresql.conf
projects/stargazer/main.cpp
projects/stargazer/plugins/Makefile.in
projects/stargazer/plugins/authorization/ao/Makefile
projects/stargazer/plugins/authorization/ao/ao.cpp
projects/stargazer/plugins/authorization/ao/ao.h
projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp
projects/stargazer/plugins/authorization/inetaccess/inetaccess.h
projects/stargazer/plugins/capture/cap_debug/debug_cap.cpp
projects/stargazer/plugins/capture/cap_debug/debug_cap.h
projects/stargazer/plugins/capture/cap_nf/Makefile
projects/stargazer/plugins/capture/cap_nf/cap_nf.cpp
projects/stargazer/plugins/capture/cap_nf/cap_nf.h
projects/stargazer/plugins/capture/divert_freebsd/Makefile
projects/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp
projects/stargazer/plugins/capture/divert_freebsd/divert_cap.h
projects/stargazer/plugins/capture/ether_freebsd/Makefile
projects/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp
projects/stargazer/plugins/capture/ether_freebsd/ether_cap.h
projects/stargazer/plugins/capture/ether_linux/Makefile
projects/stargazer/plugins/capture/ether_linux/ether_cap.cpp
projects/stargazer/plugins/capture/ether_linux/ether_cap.h
projects/stargazer/plugins/capture/ipq_linux/Makefile
projects/stargazer/plugins/capture/ipq_linux/ipq_cap.cpp
projects/stargazer/plugins/capture/ipq_linux/ipq_cap.h
projects/stargazer/plugins/capture/ipq_linux/libipq.c
projects/stargazer/plugins/capture/ipq_linux/libipq.h
projects/stargazer/plugins/configuration/rpcconfig/admins_methods.cpp
projects/stargazer/plugins/configuration/rpcconfig/info_methods.cpp
projects/stargazer/plugins/configuration/rpcconfig/messages_methods.cpp
projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp
projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.h
projects/stargazer/plugins/configuration/rpcconfig/user_helper.cpp
projects/stargazer/plugins/configuration/rpcconfig/user_helper.h
projects/stargazer/plugins/configuration/rpcconfig/users_methods.cpp
projects/stargazer/plugins/configuration/rpcconfig/users_methods.h
projects/stargazer/plugins/configuration/rpcconfig/utils.cpp [deleted file]
projects/stargazer/plugins/configuration/rpcconfig/utils.h [deleted file]
projects/stargazer/plugins/configuration/sgconfig/Makefile
projects/stargazer/plugins/configuration/sgconfig/configproto.cpp
projects/stargazer/plugins/configuration/sgconfig/configproto.h
projects/stargazer/plugins/configuration/sgconfig/parser.cpp
projects/stargazer/plugins/configuration/sgconfig/parser.h
projects/stargazer/plugins/configuration/sgconfig/parser_admin.cpp
projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp [new file with mode: 0644]
projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.h [new file with mode: 0644]
projects/stargazer/plugins/configuration/sgconfig/parser_tariff.cpp
projects/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp [new file with mode: 0644]
projects/stargazer/plugins/configuration/sgconfig/parser_user_info.h [new file with mode: 0644]
projects/stargazer/plugins/configuration/sgconfig/rsconf.cpp
projects/stargazer/plugins/configuration/sgconfig/stgconfig.cpp
projects/stargazer/plugins/configuration/sgconfig/stgconfig.h
projects/stargazer/plugins/other/ping/ping.cpp
projects/stargazer/plugins/other/ping/ping.h
projects/stargazer/plugins/other/radius/radius.cpp
projects/stargazer/plugins/other/radius/radius.h
projects/stargazer/plugins/other/rscript/nrmap_parser.h
projects/stargazer/plugins/other/rscript/rscript.cpp
projects/stargazer/plugins/other/rscript/rscript.h
projects/stargazer/plugins/other/rscript/send_functor.h
projects/stargazer/plugins/other/rscript/ur_functor.h
projects/stargazer/plugins/other/smux/smux.cpp
projects/stargazer/plugins/other/smux/smux.h
projects/stargazer/plugins/other/smux/tables.cpp
projects/stargazer/plugins/other/smux/types.cpp
projects/stargazer/plugins/other/smux/utils.cpp
projects/stargazer/plugins/other/smux/value2os.h
projects/stargazer/plugins/store/files/file_store.cpp
projects/stargazer/plugins/store/files/file_store.h
projects/stargazer/plugins/store/firebird/Makefile
projects/stargazer/plugins/store/firebird/firebird_store.cpp
projects/stargazer/plugins/store/firebird/firebird_store.h
projects/stargazer/plugins/store/firebird/firebird_store_corporations.cpp
projects/stargazer/plugins/store/firebird/firebird_store_messages.cpp
projects/stargazer/plugins/store/firebird/firebird_store_services.cpp
projects/stargazer/plugins/store/firebird/firebird_store_tariffs.cpp
projects/stargazer/plugins/store/firebird/firebird_store_users.cpp
projects/stargazer/plugins/store/mysql/Makefile
projects/stargazer/plugins/store/mysql/mysql_store.cpp
projects/stargazer/plugins/store/mysql/mysql_store.h
projects/stargazer/plugins/store/postgresql/Makefile
projects/stargazer/plugins/store/postgresql/postgresql_store.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store.h
projects/stargazer/plugins/store/postgresql/postgresql_store_admins.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_corporations.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_messages.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_services.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_tariffs.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_users.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_utils.cpp
projects/stargazer/plugins/store/postgresql/postgresql_store_utils.h [deleted file]
projects/stargazer/services_impl.cpp
projects/stargazer/services_impl.h
projects/stargazer/settings_impl.cpp
projects/stargazer/settings_impl.h
projects/stargazer/stg_timer.cpp
projects/stargazer/stg_timer.h
projects/stargazer/store_loader.cpp
projects/stargazer/tariff_impl.cpp
projects/stargazer/tariff_impl.h
projects/stargazer/tariffs_impl.cpp
projects/stargazer/tariffs_impl.h
projects/stargazer/traffcounter_impl.cpp
projects/stargazer/traffcounter_impl.h
projects/stargazer/user_impl.cpp
projects/stargazer/user_impl.h
projects/stargazer/user_property.cpp
projects/stargazer/users_impl.cpp
projects/stargazer/users_impl.h
stglibs/Makefile
stglibs/Makefile.in
stglibs/common.lib/common.cpp
stglibs/common.lib/include/stg/common.h
stglibs/common.lib/strptime.cpp
stglibs/conffiles.lib/conffiles.cpp
stglibs/conffiles.lib/include/stg/conffiles.h
stglibs/crypto.lib/include/stg/blowfish.h
stglibs/dotconfpp.lib/include/stg/dotconfpp.h
stglibs/ia.lib/ia.cpp
stglibs/ia.lib/include/stg/ia.h
stglibs/ibpp.lib/_ibpp.h
stglibs/ibpp.lib/blob.cpp
stglibs/ibpp.lib/ibase.h
stglibs/ibpp.lib/include/stg/ibpp.h
stglibs/ibpp.lib/statement.cpp
stglibs/ibpp.lib/transaction.cpp
stglibs/locker.lib/include/stg/locker.h
stglibs/logger.lib/include/stg/logger.h
stglibs/logger.lib/logger.cpp
stglibs/pinger.lib/include/stg/pinger.h
stglibs/pinger.lib/pinger.cpp
stglibs/scriptexecuter.lib/include/stg/scriptexecuter.h
stglibs/scriptexecuter.lib/scriptexecuter.c
stglibs/srvconf.lib/Makefile
stglibs/srvconf.lib/include/stg/netunit.h [deleted file]
stglibs/srvconf.lib/include/stg/servconf.h
stglibs/srvconf.lib/include/stg/servconf_types.h [new file with mode: 0644]
stglibs/srvconf.lib/netunit.cpp
stglibs/srvconf.lib/netunit.h [new file with mode: 0644]
stglibs/srvconf.lib/parser.cpp [deleted file]
stglibs/srvconf.lib/parsers/auth_by.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/auth_by.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/base.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_admin.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_admin.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_corp.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_corp.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_service.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_service.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_tariff.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_tariff.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_user.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/chg_user.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_admin.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_admin.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_container.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_corp.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_corp.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_service.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_service.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_tariff.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_tariff.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_user.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/get_user.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/property.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/property.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/resetable_utils.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/server_info.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/server_info.h [new file with mode: 0644]
stglibs/srvconf.lib/parsers/simple.cpp [new file with mode: 0644]
stglibs/srvconf.lib/parsers/simple.h [new file with mode: 0644]
stglibs/srvconf.lib/servconf.cpp
stglibs/srvconf.lib/servconf.vpj [deleted file]
stglibs/srvconf.lib/servconf.vpw [deleted file]

index cca2afcfdd916d2c34b3a58cee8ea6f88dae1077..0879a49eeea84ed259105023a2e9751f9c67f615 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,5 @@
 General:
-    * Стандартизован стиль именования параметров: SnakeCase.
+    * Стандартизован стиль именования параметров: CamelCase.
     * В документации к XML-RPC API добавлено пропущенное поле 'password' для
     метода chg_admin.
     * Приведена в порядок работа с сигналами. Теперь сигналы перехватываются
index fac4f2be8b597e2d3a7354b99842cd7d23a0e021..82f8e7eeb1950d5a19ed9d74402b1ecf1fe50358 100644 (file)
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>
                 <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
             </para>
         </refsect1>
     </refentry>
                 <link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
                 <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>
                 <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
+                <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
+            </para>
+        </refsect1>
+    </refentry>
+    <refentry id="stargazer.get_user_auth_by">
+        <refmeta>
+            <refentrytitle>stargazer.get_user_auth_by</refentrytitle>
+        </refmeta>
+        <refnamediv>
+            <refname>stargazer.get_user_auth_by</refname>
+            <refpurpose>Получение списка авторизаторов которыми авторизован пользователь</refpurpose>
+        </refnamediv>
+        <refsynopsisdiv>
+            <funcsynopsis>
+                <funcprototype>
+                    <funcdef><function>stargazer.get_user_auth_by</function></funcdef>
+                    <paramdef>string <parameter>cookie</parameter></paramdef>
+                    <paramdef>string <parameter>login</parameter></paramdef>
+                </funcprototype>
+            </funcsynopsis>
+        </refsynopsisdiv>
+        <refsect1>
+            <title>Description</title>
+            <para>Метод <function>stargazer.get_user_auth_by</function> позволяет получить список авторизаторов которыми в данный момент авторизован пользователь.</para>
+            <variablelist>
+                <varlistentry>
+                    <term>string <parameter>cookie</parameter></term>
+                    <listitem>
+                        <para>Авторизационный cookie. Для авторизации в системе используется метод <function><link linkend="stargazer.login">stargazer.login</link></function></para>
+                    </listitem>
+                </varlistentry>
+                <varlistentry>
+                    <term>string <parameter>login</parameter></term>
+                    <listitem>
+                        <para>Логин пользователя</para>
+                    </listitem>
+                </varlistentry>
+            </variablelist>
+            <refsect2>
+                <title>Return Value</title>
+                <para>Возвращает структуру:</para>
+                <variablelist>
+                    <varlistentry>
+                        <term>bool <structfield>result</structfield></term>
+                        <listitem>
+                            <para>Результат операции. true - успешно, false - неудача (неправильный или устаревший cookie).</para>
+                        </listitem>
+                    </varlistentry>
+                    <varlistentry>
+                        <term>array of strings <structfield>auths</structfield></term>
+                        <listitem>
+                            <para>Список авторизаторов которыми авторизован пользователь.</para>
+                        </listitem>
+                    </varlistentry>
+                </variablelist>
+            </refsect2>
+        </refsect1>
+        <refsect1>
+            <title>See also</title>
+            <para>
+                <link linkend="stargazer.get_users"><function>stargazer.get_users</function></link>,
+                <link linkend="stargazer.get_user"><function>stargazer.get_user</function></link>,
+                <link linkend="stargazer.add_user"><function>stargazer.add_user</function></link>,
+                <link linkend="stargazer.chg_user"><function>stargazer.chg_user</function></link>,
+                <link linkend="stargazer.del_user"><function>stargazer.del_user</function></link>,
+                <link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
+                <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>
+                <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
+                <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
             </para>
         </refsect1>
     </refentry>
index 7552a1a12a39c415165e259b841236b5845a4568..961968a1065234e12a2a803c2812abf078b23655 100644 (file)
@@ -32,7 +32,7 @@ public:
     virtual const std::string & GetPassword() const = 0;
     virtual const std::string & GetLogin() const = 0;
     virtual PRIV const *        GetPriv() const = 0;
-    virtual uint16_t            GetPrivAsInt() const = 0;
+    virtual uint32_t            GetPrivAsInt() const = 0;
     virtual const ADMIN_CONF &  GetConf() const = 0;
     virtual uint32_t            GetIP() const = 0;
     virtual std::string         GetIPStr() const = 0;
index df6d9e22456f0f633a804c1311cf25fa7d7dff90..8b1a988e1877ff79c77e73bfd404b67e22710583 100644 (file)
@@ -7,9 +7,10 @@
 #ifndef ADMIN_CONF_H
 #define ADMIN_CONF_H
 
-#include <string>
-
 #include "os_int.h"
+#include "resetable.h"
+
+#include <string>
 
 #define ADM_LOGIN_LEN   (32)
 #define ADM_PASSWD_LEN  (32)
@@ -75,6 +76,29 @@ struct ADMIN_CONF
     std::string   password;
 };
 //-----------------------------------------------------------------------------
+struct ADMIN_CONF_RES
+{
+    ADMIN_CONF_RES(const ADMIN_CONF & conf)
+        : priv(conf.priv),
+          login(conf.login),
+          password(conf.password)
+    {}
+    ADMIN_CONF_RES(const ADMIN_CONF_RES & rhs)
+        : priv(rhs.priv),
+          login(rhs.login),
+          password(rhs.password)
+    {}
+    ADMIN_CONF_RES & operator=(const ADMIN_CONF_RES & rhs)
+    {
+        priv = rhs.priv;
+        login = rhs.login;
+        password = rhs.password;
+        return *this;
+    }
+    RESETABLE<PRIV> priv;
+    RESETABLE<std::string> login;
+    RESETABLE<std::string> password;
+};
 
 #include "admin_conf.inc.h"
 
index e882200df1c1783d2280088c4a79d21349c7987b..55f5b54bc9e6102f9cc1cb7f82e2aa5981964585 100644 (file)
@@ -80,8 +80,6 @@
 #define NO_TARIFF_NAME  "*_NO_TARIFF_*"
 #define NO_CORP_NAME    "*_NO_CORP_*"
 
-#define mega (1024 * 1024)
-
 #define MONITOR_TIME_DELAY_SEC  (60)
 
 #endif
index d6cc2ebbe626f5422de591c3f9e47f26d4e97a83..9bbc03d326941e2edce782663cbec4e3cbd15163 100644 (file)
@@ -1,6 +1,28 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
 #ifndef CORP_CONF_H
 #define CORP_CONF_H
 
+#include "resetable.h"
+
 #include <string>
 
 struct CORP_CONF
@@ -13,6 +35,31 @@ std::string name;
 double      cash;
 };
 
+struct CORP_CONF_RES
+{
+CORP_CONF_RES()
+    : name(), cash()
+{}
+
+CORP_CONF_RES & operator=(const CORP_CONF & conf)
+{
+name = conf.name;
+cash = conf.cash;
+return *this;
+}
+
+CORP_CONF GetData() const
+{
+CORP_CONF cc;
+cc.name = name.data();
+cc.cash = cash.data();
+return cc;
+}
+
+RESETABLE<std::string> name;
+RESETABLE<double>      cash;
+};
+
 inline
 bool operator==(const CORP_CONF & a, const CORP_CONF & b)
 {
index 2d07c6c659c704a28c532bec285247608e93ac2d..e167301b5d72fa1cf2fdc480ab13ebbf92728759 100644 (file)
 #ifndef CORPORATIONS_H
 #define CORPORATIONS_H
 
-#include <string>
-
 #include "corp_conf.h"
 
+#include <string>
+
 class ADMIN;
 
 class CORPORATIONS {
index 57f9928e1aa7989cfbb2cbc417570fbb1372de57..6f2133282d355ea081e783a4a19d1f2e184e2921 100644 (file)
@@ -12,7 +12,7 @@ template <typename varParamType>
 class PROPERTY_NOTIFIER_BASE
 {
 public:
-    virtual      ~PROPERTY_NOTIFIER_BASE(){};
+    virtual      ~PROPERTY_NOTIFIER_BASE(){}
     virtual void Notify(const varParamType & oldValue, const varParamType & newValue) = 0;
 };
 //-----------------------------------------------------------------------------
@@ -20,7 +20,7 @@ template <typename varParamType>
 class NOTIFIER_BASE
 {
 public:
-    virtual      ~NOTIFIER_BASE(){};
+    virtual      ~NOTIFIER_BASE(){}
     virtual void Notify(const varParamType & value) = 0;
 };
 //-----------------------------------------------------------------------------
index cc017b84b8b5624bd1f3389f3b203ea01c8ff4a7..00ab3fad579fd3169be8a3c0aed8b7f28bb6bbd2 100644 (file)
@@ -31,7 +31,7 @@
 #include <stdint.h>
 #endif
 
-#ifdef FREE_BSD5
+#if defined(FREE_BSD5) || defined(DARWIN)
 #include <inttypes.h>
 #endif
 
index 2ecf7af08161e56faa7d02564cb4a765d77d559e..114ffc8bc61e58f67ed0e1fb05868007df6f1b0e 100644 (file)
@@ -62,7 +62,7 @@ public:
     virtual int                 Reload() = 0;
     virtual bool                IsRunning() = 0;
     virtual const std::string & GetStrError() const = 0;
-    virtual const std::string   GetVersion() const = 0;
+    virtual std::string         GetVersion() const = 0;
     virtual uint16_t            GetStartPosition() const = 0;
     virtual uint16_t            GetStopPosition() const = 0;
 };
index f07bf2280b4ab2db68c5b1532ca819bd1236579c..b94faf868b40451484bd4b5c9b1e03910544a82f 100644 (file)
@@ -23,13 +23,6 @@ struct RAW_PACKET
     memset(rawPacket.pckt, 0, pcktSize);
     }
 
-    RAW_PACKET(const RAW_PACKET & rp)
-        : rawPacket(),
-          dataLen(rp.dataLen)
-    {
-    memcpy(rawPacket.pckt, rp.rawPacket.pckt, pcktSize);
-    }
-
 uint16_t    GetIPVersion() const;
 uint8_t     GetHeaderLen() const;
 uint8_t     GetProto() const;
@@ -40,7 +33,7 @@ uint16_t    GetSrcPort() const;
 uint16_t    GetDstPort() const;
 
 bool        operator==(const RAW_PACKET & rvalue) const;
-bool        operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); };
+bool        operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); }
 bool        operator<(const RAW_PACKET & rvalue) const;
 
 union
@@ -52,7 +45,7 @@ union
         // Only for packets without options field
         uint16_t    sPort;
         uint16_t    dPort;
-        } header __attribute__ ((packed));
+        } header;
     } rawPacket;
 int32_t dataLen; // IP packet length. Set to -1 to use length field from the header
 };
@@ -93,14 +86,16 @@ inline uint16_t RAW_PACKET::GetSrcPort() const
 {
 if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0
     return 0;
-return ntohs(*((uint16_t*)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)));
+const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4;
+return ntohs(*reinterpret_cast<const uint16_t *>(pos));
 }
 //-----------------------------------------------------------------------------
 inline uint16_t RAW_PACKET::GetDstPort() const
 {
 if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0
     return 0;
-return ntohs(*((uint16_t*)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)));
+const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2;
+return ntohs(*reinterpret_cast<const uint16_t *>(pos));
 }
 //-----------------------------------------------------------------------------
 inline bool RAW_PACKET::operator==(const RAW_PACKET & rvalue) const
@@ -113,12 +108,14 @@ if (rawPacket.header.ipHeader.ip_dst.s_addr != rvalue.rawPacket.header.ipHeader.
 
 if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1)
     {
-    if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) !=
-        *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4)))
+    const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4;
+    const uint8_t * rpos = rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4;
+    if (*reinterpret_cast<const uint16_t *>(pos) != *reinterpret_cast<const uint16_t *>(rpos))
         return false;
 
-    if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) !=
-        *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2)))
+    pos += 2;
+    rpos += 2;
+    if (*reinterpret_cast<const uint16_t *>(pos) != *reinterpret_cast<const uint16_t *>(rpos))
         return false;
     }
 
@@ -142,18 +139,18 @@ if (rawPacket.header.ipHeader.ip_dst.s_addr > rvalue.rawPacket.header.ipHeader.i
 
 if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1)
     {
-    if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) <
-        *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4))) 
+    const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4;
+    const uint8_t * rpos = rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4;
+    if (*reinterpret_cast<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
         return true;
-    if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) >
-        *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4))) 
+    if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(rpos))
         return false;
 
-    if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) <
-        *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2))) 
+    pos += 2;
+    rpos += 2;
+    if (*reinterpret_cast<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
         return true;
-    if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) >
-        *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2))) 
+    if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(rpos))
         return false;
     }
 
index f3cecac843b65ba94f85ffc023f945e7c8981c64..c78d02476e5cbea97d9b80acd764a80aad8d1c61 100644 (file)
@@ -1,9 +1,3 @@
- /*
- $Revision: 1.9 $
- $Date: 2010/03/11 14:42:04 $
- $Author: faust $
- */
-
 /*
  * Copyright (c) 2001 by Peter Simons <simons@cryp.to>.
  * All rights reserved.
@@ -15,8 +9,6 @@
 // This is a wrapper class about variables where you want to keep
 // track of whether it has been assigened yet or not.
 
-#include <iostream>
-
 template <typename T>
 class RESETABLE
 {
@@ -24,32 +16,31 @@ public:
     typedef T value_type;
 
     RESETABLE() : value(), is_set(false) {}
+    RESETABLE(const T & v) : value(v), is_set(true) {}
 
-    RESETABLE(const RESETABLE<value_type> & rvalue)
+    RESETABLE(const RESETABLE<T> & rvalue)
         : value(rvalue.value),
           is_set(rvalue.is_set)
     {}
 
-    RESETABLE(const value_type& val) : value(val), is_set(true) {}
-
-    RESETABLE<value_type> & operator=(const RESETABLE<value_type> & rvalue)
+    RESETABLE<T> & operator=(const RESETABLE<T> & rhs)
     {
-        value = rvalue.value;
-        is_set = rvalue.is_set;
+        value = rhs.value;
+        is_set = rhs.is_set;
         return *this;
     }
 
-    RESETABLE<value_type> & operator=(const value_type& rhs)
+    RESETABLE<T> & operator=(const T & rhs)
     {
         value = rhs;
         is_set = true;
         return *this;
     }
 
-    const value_type & const_data() const throw() { return value; }
-    value_type & data() throw() { return value; }
-    operator const value_type&() const throw() { return value; }
-    bool res_empty() const throw() { return !is_set; }
+    const T & const_data() const throw() { return value; }
+    T & data() throw() { return value; }
+    const T & data() const throw() { return value; }
+    bool empty() const throw() { return !is_set; }
     void reset() throw() { is_set = false; }
 
 private:
@@ -57,14 +48,4 @@ private:
     bool       is_set;
 };
 
-template <typename T>
-std::ostream & operator<<(std::ostream & o, const RESETABLE<T> & v);
-
-template <typename T>
-inline
-std::ostream & operator<<(std::ostream & o, const RESETABLE<T> & v)
-{
-    return o << v.const_data();
-}
-
 #endif // RESETABLE_VARIABLE_H
index 1a038be7f1a68f07e20b7344d9f03481fd09c43a..503fe91d7584522d9280c760eabc9f55eda7fa3f 100644 (file)
@@ -1,3 +1,24 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
 #ifndef RS_PACKETSH
 #define RS_PACKETSH
 
 
 #include "os_int.h"
 
-struct RS_PACKET_HEADER
+namespace RS
+{
+
+struct PACKET_HEADER
 {
 int8_t              magic[RS_MAGIC_LEN];
 int8_t              protoVer[RS_PROTO_VER_LEN];
@@ -26,11 +50,13 @@ int8_t              login[RS_LOGIN_LEN];
 int8_t              padding[7];
 } __attribute__((__packed__)); // 48 bytes, 6 blocks
 
-struct RS_PACKET_TAIL
+struct PACKET_TAIL
 {
 int8_t              magic[RS_MAGIC_LEN];
 int8_t              params[RS_PARAMS_LEN];
 int8_t              padding[7];
 } __attribute__((__packed__)); // 992 bytes, 124 blocks
 
+} // namespace RS
+
 #endif
index ef487f8ee78a41e624191930dd12660604dc0257..473830e44393636b301efdb16cc97a1a926acf99 100644 (file)
@@ -1,10 +1,31 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
 #ifndef SERVICE_CONF_H
 #define SERVICE_CONF_H
 
-#include <string>
-
+#include "resetable.h"
 #include "os_int.h"
 
+#include <string>
+
 struct SERVICE_CONF
 {
 SERVICE_CONF()
@@ -17,11 +38,11 @@ SERVICE_CONF(const std::string & n, double c)
     : name(n), comment(), cost(c), payDay(0)
 {}
 SERVICE_CONF(const std::string & n, double c, unsigned p)
-    : name(n), comment(), cost(c), payDay(p)
+    : name(n), comment(), cost(c), payDay(static_cast<uint8_t>(p))
 {}
 SERVICE_CONF(const std::string & n, double c,
              unsigned p, const std::string & com)
-    : name(n), comment(com), cost(c), payDay(p)
+    : name(n), comment(com), cost(c), payDay(static_cast<uint8_t>(p))
 {}
 
 std::string name;
@@ -30,6 +51,38 @@ double      cost;
 uint8_t     payDay;
 };
 
+struct SERVICE_CONF_RES
+{
+SERVICE_CONF_RES()
+    : name(), comment(),
+      cost(), payDay()
+{}
+
+SERVICE_CONF_RES & operator=(const SERVICE_CONF & conf)
+{
+name = conf.name;
+comment = conf.comment;
+cost = conf.cost;
+payDay = conf.payDay;
+return *this;
+}
+
+SERVICE_CONF GetData() const
+{
+SERVICE_CONF sc;
+sc.name = name.data();
+sc.comment = comment.data();
+sc.cost = cost.data();
+sc.payDay = payDay.data();
+return sc;
+}
+
+RESETABLE<std::string> name;
+RESETABLE<std::string> comment;
+RESETABLE<double>      cost;
+RESETABLE<uint8_t>     payDay;
+};
+
 inline
 bool operator==(const SERVICE_CONF & a, const SERVICE_CONF & b)
 {
index ddec31beb9af61a602a27bb8b8f05ee2956bc34c..8c49f7813b913cfe855526fadefc5e767f851596 100644 (file)
 #ifndef SERVICES_H
 #define SERVICES_H
 
-#include <string>
-
 #include "service_conf.h"
 
+#include <string>
+
 class ADMIN;
 
 class SERVICES {
index d23494bc5edd1aa91edd25ed3a7f4a864d76b52d..170f71cada5dc1f3edfbe0c475830ebdcd1ec214 100644 (file)
 class SETTINGS {
 public:
     virtual ~SETTINGS() {}
-    virtual const std::string & GetDirName(size_t num) const = 0;
-    virtual const std::string & GetScriptsDir() const = 0;
-    virtual unsigned            GetDetailStatWritePeriod() const = 0;
-    virtual unsigned            GetStatWritePeriod() const = 0;
-    virtual unsigned            GetDayFee() const = 0;
-    virtual bool                GetFullFee() const = 0;
-    virtual unsigned            GetDayResetTraff() const = 0;
-    virtual bool                GetSpreadFee() const = 0;
-    virtual bool                GetFreeMbAllowInet() const = 0;
-    virtual bool                GetDayFeeIsLastDay() const = 0;
-    virtual bool                GetWriteFreeMbTraffCost() const = 0;
-    virtual bool                GetShowFeeInCash() const = 0;
-    virtual unsigned            GetMessageTimeout() const = 0;
-    virtual unsigned            GetFeeChargeType() const = 0;
-    virtual bool                GetReconnectOnTariffChange() const = 0;
-    virtual const std::string & GetMonitorDir() const = 0;
-    virtual bool                GetMonitoring() const = 0;
+    virtual const std::string &              GetDirName(size_t num) const = 0;
+    virtual const std::string &              GetScriptsDir() const = 0;
+    virtual unsigned                         GetDetailStatWritePeriod() const = 0;
+    virtual unsigned                         GetStatWritePeriod() const = 0;
+    virtual unsigned                         GetDayFee() const = 0;
+    virtual bool                             GetFullFee() const = 0;
+    virtual unsigned                         GetDayResetTraff() const = 0;
+    virtual bool                             GetSpreadFee() const = 0;
+    virtual bool                             GetFreeMbAllowInet() const = 0;
+    virtual bool                             GetDayFeeIsLastDay() const = 0;
+    virtual bool                             GetWriteFreeMbTraffCost() const = 0;
+    virtual bool                             GetShowFeeInCash() const = 0;
+    virtual unsigned                         GetMessageTimeout() const = 0;
+    virtual unsigned                         GetFeeChargeType() const = 0;
+    virtual bool                             GetReconnectOnTariffChange() const = 0;
+    virtual const std::string &              GetMonitorDir() const = 0;
+    virtual bool                             GetMonitoring() const = 0;
+    virtual const std::vector<std::string> & GetScriptParams() const = 0;
 };
 //-----------------------------------------------------------------------------
 
index e966076f00a7a4b9c288e60df325ace1b8a8fe99..412ed65dc5bc200e1a13f3c3c8d04aa15eb83eb8 100644 (file)
@@ -79,7 +79,7 @@ public:
     virtual int EditMessage(const STG_MSG & msg, const std::string & login) const = 0;
     virtual int GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const = 0;
     virtual int DelMessage(uint64_t id, const std::string & login) const = 0;
-    virtual int GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const std::string & login) const = 0;
+    virtual int GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const = 0;
 
     virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const = 0;
 
index 376ed378e527fc1ed74c0a3d79ba290677661ebb..6a296230d8413e3b148d3969ffc69992fb115ae2 100644 (file)
@@ -103,21 +103,21 @@ struct DIRPRICE_DATA_RES
         return *this;
         }
 
-    DIRPRICE_DATA GetData()
+    DIRPRICE_DATA GetData() const
         {
         DIRPRICE_DATA dd;
-        dd.hDay        = hDay;
-        dd.hNight      = hNight;
-        dd.mDay        = mDay;
-        dd.mNight      = mNight;
-        dd.noDiscount  = noDiscount;
-        dd.priceDayA   = priceDayA;
-        dd.priceDayB   = priceDayB;
-
-        dd.priceNightA = priceNightA;
-        dd.priceNightB = priceNightB;
-        dd.singlePrice = singlePrice;
-        dd.threshold   = threshold;
+        dd.hDay        = hDay.data();
+        dd.hNight      = hNight.data();
+        dd.mDay        = mDay.data();
+        dd.mNight      = mNight.data();
+        dd.noDiscount  = noDiscount.data();
+        dd.priceDayA   = priceDayA.data();
+        dd.priceDayB   = priceDayB.data();
+
+        dd.priceNightA = priceNightA.data();
+        dd.priceNightB = priceNightB.data();
+        dd.singlePrice = singlePrice.data();
+        dd.threshold   = threshold.data();
         return dd;
         }
 
@@ -184,15 +184,15 @@ struct TARIFF_CONF_RES
         return *this;
         }
 
-    TARIFF_CONF GetData()
+    TARIFF_CONF GetData() const
         {
         TARIFF_CONF tc;
-        tc.fee         = fee;
-        tc.free        = free;
-        tc.name        = name;
-        tc.passiveCost = passiveCost;
-        tc.traffType   = traffType;
-        tc.period      = period;
+        tc.fee         = fee.data();
+        tc.free        = free.data();
+        tc.name        = name.data();
+        tc.passiveCost = passiveCost.data();
+        tc.traffType   = traffType.data();
+        tc.period      = period.data();
         return tc;
         }
 
@@ -242,7 +242,7 @@ struct TARIFF_DATA_RES
           dirPrice(DIR_NUM)
         {}
 
-    TARIFF_DATA GetData()
+    TARIFF_DATA GetData() const
         {
         TARIFF_DATA td;
         td.tariffConf = tariffConf.GetData();
index 9a35f6458145dfde2334c678733515e877392e20..13a3f05cfb49d569f316ed45a1a1a68ddd3caa7a 100644 (file)
@@ -32,6 +32,8 @@ struct TARIFF_DATA;
 
 class TARIFFS {
 public:
+    typedef std::list<TARIFF> Tariffs;
+
     virtual ~TARIFFS() {}
     virtual int ReadTariffs () = 0;
     virtual const TARIFF * FindByName(const std::string & name) const = 0;
index 204899acb54020e1917b0699e55843ce5e78a7cc..a8f61105ec3adb3e04cf64be201615703d2d2189 100644 (file)
 #ifndef USER_H
 #define USER_H
 
-#include <ctime>
-#include <string>
-
-#include "os_int.h"
 #include "notifer.h"
 #include "message.h"
 #include "tariff.h"
 #include "user_traff.h"
+#include "os_int.h"
+
+#include <vector>
+#include <string>
+
+#include <ctime>
 
 class USER_PROPERTIES;
 class AUTH;
 
+typedef PROPERTY_NOTIFIER_BASE<uint32_t> CURR_IP_NOTIFIER;
+typedef PROPERTY_NOTIFIER_BASE<bool> CONNECTED_NOTIFIER;
+
 class USER {
 public:
     virtual ~USER() {}
@@ -44,17 +49,17 @@ public:
     virtual uint32_t            GetCurrIP() const = 0;
     virtual time_t              GetCurrIPModificationTime() const = 0;
 
-    virtual void                AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * notifier) = 0;
-    virtual void                DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * notifier) = 0;
+    virtual void                AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) = 0;
+    virtual void                DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) = 0;
 
-    virtual void                AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * notifier) = 0;
-    virtual void                DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * notifier) = 0;
+    virtual void                AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) = 0;
+    virtual void                DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) = 0;
 
-    virtual void                AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
-    virtual void                DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
+    virtual void                AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) = 0;
+    virtual void                DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) = 0;
 
-    virtual void                AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
-    virtual void                DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
+    virtual void                AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) = 0;
+    virtual void                DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) = 0;
 
     virtual int                 GetID() const = 0;
 
@@ -68,12 +73,12 @@ public:
 
     virtual bool                GetConnected() const = 0;
     virtual time_t              GetConnectedModificationTime() const = 0;
+    virtual const std::string & GetLastDisconnectReason() const = 0;
     virtual int                 GetAuthorized() const = 0;
-    /*virtual int                 Authorize(uint32_t ip,
-                                          uint32_t enabledDirs,
-                                          const AUTH * auth) = 0;
-    virtual void                Unauthorize(const AUTH * auth) = 0;*/
+    virtual time_t              GetAuthorizedModificationTime() const = 0;
+
     virtual bool                IsAuthorizedBy(const AUTH * auth) const = 0;
+    virtual std::vector<std::string> GetAuthorizers() const = 0;
 
     virtual int                 AddMessage(STG_MSG * msg) = 0;
 
@@ -97,6 +102,8 @@ public:
 
     virtual void                OnAdd() = 0;
     virtual void                OnDelete() = 0;
+
+    virtual std::string GetParamValue(const std::string & name) const = 0;
 };
 
 typedef USER * USER_PTR;
index 70cb4fa7f5f2fd0d76e01f9abb02ef1b78dd0f55..5d65fcee9f606dc053b66a3f66b53bd173b14a43 100644 (file)
@@ -37,7 +37,7 @@ struct USER_CONF
           userdata(USERDATA_NUM),
           creditExpire(0),
           ips()
-    {};
+    {}
 
     std::string              password;
     int                      passive;
@@ -77,11 +77,11 @@ struct USER_CONF_RES
           group(),
           credit(),
           nextTariff(),
-          userdata(USERDATA_NUM, RESETABLE<std::string>()),
+          userdata(USERDATA_NUM),
           creditExpire(),
           ips()
     {
-    };
+    }
 
     USER_CONF_RES & operator=(const USER_CONF & uc)
     {
@@ -100,37 +100,34 @@ struct USER_CONF_RES
         group        = uc.group;
         credit       = uc.credit;
         nextTariff   = uc.nextTariff;
-        for (int i = 0; i < USERDATA_NUM; i++)
-            {
-            userdata[i]  = uc.userdata[i];
-            }
+        for (size_t i = 0; i < USERDATA_NUM; i++) userdata[i]  = uc.userdata[i];
         creditExpire = uc.creditExpire;
         ips          = uc.ips;
         return *this;
-    };
-    operator USER_CONF() const
+    }
+    USER_CONF GetData() const
     {
         USER_CONF uc;
-        uc.password     = password;
-        uc.passive      = passive;
-        uc.disabled     = disabled;
-        uc.disabledDetailStat = disabledDetailStat;
-        uc.alwaysOnline = alwaysOnline;
-        uc.tariffName   = tariffName;
-        uc.address      = address;
-        uc.phone        = phone;
-        uc.email        = email;
-        uc.note         = note;
-        uc.realName     = realName;
-        uc.group        = group;
-        uc.credit       = credit;
-        uc.nextTariff   = nextTariff;
+        uc.password     = password.data();
+        uc.passive      = passive.data();
+        uc.disabled     = disabled.data();
+        uc.disabledDetailStat = disabledDetailStat.data();
+        uc.alwaysOnline = alwaysOnline.data();
+        uc.tariffName   = tariffName.data();
+        uc.address      = address.data();
+        uc.phone        = phone.data();
+        uc.email        = email.data();
+        uc.note         = note.data();
+        uc.realName     = realName.data();
+        uc.group        = group.data();
+        uc.credit       = credit.data();
+        uc.nextTariff   = nextTariff.data();
         for (int i = 0; i < USERDATA_NUM; i++)
             {
-            uc.userdata[i]  = userdata[i];
+            uc.userdata[i]  = userdata[i].data();
             }
-        uc.creditExpire = creditExpire;
-        uc.ips          = ips;
+        uc.creditExpire = creditExpire.data();
+        uc.ips          = ips.data();
         return uc;
     }
     //-------------------------------------------------------------------------
@@ -155,4 +152,3 @@ struct USER_CONF_RES
 };
 //-----------------------------------------------------------------------------
 #endif
-
index a29e28128c07f5a651df94e839128fe4bf2df70e..e55f99fa7fc114460681fcebe87c8639ef2ee259 100644 (file)
@@ -44,8 +44,6 @@
 #include "stg/common.h"
 #include "os_int.h"
 
-using namespace std;
-
 //-------------------------------------------------------------------------
 struct IP_MASK
 {
@@ -57,25 +55,29 @@ uint32_t mask;
 //-------------------------------------------------------------------------
 class USER_IPS
 {
-    friend std::ostream & operator<< (ostream & o, const USER_IPS & i);
+    friend std::ostream & operator<< (std::ostream & o, const USER_IPS & i);
     //friend stringstream & operator<< (stringstream & s, const USER_IPS & i);
-    friend const USER_IPS StrToIPS(const string & ipsStr) throw(string);
+    friend const USER_IPS StrToIPS(const std::string & ipsStr);
 
 public:
+    typedef std::vector<IP_MASK> ContainerType;
+    typedef ContainerType::size_type IndexType;
+
     USER_IPS();
     USER_IPS(const USER_IPS &);
     USER_IPS & operator=(const USER_IPS &);
-    const IP_MASK & operator[](int idx) const;
+    const IP_MASK & operator[](IndexType idx) const;
     std::string GetIpStr() const;
     bool IsIPInIPS(uint32_t ip) const;
     bool OnlyOneIP() const;
-    int  Count() const;
+    bool IsAnyIP() const;
+    size_t  Count() const;
     void Add(const IP_MASK &im);
     void Erase();
 
 private:
     uint32_t CalcMask(unsigned int msk) const;
-    std::vector<IP_MASK> ips;
+    ContainerType ips;
 };
 //-------------------------------------------------------------------------
 
@@ -98,7 +100,7 @@ return *this;
 }
 //-----------------------------------------------------------------------------
 inline
-const IP_MASK & USER_IPS::operator[](int idx) const
+const IP_MASK & USER_IPS::operator[](IndexType idx) const
 {
 return ips[idx];
 }
@@ -116,8 +118,8 @@ if (ips[0].ip == 0)
     return "*";
     }
 
-std::vector<IP_MASK>::const_iterator it(ips.begin());
-std::stringstream s;
+ContainerType::const_iterator it(ips.begin());
+std::ostringstream s;
 s << inet_ntostring(it->ip);
 ++it;
 for (; it != ips.end(); ++it)
@@ -128,7 +130,7 @@ return s.str();
 }
 //-----------------------------------------------------------------------------
 inline
-int USER_IPS::Count() const
+size_t USER_IPS::Count() const
 {
 return ips.size();
 }
@@ -152,7 +154,7 @@ if (ips.empty())
 if (ips.front().ip == 0)
     return true;
 
-for (std::vector<IP_MASK>::const_iterator it(ips.begin()); it != ips.end(); ++it)
+for (ContainerType::const_iterator it(ips.begin()); it != ips.end(); ++it)
     {
     uint32_t mask(CalcMask(it->mask));
     if ((ip & mask) == (it->ip & mask))
@@ -171,6 +173,12 @@ return false;
 }
 //-----------------------------------------------------------------------------
 inline
+bool USER_IPS::IsAnyIP() const
+{
+    return !ips.empty() && ips.front().ip == 0;
+}
+//-----------------------------------------------------------------------------
+inline
 void USER_IPS::Add(const IP_MASK &im)
 {
 ips.push_back(im);
@@ -196,7 +204,7 @@ return s;
 }*/
 //-----------------------------------------------------------------------------
 inline
-const USER_IPS StrToIPS(const std::string & ipsStr) throw(std::string)
+const USER_IPS StrToIPS(const std::string & ipsStr)
 {
 USER_IPS ips;
 char * paddr;
@@ -215,18 +223,18 @@ if (ipsStr[0] == '*' && ipsStr.size() == 1)
     return ips;
     }
 
-char * str = new char[ipsStr.size() + 1];
-strcpy(str, ipsStr.c_str());
-char * pstr = str;
+char * tmp = new char[ipsStr.size() + 1];
+strcpy(tmp, ipsStr.c_str());
+char * pstr = tmp;
 while ((paddr = strtok(pstr, ",")))
     {
     pstr = NULL;
     ipMask.push_back(paddr);
     }
 
-delete[] str;
+delete[] tmp;
 
-for (unsigned int i = 0; i < ipMask.size(); i++)
+for (USER_IPS::IndexType i = 0; i < ipMask.size(); i++)
     {
     char str[128];
     char * strIp;
index fbd6aa4668ed2d351bfc6615badfeff3190aefdb..1716296acd7300482c53f3014c41d7f13869574d 100644 (file)
@@ -24,7 +24,7 @@ $Author: faust $
 #include "notifer.h"
 #include "noncopyable.h"
 
-extern const volatile time_t stgTime;
+extern volatile time_t stgTime;
 
 //-----------------------------------------------------------------------------
 template<typename varT>
@@ -43,14 +43,15 @@ public:
     operator const varT&() const throw() { return value; }
 
     void    AddBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
-    void    DelBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
+    void    DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n);
 
     void    AddAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
-    void    DelAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
+    void    DelAfterNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n);
 
     time_t  ModificationTime() const throw() { return modificationTime; }
     void    ModifyTime() throw();
 
+    std::string ToString() const;
 private:
     varT & value;
     time_t modificationTime;
@@ -236,10 +237,10 @@ beforeNotifiers.insert(n);
 //-----------------------------------------------------------------------------
 template <typename varT>
 inline
-void USER_PROPERTY<varT>::DelBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n)
+void USER_PROPERTY<varT>::DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n)
 {
 STG_LOCKER locker(&mutex, __FILE__, __LINE__);
-beforeNotifiers.erase(n);
+beforeNotifiers.erase(const_cast<PROPERTY_NOTIFIER_BASE<varT> *>(n));
 }
 //-----------------------------------------------------------------------------
 template <typename varT>
@@ -252,10 +253,10 @@ afterNotifiers.insert(n);
 //-----------------------------------------------------------------------------
 template <typename varT>
 inline
-void USER_PROPERTY<varT>::DelAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n)
+void USER_PROPERTY<varT>::DelAfterNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n)
 {
 STG_LOCKER locker(&mutex, __FILE__, __LINE__);
-afterNotifiers.erase(n);
+afterNotifiers.erase(const_cast<PROPERTY_NOTIFIER_BASE<varT> *>(n));
 }
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -295,8 +296,8 @@ if ((priv->userConf && !isStat) ||
     std::stringstream oldVal;
     std::stringstream newVal;
 
-    oldVal.flags(oldVal.flags() | ios::fixed);
-    newVal.flags(newVal.flags() | ios::fixed);
+    oldVal.flags(oldVal.flags() | std::ios::fixed);
+    newVal.flags(newVal.flags() | std::ios::fixed);
 
     oldVal << USER_PROPERTY<varT>::ConstData();
     newVal << val;
@@ -377,10 +378,16 @@ else
 //-------------------------------------------------------------------------
 template<typename varT>
 inline
-ostream & operator<< (ostream & stream, const USER_PROPERTY<varT> & value)
+std::ostream & operator<< (std::ostream & stream, const USER_PROPERTY<varT> & value)
 {
 return stream << value.ConstData();
 }
 //-----------------------------------------------------------------------------
-
+template<typename varT>
+std::string USER_PROPERTY<varT>::ToString() const
+{
+std::stringstream stream;
+stream << value;
+return stream.str();
+}
 #endif // USER_PROPERTY_H
index 42d436fdc96c472675eef9f2e5d0ce980d4db05e..ff020dc7021195e8d3a921e3b52a72408f0fe6c8 100644 (file)
@@ -29,6 +29,8 @@
 
 #include <ctime>
 #include <map>
+#include <utility>
+#include <string>
 
 #include "os_int.h"
 #include "resetable.h"
@@ -113,20 +115,23 @@ struct STAT_NODE
 //-----------------------------------------------------------------------------
 struct USER_STAT
 {
-    //USER_STAT & operator= (const USER_STAT_RES & usr);
     USER_STAT()
-        : up(),
-          down(),
+        : sessionUp(),
+          sessionDown(),
+          monthUp(),
+          monthDown(),
           cash(0),
           freeMb(0),
           lastCashAdd(0),
           lastCashAddTime(0),
           passiveTime(0),
           lastActivityTime(0)
-    {};
+    {}
 
-    DIR_TRAFF   up;
-    DIR_TRAFF   down;
+    DIR_TRAFF   sessionUp;
+    DIR_TRAFF   sessionDown;
+    DIR_TRAFF   monthUp;
+    DIR_TRAFF   monthDown;
     double      cash;
     double      freeMb;
     double      lastCashAdd;
@@ -137,6 +142,8 @@ struct USER_STAT
 //-----------------------------------------------------------------------------
 typedef std::map<IP_DIR_PAIR, STAT_NODE> TRAFF_STAT;
 //-----------------------------------------------------------------------------
+typedef std::pair<double, std::string> CASH_INFO;
+//-----------------------------------------------------------------------------
 struct USER_STAT_RES
 {
     USER_STAT_RES()
@@ -146,8 +153,10 @@ struct USER_STAT_RES
           lastCashAddTime(),
           passiveTime(),
           lastActivityTime(),
-          up(),
-          down()
+          sessionUp(),
+          sessionDown(),
+          monthUp(),
+          monthDown()
     {}
 
     USER_STAT_RES & operator= (const USER_STAT & us)
@@ -158,32 +167,40 @@ struct USER_STAT_RES
         lastCashAddTime  = us.lastCashAddTime;
         passiveTime      = us.passiveTime;
         lastActivityTime = us.lastActivityTime;
-        up = us.up;
-        down = us.down;
-        return * this;
-    };
-    operator USER_STAT() const
+        sessionUp        = us.sessionUp;
+        sessionDown      = us.sessionDown;
+        monthUp          = us.monthUp;
+        monthDown        = us.monthDown;
+        return *this;
+    }
+    USER_STAT GetData() const
     {
         USER_STAT us;
-        us.cash             = cash;
-        us.freeMb           = freeMb;
-        us.lastCashAdd      = lastCashAdd;
-        us.lastCashAddTime  = lastCashAddTime;
-        us.passiveTime      = passiveTime;
-        us.lastActivityTime = lastActivityTime;
-        us.up               = up;
-        us.down             = down;
+        us.cash             = cash.data();
+        us.freeMb           = freeMb.data();
+        us.lastCashAdd      = lastCashAdd.data();
+        us.lastCashAddTime  = lastCashAddTime.data();
+        us.passiveTime      = passiveTime.data();
+        us.lastActivityTime = lastActivityTime.data();
+        us.sessionUp        = sessionUp.GetData();
+        us.sessionDown      = sessionDown.GetData();
+        us.monthUp          = monthUp.GetData();
+        us.monthDown        = monthDown.GetData();
         return us;
-    };
+    }
 
     RESETABLE<double>      cash;
+    RESETABLE<CASH_INFO>   cashAdd;
+    RESETABLE<CASH_INFO>   cashSet;
     RESETABLE<double>      freeMb;
     RESETABLE<double>      lastCashAdd;
     RESETABLE<time_t>      lastCashAddTime;
     RESETABLE<time_t>      passiveTime;
     RESETABLE<time_t>      lastActivityTime;
-    RESETABLE<DIR_TRAFF>   up;
-    RESETABLE<DIR_TRAFF>   down;
+    DIR_TRAFF_RES          sessionUp;
+    DIR_TRAFF_RES          sessionDown;
+    DIR_TRAFF_RES          monthUp;
+    DIR_TRAFF_RES          monthDown;
 };
 //-----------------------------------------------------------------------------
 #endif
index 7ed1636152a05a7abd13b2ee6b290889f9c0978e..48843a49945a38c2472c390063ea7cf7300b08ef 100644 (file)
@@ -40,64 +40,26 @@ class DIR_TRAFF
     friend std::ostream & operator<< (std::ostream & o, const DIR_TRAFF & traff);
 
 public:
-    //-------------------------------------------------------------------------
-    DIR_TRAFF();
-    DIR_TRAFF(const DIR_TRAFF & ts);
-    DIR_TRAFF & operator=(const DIR_TRAFF & ts);
-    ~DIR_TRAFF();
-    uint64_t operator[](int idx) const;
-    uint64_t & operator[](int idx);
-    DIR_TRAFF operator+(const DIR_TRAFF & ts);
+    typedef std::vector<uint64_t> ContainerType;
+    typedef ContainerType::size_type IndexType;
+
+    DIR_TRAFF() : traff(DIR_NUM) {}
+    DIR_TRAFF(const DIR_TRAFF & ts) : traff(ts.traff) {}
+    DIR_TRAFF & operator=(const DIR_TRAFF & ts) { traff = ts.traff; return *this; }
+    const uint64_t & operator[](IndexType idx) const { return traff[idx]; }
+    uint64_t & operator[](IndexType idx) { return traff[idx]; }
+    IndexType size() const { return traff.size(); }
 
 private:
-    std::vector<uint64_t> traff;
+    ContainerType traff;
 };
-//-----------------------------------------------------------------------------
 
 //-----------------------------------------------------------------------------
-inline DIR_TRAFF::DIR_TRAFF()
-    : traff(DIR_NUM, 0)
-{
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF::DIR_TRAFF(const DIR_TRAFF & ts)
-    : traff(ts.traff)
-{
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF::~DIR_TRAFF()
-{
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF & DIR_TRAFF::operator=(const DIR_TRAFF & ts)
-{
-traff = ts.traff;
-return *this;
-}
-//-----------------------------------------------------------------------------
-inline uint64_t & DIR_TRAFF::operator[](int idx)
-{
-return traff[idx];
-}
-//-----------------------------------------------------------------------------
-inline uint64_t DIR_TRAFF::operator[](int idx) const
-{
-return traff[idx];
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF DIR_TRAFF::operator+(const DIR_TRAFF & ts)
-{
-for (int i = 0; i < DIR_NUM; i++)
-    {
-    traff[i] = traff[i] + ts.traff[i];
-    }
-return *this;
-}
-//-----------------------------------------------------------------------------
-inline std::ostream & operator<<(std::ostream & o, const DIR_TRAFF & traff)
+inline
+std::ostream & operator<<(std::ostream & o, const DIR_TRAFF & traff)
 {
 bool first = true;
-for (size_t i = 0; i < DIR_NUM; ++i)
+for (DIR_TRAFF::IndexType i = 0; i < traff.size(); ++i)
     {
     if (first)
         first = false;
@@ -107,5 +69,36 @@ for (size_t i = 0; i < DIR_NUM; ++i)
     }
 return o;
 }
-//-----------------------------------------------------------------------------
+
+class DIR_TRAFF_RES
+{
+public:
+    typedef RESETABLE<uint64_t> value_type;
+    typedef RESETABLE<uint64_t> ValueType;
+    typedef std::vector<ValueType> ContainerType;
+    typedef ContainerType::size_type IndexType;
+
+    DIR_TRAFF_RES() : traff(DIR_NUM) {}
+    DIR_TRAFF_RES(const DIR_TRAFF & ts)
+        : traff(ts.size())
+    {
+    for (IndexType i = 0; i < ts.size(); ++i)
+        traff[i] = ts[i];
+    }
+    const ValueType & operator[](IndexType idx) const { return traff[idx]; }
+    ValueType & operator[](IndexType idx) { return traff[idx]; }
+    IndexType size() const { return traff.size(); }
+    DIR_TRAFF GetData() const
+    {
+    DIR_TRAFF res;
+    for (IndexType i = 0; i < traff.size(); ++i)
+        if (!traff[i].empty())
+            res[i] = traff[i].data();
+    return res;
+    }
+
+private:
+    ContainerType traff;
+};
+
 #endif
index 2ba238332297b5b70d0267dc4e967d5aacec9428..1a8d7a4379bff76d74b685dea039fcf3057aa44e 100644 (file)
@@ -32,6 +32,7 @@ class USERS {
 public:
     virtual ~USERS() {}
     virtual int  FindByName(const std::string & login, USER_PTR * user) = 0;
+    virtual int  FindByName(const std::string & login, CONST_USER_PTR * user) const = 0;
 
     virtual bool TariffInUse(const std::string & tariffName) const = 0;
 
@@ -46,13 +47,16 @@ public:
 
     virtual bool Authorize(const std::string & login, uint32_t ip,
                            uint32_t enabledDirs, const AUTH * auth) = 0;
-    virtual bool Unauthorize(const std::string & login, const AUTH * auth) = 0;
+    virtual bool Unauthorize(const std::string & login,
+                             const AUTH * auth,
+                             const std::string & reason = std::string()) = 0;
 
     virtual int  ReadUsers() = 0;
     virtual size_t Count() const = 0;
 
     virtual int  FindByIPIdx(uint32_t ip, USER_PTR * user) const = 0;
     virtual bool IsIPInIndex(uint32_t ip) const = 0;
+    virtual bool IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const = 0;
 
     virtual int  OpenSearch() = 0;
     virtual int  SearchNext(int handle, USER_PTR * u) = 0;
@@ -60,6 +64,7 @@ public:
 
     virtual int  Start() = 0;
     virtual int  Stop() = 0;
+
 };
 
 #endif
index 20da4e432a7081b73c7cf131ed5e1c0642957f24..fe6b3f69d9601d2f737404f78e0bfc31e24196a3 100644 (file)
@@ -164,6 +164,11 @@ struct UTIME: public timeval
     {
     return tv_usec;
     }
+
+    double AsDouble() const
+    {
+    return tv_sec + tv_usec * 1e-6;
+    }
 };
 
 
index 9b94ca1282986bf89452542b22ff508ec92552b7..3698b59d51aa2f0019510586c2e8b8cfb231ecc9 100644 (file)
@@ -27,6 +27,6 @@
 #define __VERSION_H__
 
 // Stargazer version
-#define SERVER_VERSION "2.408
+#define SERVER_VERSION "2.409-alpha
 
 #endif
diff --git a/projects/convertor/Makefile b/projects/convertor/Makefile
deleted file mode 100644 (file)
index efacbb6..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-###############################################################################
-# $Id: Makefile,v 1.12 2009/03/03 15:49:34 faust Exp $
-###############################################################################
-
-include ../../Makefile.conf
-
-PROG = convertor
-
-SRCS = ./main.cpp \
-       ./settings_impl.cpp
-
-STGLIBS = dotconfpp \
-         conffiles \
-         logger \
-         crypto \
-          common
-
-STGLIBS_INCS = $(addprefix -I ../../stglibs/,$(addsuffix .lib/include,$(STGLIBS)))
-STGLIBS_LIBS = $(addprefix -L ../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
-
-LIBS += $(addprefix -lstg,$(STGLIBS)) $(LIB_THREAD)
-
-ifeq ($(OS),linux)
-LIBS += -ldl
-else
-LIBS += -lc -liconv
-endif
-
-SEARCH_DIRS = -I ../../include
-
-OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
-
-CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
-CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
-LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
-
-.PHONY: all clean distclean libs plugins install uninstall
-all: libs plugins $(PROG) ../../Makefile.conf
-
-libs:
-       $(MAKE) -C $(DIR_LIBSRC)
-
-plugins: libs 
-       $(MAKE) -C $(DIR_PLUGINS)
-
-$(PROG): $(OBJS)
-       $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG)
-
-clean:
-       rm -f deps $(PROG) *.o tags *.*~ .OS
-       rm -f .OS
-       rm -f .store
-       rm -f .db.sql
-       rm -f core*
-       $(MAKE) -C $(DIR_LIBSRC) clean
-       $(MAKE) -C $(DIR_PLUGINS) clean
-
-distclean: clean
-       rm -f ../../Makefile.conf
-
-ifneq ($(MAKECMDGOALS),distclean)
-ifneq ($(MAKECMDGOALS),clean)
-ifneq ($(MAKECMDGOALS),uninstall)
--include deps
-endif
-endif
-endif
-
-deps:  $(SRCS) ../../Makefile.conf
-       $(MAKE) -C $(DIR_LIBSRC)
-       @>deps ;\
-       for file in $(SRCS); do\
-         echo "$$file" | grep ".c$$" > /dev/null;\
-         if [ $$? -eq 0 ];\
-         then\
-           echo "`$(CC) $(CFLAGS) -MM $$file` Makefile" >> deps ;\
-           printf '%b\n' '\t$$(CC) $(CFLAGS) -c $$<' >> deps ;\
-         else\
-           echo "`$(CXX) $(CXXFLAGS) -MM $$file` Makefile" >> deps ;\
-           printf '%b\n' '\t$$(CXX) $(CXXFLAGS) -c $$<' >> deps ;\
-         fi;\
-       done
diff --git a/projects/convertor/build b/projects/convertor/build
deleted file mode 100755 (executable)
index 0144b0f..0000000
+++ /dev/null
@@ -1,289 +0,0 @@
-#!/bin/sh
-
-#   $Revision: 1.20 $
-#   $Author: faust $
-#   $Date: 2010/04/14 08:58:43 $
-######################################################
-
-OS=unknown
-sys=`uname -s`
-release=`uname -r | cut -b1`
-BUILD_DIR=`pwd`
-CONFFILE="../../Makefile.conf"
-PREFIX="/"
-BIN_MODE=0755
-DATA_MODE=0644
-DIR_MODE=0755
-OWNER=root
-VAR_DIR="./inst/var/stargazer"
-DEFS="-DDEBUG"
-MAKEOPTS="-j1"
-CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -I/usr/local/include"
-LDFLAGS="$LDFLAGS -L/usr/local/lib"
-
-if [ "$sys" = "Linux" ]
-then
-    OS=linux
-    release=""
-    MAKE="make"
-fi
-
-if [ "$sys" = "FreeBSD" ]
-then
-    case $release in
-        4) OS=bsd;;
-        5) OS=bsd5;;
-        6) OS=bsd5;;
-        7) OS=bsd7;;
-        8) OS=bsd7;;
-        9) OS=bsd7;;
-        *) OS=unknown;;
-    esac
-    MAKE="gmake"
-fi
-
-if [ "$OS" = "unknown" ]
-then 
-    echo "#############################################################################"
-    echo "# Sorry, but convertor currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
-    exit 1
-fi
-
-echo "#############################################################################"
-echo "       Building convertor for $sys $release"
-echo "#############################################################################"
-
-STG_LIBS="logger.lib 
-          locker.lib
-         crypto.lib 
-         common.lib 
-         conffiles.lib
-         dotconfpp.lib"
-
-PLUGINS="store/files"
-
-if [ "$OS" = "linux" ]
-then
-    DEFS="$DEFS -DLINUX"
-    LIB_THREAD=-lpthread
-else
-    if [ "$OS" = "bsd" ]
-    then
-        DEFS="$DEFS -DFREE_BSD"
-        LIB_THREAD=-lc_r
-    else
-        DEFS="$DEFS -DFREE_BSD5"
-        if [ "$OS" = "bsd7" ]
-        then
-            LIB_THREAD=-lpthread
-        else
-            LIB_THREAD=-lc_r
-        fi
-    fi
-fi
-
-if [ -z "$CC" ]
-then
-    CC=gcc
-fi
-
-if [ -z "$CXX" ]
-then
-    CXX=g++
-fi
-
-echo -n "Checking CC... "
-$CC --version > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
-    echo "FAIL!"
-    echo "$CC not found"
-    exit;
-fi
-echo "found"
-echo -n "Checking CXX... "
-$CXX --version > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
-    echo "FAIL!"
-    echo "$CXX not found"
-    exit;
-fi
-echo "found"
-
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
-$CC $CFLAGS $LDFLAGS -L/usr/lib/mysql -L/usr/local/lib/mysql build_check.c -o fake > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
-    echo "FAIL!"
-    echo "Endianess checking failed"
-    exit;
-else
-    ./fake
-    if [ $? = 1 ]
-    then
-        ARCH=le
-        CXXFLAGS="$CXXFLAGS -DARCH_LE"
-        CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
-    else
-        ARCH=be
-        CXXFLAGS="$CXXFLAGS -DARCH_BE"
-        CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
-    fi
-fi
-rm -f fake
-
-echo -n "Checking for -lfbclient... "
-$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
-    CHECK_FBCLIENT=no
-    echo "no"
-else
-    CHECK_FBCLIENT=yes
-    echo "yes"
-fi
-rm -f fake
-
-echo -n "Checking for mysql_config... "
-MYSQL_VERSION=`mysql_config --version 2> /dev/null`
-if [ $? != 0 ]
-then
-    echo "no";
-    echo -n "Checking for -lmysqlclient... "
-    $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
-    if [ $? != 0 ]
-    then
-        CHECK_MYSQLCLIENT=no
-        echo "no"
-    else
-        CHECK_MYSQLCLIENT=yes
-        echo "yes"
-    fi
-    rm -f fake
-else
-    echo "yes"
-    echo -n "Checking for mysql_config --cflags... "
-    MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
-    if [ $? != 0 ]
-    then
-        CHECK_MYSQLCLIENT=no
-        echo "no"
-    else
-        echo "[$MYSQL_CFLAGS]"
-        echo -n "Checking for mysql_config --libs_r... "
-        MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
-        if [ $? != 0 ]
-        then
-            CHECK_MYSQLCLIENT=no
-            echo "no"
-        else
-            CHECK_MYSQLCLIENT=yes
-            echo "[$MYSQL_LDFLAGS]"
-        fi
-    fi
-fi
-
-echo -n "Checking for pg_config... "
-PG_VERSION=`pg_config --version 2> /dev/null`
-if [ $? != 0 ]
-then
-    echo "no";
-    echo -n "Checking for -lpq... "
-    $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
-    if [ $? != 0 ]
-    then
-        CHECK_PQ=no
-        echo "no"
-    else
-        CHECK_PQ=yes
-        echo "yes"
-    fi
-    rm -f fake
-else
-    echo "yes";
-    echo -n "Checking for pg_config --includedir... "
-    PG_CFLAGS=`pg_config --includedir 2> /dev/null`
-    if [ $? != 0 ]
-    then
-        CHECK_PQ=no
-        echo "no"
-    else
-        echo "[$PG_CFLAGS]"
-        echo -n "Checking for pg_config --libdir... "
-        PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
-        if [ $? != 0 ]
-        then
-            CHECK_PQ=no
-            echo "no"
-        else
-            CHECK_PQ=yes
-            echo "[$PG_LDFLAGS]"
-        fi
-    fi
-fi
-
-rm -f build_check.c
-
-if [ "$CHECK_FBCLIENT" = "yes" ]
-then
-    STG_LIBS="$STG_LIBS
-          ibpp.lib"
-    PLUGINS="$PLUGINS
-         store/firebird"
-fi
-
-if [ "$CHECK_PQ" = "yes" ]
-then
-    PLUGINS="$PLUGINS
-             store/postgresql"
-fi
-
-if [ "$CHECK_MYSQLCLIENT" = "yes" ]
-then
-    PLUGINS="$PLUGINS
-         store/mysql"
-fi
-
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules" >> $CONFFILE
-echo "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_FBCLIENT=$CHECK_FBCLIENT" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
-for lib in $STG_LIBS
-do
-    echo -n "$lib " >> $CONFFILE
-done
-echo "" >> $CONFFILE
-echo -n "PLUGINS=" >> $CONFFILE
-for plugin in $PLUGINS
-do
-    echo -n "$plugin " >> $CONFFILE
-done
-echo "" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
-echo "VAR_DIR=$VAR_DIR" >> $CONFFILE
-
-mkdir -p ../stargazer/modules
-
-$MAKE $MAKEOPTS
-
diff --git a/projects/convertor/convertor.conf b/projects/convertor/convertor.conf
deleted file mode 100644 (file)
index 41e18b6..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-################################################################################
-#                   Stargazer Convertor Configuration file                     #
-################################################################################
-
-# The path to directory with server modules
-# Parameter: required
-# Value: directory path
-# Default: /usr/lib/stg
-ModulesPath = /usr/lib/stg
-
-#################################################################################
-Store module
-# Configure the module that works with the database server
-# Option - the name of the module without 'mod_' at the beginning and '.so'
-# in the end ie full name of the module mod_store_files.so
-<SourceStoreModule store_files>
-
-    # Working server directory, provides data on tariffs, users, administrators.
-    # Parameter: required
-    # Value: directory path
-    WorkDir = /var/stargazer
-
-    # Owner, group and permissions of the files of user statistics (stat)
-    # Parameter: required
-    # Values: any, supported by OS
-    ConfOwner = root
-    ConfGroup = root
-    ConfMode = 600
-
-    # Owner, group and permissions on user configuration files (conf)
-    # Parameter: required
-    # Values: any, supported by OS
-    StatOwner = root
-    StatGroup = root
-    StatMode = 640
-
-    # Owner, group and permissions for user log files (log)
-    # Parameter: required
-    # Values: any, supported by OS
-    UserLogOwner = root
-    UserLogGroup = root
-    UserLogMode = 640
-
-</SourceStoreModule>
-
-#<DestStoreModule store_firebird>
-    # Database server address
-    # Parameter: required
-    # Value: IP address or DNS name
-    # Default: localhost
-    # server = localhost
-
-    # Path to the database on the server or its alias
-    # Parameter: required
-    # Value: file path
-    # Default: /var/stg/stargazer.fdb
-    # database = /var/stg/stargazer.fdb
-
-    # Database username
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: stg
-    # user = stg
-
-    # Database password
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: 123456
-    # password = 123456
-#</DestStoreModule>
-
-<DestStoreModule store_postgresql>
-    # Database server address
-    # Parameter: required
-    # Value: IP address or DNS name
-    # Default: localhost
-    server = localhost
-
-    # Database name
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: stargazer
-    database = stargazer
-
-    # Database username
-    # Parameter: mandatory
-    # Value: any, supported by database
-    # Default: stg
-    user = stg
-
-    # Database password
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: 123456
-    password = 123456
-
-</DestStoreModule>
-
-#<DestStoreModule store_mysql>
-    # Database server address
-    # Parameter: required
-    # Value: IP address or DNS name
-    # Default: localhost
-    # dbhost = localhost
-
-    # Database name
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: stg
-    # dbname = stg
-
-    # Database username
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: stg
-    # dbuser = stg
-
-    # Database password
-    # Parameter: required
-    # Value: any, supported by database
-    # Default: 123456
-    # rootdbpass = 123456
-
-#</DestStoreModule>
diff --git a/projects/convertor/main.cpp b/projects/convertor/main.cpp
deleted file mode 100644 (file)
index e0679d0..0000000
+++ /dev/null
@@ -1,446 +0,0 @@
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
- */
-
- /*
- $Revision: 1.11 $
- $Date: 2010/03/25 12:32:30 $
- $Author: faust $
- */
-
-#include <dlfcn.h>
-
-#include <string>
-#include <vector>
-#include <iostream>
-#include <ctime>
-#include <algorithm>
-
-#include "stg/common.h"
-#include "stg/store.h"
-#include "stg/conffiles.h"
-
-#include "stg/user_stat.h"
-#include "stg/user_conf.h"
-#include "stg/corp_conf.h"
-#include "stg/service_conf.h"
-#include "stg/admin_conf.h"
-#include "stg/tariff_conf.h"
-#include "stg/settings.h"
-#include "stg/message.h"
-
-#include "settings_impl.h"
-
-using namespace std;
-
-volatile time_t stgTime = time(NULL);
-
-int main(int argc, char **argv)
-{
-printfd(__FILE__, "Start\n");
-
-STORE * fromStore = NULL;
-STORE * toStore = NULL;
-
-SETTINGS_IMPL * settings = NULL;
-
-string modulePath;
-
-MODULE_SETTINGS fromStoreSettings;
-MODULE_SETTINGS toStoreSettings;
-
-ADMIN_CONF ac;
-USER_CONF uc;
-USER_STAT us;
-STG_MSG msg;
-TARIFF_DATA td;
-CORP_CONF cc;
-SERVICE_CONF sc;
-vector<STG_MSG_HDR> hdrs;
-
-if (argc == 2)
-    settings = new SETTINGS_IMPL(argv[1]);
-else
-    settings = new SETTINGS_IMPL();
-
-if (settings->ReadSettings())
-    {
-    printfd(__FILE__, "Error reading settings\n");
-    delete settings;
-    return -1;
-    }
-
-fromStoreSettings = settings->GetSourceStoreModuleSettings();
-toStoreSettings = settings->GetDestStoreModuleSettings();
-modulePath = settings->GetModulesPath();
-
-string sourcePlugin(modulePath + "/mod_" + fromStoreSettings.moduleName + ".so");
-string destPlugin(modulePath + "/mod_" + toStoreSettings.moduleName + ".so");
-
-void * src_lh = dlopen(sourcePlugin.c_str(), RTLD_NOW);
-if (!src_lh)
-    {
-    printfd(__FILE__, "Source storage plugin loading failed: %s\n", dlerror());
-    delete settings;
-    return -1;
-    }
-
-void * dst_lh = dlopen(destPlugin.c_str(), RTLD_NOW);
-if (!dst_lh)
-    {
-    printfd(__FILE__, "Destination storage plugin loading failed: %s\n", dlerror());
-    delete settings;
-    return -1;
-    }
-
-STORE * (*GetSourceStore)();
-STORE * (*GetDestStore)();
-GetSourceStore = (STORE * (*)())dlsym(src_lh, "GetStore");
-if (!GetSourceStore)
-    {
-    printfd(__FILE__, "Source storage plugin loading failed. GetStore not found: %s\n", dlerror());
-    delete settings;
-    return -1;
-    }
-GetDestStore = (STORE * (*)())dlsym(dst_lh, "GetStore");
-if (!GetDestStore)
-    {
-    printfd(__FILE__, "Storage plugin (firebird) loading failed. GetStore not found: %s\n", dlerror());
-    delete settings;
-    return -1;
-    }
-
-fromStore = GetSourceStore();
-toStore = GetDestStore();
-
-vector<string> entities;
-vector<string> ready;
-fromStore->SetSettings(fromStoreSettings);
-fromStore->ParseSettings();
-toStore->SetSettings(toStoreSettings);
-toStore->ParseSettings();
-
-printfd(__FILE__, "Importing admins:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetAdminsList(&entities))
-    {
-    printfd(__FILE__, "Error getting admins list: %s\n", fromStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-if (toStore->GetAdminsList(&ready))
-    {
-    printfd(__FILE__, "Error getting admins list: %s\n", toStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-
-vector<string>::const_iterator it;
-for (it = entities.begin(); it != entities.end(); ++it)
-    {
-    printfd(__FILE__, "\t - %s\n", it->c_str());
-    if (find(ready.begin(), ready.end(), *it) == ready.end())
-        if (toStore->AddAdmin(*it))
-            {
-            printfd(__FILE__, "Error adding admin: %s\n", toStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-    if (fromStore->RestoreAdmin(&ac, *it))
-        {
-        printfd(__FILE__, "Error getting admin's confi: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    ac.login = *it;
-    if (toStore->SaveAdmin(ac))
-        {
-        printfd(__FILE__, "Error saving admin's conf: %s\n", toStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    }
-
-printfd(__FILE__, "Importing tariffs:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetTariffsList(&entities))
-    {
-    printfd(__FILE__, "Error getting tariffs list: %s\n", fromStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-if (toStore->GetTariffsList(&ready))
-    {
-    printfd(__FILE__, "Error getting tariffs list: %s\n", toStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-
-for (it = entities.begin(); it != entities.end(); ++it)
-    {
-    printfd(__FILE__, "\t - %s\n", it->c_str());
-    if (find(ready.begin(), ready.end(), *it) == ready.end())
-        if (toStore->AddTariff(*it))
-            {
-            printfd(__FILE__, "Error adding tariff: %s\n", toStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-    if (fromStore->RestoreTariff(&td, *it))
-        {
-        printfd(__FILE__, "Error getting tariff's data: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    if (toStore->SaveTariff(td, *it))
-        {
-        printfd(__FILE__, "Error saving tariff's data: %s\n", toStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    }
-
-printfd(__FILE__, "Importing services:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetServicesList(&entities))
-    {
-    printfd(__FILE__, "Error getting service list: %s\n", fromStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-if (toStore->GetServicesList(&ready))
-    {
-    printfd(__FILE__, "Error getting service list: %s\n", toStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-
-for (it = entities.begin(); it != entities.end(); ++it)
-    {
-    printfd(__FILE__, "\t - %s\n", it->c_str());
-    if (find(ready.begin(), ready.end(), *it) == ready.end())
-        if (toStore->AddService(*it))
-            {
-            printfd(__FILE__, "Error adding service: %s\n", toStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-    if (fromStore->RestoreService(&sc, *it))
-        {
-        printfd(__FILE__, "Error getting service's data: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    if (toStore->SaveService(sc))
-        {
-        printfd(__FILE__, "Error saving service's data: %s\n", toStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    }
-
-printfd(__FILE__, "Importing corporations:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetCorpsList(&entities))
-    {
-    printfd(__FILE__, "Error getting corporations list: %s\n", fromStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-if (toStore->GetCorpsList(&ready))
-    {
-    printfd(__FILE__, "Error getting corporations list: %s\n", toStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-
-for (it = entities.begin(); it != entities.end(); ++it)
-    {
-    printfd(__FILE__, "\t - %s\n", it->c_str());
-    if (find(ready.begin(), ready.end(), *it) == ready.end())
-        if (toStore->AddCorp(*it))
-            {
-            printfd(__FILE__, "Error adding corporation: %s\n", toStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-    if (fromStore->RestoreCorp(&cc, *it))
-        {
-        printfd(__FILE__, "Error getting corporation's data: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    if (toStore->SaveCorp(cc))
-        {
-        printfd(__FILE__, "Error saving corporation's data: %s\n", toStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    }
-
-printfd(__FILE__, "Importing users:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetUsersList(&entities))
-    {
-    printfd(__FILE__, "Error getting users list: %s\n", fromStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-if (toStore->GetUsersList(&ready))
-    {
-    printfd(__FILE__, "Error getting users list: %s\n", toStore->GetStrError().c_str());
-    dlclose(src_lh);
-    dlclose(dst_lh);
-    delete settings;
-    return -1;
-    }
-
-sort(ready.begin(), ready.end());
-for (it = entities.begin(); it != entities.end(); ++it)
-    {
-    printfd(__FILE__, "\t - %s\n", it->c_str());
-    if (!binary_search(ready.begin(), ready.end(), *it)) {
-        if (toStore->AddUser(*it))
-            {
-            printfd(__FILE__, "Error adding user: %s\n", toStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-    } else {
-        printfd(__FILE__, "\t\t(adding passed)\n");
-    }
-    if (fromStore->RestoreUserConf(&uc, *it))
-        {
-        printfd(__FILE__, "Error getting user's conf: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    if (fromStore->RestoreUserStat(&us, *it))
-        {
-        printfd(__FILE__, "Error getting user's stat: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    if (toStore->SaveUserConf(uc, *it))
-        {
-        printfd(__FILE__, "Error saving user's conf: %s\n", toStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    if (toStore->SaveUserStat(us, *it))
-        {
-        printfd(__FILE__, "Error saving user's stat: %s\n", toStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    hdrs.erase(hdrs.begin(), hdrs.end());
-    if (fromStore->GetMessageHdrs(&hdrs, *it))
-        {
-        printfd(__FILE__, "Error getting user's messages: %s\n", fromStore->GetStrError().c_str());
-        dlclose(src_lh);
-        dlclose(dst_lh);
-        delete settings;
-        return -1;
-        }
-    vector<STG_MSG_HDR>::iterator mit;
-    for (mit = hdrs.begin(); mit != hdrs.end(); ++mit)
-        {
-        if (fromStore->GetMessage(mit->id, &msg, *it))
-            {
-            printfd(__FILE__, "Error getting message for a user: %s\n", fromStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-        printfd(__FILE__, "\t\t * %s\n", msg.text.c_str());
-        if (toStore->AddMessage(&msg, *it))
-            {
-            printfd(__FILE__, "Error adding message to a user: %s\n", toStore->GetStrError().c_str());
-            dlclose(src_lh);
-            dlclose(dst_lh);
-            delete settings;
-            return -1;
-            }
-        }
-    }
-
-dlclose(src_lh);
-dlclose(dst_lh);
-printfd(__FILE__, "Done\n");
-delete settings;
-return 0;
-}
diff --git a/projects/convertor/settings_impl.cpp b/projects/convertor/settings_impl.cpp
deleted file mode 100644 (file)
index 645865c..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Date: 27.10.2002
- */
-
-/*
- *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
-/*
-$Revision: 1.6 $
-$Date: 2009/06/22 16:26:54 $
-*/
-
-#include "stg/dotconfpp.h"
-#include "stg/module_settings.h"
-#include "stg/common.h"
-
-#include "settings_impl.h"
-
-int SETTINGS_IMPL::ParseModuleSettings(const DOTCONFDocumentNode * node, std::vector<PARAM_VALUE> * params)
-{
-if (!node)
-    return 0;
-
-PARAM_VALUE pv;
-
-pv.param = node->getName();
-
-if (node->getValue(1))
-    {
-    strError = "Unexpected value \'" + std::string(node->getValue(1)) + "\'.";
-    printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
-    return -1;
-    }
-
-const char * value = node->getValue(0);
-
-if (!value)
-    {
-    strError = "Module name expected.";
-    printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
-    return -1;
-    }
-
-const DOTCONFDocumentNode * childNode = node->getChildNode();
-while (childNode)
-    {
-    pv.param = childNode->getName();
-    int i = 0;
-    while ((value = childNode->getValue(i)) != NULL)
-        {
-        pv.value.push_back(value);
-        ++i;
-        }
-    params->push_back(pv);
-    pv.value.clear();
-    childNode = childNode->getNextNode();
-    }
-
-return 0;
-}
-//-----------------------------------------------------------------------------
-int SETTINGS_IMPL::ReadSettings()
-{
-const char * requiredOptions[] = {
-    "ModulesPath",
-    "SourceStoreModule",
-    "DestStoreModule",
-    NULL
-    };
-int sourceStoreModulesCount = 0;
-int destStoreModulesCount = 0;
-
-DOTCONFDocument conf(DOTCONFDocument::CASEINSENSITIVE);
-conf.setRequiredOptionNames(requiredOptions);
-
-if(conf.setContent(confFile.c_str()) != 0)
-    {
-    strError = "Cannot read file " + confFile + ".";
-    printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
-    return -1;
-    }
-
-const DOTCONFDocumentNode * node = conf.getFirstNode();
-
-while (node)
-    {
-    if (strcasecmp(node->getName(), "ModulesPath") == 0)
-        {
-        modulesPath = node->getValue(0);
-        }
-
-    if (strcasecmp(node->getName(), "SourceStoreModule") == 0)
-        {
-        if (node->getValue(1))
-            {
-            strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
-            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
-            return -1;
-            }
-
-        if (sourceStoreModulesCount)
-            {
-            strError = "Should be only one source StoreModule.";
-            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
-            return -1;
-            }
-        ++sourceStoreModulesCount;
-
-        sourceStoreModuleSettings.moduleName = node->getValue(0);
-        ParseModuleSettings(node, &sourceStoreModuleSettings.moduleParams);
-        }
-
-    if (strcasecmp(node->getName(), "DestStoreModule") == 0)
-        {
-        if (node->getValue(1))
-            {
-            strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
-            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
-            return -1;
-            }
-
-        if (destStoreModulesCount)
-            {
-            strError = "Should be only one dest StoreModule.";
-            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
-            return -1;
-            }
-        ++destStoreModulesCount;
-
-        destStoreModuleSettings.moduleName = node->getValue(0);
-        ParseModuleSettings(node, &destStoreModuleSettings.moduleParams);
-        }
-
-    node = node->getNextNode();
-    }
-
-return 0;
-}
-//-----------------------------------------------------------------------------
diff --git a/projects/convertor/settings_impl.h b/projects/convertor/settings_impl.h
deleted file mode 100644 (file)
index eec21d6..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
- /*
- $Revision: 1.6 $
- $Date: 2009/06/22 16:26:54 $
- */
-
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Date: 27.10.2002
- */
-
-/*
- *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
-#ifndef SETTINGS_IMPL_H
-#define SETTINGS_IMPL_H
-
-#include <string>
-#include <vector>
-
-struct MODULE_SETTINGS;
-class DOTCONFDocumentNode;
-
-class SETTINGS_IMPL {
-public:
-    SETTINGS_IMPL() : confFile("./convertor.conf") {}
-    SETTINGS_IMPL(const std::string & cf) : confFile(cf) {}
-    ~SETTINGS_IMPL() {}
-    int ReadSettings();
-
-    std::string GetStrError() const { return strError; }
-
-    const std::string & GetConfDir() const;
-
-    const std::string & GetModulesPath() const { return modulesPath; }
-    const MODULE_SETTINGS & GetSourceStoreModuleSettings() const { return sourceStoreModuleSettings; }
-    const MODULE_SETTINGS & GetDestStoreModuleSettings() const { return destStoreModuleSettings; }
-
-private:
-    int ParseModuleSettings(const DOTCONFDocumentNode * dirNameNode, std::vector<PARAM_VALUE> * params);
-
-    std::string strError;
-    std::string modulesPath;
-    std::string confFile;
-
-    MODULE_SETTINGS sourceStoreModuleSettings;
-    MODULE_SETTINGS destStoreModuleSettings;
-};
-
-#endif
index 9d51021bbf74820ed17b680788fb15247dcb81ed..3d4104838be58f4aa0a851281f2b08758a983648 100644 (file)
@@ -8,7 +8,8 @@ LIB_NAME = rlm_stg
 
 PROG = $(LIB_NAME).so
 
-SRCS = ./rlm_stg.cpp \
+SRCS = ./rlm_stg.c \
+       ./iface.cpp \
        ./stg_client.cpp
 
 STGLIBS = crypto \
@@ -56,13 +57,30 @@ distclean: clean
 install: install-bin
 
 install-bin:
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/$(PROG)
+ifeq ($(DEBUG), yes)
+ifeq ($(OS), linux)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/$(PROG)
+endif
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG)
+ifeq ($(OS), linux)
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/$(PROG)
+endif
+endif
        $(MAKE) -C $(DIR_LIBSRC) install
 
 uninstall: uninstall-bin
 
 uninstall-bin:
+ifeq ($(OS), linux)
+       rm -f $(PREFIX)/usr/lib/freeradius/$(PROG)
+else
        rm -f $(PREFIX)/usr/lib/$(PROG)
+endif
 
 ifneq ($(MAKECMDGOALS),distclean)
 ifneq ($(MAKECMDGOALS),clean)
index 0145d0388fd79e7e45326ce4375d597edaa9e711..6459cdb9e4f5e3fc049fada62d5bfba6e8f13b0a 100755 (executable)
@@ -16,18 +16,15 @@ DATA_MODE=0644
 DIR_MODE=0755
 OWNER=root
 
-if [ -z $1 ]
+if [ "$1" = "debug" ]
 then
-    MAKEOPTS="-j1"
+   DEFS="$DEFS -DDEBUG"
+   MAKEOPTS="$MAKEOPTS -j1"
+   CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+   DEBUG="yes"
 else
-    if [ "$1" = "debug" ]
-    then
-        DEFS="-DDEBUG"
-        MAKEOPTS="-j1"
-        CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
-    else
-        MAKEOPTS="-j1"
-    fi
+   DEFS="$DEFS -DNDEBUG"
+   DEBUG="no"
 fi
 
 CXXFLAGS="$CXXFLAGS -I/usr/local/include"
@@ -56,15 +53,15 @@ fi
 
 if [ "$OS" = "unknown" ]
 then 
-    echo "#############################################################################"
-    echo "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
+    printf "#############################################################################\n"
+    printf "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #\n"
+    printf "#############################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building rlm_stg for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building rlm_stg for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="crypto.lib common.lib"
 
@@ -98,32 +95,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -132,38 +129,39 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
 $MAKE $MAKEOPTS
 
diff --git a/projects/rlm_stg/build_check.c b/projects/rlm_stg/build_check.c
deleted file mode 100644 (file)
index a5a7341..0000000
+++ /dev/null
@@ -1 +0,0 @@
-int main() { int probe = 0x00000001; return *(char *)&probe; }
diff --git a/projects/rlm_stg/conf.h b/projects/rlm_stg/conf.h
deleted file mode 100644 (file)
index e96eb71..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Default Database File Names */
-
-#define RADIUS_DIR             RADDBDIR
-#define RADACCT_DIR            RADIR
-#define RADLOG_DIR             LOGDIR
-
-#define RADIUS_DICTIONARY      "dictionary"
-#define RADIUS_CLIENTS         "clients"
-#define RADIUS_NASLIST         "naslist"
-#define RADIUS_REALMS          "realms"
-
-#define RADUTMP                        LOGDIR "/radutmp"
-#define SRADUTMP               LOGDIR "/sradutmp"
-#define RADWTMP                        LOGDIR "/radwtmp"
-#define SRADWTMP               LOGDIR "/sradwtmp"
-
-/* Hack for funky ascend ports on MAX 4048 (and probably others)
-   The "NAS-Port-Id" value is "xyyzz" where "x" = 1 for digital, 2 for analog;
-   "yy" = line number (1 for first PRI/T1/E1, 2 for second, so on);
-   "zz" = channel number (on the PRI or Channelized T1/E1).
-    This should work with normal terminal servers, unless you have a TS with
-        more than 9999 ports ;^).
-    The "ASCEND_CHANNELS_PER_LINE" is the number of channels for each line into
-        the unit.  For my US/PRI that's 23.  A US/T1 would be 24, and a
-        European E1 would be 30 (I think ... never had one ;^).
-    This will NOT change the "NAS-Port-Id" reported in the detail log.  This
-        is simply to fix the dynamic IP assignments a la Cistron.
-    You can change the default of 23 with an argument to ./configure.
-    WARNING: This hack works for me, but I only have one PRI!!!  I've not
-        tested it on 2 or more (or with models other than the Max 4048)
-    Use at your own risk!
-  -- dgreer@austintx.com
-*/
-#ifdef ASCEND_PORT_HACK
-#  ifndef ASCEND_CHANNELS_PER_LINE
-#    define ASCEND_CHANNELS_PER_LINE        23
-#  endif
-#endif
diff --git a/projects/rlm_stg/conffile.h b/projects/rlm_stg/conffile.h
deleted file mode 100644 (file)
index 8998c36..0000000
+++ /dev/null
@@ -1,127 +0,0 @@
-#ifndef _CONFFILE_H
-#define _CONFFILE_H
-
-/*
- * conffile.h  Defines for the conffile parsing routines.
- *
- * Version:    $Id: conffile.h,v 1.1 2010/08/14 04:13:52 faust Exp $
- *
- */
-
-//#include <freeradius/ident.h>
-//RCSIDH(conffile_h, "$Id: conffile.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#include <stddef.h>
-//#include <freeradius/token.h>
-#include "libradius.h"
-
-/*
- * Export the minimum amount of information about these structs
- */
-typedef struct conf_item CONF_ITEM;
-typedef struct conf_pair CONF_PAIR;
-typedef struct conf_part CONF_SECTION;
-typedef struct conf_data CONF_DATA;
-
-/*
- *  Instead of putting the information into a configuration structure,
- *  the configuration file routines MAY just parse it directly into
- *  user-supplied variables.
- */
-#define PW_TYPE_STRING_PTR     100
-#define PW_TYPE_BOOLEAN                101
-#define PW_TYPE_SUBSECTION     102
-#define PW_TYPE_FILENAME       103
-
-typedef struct CONF_PARSER {
-  const char *name;
-  int type;                    /* PW_TYPE_STRING, etc. */
-  size_t offset;               /* relative pointer within "base" */
-  void *data;                  /* absolute pointer if base is NULL */
-  const char *dflt;            /* default as it would appear in radiusd.conf */
-} CONF_PARSER;
-
-/* This preprocessor trick will be useful in initializing CONF_PARSER struct */
-#define XStringify(x) #x
-#define Stringify(x) XStringify(x)
-
-void           cf_pair_free(CONF_PAIR **cp);
-int            cf_pair_replace(CONF_SECTION *cs, CONF_PAIR *cp,
-                               const char *value);
-void           cf_section_free(CONF_SECTION **cp);
-int            cf_item_parse(CONF_SECTION *cs, const char *name,
-                             int type, void *data, const char *dflt);
-int            cf_section_parse(CONF_SECTION *, void *base,
-                                const CONF_PARSER *variables);
-void           cf_section_parse_free(CONF_SECTION *cs, void *base);
-const CONF_PARSER *cf_section_parse_table(CONF_SECTION *cs);
-CONF_SECTION   *cf_file_read(const char *file);
-int            cf_file_include(const char *file, CONF_SECTION *cs);
-
-CONF_PAIR      *cf_pair_find(const CONF_SECTION *, const char *name);
-CONF_PAIR      *cf_pair_find_next(const CONF_SECTION *, CONF_PAIR *, const char *name);
-CONF_SECTION   *cf_section_find(const char *name);
-CONF_SECTION   *cf_section_sub_find(const CONF_SECTION *, const char *name);
-CONF_SECTION   *cf_section_sub_find_name2(const CONF_SECTION *, const char *name1, const char *name2);
-const char     *cf_section_value_find(const CONF_SECTION *, const char *attr);
-CONF_SECTION   *cf_top_section(CONF_SECTION *cs);
-
-void *cf_data_find(CONF_SECTION *, const char *);
-int cf_data_add(CONF_SECTION *, const char *, void *, void (*)(void *));
-
-const char *cf_pair_attr(CONF_PAIR *pair);
-const char *cf_pair_value(CONF_PAIR *pair);
-VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair);
-const char *cf_section_name1(const CONF_SECTION *);
-const char *cf_section_name2(const CONF_SECTION *);
-int dump_config(CONF_SECTION *cs);
-CONF_SECTION *cf_subsection_find_next(CONF_SECTION *section,
-                                     CONF_SECTION *subsection,
-                                     const char *name1);
-CONF_SECTION *cf_section_find_next(CONF_SECTION *section,
-                                  CONF_SECTION *subsection,
-                                  const char *name1);
-int cf_section_lineno(CONF_SECTION *section);
-int cf_pair_lineno(CONF_PAIR *pair);
-const char *cf_pair_filename(CONF_PAIR *pair);
-const char *cf_section_filename(CONF_SECTION *section);
-CONF_ITEM *cf_item_find_next(CONF_SECTION *section, CONF_ITEM *item);
-int cf_item_is_section(CONF_ITEM *item);
-int cf_item_is_pair(CONF_ITEM *item);
-CONF_PAIR *cf_itemtopair(CONF_ITEM *item);
-CONF_SECTION *cf_itemtosection(CONF_ITEM *item);
-CONF_ITEM *cf_pairtoitem(CONF_PAIR *cp);
-CONF_ITEM *cf_sectiontoitem(CONF_SECTION *cs);
-int cf_section_template(CONF_SECTION *cs, CONF_SECTION *_template);
-void cf_log_err(CONF_ITEM *ci, const char *fmt, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 2, 3)))
-#endif
-;
-void cf_log_info(CONF_SECTION *cs, const char *fmt, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 2, 3)))
-#endif
-;
-void cf_log_module(CONF_SECTION *cs, const char *fmt, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 2, 3)))
-#endif
-;
-CONF_ITEM *cf_reference_item(const CONF_SECTION *parentcs,
-                            CONF_SECTION *outercs,
-                            const char *ptr);
-extern int cf_log_config;
-extern int cf_log_modules;
-
-extern int cf_pair2xml(FILE *fp, CONF_PAIR *cp);
-extern int cf_section2xml(FILE *fp, CONF_SECTION *cs);
-extern int cf_pair2file(FILE *fp, CONF_PAIR *cp);
-extern int cf_section2file(FILE *fp, CONF_SECTION *cs);
-
-/*
- *     Big magic.
- */
-int cf_section_migrate(CONF_SECTION *dst, CONF_SECTION *src);
-
-#endif /* _CONFFILE_H */
diff --git a/projects/rlm_stg/iface.cpp b/projects/rlm_stg/iface.cpp
new file mode 100644 (file)
index 0000000..741017b
--- /dev/null
@@ -0,0 +1,41 @@
+#include "iface.h"
+
+#include "thriftclient.h"
+
+int stgInstantiateImpl(const char * server, uint16_t port, const char * password)
+{
+    if (STG_CLIENT_ST::Get().Configure(server, port, password))
+        return 1;
+
+    return 0;
+}
+
+const STG_PAIR * stgAuthorizeImpl(const char * userName, const char * serviceType)
+{
+    return STG_CLIENT_ST::Get().Authorize(userName, serviceType);
+}
+
+const STG_PAIR * stgAuthenticateImpl(const char * userName, const char * serviceType)
+{
+    return STG_CLIENT_ST::Get().Authenticate(userName, serviceType);
+}
+
+const STG_PAIR * stgPostAuthImpl(const char * userName, const char * serviceType)
+{
+    return STG_CLIENT_ST::Get().PostAuth(userName, serviceType);
+}
+
+const STG_PAIR * stgPreAcctImpl(const char * userName, const char * serviceType)
+{
+    return STG_CLIENT_ST::Get().PreAcct(userName, serviceType);
+}
+
+const STG_PAIR * stgAccountingImpl(const char * userName, const char * serviceType, const char * statusType, const char * sessionId)
+{
+    return STG_CLIENT_ST::Get().Account(userName, serviceType, statusType, sessionId);
+}
+
+void deletePairs(const STG_PAIR * pairs)
+{
+    delete[] pairs;
+}
diff --git a/projects/rlm_stg/iface.h b/projects/rlm_stg/iface.h
new file mode 100644 (file)
index 0000000..57bb9f4
--- /dev/null
@@ -0,0 +1,25 @@
+#ifndef __STG_IFACE_H__
+#define __STG_IFACE_H__
+
+#include <stdint.h>
+
+#include "stgpair.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int stgInstantiateImpl(const char * server, uint16_t port, const char * password);
+const STG_PAIR * stgAuthorizeImpl(const char * userName, const char * serviceType);
+const STG_PAIR * stgAuthenticateImpl(const char * userName, const char * serviceType);
+const STG_PAIR * stgPostAuthImpl(const char * userName, const char * serviceType);
+const STG_PAIR * stgPreAcctImpl(const char * userName, const char * serviceType);
+const STG_PAIR * stgAccountingImpl(const char * userName, const char * serviceType, const char * statusType, const char * sessionId);
+
+void deletePairs(const STG_PAIR * pairs);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/projects/rlm_stg/libradius.h b/projects/rlm_stg/libradius.h
deleted file mode 100644 (file)
index 25cb98e..0000000
+++ /dev/null
@@ -1,475 +0,0 @@
-#ifndef LIBRADIUS_H
-#define LIBRADIUS_H
-
-/*
- * libradius.h Structures and prototypes
- *             for the radius library.
- *
- * Version:    $Id: libradius.h,v 1.1 2010/08/14 04:13:52 faust Exp $
- *
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation; either version 2 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program; if not, write to the Free Software
- *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
- *
- * Copyright 1999,2000,2001,2002,2003,2004,2005,2006,2007,2008  The FreeRADIUS server project
- */
-
-//#include <freeradius/ident.h>
-//RCSIDH(libradius_h, "$Id: libradius.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#include <errno.h>
-#include <time.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include "stg/os_int.h"
-
-#ifdef FREE_BSD
-#include <sys/types.h>
-#endif
-#include <netinet/in.h>
-#include <sys/socket.h>
-
-/*#include <freeradius/radius.h>
-#include <freeradius/hash.h>*/
-
-#include "token.h"
-
-#ifdef SIZEOF_UNSIGNED_INT
-#if SIZEOF_UNSIGNED_INT != 4
-#error FATAL: sizeof(unsigned int) != 4
-#endif
-#endif
-
-/*
- *  Include for modules.
- */
-/*#include <freeradius/sha1.h>
-#include <freeradius/md4.h>*/
-
-#define EAP_START               2
-
-#define AUTH_VECTOR_LEN                16
-#define CHAP_VALUE_LENGTH       16
-#define MAX_STRING_LEN         254     /* RFC2138: string 0-253 octets */
-
-#  define VENDOR(x)            ((x >> 16) & 0xffff)
-
-#ifdef _LIBRADIUS
-#  define AUTH_HDR_LEN         20
-#  define VENDORPEC_USR                429
-#define VENDORPEC_LUCENT       4846
-#define VENDORPEC_STARENT      8164
-#  define DEBUG                        if (fr_debug_flag && fr_log_fp) fr_printf_log
-#  define debug_pair(vp)       do { if (fr_debug_flag && fr_log_fp) { \
-                                       fputc('\t', fr_log_fp); \
-                                       vp_print(fr_log_fp, vp); \
-                                       fputc('\n', fr_log_fp); \
-                                    } \
-                               } while(0)
-#  define TAG_VALID(x)          ((x) > 0 && (x) < 0x20)
-#  define TAG_VALID_ZERO(x)     ((x) < 0x20)
-#  define TAG_ANY               -128   /* minimum signed char */
-#endif
-
-#if defined(__GNUC__)
-# define PRINTF_LIKE(n) __attribute__ ((format(printf, n, n+1)))
-# define NEVER_RETURNS __attribute__ ((noreturn))
-# define UNUSED __attribute__ ((unused))
-# define BLANK_FORMAT " "      /* GCC_LINT whines about empty formats */
-#else
-# define PRINTF_LIKE(n)        /* ignore */
-# define NEVER_RETURNS /* ignore */
-# define UNUSED /* ignore */
-# define BLANK_FORMAT ""
-#endif
-
-typedef struct attr_flags {
-       unsigned int            addport : 1;  /* add NAS-Port to IP address */
-       unsigned int            has_tag : 1;  /* tagged attribute */
-       unsigned int            do_xlat : 1;  /* strvalue is dynamic */
-       unsigned int            unknown_attr : 1; /* not in dictionary */
-       unsigned int            array : 1; /* pack multiples into 1 attr */
-       unsigned int            has_value : 1; /* has a value */
-       unsigned int            has_value_alias : 1; /* has a value alias */
-       unsigned int            has_tlv : 1; /* has sub attributes */
-       unsigned int            is_tlv : 1; /* is a sub attribute */
-       unsigned int            encoded : 1; /* has been put into packet */
-
-       int8_t                  tag;          /* tag for tunneled attributes */
-       uint8_t                 encrypt;      /* encryption method */
-} ATTR_FLAGS;
-
-/*
- *  Values of the encryption flags.
- */
-#define FLAG_ENCRYPT_NONE            (0)
-#define FLAG_ENCRYPT_USER_PASSWORD   (1)
-#define FLAG_ENCRYPT_TUNNEL_PASSWORD (2)
-#define FLAG_ENCRYPT_ASCEND_SECRET   (3)
-
-typedef struct dict_attr {
-       unsigned int            attr;
-       int                     type;
-       int                     vendor;
-        ATTR_FLAGS              flags;
-       char                    name[1];
-} DICT_ATTR;
-
-typedef struct dict_value {
-       unsigned int            attr;
-       int                     value;
-       char                    name[1];
-} DICT_VALUE;
-
-typedef struct dict_vendor {
-       int                     vendorpec;
-       int                     type; /* length of type data */
-       int                     length; /* length of length data */
-       int                     flags;
-       char                    name[1];
-} DICT_VENDOR;
-
-typedef union value_pair_data {
-       char                    strvalue[MAX_STRING_LEN];
-       uint8_t                 octets[MAX_STRING_LEN];
-       struct in_addr          ipaddr;
-       struct in6_addr         ipv6addr;
-       uint32_t                date;
-       uint32_t                integer;
-       int32_t                 sinteger;
-       uint8_t                 filter[32];
-       uint8_t                 ifid[8]; /* struct? */
-       uint8_t                 ipv6prefix[18]; /* struct? */
-       uint8_t                 ether[6];
-       uint8_t                 *tlv;
-} VALUE_PAIR_DATA;
-
-typedef struct value_pair {
-       const char              *name;
-       int                     attribute;
-       int                     vendor;
-       int                     type;
-       size_t                  length; /* of data */
-       FR_TOKEN                _operator;
-        ATTR_FLAGS              flags;
-       struct value_pair       *next;
-       uint32_t                lvalue;
-       VALUE_PAIR_DATA         data;
-} VALUE_PAIR;
-#define vp_strvalue   data.strvalue
-#define vp_octets     data.octets
-#define vp_ipv6addr   data.ipv6addr
-#define vp_ifid       data.ifid
-#define vp_ipv6prefix data.ipv6prefix
-#define vp_filter     data.filter
-#define vp_ether      data.ether
-#define vp_signed     data.sinteger
-#define vp_tlv       data.tlv
-
-#if 0
-#define vp_ipaddr     data.ipaddr.s_addr
-#define vp_date       data.date
-#define vp_integer    data.integer
-#else
-/*
- *     These are left as lvalue until we audit the source for code
- *     that prints to vp_strvalue for integer/ipaddr/date types.
- */
-#define vp_ipaddr     lvalue
-#define vp_date       lvalue
-#define vp_integer    lvalue
-#endif
-
-
-typedef struct fr_ipaddr_t {
-       int             af;     /* address family */
-       union {
-               struct in_addr  ip4addr;
-               struct in6_addr ip6addr; /* maybe defined in missing.h */
-       } ipaddr;
-} fr_ipaddr_t;
-
-/*
- *     vector:         Request authenticator from access-request packet
- *                     Put in there by rad_decode, and must be put in the
- *                     response RADIUS_PACKET as well before calling rad_send
- *
- *     verified:       Filled in by rad_decode for accounting-request packets
- *
- *     data,data_len:  Used between rad_recv and rad_decode.
- */
-typedef struct radius_packet {
-       int                     sockfd;
-       fr_ipaddr_t             src_ipaddr;
-        fr_ipaddr_t            dst_ipaddr;
-       uint16_t                src_port;
-       uint16_t                dst_port;
-       int                     id;
-       unsigned int            code;
-       uint32_t                hash;
-       uint8_t                 vector[AUTH_VECTOR_LEN];
-       time_t                  timestamp;
-       uint8_t                 *data;
-       int                     data_len;
-       VALUE_PAIR              *vps;
-       ssize_t                 offset;
-} RADIUS_PACKET;
-
-/*
- *     Printing functions.
- */
-int            fr_utf8_char(const uint8_t *str);
-void           fr_print_string(const char *in, size_t inlen,
-                                char *out, size_t outlen);
-int            vp_prints_value(char *out, size_t outlen,
-                               VALUE_PAIR *vp, int delimitst);
-const char     *vp_print_name(char *buffer, size_t bufsize, int attr);
-int            vp_prints(char *out, size_t outlen, VALUE_PAIR *vp);
-void           vp_print(FILE *, VALUE_PAIR *);
-void           vp_printlist(FILE *, VALUE_PAIR *);
-#define                fprint_attr_val vp_print
-
-/*
- *     Dictionary functions.
- */
-int            dict_addvendor(const char *name, int value);
-int            dict_addattr(const char *name, int vendor, int type, int value, ATTR_FLAGS flags);
-int            dict_addvalue(const char *namestr, const char *attrstr, int value);
-int            dict_init(const char *dir, const char *fn);
-void           dict_free(void);
-DICT_ATTR      *dict_attrbyvalue(unsigned int attr);
-DICT_ATTR      *dict_attrbyname(const char *attr);
-DICT_VALUE     *dict_valbyattr(unsigned int attr, int val);
-DICT_VALUE     *dict_valbyname(unsigned int attr, const char *val);
-int            dict_vendorbyname(const char *name);
-DICT_VENDOR    *dict_vendorbyvalue(int vendor);
-
-#if 1 /* FIXME: compat */
-#define dict_attrget   dict_attrbyvalue
-#define dict_attrfind  dict_attrbyname
-#define dict_valfind   dict_valbyname
-/*#define dict_valget  dict_valbyattr almost but not quite*/
-#endif
-
-/* get around diffrent ctime_r styles */
-#ifdef CTIMERSTYLE
-#if CTIMERSTYLE == SOLARISSTYLE
-#define CTIME_R(a,b,c) ctime_r(a,b,c)
-#else
-#define CTIME_R(a,b,c) ctime_r(a,b)
-#endif
-#else
-#define CTIME_R(a,b,c) ctime_r(a,b)
-#endif
-
-/* md5.c */
-
-void           fr_md5_calc(uint8_t *, const uint8_t *, unsigned int);
-
-/* hmac.c */
-
-void fr_hmac_md5(const uint8_t *text, int text_len,
-                  const uint8_t *key, int key_len,
-                  unsigned char *digest);
-
-/* hmacsha1.c */
-
-void fr_hmac_sha1(const uint8_t *text, int text_len,
-                   const uint8_t *key, int key_len,
-                   uint8_t *digest);
-
-/* radius.c */
-int            rad_send(RADIUS_PACKET *, const RADIUS_PACKET *, const char *secret);
-int            rad_packet_ok(RADIUS_PACKET *packet, int flags);
-RADIUS_PACKET  *rad_recv(int fd, int flags);
-ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
-                       int *code);
-void           rad_recv_discard(int sockfd);
-int            rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
-                          const char *secret);
-int            rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original, const char *secret);
-int            rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
-                          const char *secret);
-int            rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
-                        const char *secret);
-
-RADIUS_PACKET  *rad_alloc(int newvector);
-RADIUS_PACKET  *rad_alloc_reply(RADIUS_PACKET *);
-void           rad_free(RADIUS_PACKET **);
-int            rad_pwencode(char *encpw, size_t *len, const char *secret,
-                            const uint8_t *vector);
-int            rad_pwdecode(char *encpw, size_t len, const char *secret,
-                            const uint8_t *vector);
-int            rad_tunnel_pwencode(char *encpw, size_t *len, const char *secret,
-                                   const uint8_t *vector);
-int            rad_tunnel_pwdecode(uint8_t *encpw, size_t *len,
-                                   const char *secret, const uint8_t *vector);
-int            rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output,
-                               int id, VALUE_PAIR *password);
-VALUE_PAIR     *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
-                            const char *secret, int attribute, int length,
-                            const uint8_t *data);
-int            rad_vp2attr(const RADIUS_PACKET *packet,
-                           const RADIUS_PACKET *original, const char *secret,
-                           const VALUE_PAIR *vp, uint8_t *ptr);
-
-/* valuepair.c */
-VALUE_PAIR     *pairalloc(DICT_ATTR *da);
-VALUE_PAIR     *paircreate(int attr, int type);
-void           pairfree(VALUE_PAIR **);
-void            pairbasicfree(VALUE_PAIR *pair);
-VALUE_PAIR     *pairfind(VALUE_PAIR *, int);
-void           pairdelete(VALUE_PAIR **, int);
-void           pairadd(VALUE_PAIR **, VALUE_PAIR *);
-void            pairreplace(VALUE_PAIR **first, VALUE_PAIR *add);
-int            paircmp(VALUE_PAIR *check, VALUE_PAIR *data);
-VALUE_PAIR     *paircopyvp(const VALUE_PAIR *vp);
-VALUE_PAIR     *paircopy(VALUE_PAIR *vp);
-VALUE_PAIR     *paircopy2(VALUE_PAIR *vp, int attr);
-void           pairmove(VALUE_PAIR **to, VALUE_PAIR **from);
-void           pairmove2(VALUE_PAIR **to, VALUE_PAIR **from, int attr);
-VALUE_PAIR     *pairparsevalue(VALUE_PAIR *vp, const char *value);
-VALUE_PAIR     *pairmake(const char *attribute, const char *value, int _operator);
-VALUE_PAIR     *pairread(const char **ptr, FR_TOKEN *eol);
-FR_TOKEN       userparse(const char *buffer, VALUE_PAIR **first_pair);
-VALUE_PAIR     *readvp2(FILE *fp, int *pfiledone, const char *errprefix);
-
-/*
- *     Error functions.
- */
-#ifdef _LIBRADIUS
-void           fr_strerror_printf(const char *, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 1, 2)))
-#endif
-;
-#endif
-void           fr_perror(const char *, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 1, 2)))
-#endif
-;
-extern const char *fr_strerror(void);
-extern int     fr_dns_lookups; /* 0 = no dns lookups */
-extern int     fr_debug_flag;  /* 0 = no debugging information */
-extern int     fr_max_attributes; /* per incoming packet */
-#define        FR_MAX_PACKET_CODE (52)
-extern const char *fr_packet_codes[FR_MAX_PACKET_CODE];
-extern FILE    *fr_log_fp;
-void           fr_printf_log(const char *, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 1, 2)))
-#endif
-;
-
-/*
- *     Several handy miscellaneous functions.
- */
-const char *   ip_ntoa(char *, uint32_t);
-char           *ifid_ntoa(char *buffer, size_t size, uint8_t *ifid);
-uint8_t                *ifid_aton(const char *ifid_str, uint8_t *ifid);
-int            rad_lockfd(int fd, int lock_len);
-int            rad_lockfd_nonblock(int fd, int lock_len);
-int            rad_unlockfd(int fd, int lock_len);
-void           fr_bin2hex(const uint8_t *bin, char *hex, size_t len);
-size_t         fr_hex2bin(const char *hex, uint8_t *bin, size_t len);
-#ifndef HAVE_CLOSEFROM
-int            closefrom(int fd);
-#endif
-int fr_ipaddr_cmp(const fr_ipaddr_t *a, const fr_ipaddr_t *b);
-
-int            ip_hton(const char *src, int af, fr_ipaddr_t *dst);
-const char     *ip_ntoh(const fr_ipaddr_t *src, char *dst, size_t cnt);
-int fr_ipaddr2sockaddr(const fr_ipaddr_t *ipaddr, int port,
-                      struct sockaddr_storage *sa, socklen_t *salen);
-int fr_sockaddr2ipaddr(const struct sockaddr_storage *sa, socklen_t salen,
-                      fr_ipaddr_t *ipaddr, int * port);
-
-
-#ifdef ASCEND_BINARY
-/* filters.c */
-int            ascend_parse_filter(VALUE_PAIR *pair);
-void           print_abinary(VALUE_PAIR *vp, char *buffer, size_t len);
-#endif /*ASCEND_BINARY*/
-
-/* random numbers in isaac.c */
-/* context of random number generator */
-typedef struct fr_randctx {
-  uint32_t randcnt;
-  uint32_t randrsl[256];
-  uint32_t randmem[256];
-  uint32_t randa;
-  uint32_t randb;
-  uint32_t randc;
-} fr_randctx;
-
-void fr_isaac(fr_randctx *ctx);
-void fr_randinit(fr_randctx *ctx, int flag);
-uint32_t fr_rand(void);        /* like rand(), but better. */
-void fr_rand_seed(const void *, size_t ); /* seed the random pool */
-
-
-/* crypt wrapper from crypt.c */
-int fr_crypt_check(const char *key, const char *salt);
-
-/* rbtree.c */
-typedef struct rbtree_t rbtree_t;
-typedef struct rbnode_t rbnode_t;
-
-rbtree_t       *rbtree_create(int (*Compare)(const void *, const void *),
-                              void (*freeNode)(void *),
-                              int replace_flag);
-void           rbtree_free(rbtree_t *tree);
-int            rbtree_insert(rbtree_t *tree, void *Data);
-rbnode_t       *rbtree_insertnode(rbtree_t *tree, void *Data);
-void           rbtree_delete(rbtree_t *tree, rbnode_t *Z);
-int            rbtree_deletebydata(rbtree_t *tree, const void *data);
-rbnode_t       *rbtree_find(rbtree_t *tree, const void *Data);
-void          *rbtree_finddata(rbtree_t *tree, const void *Data);
-int            rbtree_num_elements(rbtree_t *tree);
-void          *rbtree_min(rbtree_t *tree);
-void          *rbtree_node2data(rbtree_t *tree, rbnode_t *node);
-
-/* callback order for walking  */
-typedef enum { PreOrder, InOrder, PostOrder } RBTREE_ORDER;
-
-/*
- *     The callback should be declared as:
- *     int callback(void *context, void *data)
- *
- *     The "context" is some user-defined context.
- *     The "data" is the pointer to the user data in the node,
- *       NOT the node itself.
- *
- *     It should return 0 if all is OK, and !0 for any error.
- *     The walking will stop on any error.
- */
-int rbtree_walk(rbtree_t *tree, RBTREE_ORDER order, int (*callback)(void *, void *), void *context);
-
-/*
- *     FIFOs
- */
-typedef struct fr_fifo_t fr_fifo_t;
-typedef void (*fr_fifo_free_t)(void *);
-fr_fifo_t *fr_fifo_create(int max_entries, fr_fifo_free_t freeNode);
-void fr_fifo_free(fr_fifo_t *fi);
-int fr_fifo_push(fr_fifo_t *fi, void *data);
-void *fr_fifo_pop(fr_fifo_t *fi);
-void *fr_fifo_peek(fr_fifo_t *fi);
-int fr_fifo_num_elements(fr_fifo_t *fi);
-
-//#include <freeradius/packet.h>
-
-#endif /*LIBRADIUS_H*/
diff --git a/projects/rlm_stg/modules.h b/projects/rlm_stg/modules.h
deleted file mode 100644 (file)
index cb49f47..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * module.h    Interface to the RADIUS module system.
- *
- * Version:    $Id: modules.h,v 1.1 2010/08/14 04:13:52 faust Exp $
- *
- */
-
-#ifndef RADIUS_MODULES_H
-#define RADIUS_MODULES_H
-
-//#include <freeradius/ident.h>
-//RCSIDH(modules_h, "$Id: modules.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-//#include "conffile.h"
-#include "radiusd.h"
-
-typedef int (*packetmethod)(void *instance, REQUEST *request);
-
-enum {
-  RLM_COMPONENT_AUTH = 0,
-  RLM_COMPONENT_AUTZ,          /* 1 */
-  RLM_COMPONENT_PREACCT,       /* 2 */
-  RLM_COMPONENT_ACCT,          /* 3 */
-  RLM_COMPONENT_SESS,          /* 4 */
-  RLM_COMPONENT_PRE_PROXY,     /* 5 */
-  RLM_COMPONENT_POST_PROXY,    /* 6 */
-  RLM_COMPONENT_POST_AUTH,     /* 7 */
-#ifdef WITH_COA
-  RLM_COMPONENT_RECV_COA,      /* 8 */
-  RLM_COMPONENT_SEND_COA,      /* 9 */
-#endif
-  RLM_COMPONENT_COUNT          /* 8 / 10: How many components are there */
-};
-
-#define RLM_TYPE_THREAD_SAFE           (0 << 0)
-#define RLM_TYPE_THREAD_UNSAFE         (1 << 0)
-#define RLM_TYPE_CHECK_CONFIG_SAFE     (1 << 1)
-#define RLM_TYPE_HUP_SAFE              (1 << 2)
-
-#define RLM_MODULE_MAGIC_NUMBER ((uint32_t) (0xf4ee4ad2))
-#define RLM_MODULE_INIT RLM_MODULE_MAGIC_NUMBER
-
-typedef struct module_t {
-       uint32_t        magic;  /* may later be opaque struct */
-       const char      *name;
-       int             type;
-       int             (*instantiate)(CONF_SECTION *mod_cs, void **instance);
-       int             (*detach)(void *instance);
-       packetmethod    methods[RLM_COMPONENT_COUNT];
-} module_t;
-
-enum {
-       RLM_MODULE_REJECT,      /* immediately reject the request */
-       RLM_MODULE_FAIL,        /* module failed, don't reply */
-       RLM_MODULE_OK,          /* the module is OK, continue */
-       RLM_MODULE_HANDLED,     /* the module handled the request, so stop. */
-       RLM_MODULE_INVALID,     /* the module considers the request invalid. */
-       RLM_MODULE_USERLOCK,    /* reject the request (user is locked out) */
-       RLM_MODULE_NOTFOUND,    /* user not found */
-       RLM_MODULE_NOOP,        /* module succeeded without doing anything */
-       RLM_MODULE_UPDATED,     /* OK (pairs modified) */
-       RLM_MODULE_NUMCODES     /* How many return codes there are */
-};
-
-int setup_modules(int, CONF_SECTION *);
-int detach_modules(void);
-int module_hup(CONF_SECTION *modules);
-int module_authorize(int type, REQUEST *request);
-int module_authenticate(int type, REQUEST *request);
-int module_preacct(REQUEST *request);
-int module_accounting(int type, REQUEST *request);
-int module_checksimul(int type, REQUEST *request, int maxsimul);
-int module_pre_proxy(int type, REQUEST *request);
-int module_post_proxy(int type, REQUEST *request);
-int module_post_auth(int type, REQUEST *request);
-#ifdef WITH_COA
-int module_recv_coa(int type, REQUEST *request);
-int module_send_coa(int type, REQUEST *request);
-#define MODULE_NULL_COA_FUNCS ,NULL,NULL
-#else
-#define MODULE_NULL_COA_FUNCS
-#endif
-int indexed_modcall(int comp, int idx, REQUEST *request);
-
-/*
- *     For now, these are strongly tied together.
- */
-int virtual_servers_load(CONF_SECTION *config);
-void virtual_servers_free(time_t when);
-
-
-#endif /* RADIUS_MODULES_H */
diff --git a/projects/rlm_stg/radius.h b/projects/rlm_stg/radius.h
deleted file mode 100644 (file)
index 3cf5028..0000000
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
- * radius.h    Constants of the radius protocol.
- *
- * Version:    $Id$
- *
- */
-
-
-#define PW_TYPE_STRING                 0
-#define PW_TYPE_INTEGER                        1
-#define PW_TYPE_IPADDR                 2
-#define PW_TYPE_DATE                   3
-#define PW_TYPE_ABINARY                        4
-#define PW_TYPE_OCTETS                 5
-#define PW_TYPE_IFID                   6
-#define PW_TYPE_IPV6ADDR               7
-#define PW_TYPE_IPV6PREFIX             8
-#define PW_TYPE_BYTE                   9
-#define PW_TYPE_SHORT                  10
-#define PW_TYPE_ETHERNET               11
-#define PW_TYPE_SIGNED                 12
-#define PW_TYPE_COMBO_IP               13
-#define PW_TYPE_TLV                    14
-
-#define        PW_AUTHENTICATION_REQUEST       1
-#define        PW_AUTHENTICATION_ACK           2
-#define        PW_AUTHENTICATION_REJECT        3
-#define        PW_ACCOUNTING_REQUEST           4
-#define        PW_ACCOUNTING_RESPONSE          5
-#define        PW_ACCOUNTING_STATUS            6
-#define PW_PASSWORD_REQUEST            7
-#define PW_PASSWORD_ACK                        8
-#define PW_PASSWORD_REJECT             9
-#define        PW_ACCOUNTING_MESSAGE           10
-#define PW_ACCESS_CHALLENGE            11
-#define PW_STATUS_SERVER               12
-#define PW_STATUS_CLIENT               13
-#define PW_DISCONNECT_REQUEST          40
-#define PW_DISCONNECT_ACK              41
-#define PW_DISCONNECT_NAK              42
-#define PW_COA_REQUEST                 43
-#define PW_COA_ACK                     44
-#define PW_COA_NAK                     45
-
-#define PW_AUTH_UDP_PORT                1812
-#define PW_ACCT_UDP_PORT                1813
-#define PW_POD_UDP_PORT                        1700
-#define PW_COA_UDP_PORT                        3799
-
-#define        PW_USER_NAME                    1
-#define        PW_USER_PASSWORD                2
-#define        PW_PASSWORD                     2
-#define        PW_CHAP_PASSWORD                3
-#define        PW_NAS_IP_ADDRESS               4
-#define        PW_NAS_PORT                     5
-#define        PW_SERVICE_TYPE                 6
-#define        PW_FRAMED_PROTOCOL              7
-#define        PW_FRAMED_IP_ADDRESS            8
-#define        PW_FRAMED_IP_NETMASK            9
-#define        PW_FRAMED_ROUTING               10
-#define        PW_FILTER_ID                    11
-#define        PW_FRAMED_MTU                   12
-#define        PW_FRAMED_COMPRESSION           13
-#define        PW_LOGIN_IP_HOST                14
-#define        PW_LOGIN_SERVICE                15
-#define        PW_LOGIN_TCP_PORT               16
-#define PW_OLD_PASSWORD                        17
-#define PW_REPLY_MESSAGE               18
-#define PW_CALLBACK_NUMBER             19
-#define PW_CALLBACK_ID                 20
-#if 0
-/*
- *  Deprecated, and no longer used.
- */
-#define PW_EXPIRATION                  21
-#endif
-#define PW_FRAMED_ROUTE                        22
-#define PW_FRAMED_IPXNET               23
-#define PW_STATE                       24
-#define PW_CLASS                       25
-#define PW_VENDOR_SPECIFIC             26
-#define PW_SESSION_TIMEOUT             27
-#define PW_IDLE_TIMEOUT                        28
-#define PW_CALLED_STATION_ID           30
-#define PW_CALLING_STATION_ID          31
-#define PW_NAS_IDENTIFIER              32
-#define PW_PROXY_STATE                 33
-
-#define PW_ACCT_STATUS_TYPE            40
-#define PW_ACCT_DELAY_TIME             41
-#define PW_ACCT_INPUT_OCTETS           42
-#define PW_ACCT_OUTPUT_OCTETS          43
-#define PW_ACCT_SESSION_ID             44
-#define PW_ACCT_AUTHENTIC              45
-#define PW_ACCT_SESSION_TIME           46
-#define PW_ACCT_INPUT_PACKETS          47
-#define PW_ACCT_OUTPUT_PACKETS         48
-#define PW_ACCT_TERMINATE_CAUSE                49
-
-#define PW_EVENT_TIMESTAMP             55
-
-#define PW_CHAP_CHALLENGE              60
-#define PW_NAS_PORT_TYPE               61
-#define PW_PORT_LIMIT                  62
-
-#define PW_ARAP_PASSWORD               70
-#define PW_ARAP_FEATURES               71
-#define PW_ARAP_ZONE_ACCESS            72
-#define PW_ARAP_SECURITY               73
-#define PW_ARAP_SECURITY_DATA          74
-#define PW_PASSWORD_RETRY              75
-#define PW_PROMPT                      76
-#define PW_CONNECT_INFO                        77
-#define PW_CONFIGURATION_TOKEN         78
-#define PW_EAP_MESSAGE                  79
-#define PW_MESSAGE_AUTHENTICATOR        80
-
-#define PW_ARAP_CHALLENGE_RESPONSE     84
-#define PW_NAS_PORT_ID_STRING                  87
-#define PW_FRAMED_POOL                 88
-#define PW_CHARGEABLE_USER_IDENTITY    89
-#define PW_NAS_IPV6_ADDRESS            95
-
-#define PW_EXTENDED_ATTRIBUTE          192
-
-#define PW_DIGEST_RESPONSE             206
-#define PW_DIGEST_ATTRIBUTES           207
-
-#define PW_FALL_THROUGH                        500
-#define PW_EXEC_PROGRAM                        502
-#define PW_EXEC_PROGRAM_WAIT           503
-
-#define PW_AUTH_TYPE                   1000
-#define PW_PREFIX                      1003
-#define PW_SUFFIX                      1004
-#define PW_GROUP                       1005
-#define PW_CRYPT_PASSWORD              1006
-#define PW_CONNECT_RATE                        1007
-#define PW_ADD_PREFIX                  1008
-#define PW_ADD_SUFFIX                  1009
-#define PW_EXPIRATION                  1010
-#define PW_AUTZ_TYPE                   1011
-#define PW_ACCT_TYPE                   1012
-#define PW_SESSION_TYPE                        1013
-#define PW_POST_AUTH_TYPE              1014
-#define PW_PRE_PROXY_TYPE              1015
-#define PW_POST_PROXY_TYPE             1016
-#define PW_PRE_ACCT_TYPE               1017
-#define PW_EAP_TYPE                    1018
-#define PW_EAP_TLS_REQUIRE_CLIENT_CERT 1019
-#define PW_CLIENT_SHORTNAME            1024
-#define PW_LOAD_BALANCE_KEY            1025
-#define PW_RAW_ATTRIBUTE               1026
-#define PW_TNC_VLAN_ACCESS             1027
-#define PW_TNC_VLAN_ISOLATE            1028
-#define PW_USER_CATEGORY               1029
-#define PW_GROUP_NAME                  1030
-#define PW_HUNTGROUP_NAME              1031
-#define PW_SIMULTANEOUS_USE            1034
-#define PW_STRIP_USER_NAME             1035
-#define PW_HINT                                1040
-#define PAM_AUTH_ATTR                  1041
-#define PW_LOGIN_TIME                  1042
-#define PW_STRIPPED_USER_NAME          1043
-#define PW_CURRENT_TIME                        1044
-#define PW_REALM                       1045
-#define PW_NO_SUCH_ATTRIBUTE           1046
-#define PW_PACKET_TYPE                 1047
-#define PW_PROXY_TO_REALM                      1048
-#define PW_REPLICATE_TO_REALM                  1049
-#define PW_ACCT_SESSION_START_TIME     1050
-#define PW_ACCT_UNIQUE_SESSION_ID      1051
-#define PW_CLIENT_IP_ADDRESS           1052
-#define PW_LDAP_USERDN                 1053
-#define PW_NS_MTA_MD5_PASSWORD         1054
-#define PW_SQL_USER_NAME               1055
-#define PW_LM_PASSWORD                 1057
-#define PW_NT_PASSWORD                 1058
-#define PW_SMB_ACCOUNT_CTRL            1059
-#define PW_SMB_ACCOUNT_CTRL_TEXT       1061
-#define PW_USER_PROFILE                        1062
-#define PW_DIGEST_REALM                        1063
-#define PW_DIGEST_NONCE                        1064
-#define PW_DIGEST_METHOD               1065
-#define PW_DIGEST_URI                  1066
-#define PW_DIGEST_QOP                  1067
-#define PW_DIGEST_ALGORITHM            1068
-#define PW_DIGEST_BODY_DIGEST          1069
-#define PW_DIGEST_CNONCE               1070
-#define PW_DIGEST_NONCE_COUNT          1071
-#define PW_DIGEST_USER_NAME            1072
-#define PW_POOL_NAME                   1073
-#define PW_LDAP_GROUP                  1074
-#define PW_MODULE_SUCCESS_MESSAGE      1075
-#define PW_MODULE_FAILURE_MESSAGE      1076
-#if 0 /* no longer used */
-#define PW_X99_FAST                    1077
-#endif
-#define PW_REWRITE_RULE                        1078
-#define PW_SQL_GROUP                   1079
-#define PW_RESPONSE_PACKET_TYPE                1080
-#define PW_DIGEST_HA1                  1081
-#define PW_MS_CHAP_USE_NTLM_AUTH       1082
-#define PW_MS_CHAP_USER_NAME           1083
-#define PW_PACKET_SRC_IP_ADDRESS       1084
-#define PW_PACKET_DST_IP_ADDRESS       1085
-#define PW_PACKET_SRC_PORT             1086
-#define PW_PACKET_DST_PORT             1087
-#define PW_PACKET_AUTHENTICATION_VECTOR        1088
-#define PW_TIME_OF_DAY                 1089
-#define PW_REQUEST_PROCESSING_STAGE    1090
-#define PW_CACHE_NO_CACHING            1091
-#define PW_CACHE_DELETE_CACHE          1092
-
-#define PW_SHA_PASSWORD                        1093
-#define PW_SSHA_PASSWORD               1094
-#define PW_MD5_PASSWORD                        1095
-#define PW_SMD5_PASSWORD               1096
-
-#define PW_PACKET_SRC_IPV6_ADDRESS     1097
-#define PW_PACKET_DST_IPV6_ADDRESS     1098
-#define PW_VIRTUAL_SERVER              1099
-#define PW_CLEARTEXT_PASSWORD          1100
-#define PW_PASSWORD_WITH_HEADER                1101
-#define PW_SEND_COA_REQUEST            1107
-#define PW_MODULE_RETURN_CODE          1108
-#define PW_PACKET_ORIGINAL_TIMESTAMP           1109
-#define PW_HOME_SERVER_POOL            1111
-#define PW_RECV_COA_TYPE               1131
-#define PW_SEND_COA_TYPE               1132
-#define PW_MSCHAP_PASSWORD             1133
-#define PW_PACKET_TRANSMIT_COUNTER             1134
-#define PW_CACHED_SESSION_POLICY       1135
-
-/*
- *     Integer Translations
- */
-
-/*     User Types      */
-
-#define        PW_LOGIN_USER                   1
-#define        PW_FRAMED_USER                  2
-#define        PW_CALLBACK_LOGIN_USER          3
-#define        PW_CALLBACK_FRAMED_USER         4
-#define PW_OUTBOUND_USER               5
-#define PW_ADMINISTRATIVE_USER         6
-#define PW_NAS_PROMPT_USER             7
-#define PW_AUTHENTICATE_ONLY           8
-#define PW_CALLBACK_NAS_PROMPT         9
-
-/*     Framed Protocols        */
-
-#define        PW_PPP                          1
-#define        PW_SLIP                         2
-
-/*     Framed Routing Values   */
-
-#define        PW_NONE                         0
-#define        PW_BROADCAST                    1
-#define        PW_LISTEN                       2
-#define        PW_BROADCAST_LISTEN             3
-
-/*     Framed Compression Types        */
-
-#define        PW_VAN_JACOBSEN_TCP_IP          1
-
-/*     Login Services  */
-
-#define        PW_TELNET                       0
-#define        PW_RLOGIN                       1
-#define        PW_TCP_CLEAR                    2
-#define        PW_PORTMASTER                   3
-
-/*     Authentication Level    */
-
-#define PW_AUTHTYPE_LOCAL              0
-#define PW_AUTHTYPE_SYSTEM             1
-#define PW_AUTHTYPE_SECURID            2
-#define PW_AUTHTYPE_CRYPT              3
-#define PW_AUTHTYPE_REJECT             4
-#define PW_AUTHTYPE_ACTIVCARD          5
-#define PW_AUTHTYPE_EAP                 6
-#define PW_AUTHTYPE_ACCEPT             254
-#define PW_AUTHTYPE_MS_CHAP            1028
-
-/*     Port Types              */
-
-#define PW_NAS_PORT_ASYNC              0
-#define PW_NAS_PORT_SYNC               1
-#define PW_NAS_PORT_ISDN               2
-#define PW_NAS_PORT_ISDN_V120          3
-#define PW_NAS_PORT_ISDN_V110          4
-
-/*     Status Types    */
-
-#define PW_STATUS_START                        1
-#define PW_STATUS_STOP                 2
-#define PW_STATUS_ALIVE                        3
-#define PW_STATUS_ACCOUNTING_ON                7
-#define PW_STATUS_ACCOUNTING_OFF       8
-
-/*
- *  Vendor Private Enterprise Codes
- */
-#define VENDORPEC_FREERADIUS   11344
-
-
-/*
- * Vendor specific attributes
- */
-#define PW_FREERADIUS_PROXIED_TO       ((VENDORPEC_FREERADIUS<<16)|1)
-
-/*
- *  Microsoft has vendor code 311.
- */
-#define PW_MSCHAP_RESPONSE     ((311 << 16) | 1)
-#define PW_MSCHAP_ERROR                ((311 << 16) | 2)
-#define PW_MSCHAP_CHALLENGE    ((311 << 16) | 11)
-#define PW_MSCHAP2_RESPONSE    ((311 << 16) | 25)
-#define PW_MSCHAP2_SUCCESS     ((311 << 16) | 26)
-
-
-/*
- *  Old nonsense.  Will be deleted ASAP
- */
-#define PW_AUTHTYPE                    1000
-#define PW_AUTZTYPE                    1011
-#define PW_ACCTTYPE                    1012
-#define PW_SESSTYPE                    1013
-#define PW_POSTAUTHTYPE                        1014
-
-/*
- *     Cisco's VLAN Query Protocol.
- */
-#define PW_VQP_PACKET_TYPE             0x2b00
-#define PW_VQP_ERROR_CODE              0x2b01
-#define PW_VQP_SEQUENCE_NUMBER         0x2b02
-
-#define PW_VQP_CLIENT_IP_ADDRESS        0x2c01
-#define PW_VQP_PORT_NAME               0x2c02
-#define PW_VQP_VLAN_NAME               0x2c03
-#define PW_VQP_DOMAIN_NAME             0x2c04
-#define PW_VQP_ETHERNET_FRAME          0x2c05
-#define PW_VQP_MAC                     0x2c06
-#define PW_VQP_UNKNOWN                 0x2c07
-#define PW_VQP_COOKIE                  0x2c08
diff --git a/projects/rlm_stg/radiusd.h b/projects/rlm_stg/radiusd.h
deleted file mode 100644 (file)
index 4cbf403..0000000
+++ /dev/null
@@ -1,636 +0,0 @@
-#ifndef RADIUSD_H
-#define RADIUSD_H
-/*
- * radiusd.h   Structures, prototypes and global variables
- *             for the FreeRADIUS server.
- *
- * Version:    $Id: radiusd.h,v 1.1 2010/08/14 04:13:52 faust Exp $
- *
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation; either version 2 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program; if not, write to the Free Software
- *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
- *
- * Copyright 1999,2000,2002,2003,2004,2005,2006,2007,2008  The FreeRADIUS server project
- *
- */
-
-//#include <freeradius/ident.h>
-//RCSIDH(radiusd_h, "$Id: radiusd.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#include "libradius.h"
-//#include <freeradius/radpaths.h>
-//#include "conf.h"
-#include "conffile.h"
-#include "event.h"
-
-typedef struct auth_req REQUEST;
-
-#ifdef HAVE_PTHREAD_H
-#include       <pthread.h>
-#endif
-
-#ifndef NDEBUG
-#define REQUEST_MAGIC (0xdeadbeef)
-#endif
-
-/*
- *     New defines for minimizing the size of the server, to strip
- *     out functionality.  In order to ensure that people don't have
- *     to re-run "configure", after "cvs update", we play some
- *     special games with the defines.  i.e. any top-level "configure"
- *     option should set both WITH_FOO and WITHOUT_FOO.  After a few
- *     weeks, the WITHOUT_FOO can be deleted from the configure script.
- */
-#ifndef WITHOUT_PROXY
-#define WITH_PROXY (1)
-#endif
-
-#ifndef WITHOUT_DETAIL
-#define WITH_DETAIL (1)
-#endif
-
-#ifndef WITHOUT_SESSION_MGMT
-#define WITH_SESSION_MGMT (1)
-#endif
-
-#ifndef WITHOUT_UNLANG
-#define WITH_UNLANG (1)
-#endif
-
-#ifndef WITHOUT_ACCOUNTING
-#define WITH_ACCOUNTING (1)
-#else
-#ifdef WITH_SESSION_MGMT
-#error WITH_SESSION_MGMT is defined, but WITH_ACCOUNTING is not.  Session management requires accounting.
-#endif
-#ifdef WITH_DETAIL
-#error WITH_DETAIL is defined, but WITH_ACCOUNTING is not.  Detail file reading requires accounting.
-#endif
-#endif
-
-#ifndef WITHOUT_DYNAMIC_CLIENTS
-#define WITH_DYNAMIC_CLIENTS (1)
-#endif
-
-#ifndef WITHOUT_STATS
-#define WITH_STATS
-#endif
-
-#ifndef WITHOUT_COMMAND_SOCKET
-#ifdef HAVE_SYS_UN_H
-#define WITH_COMMAND_SOCKET (1)
-#endif
-#endif
-
-#ifndef WITHOUT_COA
-#define WITH_COA (1)
-#ifndef WITH_PROXY
-#error WITH_COA requires WITH_PROXY
-#endif
-#endif
-
-#include "stats.h"
-/*#include "realms.h"*/
-
-
-/*
- *     See util.c
- */
-typedef struct request_data_t request_data_t;
-
-typedef struct radclient {
-       fr_ipaddr_t             ipaddr;
-       int                     prefix;
-       char                    *longname;
-       char                    *secret;
-       char                    *shortname;
-       int                     message_authenticator;
-       char                    *nastype;
-       char                    *login;
-       char                    *password;
-       char                    *server;
-       int                     number;
-       const CONF_SECTION      *cs;
-#ifdef WITH_STATS
-       fr_stats_t              *auth;
-#ifdef WITH_ACCOUNTING
-       fr_stats_t              *acct;
-#endif
-#endif
-
-#ifdef WITH_DYNAMIC_CLIENTS
-       int                     lifetime;
-       int                     dynamic;
-       time_t                  created;
-       time_t                  last_new_client;
-       char                    *client_server;
-#endif
-} RADCLIENT;
-
-/*
- *     Types of listeners.
- *
- *     Ordered by priority!
- */
-typedef enum RAD_LISTEN_TYPE {
-       RAD_LISTEN_NONE = 0,
-#ifdef WITH_PROXY
-       RAD_LISTEN_PROXY,
-#endif
-       RAD_LISTEN_AUTH,
-#ifdef WITH_ACCOUNTING
-       RAD_LISTEN_ACCT,
-#endif
-#ifdef WITH_DETAIL
-       RAD_LISTEN_DETAIL,
-#endif
-#ifdef WITH_VMPS
-       RAD_LISTEN_VQP,
-#endif
-#ifdef WITH_DHCP
-       RAD_LISTEN_DHCP,
-#endif
-#ifdef WITH_COMMAND_SOCKET
-       RAD_LISTEN_COMMAND,
-#endif
-#ifdef WITH_COA
-       RAD_LISTEN_COA,
-#endif
-       RAD_LISTEN_MAX
-} RAD_LISTEN_TYPE;
-
-#if defined(FREE_BSD) || defined(FREE_BSD5)
-#include <sys/time.h>
-#endif
-
-/*
- *     For listening on multiple IP's and ports.
- */
-typedef struct rad_listen_t rad_listen_t;
-typedef                void (*radlog_func_t)(int, int, REQUEST *, const char *, ...);
-
-#define REQUEST_DATA_REGEX (0xadbeef00)
-#define REQUEST_MAX_REGEX (8)
-
-struct auth_req {
-#ifndef NDEBUG
-       uint32_t                magic; /* for debugging only */
-#endif
-       RADIUS_PACKET           *packet;
-#ifdef WITH_PROXY
-       RADIUS_PACKET           *proxy;
-#endif
-       RADIUS_PACKET           *reply;
-#ifdef WITH_PROXY
-       RADIUS_PACKET           *proxy_reply;
-#endif
-       VALUE_PAIR              *config_items;
-       VALUE_PAIR              *username;
-       VALUE_PAIR              *password;
-
-       struct main_config_t    *root;
-
-       request_data_t          *data;
-       RADCLIENT               *client;
-#ifdef HAVE_PTHREAD_H
-       pthread_t               child_pid;
-#endif
-       time_t                  timestamp;
-       int                     number; /* internal server number */
-
-       rad_listen_t            *listener;
-#ifdef WITH_PROXY
-       rad_listen_t            *proxy_listener;
-#endif
-
-
-       int                     simul_max; /* see modcall.c && xlat.c */
-#ifdef WITH_SESSION_MGMT
-       int                     simul_count;
-       int                     simul_mpp; /* WEIRD: 1 is false, 2 is true */
-#endif
-
-       int                     options; /* miscellanous options */
-       const char              *module; /* for debugging unresponsive children */
-       const char              *component; /* ditto */
-
-       struct timeval          received;
-       struct timeval          when;           /* to wake up */
-       int                     delay;
-
-       int                     master_state;
-       int                     child_state;
-       RAD_LISTEN_TYPE         priority;
-
-       fr_event_t              *ev;
-       struct timeval          next_when;
-       fr_event_callback_t     next_callback;
-
-       int                     in_request_hash;
-
-       const char              *server;
-       REQUEST                 *parent;
-       radlog_func_t           radlog; /* logging function, if set */
-#ifdef WITH_COA
-       REQUEST                 *coa;
-       int                     num_coa_requests;
-#endif
-};                             /* REQUEST typedef */
-
-#define RAD_REQUEST_OPTION_NONE            (0)
-#define RAD_REQUEST_OPTION_DEBUG           (1)
-#define RAD_REQUEST_OPTION_DEBUG2          (2)
-#define RAD_REQUEST_OPTION_DEBUG3          (3)
-#define RAD_REQUEST_OPTION_DEBUG4          (4)
-
-#define REQUEST_ACTIVE                 (1)
-#define REQUEST_STOP_PROCESSING (2)
-#define REQUEST_COUNTED                (3)
-
-#define REQUEST_QUEUED         (1)
-#define REQUEST_RUNNING                (2)
-#define REQUEST_PROXIED                (3)
-#define REQUEST_REJECT_DELAY   (4)
-#define REQUEST_CLEANUP_DELAY  (5)
-#define REQUEST_DONE           (6)
-
-/*
- *  Function handler for requests.
- */
-typedef                int (*RAD_REQUEST_FUNP)(REQUEST *);
-
-typedef struct radclient_list RADCLIENT_LIST;
-
-typedef struct pair_list {
-       const char              *name;
-       VALUE_PAIR              *check;
-       VALUE_PAIR              *reply;
-       int                     lineno;
-       int                     order;
-       struct pair_list        *next;
-       struct pair_list        *lastdefault;
-} PAIR_LIST;
-
-
-typedef int (*rad_listen_recv_t)(rad_listen_t *, RAD_REQUEST_FUNP *, REQUEST **);
-typedef int (*rad_listen_send_t)(rad_listen_t *, REQUEST *);
-typedef int (*rad_listen_print_t)(rad_listen_t *, char *, size_t);
-typedef int (*rad_listen_encode_t)(rad_listen_t *, REQUEST *);
-typedef int (*rad_listen_decode_t)(rad_listen_t *, REQUEST *);
-
-struct rad_listen_t {
-       struct rad_listen_t *next; /* should be rbtree stuff */
-
-       /*
-        *      For normal sockets.
-        */
-       RAD_LISTEN_TYPE type;
-       int             fd;
-       const char      *server;
-       int             status;
-
-       rad_listen_recv_t recv;
-       rad_listen_send_t send;
-       rad_listen_encode_t encode;
-       rad_listen_decode_t decode;
-       rad_listen_print_t print;
-
-       void            *data;
-
-#ifdef WITH_STATS
-       fr_stats_t      stats;
-#endif
-};
-
-#define RAD_LISTEN_STATUS_INIT   (0)
-#define RAD_LISTEN_STATUS_KNOWN  (1)
-#define RAD_LISTEN_STATUS_CLOSED (2)
-#define RAD_LISTEN_STATUS_FINISH (3)
-
-typedef enum radlog_dest_t {
-  RADLOG_STDOUT = 0,
-  RADLOG_FILES,
-  RADLOG_SYSLOG,
-  RADLOG_STDERR,
-  RADLOG_NULL,
-  RADLOG_NUM_DEST
-} radlog_dest_t;
-
-typedef struct main_config_t {
-       struct main_config *next;
-       int             refcount;
-       fr_ipaddr_t     myip;   /* from the command-line only */
-       int             port;   /* from the command-line only */
-       int             log_auth;
-       int             log_auth_badpass;
-       int             log_auth_goodpass;
-       int             allow_core_dumps;
-       int             debug_level;
-       int             proxy_requests;
-       int             reject_delay;
-       int             status_server;
-       int             max_request_time;
-       int             cleanup_delay;
-       int             max_requests;
-#ifdef DELETE_BLOCKED_REQUESTS
-       int             kill_unresponsive_children;
-#endif
-       char            *log_file;
-       char            *checkrad;
-       const char      *pid_file;
-       rad_listen_t    *listen;
-       int             syslog_facility;
-       int             radlog_fd;
-       radlog_dest_t   radlog_dest;
-       CONF_SECTION    *config;
-       const char      *name;
-       const char      *auth_badpass_msg;
-       const char      *auth_goodpass_msg;
-} MAIN_CONFIG_T;
-
-#define DEBUG  if(debug_flag)log_debug
-#define DEBUG2  if (debug_flag > 1)log_debug
-#define DEBUG3  if (debug_flag > 2)log_debug
-#define DEBUG4  if (debug_flag > 3)log_debug
-
-#if __GNUC__ >= 3
-#define RDEBUG(fmt, ...)   if(request && request->radlog) request->radlog(L_DBG, 1, request, fmt, ## __VA_ARGS__)
-#define RDEBUG2(fmt, ...)  if(request && request->radlog) request->radlog(L_DBG, 2, request, fmt, ## __VA_ARGS__)
-#define RDEBUG3(fmt, ...)  if(request && request->radlog) request->radlog(L_DBG, 3, request, fmt, ## __VA_ARGS__)
-#define RDEBUG4(fmt, ...)  if(request && request->radlog) request->radlog(L_DBG, 4, request, fmt, ## __VA_ARGS__)
-#else
-#define RDEBUG  DEBUG
-#define RDEBUG2 DEBUG2
-#define RDEBUG3 DEBUG3
-#define RDEBUG4 DEBUG4
-#endif
-
-#define SECONDS_PER_DAY                86400
-#define MAX_REQUEST_TIME       30
-#define CLEANUP_DELAY          5
-#define MAX_REQUESTS           256
-#define RETRY_DELAY             5
-#define RETRY_COUNT             3
-#define DEAD_TIME               120
-
-#define L_DBG                  1
-#define L_AUTH                 2
-#define L_INFO                 3
-#define L_ERR                  4
-#define L_PROXY                        5
-#define L_ACCT                 6
-#define L_CONS                 128
-
-#ifndef FALSE
-#define FALSE 0
-#endif
-#ifndef TRUE
-/*
- *     This definition of true as NOT false is definitive. :) Making
- *     it '1' can cause problems on stupid platforms.  See articles
- *     on C portability for more information.
- */
-#define TRUE (!FALSE)
-#endif
-
-/* for paircompare_register */
-typedef int (*RAD_COMPARE_FUNC)(void *instance, REQUEST *,VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **);
-
-typedef enum request_fail_t {
-  REQUEST_FAIL_UNKNOWN = 0,
-  REQUEST_FAIL_NO_THREADS,     /* no threads to handle it */
-  REQUEST_FAIL_DECODE,         /* rad_decode didn't like it */
-  REQUEST_FAIL_PROXY,          /* call to proxy modules failed */
-  REQUEST_FAIL_PROXY_SEND,     /* proxy_send didn't like it */
-  REQUEST_FAIL_NO_RESPONSE,    /* we weren't told to respond, so we reject */
-  REQUEST_FAIL_HOME_SERVER,    /* the home server didn't respond */
-  REQUEST_FAIL_HOME_SERVER2,   /* another case of the above */
-  REQUEST_FAIL_HOME_SERVER3,   /* another case of the above */
-  REQUEST_FAIL_NORMAL_REJECT,  /* authentication failure */
-  REQUEST_FAIL_SERVER_TIMEOUT  /* the server took too long to process the request */
-} request_fail_t;
-
-/*
- *     Global variables.
- *
- *     We really shouldn't have this many.
- */
-extern const char      *progname;
-extern int             debug_flag;
-extern const char      *radacct_dir;
-extern const char      *radlog_dir;
-extern const char      *radlib_dir;
-extern const char      *radius_dir;
-extern const char      *radius_libdir;
-extern uint32_t                expiration_seconds;
-extern int             log_stripped_names;
-extern int             log_auth_detail;
-extern const char      *radiusd_version;
-void                   radius_signal_self(int flag);
-
-#define RADIUS_SIGNAL_SELF_NONE                (0)
-#define RADIUS_SIGNAL_SELF_HUP         (1 << 0)
-#define RADIUS_SIGNAL_SELF_TERM                (1 << 1)
-#define RADIUS_SIGNAL_SELF_EXIT                (1 << 2)
-#define RADIUS_SIGNAL_SELF_DETAIL      (1 << 3)
-#define RADIUS_SIGNAL_SELF_NEW_FD      (1 << 4)
-#define RADIUS_SIGNAL_SELF_MAX         (1 << 5)
-
-
-/*
- *     Function prototypes.
- */
-
-/* acct.c */
-int            rad_accounting(REQUEST *);
-
-/* session.c */
-int            rad_check_ts(uint32_t nasaddr, unsigned int port, const char *user,
-                            const char *sessionid);
-int            session_zap(REQUEST *request, uint32_t nasaddr,
-                           unsigned int port, const char *user,
-                           const char *sessionid, uint32_t cliaddr,
-                           char proto,int session_time);
-
-/* radiusd.c */
-#undef debug_pair
-void           debug_pair(VALUE_PAIR *);
-void           debug_pair_list(VALUE_PAIR *);
-int            log_err (char *);
-
-/* util.c */
-void (*reset_signal(int signo, void (*func)(int)))(int);
-void           request_free(REQUEST **request);
-int            rad_mkdir(char *directory, int mode);
-int            rad_checkfilename(const char *filename);
-void           *rad_malloc(size_t size); /* calls exit(1) on error! */
-REQUEST                *request_alloc(void);
-REQUEST                *request_alloc_fake(REQUEST *oldreq);
-REQUEST                *request_alloc_coa(REQUEST *request);
-int            request_data_add(REQUEST *request,
-                                void *unique_ptr, int unique_int,
-                                void *opaque, void (*free_opaque)(void *));
-void           *request_data_get(REQUEST *request,
-                                 void *unique_ptr, int unique_int);
-void           *request_data_reference(REQUEST *request,
-                                 void *unique_ptr, int unique_int);
-int            rad_copy_string(char *dst, const char *src);
-int            rad_copy_variable(char *dst, const char *from);
-
-/* client.c */
-RADCLIENT_LIST *clients_init(void);
-void           clients_free(RADCLIENT_LIST *clients);
-RADCLIENT_LIST *clients_parse_section(CONF_SECTION *section);
-void           client_free(RADCLIENT *client);
-int            client_add(RADCLIENT_LIST *clients, RADCLIENT *client);
-#ifdef WITH_DYNAMIC_CLIENTS
-void           client_delete(RADCLIENT_LIST *clients, RADCLIENT *client);
-RADCLIENT      *client_create(RADCLIENT_LIST *clients, REQUEST *request);
-#endif
-RADCLIENT      *client_find(const RADCLIENT_LIST *clients,
-                            const fr_ipaddr_t *ipaddr);
-RADCLIENT      *client_findbynumber(const RADCLIENT_LIST *clients,
-                                    int number);
-RADCLIENT      *client_find_old(const fr_ipaddr_t *ipaddr);
-int            client_validate(RADCLIENT_LIST *clients, RADCLIENT *master,
-                               RADCLIENT *c);
-RADCLIENT      *client_read(const char *filename, int in_server, int flag);
-
-
-/* files.c */
-int            pairlist_read(const char *file, PAIR_LIST **list, int complain);
-void           pairlist_free(PAIR_LIST **);
-
-/* version.c */
-void           version(void);
-
-/* log.c */
-int            vradlog(int, const char *, va_list ap);
-int            radlog(int, const char *, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 2, 3)))
-#endif
-;
-int            log_debug(const char *, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 1, 2)))
-#endif
-;
-void           vp_listdebug(VALUE_PAIR *vp);
-void radlog_request(int lvl, int priority, REQUEST *request, const char *msg, ...)
-#ifdef __GNUC__
-               __attribute__ ((format (printf, 4, 5)))
-#endif
-;
-
-/* auth.c */
-char   *auth_name(char *buf, size_t buflen, REQUEST *request, int do_cli);
-int            rad_authenticate (REQUEST *);
-int            rad_postauth(REQUEST *);
-
-/* exec.c */
-int            radius_exec_program(const char *,  REQUEST *, int,
-                                   char *user_msg, int msg_len,
-                                   VALUE_PAIR *input_pairs,
-                                   VALUE_PAIR **output_pairs,
-                                       int shell_escape);
-
-/* timestr.c */
-int            timestr_match(char *, time_t);
-
-/* valuepair.c */
-int            paircompare_register(int attr, int otherattr,
-                                    RAD_COMPARE_FUNC func,
-                                    void *instance);
-void           paircompare_unregister(int attr, RAD_COMPARE_FUNC func);
-int            paircompare(REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check,
-                           VALUE_PAIR **reply);
-void           pairxlatmove(REQUEST *, VALUE_PAIR **to, VALUE_PAIR **from);
-int radius_compare_vps(REQUEST *request, VALUE_PAIR *check, VALUE_PAIR *vp);
-int radius_callback_compare(REQUEST *req, VALUE_PAIR *request,
-                           VALUE_PAIR *check, VALUE_PAIR *check_pairs,
-                           VALUE_PAIR **reply_pairs);
-int radius_find_compare(int attribute);
-VALUE_PAIR     *radius_paircreate(REQUEST *request, VALUE_PAIR **vps,
-                                 int attribute, int type);
-VALUE_PAIR *radius_pairmake(REQUEST *request, VALUE_PAIR **vps,
-                           const char *attribute, const char *value,
-                           int _operator);
-
-/* xlat.c */
-typedef size_t (*RADIUS_ESCAPE_STRING)(char *out, size_t outlen, const char *in);
-
-int            radius_xlat(char * out, int outlen, const char *fmt,
-                          REQUEST * request, RADIUS_ESCAPE_STRING func);
-typedef size_t (*RAD_XLAT_FUNC)(void *instance, REQUEST *, char *, char *, size_t, RADIUS_ESCAPE_STRING func);
-int            xlat_register(const char *module, RAD_XLAT_FUNC func,
-                             void *instance);
-void           xlat_unregister(const char *module, RAD_XLAT_FUNC func);
-void           xlat_free(void);
-
-/* threads.c */
-extern         int thread_pool_init(CONF_SECTION *cs, int *spawn_flag);
-extern         int thread_pool_addrequest(REQUEST *, RAD_REQUEST_FUNP);
-extern         pid_t rad_fork(void);
-extern         pid_t rad_waitpid(pid_t pid, int *status);
-extern          int total_active_threads(void);
-extern          void thread_pool_lock(void);
-extern          void thread_pool_unlock(void);
-extern         void thread_pool_queue_stats(int *array);
-
-#ifndef HAVE_PTHREAD_H
-#define rad_fork(n) fork()
-#define rad_waitpid(a,b) waitpid(a,b, 0)
-#endif
-
-/* mainconfig.c */
-/* Define a global config structure */
-extern struct main_config_t mainconfig;
-
-int read_mainconfig(int reload);
-int free_mainconfig(void);
-void hup_mainconfig(void);
-void fr_suid_down(void);
-void fr_suid_up(void);
-void fr_suid_down_permanent(void);
-
-/* listen.c */
-void listen_free(rad_listen_t **head);
-int listen_init(CONF_SECTION *cs, rad_listen_t **head);
-rad_listen_t *proxy_new_listener(fr_ipaddr_t *ipaddr, int exists);
-RADCLIENT *client_listener_find(const rad_listen_t *listener,
-                               const fr_ipaddr_t *ipaddr, int src_port);
-#ifdef WITH_STATS
-RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
-                                         int port);
-rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port);
-#endif
-
-/* event.c */
-int radius_event_init(CONF_SECTION *cs, int spawn_flag);
-void radius_event_free(void);
-int radius_event_process(void);
-void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun);
-int received_request(rad_listen_t *listener,
-                    RADIUS_PACKET *packet, REQUEST **prequest,
-                    RADCLIENT *client);
-REQUEST *received_proxy_response(RADIUS_PACKET *packet);
-void event_new_fd(rad_listen_t *listener);
-
-/* evaluate.c */
-int radius_evaluate_condition(REQUEST *request, int modreturn, int depth,
-                             const char **ptr, int evaluate_it, int *presult);
-int radius_update_attrlist(REQUEST *request, CONF_SECTION *cs,
-                          VALUE_PAIR *input_vps, const char *name);
-void radius_pairmove(REQUEST *request, VALUE_PAIR **to, VALUE_PAIR *from);
-#endif /*RADIUSD_H*/
diff --git a/projects/rlm_stg/rlm_stg.c b/projects/rlm_stg/rlm_stg.c
new file mode 100644 (file)
index 0000000..3eb913d
--- /dev/null
@@ -0,0 +1,360 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+/*
+ *  FreeRADIUS module for data access via Stargazer
+ *
+ *  $Revision: 1.8 $
+ *  $Date: 2010/08/14 04:15:08 $
+ *
+ */
+
+#ifndef NDEBUG
+#define NDEBUG
+#include <freeradius/ident.h>
+#include <freeradius/radiusd.h>
+#include <freeradius/modules.h>
+#undef NDEBUG
+#endif
+
+#include "stgpair.h"
+#include "iface.h"
+
+typedef struct rlm_stg_t {
+    char * server;
+    uint16_t port;
+    char * password;
+} rlm_stg_t;
+
+static const CONF_PARSER module_config[] = {
+  { "server",  PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,server), NULL,  "localhost"},
+  { "port",  PW_TYPE_INTEGER,     offsetof(rlm_stg_t,port), NULL,  "9091" },
+  { "password",  PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,password), NULL,  "123456"},
+
+  { NULL, -1, 0, NULL, NULL }        /* end the list */
+};
+
+int emptyPair(const STG_PAIR * pair);
+
+/*
+ *    Do any per-module initialization that is separate to each
+ *    configured instance of the module.  e.g. set up connections
+ *    to external databases, read configuration files, set up
+ *    dictionary entries, etc.
+ *
+ *    If configuration information is given in the config section
+ *    that must be referenced in later calls, store a handle to it
+ *    in *instance otherwise put a null pointer there.
+ */
+static int stg_instantiate(CONF_SECTION *conf, void **instance)
+{
+    rlm_stg_t *data;
+
+    /*
+     *    Set up a storage area for instance data
+     */
+    data = rad_malloc(sizeof(*data));
+    if (!data) {
+        return -1;
+    }
+    memset(data, 0, sizeof(*data));
+
+    /*
+     *    If the configuration parameters can't be parsed, then
+     *    fail.
+     */
+    if (cf_section_parse(conf, data, module_config) < 0) {
+        free(data);
+        return -1;
+    }
+
+    if (!stgInstantiateImpl(data->server, data->port)) {
+        free(data);
+        return -1;
+    }
+
+    *instance = data;
+
+    return 0;
+}
+
+/*
+ *    Find the named user in this modules database.  Create the set
+ *    of attribute-value pairs to check and reply with for this user
+ *    from the database. The authentication code only needs to check
+ *    the password, the rest is done here.
+ */
+static int stg_authorize(void *, REQUEST *request)
+{
+    VALUE_PAIR * pwd;
+    VALUE_PAIR * svc;
+    const STG_PAIR * pairs;
+    const STG_PAIR * pair;
+    size_t count = 0;
+
+    instance = instance;
+
+    DEBUG("rlm_stg: stg_authorize()");
+
+    if (request->username) {
+        DEBUG("rlm_stg: stg_authorize() request username field: '%s'", request->username->vp_strvalue);
+    }
+    if (request->password) {
+        DEBUG("rlm_stg: stg_authorize() request password field: '%s'", request->password->vp_strvalue);
+    }
+    // Here we need to define Framed-Protocol
+    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
+    if (svc) {
+        DEBUG("rlm_stg: stg_authorize() Service-Type defined as '%s'", svc->vp_strvalue);
+        pairs = stgAuthorizeImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue);
+    } else {
+        DEBUG("rlm_stg: stg_authorize() Service-Type undefined");
+        pairs = stgAuthorizeImpl((const char *)request->username->vp_strvalue, "");
+    }
+    if (!pairs) {
+        DEBUG("rlm_stg: stg_authorize() failed.");
+        return RLM_MODULE_REJECT;
+    }
+
+    pair = pairs;
+    while (!emptyPair(pair)) {
+        pwd = pairmake(pair->key, pair->value, T_OP_SET);
+        pairadd(&request->config_items, pwd);
+        DEBUG("Adding pair '%s': '%s'", pair->key, pair->value);
+        ++pair;
+        ++count;
+    }
+    deletePairs(pairs);
+
+    if (count)
+        return RLM_MODULE_UPDATED;
+
+    return RLM_MODULE_NOOP;
+}
+
+/*
+ *    Authenticate the user with the given password.
+ */
+static int stg_authenticate(void *, REQUEST *request)
+{
+    VALUE_PAIR * svc;
+    VALUE_PAIR * pwd;
+    const STG_PAIR * pairs;
+    const STG_PAIR * pair;
+    size_t count = 0;
+
+    instance = instance;
+
+    DEBUG("rlm_stg: stg_authenticate()");
+
+    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
+    if (svc) {
+        DEBUG("rlm_stg: stg_authenticate() Service-Type defined as '%s'", svc->vp_strvalue);
+        pairs = stgAuthenticateImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue);
+    } else {
+        DEBUG("rlm_stg: stg_authenticate() Service-Type undefined");
+        pairs = stgAuthenticateImpl((const char *)request->username->vp_strvalue, "");
+    }
+    if (!pairs) {
+        DEBUG("rlm_stg: stg_authenticate() failed.");
+        return RLM_MODULE_REJECT;
+    }
+
+    pair = pairs;
+    while (!emptyPair(pair)) {
+        pwd = pairmake(pair->key, pair->value, T_OP_SET);
+        pairadd(&request->reply->vps, pwd);
+        ++pair;
+        ++count;
+    }
+    deletePairs(pairs);
+
+    if (count)
+        return RLM_MODULE_UPDATED;
+
+    return RLM_MODULE_NOOP;
+}
+
+/*
+ *    Massage the request before recording it or proxying it
+ */
+static int stg_preacct(void *, REQUEST *)
+{
+    DEBUG("rlm_stg: stg_preacct()");
+
+    instance = instance;
+
+    return RLM_MODULE_OK;
+}
+
+/*
+ *    Write accounting information to this modules database.
+ */
+static int stg_accounting(void *, REQUEST * request)
+{
+    VALUE_PAIR * sttype;
+    VALUE_PAIR * svc;
+    VALUE_PAIR * sessid;
+    VALUE_PAIR * pwd;
+    const STG_PAIR * pairs;
+    const STG_PAIR * pair;
+    size_t count = 0;
+
+    instance = instance;
+
+    DEBUG("rlm_stg: stg_accounting()");
+
+    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
+    sessid = pairfind(request->packet->vps, PW_ACCT_SESSION_ID);
+    sttype = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE);
+
+    if (!sessid) {
+        DEBUG("rlm_stg: stg_accounting() Acct-Session-ID undefined");
+        return RLM_MODULE_FAIL;
+    }
+
+    if (sttype) {
+        DEBUG("Acct-Status-Type := %s", sttype->vp_strvalue);
+        if (svc) {
+            DEBUG("rlm_stg: stg_accounting() Service-Type defined as '%s'", svc->vp_strvalue);
+            pairs = stgAccountingImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue, (const char *)sttype->vp_strvalue, (const char *)sessid->vp_strvalue);
+        } else {
+            DEBUG("rlm_stg: stg_accounting() Service-Type undefined");
+            pairs = stgAccountingImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue, (const char *)sttype->vp_strvalue, (const char *)sessid->vp_strvalue);
+        }
+    } else {
+        DEBUG("rlm_stg: stg_accounting() Acct-Status-Type := NULL");
+        return RLM_MODULE_OK;
+    }
+    if (!pairs) {
+        DEBUG("rlm_stg: stg_accounting() failed.");
+        return RLM_MODULE_REJECT;
+    }
+
+    pair = pairs;
+    while (!emptyPair(pair)) {
+        pwd = pairmake(pair->key, pair->value, T_OP_SET);
+        pairadd(&request->reply->vps, pwd);
+        ++pair;
+        ++count;
+    }
+    deletePairs(pairs);
+
+    if (count)
+        return RLM_MODULE_UPDATED;
+
+    return RLM_MODULE_OK;
+}
+
+/*
+ *    See if a user is already logged in. Sets request->simul_count to the
+ *    current session count for this user and sets request->simul_mpp to 2
+ *    if it looks like a multilink attempt based on the requested IP
+ *    address, otherwise leaves request->simul_mpp alone.
+ *
+ *    Check twice. If on the first pass the user exceeds his
+ *    max. number of logins, do a second pass and validate all
+ *    logins by querying the terminal server (using eg. SNMP).
+ */
+static int stg_checksimul(void *, REQUEST *request)
+{
+    DEBUG("rlm_stg: stg_checksimul()");
+
+    instance = instance;
+
+    request->simul_count=0;
+
+    return RLM_MODULE_OK;
+}
+
+static int stg_postauth(void *, REQUEST *request)
+{
+    VALUE_PAIR * svc;
+    VALUE_PAIR * pwd;
+    const STG_PAIR * pairs;
+    const STG_PAIR * pair;
+    size_t count = 0;
+
+    instance = instance;
+
+    DEBUG("rlm_stg: stg_postauth()");
+
+    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
+
+    if (svc) {
+        DEBUG("rlm_stg: stg_postauth() Service-Type defined as '%s'", svc->vp_strvalue);
+        pairs = stgPostAuthImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue);
+    } else {
+        DEBUG("rlm_stg: stg_postauth() Service-Type undefined");
+        pairs = stgPostAuthImpl((const char *)request->username->vp_strvalue, "");
+    }
+    if (!pairs) {
+        DEBUG("rlm_stg: stg_postauth() failed.");
+        return RLM_MODULE_REJECT;
+    }
+
+    pair = pairs;
+    while (!emptyPair(pair)) {
+        pwd = pairmake(pair->key, pair->value, T_OP_SET);
+        pairadd(&request->reply->vps, pwd);
+        ++pair;
+        ++count;
+    }
+    deletePairs(pairs);
+
+    if (count)
+        return RLM_MODULE_UPDATED;
+
+    return RLM_MODULE_NOOP;
+}
+
+static int stg_detach(void *instance)
+{
+    free(((struct rlm_stg_t *)instance)->server);
+    free(instance);
+    return 0;
+}
+
+/*
+ *    The module name should be the only globally exported symbol.
+ *    That is, everything else should be 'static'.
+ *
+ *    If the module needs to temporarily modify it's instantiation
+ *    data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
+ *    The server will then take care of ensuring that the module
+ *    is single-threaded.
+ */
+module_t rlm_stg = {
+    RLM_MODULE_INIT,
+    "stg",
+    RLM_TYPE_THREAD_SAFE,        /* type */
+    stg_instantiate,        /* instantiation */
+    stg_detach,            /* detach */
+    {
+        stg_authenticate,    /* authentication */
+        stg_authorize,    /* authorization */
+        stg_preacct,    /* preaccounting */
+        stg_accounting,    /* accounting */
+        stg_checksimul,    /* checksimul */
+        NULL,            /* pre-proxy */
+        NULL,            /* post-proxy */
+        stg_postauth            /* post-auth */
+    },
+};
diff --git a/projects/rlm_stg/rlm_stg.cpp b/projects/rlm_stg/rlm_stg.cpp
deleted file mode 100644 (file)
index f93390c..0000000
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
- */
-
-/*
- *  FreeRADIUS module for data access via Stargazer
- *
- *  $Revision: 1.8 $
- *  $Date: 2010/08/14 04:15:08 $
- *
- */
-
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-
-#include <exception>
-
-extern "C" {
-#include "radius.h"
-#include "modules.h"
-}
-
-#include "stg_client.h"
-#include "stg/common.h"
-
-STG_CLIENT * cli;
-volatile time_t stgTime;
-
-/*
- *    Define a structure for our module configuration.
- *
- *    These variables do not need to be in a structure, but it's
- *    a lot cleaner to do so, and a pointer to the structure can
- *    be used as the instance handle.
- */
-typedef struct rlm_stg_t {
-    char * server;
-    char * password;
-    uint32_t port;
-    uint32_t localPort;
-} rlm_stg_t;
-
-/*
- *    A mapping of configuration file names to internal variables.
- *
- *    Note that the string is dynamically allocated, so it MUST
- *    be freed.  When the configuration file parse re-reads the string,
- *    it free's the old one, and strdup's the new one, placing the pointer
- *    to the strdup'd string into 'config.string'.  This gets around
- *    buffer over-flows.
- */
-static CONF_PARSER module_config[] = {
-  { "password",  PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,password), NULL,  NULL},
-  { "server",  PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,server), NULL,  NULL},
-  { "port",  PW_TYPE_INTEGER,     offsetof(rlm_stg_t,port), NULL,  "5555" },
-  { "local_port", PW_TYPE_INTEGER,    offsetof(rlm_stg_t,localPort), NULL,   "0" },
-
-  { NULL, -1, 0, NULL, NULL }        /* end the list */
-};
-
-/*
- *    Do any per-module initialization that is separate to each
- *    configured instance of the module.  e.g. set up connections
- *    to external databases, read configuration files, set up
- *    dictionary entries, etc.
- *
- *    If configuration information is given in the config section
- *    that must be referenced in later calls, store a handle to it
- *    in *instance otherwise put a null pointer there.
- */
-static int stg_instantiate(CONF_SECTION *conf, void **instance)
-{
-    rlm_stg_t *data;
-
-    /*
-     *    Set up a storage area for instance data
-     */
-    DEBUG("rlm_stg: stg_instantiate()");
-    data = (rlm_stg_t *)rad_malloc(sizeof(rlm_stg_t));
-    if (!data) {
-        return -1;
-    }
-    memset(data, 0, sizeof(rlm_stg_t));
-
-    /*
-     *    If the configuration parameters can't be parsed, then
-     *    fail.
-     */
-    if (cf_section_parse(conf, data, module_config) < 0) {
-        free(data);
-        return -1;
-    }
-
-    try {
-        cli = new STG_CLIENT(data->server, data->port, data->localPort, data->password);
-    }
-    catch (std::exception & ex) {
-        DEBUG("rlm_stg: stg_instantiate() error: '%s'", ex.what());
-        return -1;
-    }
-
-    *instance = data;
-
-    return 0;
-}
-
-/*
- *    Find the named user in this modules database.  Create the set
- *    of attribute-value pairs to check and reply with for this user
- *    from the database. The authentication code only needs to check
- *    the password, the rest is done here.
- */
-static int stg_authorize(void *, REQUEST *request)
-{
-    VALUE_PAIR *uname;
-    VALUE_PAIR *pwd;
-    VALUE_PAIR *svc;
-    DEBUG("rlm_stg: stg_authorize()");
-
-    uname = pairfind(request->packet->vps, PW_USER_NAME);
-    if (uname) {
-        DEBUG("rlm_stg: stg_authorize() user name defined as '%s'", uname->vp_strvalue);
-    } else {
-        DEBUG("rlm_stg: stg_authorize() user name undefined");
-        return RLM_MODULE_FAIL;
-    }
-    if (request->username) {
-        DEBUG("rlm_stg: stg_authorize() request username field: '%s'", request->username->vp_strvalue);
-    }
-    if (request->password) {
-        DEBUG("rlm_stg: stg_authorize() request password field: '%s'", request->password->vp_strvalue);
-    }
-    // Here we need to define Framed-Protocol
-    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
-    if (svc) {
-        DEBUG("rlm_stg: stg_authorize() Service-Type defined as '%s'", svc->vp_strvalue);
-        if (cli->Authorize((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue)) {
-            DEBUG("rlm_stg: stg_authorize() stg status: '%s'", cli->GetError().c_str());
-            return RLM_MODULE_REJECT;
-        }
-    } else {
-        DEBUG("rlm_stg: stg_authorize() Service-Type undefined");
-        if (cli->Authorize((const char *)request->username->vp_strvalue, "")) {
-            DEBUG("rlm_stg: stg_authorize() stg status: '%s'", cli->GetError().c_str());
-            return RLM_MODULE_REJECT;
-        }
-    }
-    pwd = pairmake("Cleartext-Password", cli->GetUserPassword().c_str(), T_OP_SET);
-    pairadd(&request->config_items, pwd);
-    //pairadd(&request->reply->vps, uname);
-
-    return RLM_MODULE_UPDATED;
-}
-
-/*
- *    Authenticate the user with the given password.
- */
-static int stg_authenticate(void *, REQUEST *request)
-{
-    /* quiet the compiler */
-    VALUE_PAIR *svc;
-
-    DEBUG("rlm_stg: stg_authenticate()");
-
-    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
-    if (svc) {
-        DEBUG("rlm_stg: stg_authenticate() Service-Type defined as '%s'", svc->vp_strvalue);
-        if (cli->Authenticate((char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue)) {
-            DEBUG("rlm_stg: stg_authenticate() stg status: '%s'", cli->GetError().c_str());
-            return RLM_MODULE_REJECT;
-        }
-    } else {
-        DEBUG("rlm_stg: stg_authenticate() Service-Type undefined");
-        if (cli->Authenticate((char *)request->username->vp_strvalue, "")) {
-            DEBUG("rlm_stg: stg_authenticate() stg status: '%s'", cli->GetError().c_str());
-            return RLM_MODULE_REJECT;
-        }
-    }
-
-    return RLM_MODULE_NOOP;
-}
-
-/*
- *    Massage the request before recording it or proxying it
- */
-static int stg_preacct(void *, REQUEST *)
-{
-    DEBUG("rlm_stg: stg_preacct()");
-
-    return RLM_MODULE_OK;
-}
-
-/*
- *    Write accounting information to this modules database.
- */
-static int stg_accounting(void *, REQUEST * request)
-{
-    /* quiet the compiler */
-    VALUE_PAIR * sttype;
-    VALUE_PAIR * svc;
-    VALUE_PAIR * sessid;
-    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
-
-    DEBUG("rlm_stg: stg_accounting()");
-
-    sessid = pairfind(request->packet->vps, PW_ACCT_SESSION_ID);
-    if (!sessid) {
-        DEBUG("rlm_stg: stg_accounting() Acct-Session-ID undefined");
-        return RLM_MODULE_FAIL;
-    }
-    sttype = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE);
-    if (sttype) {
-        DEBUG("Acct-Status-Type := %s", sttype->vp_strvalue);
-        if (svc) {
-            DEBUG("rlm_stg: stg_accounting() Service-Type defined as '%s'", svc->vp_strvalue);
-            if (cli->Account((const char *)sttype->vp_strvalue, (const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue, (const char *)sessid->vp_strvalue)) {
-                DEBUG("rlm_stg: stg_accounting error: '%s'", cli->GetError().c_str());
-                return RLM_MODULE_FAIL;
-            }
-        } else {
-            DEBUG("rlm_stg: stg_accounting() Service-Type undefined");
-            if (cli->Account((const char *)sttype->vp_strvalue, (const char *)request->username->vp_strvalue, "", (const char *)sessid->vp_strvalue)) {
-                DEBUG("rlm_stg: stg_accounting error: '%s'", cli->GetError().c_str());
-                return RLM_MODULE_FAIL;
-            }
-        }
-    } else {
-        DEBUG("Acct-Status-Type := NULL");
-    }
-
-    return RLM_MODULE_OK;
-}
-
-/*
- *    See if a user is already logged in. Sets request->simul_count to the
- *    current session count for this user and sets request->simul_mpp to 2
- *    if it looks like a multilink attempt based on the requested IP
- *    address, otherwise leaves request->simul_mpp alone.
- *
- *    Check twice. If on the first pass the user exceeds his
- *    max. number of logins, do a second pass and validate all
- *    logins by querying the terminal server (using eg. SNMP).
- */
-static int stg_checksimul(void *, REQUEST *request)
-{
-    DEBUG("rlm_stg: stg_checksimul()");
-
-    request->simul_count=0;
-
-    return RLM_MODULE_OK;
-}
-
-static int stg_postauth(void *, REQUEST *request)
-{
-    VALUE_PAIR *fia;
-    VALUE_PAIR *svc;
-    struct in_addr fip;
-    DEBUG("rlm_stg: stg_postauth()");
-    svc = pairfind(request->packet->vps, PW_SERVICE_TYPE);
-    if (svc) {
-        DEBUG("rlm_stg: stg_postauth() Service-Type defined as '%s'", svc->vp_strvalue);
-        if (cli->PostAuthenticate((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue)) {
-            DEBUG("rlm_stg: stg_postauth() error: '%s'", cli->GetError().c_str());
-            return RLM_MODULE_FAIL;
-        }
-    } else {
-        DEBUG("rlm_stg: stg_postauth() Service-Type undefined");
-        if (cli->PostAuthenticate((const char *)request->username->vp_strvalue, "")) {
-            DEBUG("rlm_stg: stg_postauth() error: '%s'", cli->GetError().c_str());
-            return RLM_MODULE_FAIL;
-        }
-    }
-    if (strncmp((const char *)svc->vp_strvalue, "Framed-User", 11) == 0) {
-        fip.s_addr = cli->GetFramedIP();
-        DEBUG("rlm_stg: stg_postauth() ip = '%s'", inet_ntostring(fip.s_addr).c_str());
-        fia = pairmake("Framed-IP-Address", inet_ntostring(fip.s_addr).c_str(), T_OP_SET);
-        pairadd(&request->reply->vps, fia);
-    }
-
-    return RLM_MODULE_UPDATED;
-}
-
-static int stg_detach(void *instance)
-{
-    DEBUG("rlm_stg: stg_detach()");
-    delete cli;
-    free(((struct rlm_stg_t *)instance)->server);
-    free(((struct rlm_stg_t *)instance)->password);
-    free(instance);
-    return 0;
-}
-
-/*
- *    The module name should be the only globally exported symbol.
- *    That is, everything else should be 'static'.
- *
- *    If the module needs to temporarily modify it's instantiation
- *    data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
- *    The server will then take care of ensuring that the module
- *    is single-threaded.
- */
-module_t rlm_stg = {
-    RLM_MODULE_INIT,
-    "stg",
-    RLM_TYPE_THREAD_SAFE,        /* type */
-    stg_instantiate,        /* instantiation */
-    stg_detach,            /* detach */
-    {
-        stg_authenticate,    /* authentication */
-        stg_authorize,    /* authorization */
-        stg_preacct,    /* preaccounting */
-        stg_accounting,    /* accounting */
-        stg_checksimul,    /* checksimul */
-        NULL,            /* pre-proxy */
-        NULL,            /* post-proxy */
-        stg_postauth            /* post-auth */
-    },
-};
diff --git a/projects/rlm_stg/stats.h b/projects/rlm_stg/stats.h
deleted file mode 100644 (file)
index 88ef173..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-#ifndef FR_STATS_H
-#define FR_STATS_H
-
-/*
- * stats.h     Structures and functions for statistics.
- *
- * Version:    $Id: stats.h,v 1.1 2010/08/14 04:13:52 faust Exp $
- *
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation; either version 2 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program; if not, write to the Free Software
- *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
- *
- * Copyright 2005,2006,2007,2008  The FreeRADIUS server project
- */
-
-//#include <freeradius/ident.h>
-//RCSIDH(stats_h, "$Id: stats.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#ifdef WITH_STATS_64BIT
-typedef uint64_t fr_uint_t;
-#else
-typedef uint32_t fr_uint_t;
-#endif
-
-#ifdef WITH_STATS
-typedef struct fr_stats_t {
-       fr_uint_t               total_requests;
-       fr_uint_t               total_invalid_requests;
-       fr_uint_t               total_dup_requests;
-       fr_uint_t               total_responses;
-       fr_uint_t               total_access_accepts;
-       fr_uint_t               total_access_rejects;
-       fr_uint_t               total_access_challenges;
-       fr_uint_t               total_malformed_requests;
-       fr_uint_t               total_bad_authenticators;
-       fr_uint_t               total_packets_dropped;
-       fr_uint_t               total_no_records;
-       fr_uint_t               total_unknown_types;
-} fr_stats_t;
-
-typedef struct fr_stats_ema_t {
-       int             window;
-
-       int             f1, f10;
-       int             ema1, ema10;
-
-} fr_stats_ema_t;
-
-extern fr_stats_t      radius_auth_stats;
-extern fr_stats_t      radius_acct_stats;
-#ifdef WITH_PROXY
-extern fr_stats_t      proxy_auth_stats;
-extern fr_stats_t      proxy_acct_stats;
-#endif
-
-void radius_stats_init(int flag);
-void request_stats_final(REQUEST *request);
-void request_stats_reply(REQUEST *request);
-void radius_stats_ema(fr_stats_ema_t *ema,
-                     struct timeval *start, struct timeval *end);
-
-#define RAD_STATS_INC(_x) _x++
-#ifdef WITH_ACCOUNTING
-#define RAD_STATS_TYPE_INC(_listener, _x) if (_listener->type == RAD_LISTEN_AUTH) { \
-                                       radius_auth_stats._x++; \
-                                    } else if (_listener->type == RAD_LISTEN_ACCT) { \
-                                       radius_acct_stats._x++; } \
-                                      _listener->stats._x++
-
-#define RAD_STATS_CLIENT_INC(_listener, _client, _x) if (_listener->type == RAD_LISTEN_AUTH) \
-                                       _client->auth->_x++; \
-                                    else if (_listener->type == RAD_LISTEN_ACCT) \
-                                       _client->acct->_x++
-
-#else  /* WITH_ACCOUNTING */
-
-#define RAD_STATS_TYPE_INC(_listener, _x) { radius_auth_stats._x++; _listener->stats._x++; }
-
-#define RAD_STATS_CLIENT_INC(_listener, _client, _x) _client->auth->_x++
-
-#endif /* WITH_ACCOUNTING */
-
-
-#else  /* WITH_STATS */
-#define request_stats_init(_x)
-#define request_stats_final(_x)
-
-#define  RAD_STATS_INC(_x)
-#define RAD_STATS_TYPE_INC(_listener, _x)
-#define RAD_STATS_CLIENT_INC(_listener, _client, _x)
-
-#endif
-
-#endif /* FR_STATS_H */
index 834f19c444981488dc194d3059f873a46d0bc056..113e71c97891ca42c284d73b4616f019eb9564f8 100644 (file)
 
 #include <cerrno>
 #include <cstring>
+#include <vector>
+#include <utility>
 
 #include <stdexcept>
 
 #include "stg_client.h"
 
-using namespace std;
+typedef std::vector<std::pair<std::string, std::string> > PAIRS;
 
-void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
-
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+
 STG_CLIENT::STG_CLIENT(const std::string & host, uint16_t port, uint16_t lp, const std::string & pass)
-    : localPort(lp),
-      password(pass),
+    : password(pass),
       framedIP(0)
 {
-sock = socket(AF_INET, SOCK_DGRAM, 0);
+/*sock = socket(AF_INET, SOCK_DGRAM, 0);
 if (sock == -1)
     {
     std::string message = strerror(errno);
@@ -72,45 +68,22 @@ outerAddr.sin_addr.s_addr = *(uint32_t *)he->h_addr;
 
 InitEncrypt(&ctx, password);
 
-PrepareNet();
+PrepareNet();*/
 }
-//-----------------------------------------------------------------------------
+
 STG_CLIENT::~STG_CLIENT()
 {
-close(sock);
-}
-//-----------------------------------------------------------------------------
-uint32_t STG_CLIENT::GetFramedIP() const
-{
-return framedIP;
+/*close(sock);*/
 }
-//-----------------------------------------------------------------------------
+
 int STG_CLIENT::PrepareNet()
 {
-if (localPort != 0)
-    {
-    struct sockaddr_in localAddr;
-    localAddr.sin_family = AF_INET;
-    localAddr.sin_port = htons(localPort);
-    localAddr.sin_addr.s_addr = inet_addr("0.0.0.0");;
-
-    if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)))
-        {
-        errorStr = "Bind failed";
-        return -1;
-        }
-    }
 return 0;
 }
-//-----------------------------------------------------------------------------
-string STG_CLIENT::GetUserPassword() const
-{
-return userPassword;
-}
-//-----------------------------------------------------------------------------
+
 int STG_CLIENT::Send(const RAD_PACKET & packet)
 {
-char buf[RAD_MAX_PACKET_LEN];
+/*char buf[RAD_MAX_PACKET_LEN];
     
 Encrypt(&ctx, buf, (char *)&packet, sizeof(RAD_PACKET) / 8);
 
@@ -119,12 +92,12 @@ int res = sendto(sock, buf, sizeof(RAD_PACKET), 0, (struct sockaddr *)&outerAddr
 if (res == -1)
     errorStr = "Error sending data";
 
-return res;
+return res;*/
 }
-//-----------------------------------------------------------------------------
+
 int STG_CLIENT::RecvData(RAD_PACKET * packet)
 {
-char buf[RAD_MAX_PACKET_LEN];
+/*char buf[RAD_MAX_PACKET_LEN];
 int res;
 
 struct sockaddr_in addr;
@@ -139,12 +112,12 @@ if (res == -1)
 
 Decrypt(&ctx, (char *)packet, buf, res / 8);
 
-return 0;
+return 0;*/
 }
-//-----------------------------------------------------------------------------
+
 int STG_CLIENT::Request(RAD_PACKET * packet, const std::string & login, const std::string & svc, uint8_t packetType)
 {
-int res;
+/*int res;
 
 memcpy((void *)&packet->magic, (void *)RAD_ID, RAD_MAGIC_LEN);
 packet->protoVer[0] = '0';
@@ -172,12 +145,14 @@ if (strncmp((char *)packet->magic, RAD_ID, RAD_MAGIC_LEN))
     return -1;
     }
 
-return 0;
+return 0;*/
 }
+
 //-----------------------------------------------------------------------------
-int STG_CLIENT::Authorize(const string & login, const string & svc)
+
+const STG_PAIRS * STG_CLIENT::Authorize(const std::string & login, const std::string & svc)
 {
-RAD_PACKET packet;
+/*RAD_PACKET packet;
 
 userPassword = "";
 
@@ -187,14 +162,17 @@ if (Request(&packet, login, svc, RAD_AUTZ_PACKET))
 if (packet.packetType != RAD_ACCEPT_PACKET)
     return -1;
 
-userPassword = (char *)packet.password;
+userPassword = (char *)packet.password;*/
 
-return 0;
+PAIRS pairs;
+pairs.push_back(std::make_pair("Cleartext-Password", userPassword));
+
+return ToSTGPairs(pairs);
 }
-//-----------------------------------------------------------------------------
-int STG_CLIENT::Authenticate(const string & login, const string & svc)
+
+const STG_PAIRS * STG_CLIENT::Authenticate(const std::string & login, const std::string & svc)
 {
-RAD_PACKET packet;
+/*RAD_PACKET packet;
 
 userPassword = "";
 
@@ -202,14 +180,16 @@ if (Request(&packet, login, svc, RAD_AUTH_PACKET))
     return -1;
 
 if (packet.packetType != RAD_ACCEPT_PACKET)
-    return -1;
+    return -1;*/
 
-return 0;
+PAIRS pairs;
+
+return ToSTGPairs(pairs);
 }
-//-----------------------------------------------------------------------------
-int STG_CLIENT::PostAuthenticate(const string & login, const string & svc)
+
+const STG_PAIRS * STG_CLIENT::PostAuth(const std::string & login, const std::string & svc)
 {
-RAD_PACKET packet;
+/*RAD_PACKET packet;
 
 userPassword = "";
 
@@ -222,14 +202,24 @@ if (packet.packetType != RAD_ACCEPT_PACKET)
 if (svc == "Framed-User")
     framedIP = packet.ip;
 else
-    framedIP = 0;
+    framedIP = 0;*/
 
-return 0;
+PAIRS pairs;
+pairs.push_back(std::make_pair("Framed-IP-Address", inet_ntostring(framedIP)));
+
+return ToSTGPairs(pairs);
 }
-//-----------------------------------------------------------------------------
-int STG_CLIENT::Account(const std::string & type, const string & login, const string & svc, const string & sessid)
+
+const STG_PAIRS * STG_CLIENT::PreAcct(const std::string & login, const std::String & service)
+{
+PAIRS pairs;
+
+return ToSTGPairs(pairs);
+}
+
+const STG_PAIRS * STG_CLIENT::Account(const std::string & type, const std::string & login, const std::string & svc, const std::string & sessid)
 {
-RAD_PACKET packet;
+/*RAD_PACKET packet;
 
 userPassword = "";
 strncpy((char *)packet.sessid, sessid.c_str(), RAD_SESSID_LEN);
@@ -256,39 +246,50 @@ else
     }
 
 if (packet.packetType != RAD_ACCEPT_PACKET)
-    return -1;
+    return -1;*/
 
-return 0;
+PAIRS pairs;
+
+return ToSTGPairs(pairs);
 }
+
 //-----------------------------------------------------------------------------
-inline
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)         
-{
-// len8 - длина в 8-ми байтовых блоках                                                   
-if (dst != src) 
-    memcpy(dst, src, len8 * 8);                                                          
-    
-for (int i = 0; i < len8; i++)
-    Blowfish_Encrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
-}
+
+std::string STG_CLIENT_ST::m_host;
+uint16_t STG_CLIENT_ST::m_port(6666);
+std::string STG_CLIENT_ST::m_password;
+
 //-----------------------------------------------------------------------------
-inline
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+
+STG_CLIENT * STG_CLIENT_ST::Get()
 {
-// len8 - длина в 8-ми байтовых блоках
-if (dst != src)
-    memcpy(dst, src, len8 * 8);
+    static STG_CLIENT * stgClient = NULL;
+    if ( stgClient == NULL )
+        stgClient = new STG_CLIENT(m_host, m_port, m_password);
+    return stgClient;
+}
 
-for (int i = 0; i < len8; i++)
-    Blowfish_Decrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
+void STG_CLIENT_ST::Configure(const std::string & host, uint16_t port, const std::string & password)
+{
+    m_host = host;
+    m_port = port;
+    m_password = password;
 }
+
 //-----------------------------------------------------------------------------
-inline
-void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
+
+const STG_PAIR * ToSTGPairs(const PAIRS & source)
 {
-unsigned char keyL[RAD_PASSWORD_LEN];
-memset(keyL, 0, RAD_PASSWORD_LEN);
-strncpy((char *)keyL, password.c_str(), RAD_PASSWORD_LEN);
-Blowfish_Init(ctx, keyL, RAD_PASSWORD_LEN);
+    STG_PAIR * pairs = new STG_PAIR[source.size() + 1];
+    for (size_t pos = 0; pos < source.size(); ++pos) {
+        bzero(pairs[pos].key, sizeof(STG_PAIR::key));
+        bzero(pairs[pos].value, sizeof(STG_PAIR::value));
+        strncpy(pairs[pos].key, source[pos].first.c_str(), sizeof(STG_PAIR::key));
+        strncpy(pairs[pos].value, source[pos].second.c_str(), sizeof(STG_PAIR::value));
+        ++pos;
+    }
+    bzero(pairs[sources.size()].key, sizeof(STG_PAIR::key));
+    bzero(pairs[sources.size()].value, sizeof(STG_PAIR::value));
+
+    return pairs;
 }
-//-----------------------------------------------------------------------------
index f87f816fbf1e6cc33665c07358455f1ab67149ee..5ee000c7e949b1e8735815c122db7d510036e10a 100644 (file)
 #include "stg/blowfish.h"
 #include "stg/rad_packets.h"
 
+#include "stgpair.h"
+
 class STG_CLIENT
 {
 public:
-    STG_CLIENT(const std::string & host, uint16_t port, uint16_t lp, const std::string & pass);
+    STG_CLIENT(const std::string & host, uint16_t port, const std::string & password);
     ~STG_CLIENT();
 
-    std::string GetUserPassword() const;
-
-    int Authorize(const std::string & login, const std::string & svc);
-    int Authenticate(const std::string & login, const std::string & svc);
-    int PostAuthenticate(const std::string & login, const std::string & svc);
-    int Account(const std::string & type, const std::string & login, const std::string & svc, const std::string & sessid);
-
-    uint32_t GetFramedIP() const;
-
-    const std::string & GetError() const { return errorStr; };
+    const STG_PAIR * Authorize(const std::string & login, const std::string & service);
+    const STG_PAIR * Authenticate(const std::string & login, const std::string & service);
+    const STG_PAIR * PostAuth(const std::string & login, const std::string & service);
+    const STG_PAIR * PreAcct(const std::string & login, const std::string & service);
+    const STG_PAIR * Account(const std::string & type, const std::string & login, const std::string & service, const std::string & sessionId);
 
 private:
-    uint16_t localPort;
     std::string password;
-    int sock;
-    std::string errorStr;
-
-    struct sockaddr_in outerAddr;
-
-    std::string userPassword;
-
-    uint32_t framedIP;
-
-    BLOWFISH_CTX ctx;
 
     int PrepareNet();
 
@@ -77,4 +63,16 @@ private:
     int Send(const RAD_PACKET & packet);
 };
 
+struct STG_CLIENT_ST
+{
+    public:
+        static void Configure(const std::string & host, uint16_t port, const std::string & password);
+        static STG_CLIENT * Get();
+
+    private:
+        static std::string m_host;
+        static uint16_t m_port;
+        static std::string m_password;
+};
+
 #endif
diff --git a/projects/rlm_stg/stgpair.h b/projects/rlm_stg/stgpair.h
new file mode 100644 (file)
index 0000000..19b42bc
--- /dev/null
@@ -0,0 +1,12 @@
+#ifndef __STG_STGPAIR_H__
+#define __STG_STGPAIR_H__
+
+#define STGPAIR_KEYLENGTH 64
+#define STGPAIR_VALUELENGTH 256
+
+typedef struct STG_PAIR {
+    char key[STGPAIR_KEYLENGTH];
+    char value[STGPAIR_VALUELENGTH];
+} STG_PAIR;
+
+#endif
diff --git a/projects/rlm_stg/token.h b/projects/rlm_stg/token.h
deleted file mode 100644 (file)
index 0f55378..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-#ifndef FR_TOKEN_H
-#define FR_TOKEN_H
-
-/*
- * token.h     Special tokens.
- *
- * $Id$
- *
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation; either version 2 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program; if not, write to the Free Software
- *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
- *
- * Copyright 2001,2006  The FreeRADIUS server project
- */
-
-//#include <freeradius-devel/ident.h>
-//RCSIDH(token_h, "$Id$")
-
-typedef enum fr_token_t {
-  T_OP_INVALID = 0,            /* invalid token */
-  T_EOL,                       /* end of line */
-  T_LCBRACE,                   /* { */
-  T_RCBRACE,                   /* } */
-  T_LBRACE,                    /* ( */
-  T_RBRACE,                    /* )             5 */
-  T_COMMA,                     /* , */
-  T_SEMICOLON,                 /* ; */
-
-  T_OP_ADD,                    /* += */
-  T_OP_SUB,                    /* -= */
-  T_OP_SET,                    /* :=           10 */
-  T_OP_EQ,                     /* = */
-  T_OP_NE,                     /* != */
-  T_OP_GE,                     /* >= */
-  T_OP_GT,                     /* > */
-  T_OP_LE,                     /* <=           15 */
-  T_OP_LT,                     /* < */
-  T_OP_REG_EQ,                 /* =~ */
-  T_OP_REG_NE,                 /* !~ */
-  T_OP_CMP_TRUE,                /* =* */
-  T_OP_CMP_FALSE,               /* !*          20 */
-  T_OP_CMP_EQ,                 /* == */
-  T_HASH,                      /* # */
-  T_BARE_WORD,                 /* bare word */
-  T_DOUBLE_QUOTED_STRING,      /* "foo" */
-  T_SINGLE_QUOTED_STRING,      /* 'foo'        25 */
-  T_BACK_QUOTED_STRING,                /* `foo` */
-  T_TOKEN_LAST
-} FR_TOKEN;
-
-#define T_EQSTART      T_OP_ADD
-#define        T_EQEND         (T_OP_CMP_EQ + 1)
-
-typedef struct FR_NAME_NUMBER {
-       const char      *name;
-       int             number;
-} FR_NAME_NUMBER;
-
-int fr_str2int(const FR_NAME_NUMBER *table, const char *name, int def);
-const char *fr_int2str(const FR_NAME_NUMBER *table, int number,
-                        const char *def);
-
-
-int            getword (const char **ptr, char *buf, int buflen);
-int            getbareword (const char **ptr, char *buf, int buflen);
-FR_TOKEN       gettoken(const char **ptr, char *buf, int buflen);
-FR_TOKEN       getstring(const char **ptr, char *buf, int buflen);
-
-#endif /* FR_TOKEN_H */
index 0912be081cc26b33cc1ad1afa8a95b7bf623dbd6..ce0b76dce38c50fddce86e887aad56e16d05363a 100644 (file)
@@ -57,13 +57,24 @@ distclean: clean
 install: install-bin install-data
 
 install-bin:
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+endif
        $(MAKE) -C $(DIR_LIBSRC) install
 
 install-data:
        # Install etc
        mkdir -m $(DIR_MODE) -p $(PREFIX)/etc/rscriptd
        install -m $(DATA_MODE) -o $(OWNER) ./rscriptd.conf $(PREFIX)/etc/rscriptd/rscriptd.conf
+ifeq ($(OS), linux)
+       install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/linux/etc/stargazer/OnConnect $(PREFIX)/etc/rscriptd/
+       install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/linux/etc/stargazer/OnDisconnect $(PREFIX)/etc/rscriptd/
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/freebsd/etc/stargazer/OnConnect $(PREFIX)/etc/rscriptd/
+       install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/freebsd/etc/stargazer/OnDisconnect $(PREFIX)/etc/rscriptd/
+endif
 
 uninstall: uninstall-bin uninstall-data
 
@@ -73,7 +84,8 @@ uninstall-bin:
 uninstall-data:
        # Uninstall etc
        rm -f $(PREFIX)/etc/rscriptd/rscriptd.conf
-
+       rm -f $(PREFIX)/etc/rscriptd/OnConnect
+       rm -f $(PREFIX)/etc/rscriptd/OnDisconnect
 
 ifneq ($(MAKECMDGOALS),distclean)
 ifneq ($(MAKECMDGOALS),clean)
index 885eef76558f36c88353c0ff33300d20bfa54561..c7aa090dc9d2bf79a1cd7591ff44813690f2e131 100755 (executable)
@@ -16,18 +16,15 @@ DATA_MODE=0644
 DIR_MODE=0755
 OWNER=root
 
-if [ -z $1 ]
+if [ "$1" = "debug" ]
 then
-    MAKEOPTS="-j1"
+   DEFS="$DEFS -DDEBUG"
+   MAKEOPTS="$MAKEOPTS -j1"
+   CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+   DEBUG="yes"
 else
-    if [ "$1" = "debug" ]
-    then
-        DEFS="-DDEBUG"
-        MAKEOPTS="-j1"
-        CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
-    else
-        MAKEOPTS="-j1"
-    fi
+   DEFS="$DEFS -DNDEBUG"
+   DEBUG="no"
 fi
 
 CXXFLAGS="$CXXFLAGS -I/usr/local/include"
@@ -56,15 +53,15 @@ fi
 
 if [ "$OS" = "unknown" ]
 then 
-    echo "#############################################################################"
-    echo "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
+    printf "#############################################################################\n"
+    printf "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #\n"
+    printf "#############################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building rscriptd for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building rscriptd for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="logger.lib 
           locker.lib
@@ -103,32 +100,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -137,40 +134,41 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 rm -f build_check.c
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
 
 $MAKE $MAKEOPTS
 
index 730426744e50508556802c06d7bddcb81be91022..ead5d33bdcebde8771e78cd2377c5c4b69ac9f49 100644 (file)
@@ -255,7 +255,7 @@ bool LISTENER::RecvPacket()
 struct iovec iov[2];
 
 char buffer[RS_MAX_PACKET_LEN];
-RS_PACKET_HEADER packetHead;
+RS::PACKET_HEADER packetHead;
 
 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
 iov[0].iov_len = sizeof(packetHead);
@@ -320,7 +320,7 @@ return false;
 //-----------------------------------------------------------------------------
 bool LISTENER::GetParams(char * buffer, UserData & data)
 {
-RS_PACKET_TAIL packetTail;
+RS::PACKET_TAIL packetTail;
 
 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
 
@@ -330,7 +330,7 @@ if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
     return true;
     }
 
-std::stringstream params;
+std::ostringstream params;
 params << "\"" << data.login << "\" "
        << inet_ntostring(data.ip) << " "
        << data.id << " "
@@ -356,35 +356,58 @@ while (it != pending.end() && count < 256)
             );
     if (it->type == PendingData::CONNECT)
         {
+        printfd(__FILE__, "Connect packet\n");
         if (uit == users.end() || uit->login != it->login)
             {
+            printfd(__FILE__, "Connect new user '%s'\n", it->login.c_str());
             // Add new user
             Connect(*it);
             users.insert(uit, AliveData(static_cast<UserData>(*it)));
             }
         else if (uit->login == it->login)
             {
+            printfd(__FILE__, "Update existing user '%s'\n", it->login.c_str());
             // Update already existing user
             time(&uit->lastAlive);
             uit->params = it->params;
             }
+        else
+            {
+            printfd(__FILE__, "Hmmm... Strange connect for '%s'\n", it->login.c_str());
+            }
         }
     else if (it->type == PendingData::ALIVE)
         {
+        printfd(__FILE__, "Alive packet\n");
         if (uit != users.end() && uit->login == it->login)
             {
+            printfd(__FILE__, "Alive user '%s'\n", it->login.c_str());
             // Update existing user
             time(&uit->lastAlive);
             }
+        else
+            {
+            printfd(__FILE__, "Alive user '%s' is not found\n", it->login.c_str());
+            }
         }
     else if (it->type == PendingData::DISCONNECT)
         {
+        printfd(__FILE__, "Disconnect packet\n");
         if (uit != users.end() && uit->login == it->login.c_str())
             {
+            printfd(__FILE__, "Disconnect user '%s'\n", it->login.c_str());
             // Disconnect existing user
             Disconnect(*uit);
             users.erase(uit);
             }
+        else
+            {
+            printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->login.c_str());
+            }
+        }
+    else
+        {
+        printfd(__FILE__, "Unknown packet type\n");
         }
     ++it;
     ++count;
@@ -455,7 +478,7 @@ else
 return false;
 }
 //-----------------------------------------------------------------------------
-bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const
+bool LISTENER::CheckHeader(const RS::PACKET_HEADER & header) const
 {
 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
     {
index f4d2856e7c7b0cdd35d3821d3278b396fd49b5c0..c6fb143a05c3104aeba54530ef9f1c12e296c31c 100644 (file)
@@ -96,7 +96,7 @@ private:
     bool                FinalizeNet();
     bool                RecvPacket();
     // Parsing stuff
-    bool                CheckHeader(const RS_PACKET_HEADER & header) const;
+    bool                CheckHeader(const RS::PACKET_HEADER & header) const;
     bool                GetParams(char * buffer, UserData & data);
     // Processing stuff
     void                ProcessPending();
index 96f5d4654f021728876cfd098cdfb03ed143ae47..45b7b5c0cf28bc64d19fb885516f6be88357ba0e 100644 (file)
@@ -1,8 +1,68 @@
-LogFileName=/var/log/rscriptd.log
-ExecutersNum=1
-ConfigDir=/etc/rscriptd
-Password=123456
-Port=9999
-UserTimeout=60
-ScriptOnConnect=/etc/stargazer/OnConnect
-ScriptOnDisconnect=/etc/stargazer/OnDisconnect
+################################################################################
+#                         Rscriptd Configuration file                          #
+################################################################################
+
+# LOG file name
+# Parameter: optional
+# Value: file path
+# Default: /var/log/rscriptd.log
+LogFileName = /var/log/rscriptd.log
+
+# Amount of rscriptd-exec processes.
+# These processes are responsible for the execution of scripts 
+# OnConnect and OnDisconnect.
+# Amount of processes means how many scripts can be executed simultaneously.
+# Recommend to leave 1 to avoid errors when executing scripts
+# Parameter: optional
+# Value: 1 ... 1024
+# Default: 1
+ExecutersNum = 1
+
+# Message queue identifier for the script executer.
+# It may be changed if there're a needs to run multiple copies of rscriptd.
+# Warning: If you do not understand it, do not touch this setting!
+# Parameter: optional
+# Value: 0 ... 2 ^ 32
+# Default: 5555
+# ExecMsgKey = 5555
+
+# The path to directory where config files are
+# Parameter: optional
+# Value: directory path
+# Default: /etc/rscriptd
+ConfigDir = /etc/rscriptd
+
+# Defines password for the encryption exchange between
+# Stargazer server and rscriptd.
+# Parameter: optional
+# Value: any
+# Default: 123456
+Password = 123456
+
+# Defines port number for communication between
+# Stargazer server and rscriptd.
+# Parameter: optional
+# Value: 1 ... 65535
+# Default: 9999
+Port = 9999
+
+# User timeout. If Stargazer does not respond during this time,
+# the user will be disconnected.
+# Parameter: optional
+# Values: 5 ... 600
+# Default: 60
+UserTimeout = 60
+
+# Defines file which runs when user gets access
+# Parameter: optional
+# Value: file path
+# Default: /etc/rscriptd/OnConnect
+ScriptOnConnect = /etc/rscriptd/OnConnect
+
+# Defines file which runs when user loses access
+# Parameter: optional
+# Value: file path
+# Default: /etc/rscriptd/OnDisconnect
+ScriptOnDisconnect = /etc/rscriptd/OnDisconnect
+
+################################################################################
index 99cd0e47e71755345350886711884d84a42ab668..a59371c9309a2eba4b2f2ae3d39d06b506912e7d 100644 (file)
@@ -58,7 +58,11 @@ distclean: clean
 install: install-bin install-data
 
 install-bin:
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+endif
        $(MAKE) -C $(DIR_LIBSRC) install
 
 install-data:
index ec747e2aad38a1c00860f62d972a76062f0f479e..5ea022a2fc0ed8aa2dc3b083481b84e2c5674590 100755 (executable)
@@ -16,18 +16,15 @@ DATA_MODE=0644
 DIR_MODE=0755
 OWNER=root
 
-if [ -z $1 ]
+if [ "$1" = "debug" ]
 then
-    MAKEOPTS="-j1"
+   DEFS="$DEFS -DDEBUG"
+   MAKEOPTS="$MAKEOPTS -j1"
+   CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+   DEBUG="yes"
 else
-    if [ "$1" = "debug" ]
-    then
-        DEFS="-DDEBUG"
-        MAKEOPTS="-j1"
-        CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
-    else
-        MAKEOPTS="-j1"
-    fi
+   DEFS="$DEFS -DNDEBUG"
+   DEBUG="no"
 fi
 
 CXXFLAGS="$CXXFLAGS -I/usr/local/include"
@@ -56,15 +53,15 @@ fi
 
 if [ "$OS" = "unknown" ]
 then 
-    echo "#############################################################################"
-    echo "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
+    printf "#############################################################################\n"
+    printf "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #\n"
+    printf "#############################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building sgauth for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building sgauth for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="crypto.lib 
          common.lib 
@@ -101,32 +98,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -135,39 +132,40 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 rm -f build_check.c
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
 $MAKE $MAKEOPTS
 
index 2af78b71f7667e7960d6db0ec4076e24574becd6..d0ab3c35b135b455f0fabf4b6598c0c8ed3bfa7d 100644 (file)
@@ -200,7 +200,7 @@ if (settings.GetDaemon())
         }
     }
 
-clnp = new IA_CLIENT_PROT(settings.GetServerName(), settings.GetServerPort(), settings.GetLocalPort());
+clnp = new IA_CLIENT_PROT(settings.GetServerName(), settings.GetServerPort(), settings.GetLocalName(), settings.GetLocalPort());
 
 if (!settings.GetNoWeb())
     {
index f85364201774bd1d10ce1fcf41df975887117046..1a7b8dcd71509c70a9fb4df1d6057fdec55201e9 100644 (file)
@@ -85,6 +85,8 @@ if (ParseIntInRange(temp, 1, 65535, &port))
     return -1;
     }
 
+cf.ReadString("LocalName", &localName, "");
+
 cf.ReadString("LocalPort", &temp, "0");
 if (ParseIntInRange(temp, 0, 65535, &localPort))
     {
index 9354e18decf236978f259ce8d5b9248a1ffeaf8a..253b69eabea7c3a00e485fe1862eb7f59988522b 100644 (file)
@@ -37,6 +37,7 @@ public:
 
     const std::string & GetServerName() const { return serverName; }
     uint16_t            GetServerPort() const { return port; }
+    const std::string & GetLocalName() const { return localName; }
     uint16_t            GetLocalPort() const { return localPort; }
 
     const std::string & GetLogin() const { return login; }
@@ -56,6 +57,7 @@ private:
     std::string password;
     std::string serverName;
     int         port;
+    std::string localName;
     int         localPort;
     uint32_t    listenWebIP;
     int         refreshPeriod;
index 0368ec02e585984f9c9ba21138f0392587c479e7..bb5fca32d4472d6e1a4f47d564274d522c8f5929 100644 (file)
@@ -1,37 +1,78 @@
-#Stargazer server ip
-ServerName=192.168.1.2
+################################################################################
+#                           Sgauth Configuration file                          #
+################################################################################
 
-#Stargazer server port
-#Default value 5555
-ServerPort=5555
+# Stargazer server
+# Parameter: required
+# Values: IP address or DNS name
+# Default:
+ServerName = 192.168.1.2
 
-#User's login
-Login=test
+# Port on which Stargazer interacts with sgauth
+# Parameter: optional
+# Value: 1 ... 65535
+# Default: 5555
+ServerPort = 5555
 
-#
-#
-LocalPort=12345
+# User's login in Stargazer
+# Parameter: required
+# Value: any
+# Default:
+Login = test
 
-#User's password
-Password=1234567
+# Local host to bind
+# Parameter: optional
+# Values: IP address or DNS name
+# Default: 0.0.0.0
+LocalName = localhost
 
-#
-#Default value yes
-#Reconnect=no
+# Port on which sgauth interacts with Stargazer
+# Parameter: optional
+# Value: 1 ... 65535
+# Default: 0
+LocalPort = 12345
 
-#
-#Default value yes
-#Daemon=yes
+# User's password in Stargazer
+# Parameter: required
+# Value: any
+# Default:
+Password = 123456
 
-#Refresh web page period
-#Default value 10
-#RefreshPeriod=10
+# Defines whether sgauth should try to reestablish connection to Stargazer
+# if it was lost
+# Parameter: optional
+# Value: yes, no
+# Default: yes
+Reconnect = yes
 
-#
-#Default value 127.0.0.1
-ListenWebIP=127.0.0.1
+# Defines whether sgauth should run as daemon
+# Parameter: optional
+# Value: yes, no
+# Default: yes
+Daemon = yes
 
-#Default value no
-DisableWeb=no
+# Web-page refresh period in built-in webserver
+# Parameter: optional
+# Value: any numeric (minutes)
+# Default: 10
+RefreshPeriod = 10
 
-#ShowPid=no
+# Defines whether sgauth should use built-in webserver
+# Parameter: optional
+# Value: yes, no
+# Default: no
+DisableWeb = no
+
+# Defines address on which sgauth's built-in webserver will listen
+# Parameter: optional
+# Value: IP address or DNS name
+# Default: 127.0.0.1
+ListenWebIP = 127.0.0.1
+
+# Defines whether sgauth should show its process ID
+# Parameter: optional
+# Value: yes, no
+# Default: no
+ShowPid = no
+
+################################################################################
index d2cdf77065dcc0e53f3bea30279a79458ad9e6b3..2b1456593dc88da9a43e861ce87358c9f8831e94 100755 (executable)
@@ -19,14 +19,17 @@ OWNER=root
 if [ -z $1 ]
 then
     MAKEOPTS="-j1"
+    DEBUG="no"
 else
     if [ "$1" = "debug" ]
     then
         DEFS="-DDEBUG"
         MAKEOPTS="-j1"
         CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
+        DEBUG="yes"
     else
         MAKEOPTS="-j1"
+        DEBUG="no"
     fi
 fi
 
@@ -56,15 +59,15 @@ fi
 
 if [ "$OS" = "unknown" ]
 then 
-    echo "################################################################################"
-    echo "# Sorry, but sgauthstress currently supported by Linux, FreeBSD 4.x-8.x        #"
-    echo "################################################################################"
+    printf "################################################################################\n"
+    printf "# Sorry, but sgauthstress currently supported by Linux, FreeBSD 4.x-8.x        #\n"
+    printf "################################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building sgauthstress for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building sgauthstress for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="logger.lib
           locker.lib
@@ -105,32 +108,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -139,103 +142,103 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 rm -f build_check.c
 
-echo -n "Checking for -lfbclient... "
+printf "Checking for -lfbclient... "
 $CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
     CHECK_FBCLIENT=no
-    echo "no"
+    printf "no\n"
 else
     CHECK_FBCLIENT=yes
-    echo "yes"
+    printf "yes\n"
 fi
 rm -f fake
 
-echo -n "Checking for mysql_config... "
+printf "Checking for mysql_config... "
 MYSQL_VERSION=`mysql_config --version 2> /dev/null`
 if [ $? != 0 ]
 then
-    echo "no";
-    echo -n "Checking for -lmysqlclient... "
+    printf "no\n";
+    printf "Checking for -lmysqlclient... "
     $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
     if [ $? != 0 ]
     then
         CHECK_MYSQLCLIENT=no
-        echo "no"
+        printf "no\n"
     else
         CHECK_MYSQLCLIENT=yes
-        echo "yes"
+        printf "yes\n"
     fi
     rm -f fake
 else
-    echo "yes"
-    echo -n "Checking for mysql_config --cflags... "
+    printf "yes\n"
+    printf "Checking for mysql_config --cflags... "
     MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
     if [ $? != 0 ]
     then
         CHECK_MYSQLCLIENT=no
-        echo "no"
+        printf "no\n"
     else
-        echo "[$MYSQL_CFLAGS]"
-        echo -n "Checking for mysql_config --libs_r... "
+        printf "[$MYSQL_CFLAGS]\n"
+        printf "Checking for mysql_config --libs_r... "
         MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
         if [ $? != 0 ]
         then
             CHECK_MYSQLCLIENT=no
-            echo "no"
+            printf "no\n"
         else
             CHECK_MYSQLCLIENT=yes
-            echo "[$MYSQL_LDFLAGS]"
+            printf "[$MYSQL_LDFLAGS]\n"
         fi
     fi
 fi
 
-echo -n "Checking for pg_config... "
+printf "Checking for pg_config... "
 PG_VERSION=`pg_config --version 2> /dev/null`
 if [ $? != 0 ]
 then
-    echo "no";
-    echo -n "Checking for -lpq... "
+    printf "no\n";
+    printf "Checking for -lpq... "
     $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
     if [ $? != 0 ]
     then
         CHECK_PQ=no
-        echo "no"
+        printf "no\n"
     else
         CHECK_PQ=yes
-        echo "yes"
+        printf "yes\n"
     fi
     rm -f fake
 else
-    echo "yes";
-    echo -n "Checking for pg_config --includedir... "
+    printf "yes\n";
+    printf "Checking for pg_config --includedir... "
     PG_CFLAGS=`pg_config --includedir 2> /dev/null`
     if [ $? != 0 ]
     then
         CHECK_PQ=no
-        echo "no"
+        printf "no\n"
     else
-        echo "[$PG_CFLAGS]"
-        echo -n "Checking for pg_config --libdir... "
+        printf "[$PG_CFLAGS]\n"
+        printf "Checking for pg_config --libdir... "
         PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
         if [ $? != 0 ]
         then
             CHECK_PQ=no
-            echo "no"
+            printf "no\n"
         else
             CHECK_PQ=yes
-            echo "[$PG_LDFLAGS]"
+            printf "[$PG_LDFLAGS]\n"
         fi
     fi
 fi
@@ -262,35 +265,36 @@ then
          store/mysql"
 fi
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules" >> $CONFFILE
-echo "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules\n" >> $CONFFILE
+printf "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo -n "PLUGINS=" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "PLUGINS=" >> $CONFFILE
 for plugin in $PLUGINS
 do
-    echo -n "$plugin " >> $CONFFILE
+    printf "$plugin " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
 $MAKE $MAKEOPTS
index 4d62bb536c998b0d29752f88148cb6f4fa14753c..0098ff5ef0b7adab9d1edd0e564ab22cdf69c20e 100644 (file)
@@ -7,7 +7,9 @@ include ../../Makefile.conf
 PROG = sgconf
 
 SRCS = ./main.cpp \
-       ./common_sg.cpp
+       ./common_sg.cpp \
+       ./options.cpp \
+       ./actions.cpp
 
 STGLIBS = conffiles \
           srvconf \
@@ -41,7 +43,11 @@ OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
 
 CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
 CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
-LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
+LDFLAGS += $(STGLIBS_LIBS)
+
+ifneq ($(OS),darwin)
+LDFLAGS += -Wl,-E
+endif
 
 .PHONY: all clean distclean libs install uninstall install-bin install-data uninstall-bin uninstall-data
 all: libs $(PROG) ../../Makefile.conf
@@ -66,7 +72,11 @@ distclean: clean
 install: install-bin
 
 install-bin:
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG)
+endif
        $(MAKE) -C $(DIR_LIBSRC) install
 
 uninstall: uninstall-bin
diff --git a/projects/sgconf/action.h b/projects/sgconf/action.h
new file mode 100644 (file)
index 0000000..64d7c1e
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_ACTION_H__
+#define __STG_SGCONF_ACTION_H__
+
+#include <string>
+#include <stdexcept>
+
+namespace SGCONF
+{
+
+class OPTION_BLOCK;
+struct PARSER_STATE;
+
+class ACTION
+{
+    public:
+        virtual ~ACTION() {}
+
+        virtual ACTION * Clone() const = 0;
+        virtual std::string ParamDescription() const = 0;
+        virtual std::string DefaultDescription() const = 0;
+        virtual OPTION_BLOCK & Suboptions() = 0;
+        virtual PARSER_STATE Parse(int argc, char ** argv) = 0;
+
+        class ERROR : public std::runtime_error
+        {
+            public:
+                ERROR(const std::string & message)
+                    : std::runtime_error(message.c_str()) {}
+        };
+};
+
+template <typename T>
+class ACTION_CLONE_MIXIN : public ACTION
+{
+    public:
+        virtual ACTION * Clone() const { return new T(*this); }
+};
+
+} // namespace SGCONF
+
+#endif
diff --git a/projects/sgconf/actions.cpp b/projects/sgconf/actions.cpp
new file mode 100644 (file)
index 0000000..afa5162
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
diff --git a/projects/sgconf/actions.h b/projects/sgconf/actions.h
new file mode 100644 (file)
index 0000000..c88de14
--- /dev/null
@@ -0,0 +1,163 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_ACTIONS_H__
+#define __STG_SGCONF_ACTIONS_H__
+
+#include "action.h"
+#include "options.h"
+#include "parser_state.h"
+
+#include "stg/common.h"
+#include "stg/resetable.h"
+
+#include <string>
+
+namespace SGCONF
+{
+
+typedef void (* FUNC0)();
+
+template <typename F>
+class FUNC0_ACTION : public ACTION
+{
+    public:
+        FUNC0_ACTION(const F & func) : m_func(func) {}
+
+        virtual ACTION * Clone() const { return new FUNC0_ACTION<F>(*this); }
+
+        virtual std::string ParamDescription() const { return ""; }
+        virtual std::string DefaultDescription() const { return ""; }
+        virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
+        virtual PARSER_STATE Parse(int argc, char ** argv)
+        {
+        m_func();
+        return PARSER_STATE(true, argc, argv);
+        }
+
+    private:
+        F m_func;
+        OPTION_BLOCK m_suboptions;
+};
+
+template <typename F>
+inline
+FUNC0_ACTION<F> * MakeFunc0Action(F func)
+{
+return new FUNC0_ACTION<F>(func);
+}
+
+template <typename T>
+class PARAM_ACTION : public ACTION
+{
+    public:
+        PARAM_ACTION(RESETABLE<T> & param,
+                     const T & defaultValue,
+                     const std::string & paramDescription)
+            : m_param(param),
+              m_defaltValue(defaultValue),
+              m_description(paramDescription),
+              m_hasDefault(true)
+        {}
+        PARAM_ACTION(RESETABLE<T> & param,
+                     const std::string & paramDescription)
+            : m_param(param),
+              m_description(paramDescription),
+              m_hasDefault(false)
+        {}
+
+        virtual ACTION * Clone() const { return new PARAM_ACTION<T>(*this); }
+
+        virtual std::string ParamDescription() const { return m_description; }
+        virtual std::string DefaultDescription() const;
+        virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
+        virtual PARSER_STATE Parse(int argc, char ** argv);
+
+    private:
+        RESETABLE<T> & m_param;
+        T m_defaltValue;
+        std::string m_description;
+        bool m_hasDefault;
+        OPTION_BLOCK m_suboptions;
+};
+
+template <typename T>
+inline
+std::string PARAM_ACTION<T>::DefaultDescription() const
+{
+return m_hasDefault ? " (default: '" + x2str(m_defaltValue) + "')"
+                    : "";
+}
+
+template <>
+inline
+std::string PARAM_ACTION<std::string>::DefaultDescription() const
+{
+return m_hasDefault ? " (default: '" + m_defaltValue + "')"
+                    : "";
+}
+
+template <typename T>
+inline
+PARSER_STATE PARAM_ACTION<T>::Parse(int argc, char ** argv)
+{
+if (argc == 0 ||
+    argv == NULL ||
+    *argv == NULL)
+    throw ERROR("Missing argument.");
+T value;
+if (str2x(*argv, value))
+    throw ERROR(std::string("Bad argument: '") + *argv + "'");
+m_param = value;
+return PARSER_STATE(false, --argc, ++argv);
+}
+
+template <>
+inline
+PARSER_STATE PARAM_ACTION<std::string>::Parse(int argc, char ** argv)
+{
+if (argc == 0 ||
+    argv == NULL ||
+    *argv == NULL)
+    throw ERROR("Missing argument.");
+m_param = *argv;
+return PARSER_STATE(false, --argc, ++argv);
+}
+
+template <typename T>
+inline
+PARAM_ACTION<T> * MakeParamAction(RESETABLE<T> & param,
+                                  const T & defaultValue,
+                                  const std::string & paramDescription)
+{
+return new PARAM_ACTION<T>(param, defaultValue, paramDescription);
+}
+
+template <typename T>
+inline
+PARAM_ACTION<T> * MakeParamAction(RESETABLE<T> & param,
+                                  const std::string & paramDescription)
+{
+return new PARAM_ACTION<T>(param, paramDescription);
+}
+
+} // namespace SGCONF
+
+#endif
index 1f6c0a0c95e7b1ad807e48f167e89ce10c623e2d..d7b72363cdc6dc8f23f931c637195989d292b6dd 100755 (executable)
@@ -16,18 +16,15 @@ DATA_MODE=0644
 DIR_MODE=0755
 OWNER=root
 
-if [ -z $1 ]
+if [ "$1" = "debug" ]
 then
-    MAKEOPTS="-j1"
+   DEFS="$DEFS -DDEBUG"
+   MAKEOPTS="$MAKEOPTS -j1"
+   CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+   DEBUG="yes"
 else
-    if [ "$1" = "debug" ]
-    then
-        DEFS="-DDEBUG"
-        MAKEOPTS="-j1"
-        CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
-    else
-        MAKEOPTS="-j1"
-    fi
+   DEFS="$DEFS -DNDEBUG"
+   DEBUG="no"
 fi
 
 CXXFLAGS="$CXXFLAGS -I/usr/local/include"
@@ -54,17 +51,24 @@ then
     MAKE="gmake"
 fi
 
+if [ "$sys" = "Darwin" ]
+then
+    OS=darwin
+    ETC_DIR="./inst/freebsd/etc/stargazer"
+    MAKE="gmake"
+fi
+
 if [ "$OS" = "unknown" ]
 then 
-    echo "#############################################################################"
-    echo "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
+    printf "#############################################################################\n"
+    printf "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #\n"
+    printf "#############################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building sgconf for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building sgconf for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="conffiles.lib
          crypto.lib 
@@ -80,12 +84,18 @@ else
     then
         DEFS="$DEFS -DFREE_BSD"
     else
-        DEFS="$DEFS -DFREE_BSD5"
         if [ "$OS" = "bsd7" ]
         then
+            DEFS="$DEFS -DFREE_BSD5"
             LIB_THREAD=-lpthread
         else
-            LIB_THREAD=-lc_r
+            if [ "$OS" == "darwin" ]
+            then
+                DEFS="$DEFS -DDARWIN"
+                LIB_THREAD=-lpthread
+            else
+                LIB_THREAD=-lc_r
+            fi
         fi
     fi
 fi
@@ -100,32 +110,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -134,60 +144,61 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 
-echo -n "Checking for -lexpat... "
-echo "int main() { return 0; }" > build_check.c
+printf "Checking for -lexpat... "
+printf "int main() { return 0; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
     CHECK_EXPAT=no
-    echo "no"
+    printf "no\n"
 else
     CHECK_EXPAT=yes
-    echo "yes"
+    printf "yes\n"
 fi
 rm -f fake
 rm -f build_check.c
 
 if [ "$CHECK_EXPAT" != "yes" ]
 then
-    echo "-lexpat not found!"
+    printf "-lexpat not found!\n"
     exit 1
 fi
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
 
 $MAKE $MAKEOPTS
 
index 60ad3c8473dd9b7bdcbcf3c10cacd160261835b1..e407a7165c6e560c1a85fb528b28e285d5de8930 100644 (file)
  */
 
 
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <locale.h>
-#include <langinfo.h>
-#include <iostream>
-#include <iconv.h>
-
-#include "stg/common.h"
 #include "sg_error_codes.h"
 #include "common_sg.h"
 #include "version_sg.h"
 
-using namespace std;
+#include "stg/common.h"
+
+#include <iostream>
+#include <vector>
+
+#include <cstdio>
+#include <cstring>
+#include <cstdlib>
+#include <cerrno>
+#include <clocale>
+
+#include <langinfo.h>
+#include <iconv.h>
+
+using namespace STG;
 
 const int usageConf = 0;
 const int usageInfo = 1;
@@ -47,18 +51,26 @@ const int usageInfo = 1;
 const int TO_KOI8 = 0;
 const int FROM_KOI8 = 1;
 //-----------------------------------------------------------------------------
-struct GetUserCbData
+struct ResultData
+{
+    bool result;
+    std::string reason;
+};
+//-----------------------------------------------------------------------------
+struct GetUserData
 {
-    void * data;
-    bool * result;
+    GetUserData(REQUEST & req, bool res) : request(req), result(res) {}
+    REQUEST & request;
+    bool result;
+    std::string reason;
 };
 //---------------------------------------------------------------------------
 struct HelpParams
 {
-    string setActionName;
-    string getActionName;
-    string valueName;
-    string valueParam;
+    std::string setActionName;
+    std::string getActionName;
+    std::string valueName;
+    std::string valueParam;
 };
 //---------------------------------------------------------------------------
 void Usage(int usageType)
@@ -84,7 +96,7 @@ HelpParams hp[] =
     {"set credit expire",       "get credit expire",    "-E",   "<credit_expire_date>"},
     {"set password",            "get password",         "-o",   "<new_password>"},
     {"set prepaid traffic",     "get prepaid traffic",  "-e",   "<prepaid>"},
-    {"set IP-addresses",       "get IP-addresses",     "-I",   "<*|ip_addr[,ip_addr...]>"},
+    {"set IP-addresses",        "get IP-addresses",     "-I",   "<*|ip_addr[,ip_addr...]>"},
     {"set name",                "get name",             "-A",   "<name>"},
     {"set note",                "get note",             "-N",   "<note>"},
     {"set street address",      "get street address",   "-D",   "<address>"},
@@ -122,6 +134,9 @@ printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --
 printf("To get userdata<0...9> use:\n");
 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --ud0 [--ud1 ...]\n\n");
 
+printf("To get user's authorizers list use:\n");
+printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --authorized-by\n\n");
+
 printf("To send message use:\n");
 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -m <message>\n\n");
 
@@ -149,6 +164,7 @@ for (int i = 0; i < (int)strlen(login); i++)
     if (!(( login[i] >= 'a' && login[i] <= 'z')
         || (login[i] >= 'A' && login[i] <= 'Z')
         || (login[i] >= '0' && login[i] <= '9')
+        ||  login[i] == '.'
         ||  login[i] == '_'
         ||  login[i] == '-'))
         {
@@ -163,7 +179,7 @@ short int ParseServerPort(const char * p)
 int port;
 if (str2x(p, port) != 0)
     {
-    printf("Incorresct server port %s\n", p);
+    printf("Incorrect server port %s\n", p);
     exit(NETWORK_ERR_CODE);
     }
 return (short)port;
@@ -173,7 +189,7 @@ char * ParseAdminLogin(char * adm)
 {
 if (CheckLogin(adm))
     {
-    printf("Incorresct admin login %s\n", adm);
+    printf("Incorrect admin login %s\n", adm);
     exit(PARAMETER_PARSING_ERR_CODE);
     }
 return adm;
@@ -194,13 +210,13 @@ char * ParseUser(char * usr)
 {
 if (CheckLogin(usr))
     {
-    printf("Incorresct user login %s\n", usr);
+    printf("Incorrect user login %s\n", usr);
     exit(PARAMETER_PARSING_ERR_CODE);
     }
 return usr;
 }
 //-----------------------------------------------------------------------------
-void ConvertKOI8(const string & src, string * dst, int encType)
+void ConvertKOI8(const std::string & src, std::string * dst, int encType)
 {
 iconv_t cd;
 char * ob = new char[src.size() * 2 + 1];
@@ -275,67 +291,68 @@ delete[] ob;
 delete[] ib;
 }
 //-----------------------------------------------------------------------------
-void ConvertFromKOI8(const string & src, string * dst)
+void ConvertFromKOI8(const std::string & src, std::string * dst)
 {
 ConvertKOI8(src, dst, FROM_KOI8);
 }
 //-----------------------------------------------------------------------------
-void ConvertToKOI8(const string & src, string * dst)
+void ResultCallback(bool result, const std::string & reason, void * d)
 {
-ConvertKOI8(src, dst, TO_KOI8);
+ResultData * data = static_cast<ResultData *>(d);
+data->result = result;
+data->reason = reason;
 }
 //-----------------------------------------------------------------------------
-int RecvSetUserAnswer(const char * ans, void * d)
+void RecvAuthByData(bool result, const std::string & reason,
+                    const AUTH_BY::INFO & list, void * d)
 {
-GetUserCbData * gucbd;
-gucbd = (GetUserCbData *)d;
-
-bool * result = gucbd->result;
+ResultData * data = static_cast<ResultData *>(d);
+data->result = result;
+data->reason = reason;
 
-//REQUEST * req = (REQUEST *)gucbd->data;
+if (!result)
+    return;
 
-//printf("ans=%s\n", ans);
-if (strcasecmp("Ok", ans) == 0)
-    *result = true;
-else
-    *result = false;
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+    std::cout << *it << "\n";
 
-return 0;
+std::cout << std::endl;
 }
 //-----------------------------------------------------------------------------
 struct StringReqParams
 {
-    string name;
-    RESETABLE<string> reqParam;
-    string * value;
+    std::string name;
+    RESETABLE<std::string> reqParam;
+    const std::string * value;
 };
 //-----------------------------------------------------------------------------
-void RecvUserData(USERDATA * ud, void * d)
+void GetUserCallback(bool result, const std::string& reason, const GET_USER::INFO & info, void * d)
 {
-GetUserCbData * gucbd;
-gucbd = (GetUserCbData *)d;
-
-bool * result = gucbd->result;
+GetUserData * data = static_cast<GetUserData *>(d);
+data->result = false;
+data->reason = reason;
 
-REQUEST * req = (REQUEST *)gucbd->data;
+if (!result)
+    return;
 
-if (ud->login == "")
+if (info.login == "")
     {
-    *result = false;
+    data->result = false;
+    data->reason = "Invalid login.";
     return;
     }
 
-if (!req->cash.res_empty())
-    cout << "cash=" << ud->cash << endl;
+if (!data->request.cash.empty())
+    cout << "cash = " << info.cash << endl;
 
-if (!req->credit.res_empty())
-    cout << "credit=" << ud->credit << endl;
+if (!data->request.credit.empty())
+    cout << "credit = " << info.credit << endl;
 
-if (!req->creditExpire.res_empty())
+if (!data->request.creditExpire.empty())
     {
     char buf[32];
     struct tm brokenTime;
-    time_t tt = ud->creditExpire;
+    time_t tt = info.creditExpire;
 
     brokenTime.tm_wday = 0;
     brokenTime.tm_yday = 0;
@@ -348,151 +365,172 @@ if (!req->creditExpire.res_empty())
 
     strftime(buf, 32, "%Y-%m-%d", &brokenTime);
 
-    cout << "creditExpire=" << buf << endl;
+    cout << "creditExpire = " << buf << endl;
     }
 
-if (!req->down.res_empty())
-    cout << "down=" << ud->down << endl;
+if (!data->request.down.empty())
+    cout << "down = " << info.down << endl;
 
-if (!req->passive.res_empty())
-    cout << "passive=" << ud->passive << endl;
+if (!data->request.passive.empty())
+    cout << "passive = " << info.passive << endl;
 
-if (!req->disableDetailStat.res_empty())
-    cout << "disableDetailStat=" << ud->disableDetailStat << endl;
+if (!data->request.disableDetailStat.empty())
+    cout << "disableDetailStat = " << info.disableDetailStat << endl;
 
-if (!req->alwaysOnline.res_empty())
-    cout << "alwaysOnline=" << ud->alwaysOnline << endl;
+if (!data->request.alwaysOnline.empty())
+    cout << "alwaysOnline = " << info.alwaysOnline << endl;
 
-if (!req->prepaidTraff.res_empty())
-    cout << "prepaidTraff=" << ud->prepaidTraff << endl;
+if (!data->request.prepaidTraff.empty())
+    cout << "prepaidTraff = " << info.prepaidTraff << endl;
 
 for (int i = 0; i < DIR_NUM; i++)
     {
-    if (!req->u[i].res_empty())
-        cout << "u" << i << "=" << ud->stat.mu[i] << endl;
-    if (!req->d[i].res_empty())
-        cout << "d" << i << "=" << ud->stat.md[i] << endl;
+    if (!data->request.sessionUpload[i].empty())
+        cout << "session upload for dir " << i << " = " << info.stat.su[i] << endl;
+    if (!data->request.sessionDownload[i].empty())
+        cout << "session download for dir " << i << "=" << info.stat.sd[i] << endl;
+    }
+
+for (int i = 0; i < DIR_NUM; i++)
+    {
+    if (!data->request.monthUpload[i].empty())
+        cout << "month upload for dir " << i << " = " << info.stat.mu[i] << endl;
+    if (!data->request.monthDownload[i].empty())
+        cout << "month download for dir " << i << " = " << info.stat.md[i] << endl;
     }
 
 for (int i = 0; i < USERDATA_NUM; i++)
     {
-    if (!req->ud[i].res_empty())
+    if (!data->request.userData[i].empty())
         {
-        string str;
-        ConvertFromKOI8(ud->userData[i], &str);
-        cout << "userdata" << i << "=" << str << endl;
+        std::string str;
+        ConvertFromKOI8(info.userData[i], &str);
+        cout << "user data " << i << " = " << str << endl;
         }
     }
 
 StringReqParams strReqParams[] =
 {
-    {"note",     req->note,        &ud->note},
-    {"name",     req->name,        &ud->name},
-    {"address",  req->address,     &ud->address},
-    {"email",    req->email,       &ud->email},
-    {"phone",    req->phone,       &ud->phone},
-    {"group",    req->group,       &ud->group},
-    {"tariff",   req->tariff,      &ud->tariff},
-    {"password", req->usrPasswd,   &ud->password},
-    {"ip",      req->ips,         &ud->ips}    // IP-address of user
+    {"note",     data->request.note,        &info.note},
+    {"name",     data->request.name,        &info.name},
+    {"address",  data->request.address,     &info.address},
+    {"email",    data->request.email,       &info.email},
+    {"phone",    data->request.phone,       &info.phone},
+    {"group",    data->request.group,       &info.group},
+    {"tariff",   data->request.tariff,      &info.tariff},
+    {"password", data->request.usrPasswd,   &info.password},
+    {"ip",       data->request.ips,         &info.ips} // IP-address of user
 };
 for (unsigned i = 0; i < sizeof(strReqParams) / sizeof(StringReqParams); i++)
     {
-    if (!strReqParams[i].reqParam.res_empty())
+    if (!strReqParams[i].reqParam.empty())
         {
         string str;
         ConvertFromKOI8(*strReqParams[i].value, &str);
-        cout << strReqParams[i].name << "=" << str << endl;
+        cout << strReqParams[i].name << " = " << str << endl;
         }
     }
-*result = true;
+data->result = true;
 }
 //-----------------------------------------------------------------------------
-int ProcessSetUser(const std::string &server,
-                   int port,
-                   const std::string &admLogin,
-                   const std::string &admPasswd,
-                   const std::string &str,
-                   void * data,
-                   bool isMessage)
+bool ProcessSetUser(const std::string & server,
+                    int port,
+                    const std::string & login,
+                    const std::string & password,
+                    const std::string & user,
+                    const USER_CONF_RES & conf,
+                    const USER_STAT_RES & stat)
 {
-SERVCONF sc;
+SERVCONF sc(server, port, login, password);
 
-bool result = false;
+ResultData data;
+int res = sc.ChgUser(user, conf, stat, ResultCallback, &data);
 
-
-sc.SetServer(server.c_str());  // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ
-sc.SetPort(port);           // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ
-sc.SetAdmLogin(admLogin.c_str());    // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉΠɠÐÁÒÏÌØ ÁÄÍÉÎÁ
-sc.SetAdmPassword(admPasswd.c_str());
-
-// TODO Good variable name :)
-GetUserCbData gucbd;
-
-gucbd.data = data;
-gucbd.result = &result;
-
-if (isMessage)
+if (res == st_ok && data.result)
     {
-    sc.SetSendMessageCb(RecvSetUserAnswer, &gucbd);
-    sc.MsgUser(str.c_str());
+    printf("Ok\n");
+    return false;
     }
+
+printf("Error\n");
+if (res != st_ok)
+    printf("%s\n", sc.GetStrError().c_str());
 else
-    {
-    sc.SetChgUserCb(RecvSetUserAnswer, &gucbd);
-    sc.ChgUser(str.c_str());
-    }
+    printf("%s\n", data.reason.c_str());
+return true;
+}
+//-----------------------------------------------------------------------------
+bool ProcessSendMessage(const std::string & server, uint16_t port,
+                        const std::string & login, const std::string & password,
+                        const std::string & user, const std::string & text)
+{
+SERVCONF sc(server, port, login, password);
+
+ResultData data;
+int res = sc.SendMessage(user, text, ResultCallback, &data);
 
-if (result)
+if (res == st_ok && data.result)
     {
     printf("Ok\n");
-    return 0;
+    return true;
     }
+
+printf("Error\n");
+if (res != st_ok)
+    printf("%s\n", sc.GetStrError().c_str());
 else
+    printf("%s\n", data.reason.c_str());
+return false;
+}
+//-----------------------------------------------------------------------------
+bool ProcessGetUser(const std::string &server,
+                    int port,
+                    const std::string &admLogin,
+                    const std::string &admPasswd,
+                    const std::string &login,
+                    REQUEST & request)
+{
+SERVCONF sc(server, port, admLogin, admPasswd);
+
+GetUserData data(request, false);
+bool res = (sc.GetUser(login.c_str(), GetUserCallback, &data) == st_ok);
+
+if (res && data.result)
     {
-    printf("Error\n");
-    return -1;
+    printf("Ok\n");
+    return true;
     }
 
-return 0;
+printf("Error\n");
+if (!res)
+    printf("%s\n", sc.GetStrError().c_str());
+else
+    printf("%s\n", data.reason.c_str());
+return false;
 }
 //-----------------------------------------------------------------------------
-int ProcessGetUser(const std::string &server,
+bool ProcessAuthBy(const std::string &server,
                    int port,
                    const std::string &admLogin,
                    const std::string &admPasswd,
-                   const std::string &login,
-                   void * data)
+                   const std::string &login)
 {
-SERVCONF sc;
-
-bool result = false;
-
-sc.SetServer(server.c_str());  // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ
-sc.SetPort(port);           // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ
-sc.SetAdmLogin(admLogin.c_str());    // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉΠɠÐÁÒÏÌØ ÁÄÍÉÎÁ
-sc.SetAdmPassword(admPasswd.c_str());
+SERVCONF sc(server, port, admLogin, admPasswd);
 
-// TODO Good variable name :)
-GetUserCbData gucbd;
+ResultData data;
+bool res = (sc.AuthBy(login.c_str(), RecvAuthByData, &data) == st_ok);
 
-gucbd.data = data;
-gucbd.result = &result;
-
-sc.SetGetUserDataRecvCb(RecvUserData, &gucbd);
-sc.GetUser(login.c_str());
-
-if (result)
+if (res && data.result)
     {
     printf("Ok\n");
-    return 0;
-    }
-else
-    {
-    printf("Error\n");
-    return -1;
+    return true;
     }
 
-return 0;
+printf("Error\n");
+if (!res)
+    printf("%s\n", sc.GetStrError().c_str());
+else
+    printf("%s\n", data.reason.c_str());
+return false;
 }
 //-----------------------------------------------------------------------------
index a654748a68f744ea558ef309d5d2702d21447c4e..323a8cf8f1dead9d437ef6c2c554af29f4455509 100644 (file)
 #ifndef COMMON_SG_H
 #define COMMON_SG_H
 
-#include <string>
-
 #include "stg/servconf.h"
+#include "stg/servconf_types.h"
 #include "request.h"
 
+#include <string>
+
+struct USER_CONF_RES;
+struct USER_STAT_RES;
+
 void UsageConf();
 void UsageInfo();
 
@@ -45,20 +49,29 @@ int CheckLogin(const char * login);
 void ConvertFromKOI8(const std::string & src, std::string * dst);
 void ConvertToKOI8(const std::string & src, std::string * dst);
 
-int ProcessGetUser(const std::string &server,
-                   int port,
-                   const std::string &admLogin,
-                   const std::string &admPasswd,
-                   const std::string &login,
-                   void * data);
+bool ProcessGetUser(const std::string & server,
+                    int port,
+                    const std::string & admLogin,
+                    const std::string & admPasswd,
+                    const std::string & login,
+                    REQUEST & request);
 
-int ProcessSetUser(const std::string &server,
+bool ProcessAuthBy(const std::string & server,
                    int port,
-                   const std::string &admLogin,
-                   const std::string &admPasswd,
-                   const std::string &str,
-                   void * data,
-                   bool isMessage = false);
+                   const std::string & admLogin,
+                   const std::string & admPasswd,
+                   const std::string & login);
 
-#endif
+bool ProcessSetUser(const std::string & server,
+                    int port,
+                    const std::string & admLogin,
+                    const std::string & admPasswd,
+                    const std::string & user,
+                    const USER_CONF_RES & conf,
+                    const USER_STAT_RES & stat);
 
+bool ProcessSendMessage(const std::string & server, uint16_t port,
+                        const std::string & login, const std::string & password,
+                        const std::string & user, const std::string & text);
+
+#endif
diff --git a/projects/sgconf/config.h b/projects/sgconf/config.h
new file mode 100644 (file)
index 0000000..9ed90c7
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_CONFIG_H__
+#define __STG_SGCONF_CONFIG_H__
+
+#include "stg/resetable.h"
+#include "stg/os_int.h"
+
+#include <string>
+
+namespace SGCONF
+{
+
+struct CONFIG
+{
+    RESETABLE<std::string> configFile;
+    RESETABLE<std::string> server;
+    RESETABLE<uint16_t> port;
+    RESETABLE<std::string> userName;
+    RESETABLE<std::string> userPass;
+};
+
+}
+
+#endif
index 2aaacbc01d2e5e4d723f32d1d42f37de7a376008..c1fc4c3e58a34c3388ca97dfc48666a743456e78 100644 (file)
 
 /*
  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
  */
 
- /*
- $Author: faust $
- $Revision: 1.25 $
- $Date: 2010/03/25 14:37:43 $
- */
+#include "request.h"
+#include "common_sg.h"
+#include "sg_error_codes.h"
 
-#include <unistd.h>
-#include <getopt.h>
-#include <iconv.h>
-#include <langinfo.h>
+#include "options.h"
+#include "actions.h"
+#include "config.h"
+
+#include "stg/user_conf.h"
+#include "stg/user_stat.h"
+#include "stg/common.h"
 
 #include <cerrno>
 #include <clocale>
 #include <cstdio>
+#include <cstdlib>
 #include <cstring>
 #include <string>
-#include <list>
 #include <sstream>
 
-#include "stg/common.h"
-#include "stg/netunit.h"
-#include "request.h"
-#include "common_sg.h"
-#include "sg_error_codes.h"
+#include <unistd.h>
+#include <getopt.h>
+#include <iconv.h>
+#include <langinfo.h>
 
-using namespace std;
+namespace
+{
 
-time_t stgTime;
+template <typename T>
+struct ARRAY_TYPE
+{
+typedef typename T::value_type type;
+};
+
+template <typename T>
+struct ARRAY_TYPE<T[]>
+{
+typedef T type;
+};
+
+template <typename T, size_t N>
+struct ARRAY_TYPE<T[N]>
+{
+typedef T type;
+};
+
+template <typename T>
+struct nullary_function
+{
+typedef T result_type;
+};
+
+template <typename F>
+class binder0 : public nullary_function<typename F::result_type>
+{
+    public:
+        binder0(const F & func, const typename F::argument_type & arg)
+            : m_func(func), m_arg(arg) {}
+        typename F::result_type operator()() const { return m_func(m_arg); }
+    private:
+        F m_func;
+        typename F::argument_type m_arg;
+};
+
+template <typename F>
+inline
+binder0<F> bind0(const F & func, const typename F::argument_type & arg)
+{
+return binder0<F>(func, arg);
+}
+
+template <typename C, typename A, typename R>
+class METHOD1_ADAPTER : public std::unary_function<A, R>
+{
+    public:
+        METHOD1_ADAPTER(R (C::* func)(A), C & obj) : m_func(func), m_obj(obj) {}
+        R operator()(A arg) { return (m_obj.*m_func)(arg); }
+    private:
+        R (C::* m_func)(A);
+        C & m_obj;
+};
+
+template <typename C, typename A, typename R>
+class CONST_METHOD1_ADAPTER : public std::unary_function<A, R>
+{
+    public:
+        CONST_METHOD1_ADAPTER(R (C::* func)(A) const, C & obj) : m_func(func), m_obj(obj) {}
+        R operator()(A arg) const { return (m_obj.*m_func)(arg); }
+    private:
+        R (C::* m_func)(A) const;
+        C & m_obj;
+};
+
+template <typename C, typename A, typename R>
+METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A), C & obj)
+{
+return METHOD1_ADAPTER<C, A, R>(func, obj);
+}
+
+template <typename C, typename A, typename R>
+CONST_METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A) const, C & obj)
+{
+return CONST_METHOD1_ADAPTER<C, A, R>(func, obj);
+}
+
+template <typename T>
+bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE<T>::type & value)
+{
+size_t pos = 0;
+if (str2x(index, pos))
+    return false;
+array[pos] = value;
+return true;
+}
+
+void Usage();
+void UsageAll();
+void UsageImpl(bool full);
+void UsageConnection();
+void UsageAdmins(bool full);
+void UsageTariffs(bool full);
+void UsageUsers(bool full);
+void UsageServices(bool full);
+void UsageCorporations(bool full);
+
+void Version();
+
+} // namespace anonymous
+
+namespace SGCONF
+{
+
+class CONFIG_ACTION : public ACTION
+{
+    public:
+        CONFIG_ACTION(CONFIG & config,
+                      const std::string & paramDescription)
+            : m_config(config),
+              m_description(paramDescription)
+        {}
+
+        virtual ACTION * Clone() const { return new CONFIG_ACTION(*this); }
+
+        virtual std::string ParamDescription() const { return m_description; }
+        virtual std::string DefaultDescription() const { return ""; }
+        virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
+        virtual PARSER_STATE Parse(int argc, char ** argv);
+
+    private:
+        CONFIG & m_config;
+        std::string m_description;
+        OPTION_BLOCK m_suboptions;
+
+        void ParseCredentials(const std::string & credentials);
+        void ParseHostAndPort(const std::string & hostAndPort);
+};
+
+PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv)
+{
+if (argc == 0 ||
+    argv == NULL ||
+    *argv == NULL)
+    throw ERROR("Missing argument.");
+char * pos = strchr(*argv, '@');
+if (pos != NULL)
+    {
+    ParseCredentials(std::string(*argv, pos));
+    ParseHostAndPort(std::string(pos + 1));
+    }
+else
+    {
+    ParseHostAndPort(std::string(*argv));
+    }
+return PARSER_STATE(false, --argc, ++argv);
+}
 
-int ParseReplyGet(void * data, list<string> * ans);
-//int ParseReplySet(void * data, list<string> * ans);
+void CONFIG_ACTION::ParseCredentials(const std::string & credentials)
+{
+std::string::size_type pos = credentials.find_first_of(':');
+if (pos != std::string::npos)
+    {
+    m_config.userName = credentials.substr(0, pos);
+    m_config.userPass = credentials.substr(pos + 1);
+    }
+else
+    {
+    m_config.userName = credentials;
+    }
+}
+
+void CONFIG_ACTION::ParseHostAndPort(const std::string & hostAndPort)
+{
+std::string::size_type pos = hostAndPort.find_first_of(':');
+if (pos != std::string::npos)
+    {
+    m_config.server = hostAndPort.substr(0, pos);
+    uint16_t port = 0;
+    if (str2x(hostAndPort.substr(pos + 1), port))
+        throw ERROR("Invalid port value: '" + hostAndPort.substr(pos + 1) + "'");
+    m_config.port = port;
+    }
+else
+    {
+    m_config.server = hostAndPort;
+    }
+}
+
+inline
+CONFIG_ACTION * MakeParamAction(CONFIG & config,
+                                const std::string & paramDescription)
+{
+return new CONFIG_ACTION(config, paramDescription);
+}
+
+} // namespace SGCONF
+
+time_t stgTime;
 
 struct option long_options_get[] = {
 {"server",      1, 0, 's'},  //Server
@@ -66,37 +253,12 @@ struct option long_options_get[] = {
 {"passive",     0, 0, 'i'},  //passive
 {"disable-stat",0, 0, 'S'},  //disable detail stat
 {"always-online",0, 0, 'O'}, //always online
-{"u0",          0, 0, 500},  //U0
-{"u1",          0, 0, 501},  //U1
-{"u2",          0, 0, 502},  //U2
-{"u3",          0, 0, 503},  //U3
-{"u4",          0, 0, 504},  //U4
-{"u5",          0, 0, 505},  //U5
-{"u6",          0, 0, 506},  //U6
-{"u7",          0, 0, 507},  //U7
-{"u8",          0, 0, 508},  //U8
-{"u9",          0, 0, 509},  //U9
-{"d0",          0, 0, 600},  //D0
-{"d1",          0, 0, 601},  //D1
-{"d2",          0, 0, 602},  //D2
-{"d3",          0, 0, 603},  //D3
-{"d4",          0, 0, 604},  //D4
-{"d5",          0, 0, 605},  //D5
-{"d6",          0, 0, 606},  //D6
-{"d7",          0, 0, 607},  //D7
-{"d8",          0, 0, 608},  //D8
-{"d9",          0, 0, 609},  //D9
-
-{"ud0",         0, 0, 700},  //UserData0
-{"ud1",         0, 0, 701},  //UserData1
-{"ud2",         0, 0, 702},  //UserData2
-{"ud3",         0, 0, 703},  //UserData3
-{"ud4",         0, 0, 704},  //UserData4
-{"ud5",         0, 0, 705},  //UserData5
-{"ud6",         0, 0, 706},  //UserData6
-{"ud7",         0, 0, 707},  //UserData7
-{"ud8",         0, 0, 708},  //UserData8
-{"ud9",         0, 0, 709},  //UserData9
+{"session-upload",   1, 0, 500},  //SU0
+{"session-download", 1, 0, 501},  //SD0
+{"month-upload",     1, 0, 502},  //MU0
+{"month-download",   1, 0, 503},  //MD0
+
+{"user-data",   1, 0, 700},  //UserData0
 
 {"prepaid",     0, 0, 'e'},  //prepaid traff
 {"create",      0, 0, 'n'},  //create
@@ -108,7 +270,8 @@ struct option long_options_get[] = {
 {"email",       0, 0, 'L'},  //emaiL
 {"phone",       0, 0, 'P'},  //phone
 {"group",       0, 0, 'G'},  //Group
-{"ip",         0, 0, 'I'},  //IP-address of user
+{"ip",          0, 0, 'I'},  //IP-address of user
+{"authorized-by",0, 0, 800}, //always online
 
 {0, 0, 0, 0}};
 
@@ -128,37 +291,12 @@ struct option long_options_set[] = {
 {"passive",     1, 0, 'i'},  //passive
 {"disable-stat",1, 0, 'S'},  //disable detail stat
 {"always-online",1, 0, 'O'},  //always online
-{"u0",          1, 0, 500},  //U0
-{"u1",          1, 0, 501},  //U1
-{"u2",          1, 0, 502},  //U2
-{"u3",          1, 0, 503},  //U3
-{"u4",          1, 0, 504},  //U4
-{"u5",          1, 0, 505},  //U5
-{"u6",          1, 0, 506},  //U6
-{"u7",          1, 0, 507},  //U7
-{"u8",          1, 0, 508},  //U8
-{"u9",          1, 0, 509},  //U9
-{"d0",          1, 0, 600},  //D0
-{"d1",          1, 0, 601},  //D1
-{"d2",          1, 0, 602},  //D2
-{"d3",          1, 0, 603},  //D3
-{"d4",          1, 0, 604},  //D4
-{"d5",          1, 0, 605},  //D5
-{"d6",          1, 0, 606},  //D6
-{"d7",          1, 0, 607},  //D7
-{"d8",          1, 0, 608},  //D8
-{"d9",          1, 0, 609},  //D9
-
-{"ud0",         1, 0, 700},  //UserData
-{"ud1",         1, 0, 701},  //UserData1
-{"ud2",         1, 0, 702},  //UserData2
-{"ud3",         1, 0, 703},  //UserData3
-{"ud4",         1, 0, 704},  //UserData4
-{"ud5",         1, 0, 705},  //UserData5
-{"ud6",         1, 0, 706},  //UserData6
-{"ud7",         1, 0, 707},  //UserData7
-{"ud8",         1, 0, 708},  //UserData8
-{"ud9",         1, 0, 709},  //UserData9
+{"session-upload",   1, 0, 500},  //U0
+{"session-download", 1, 0, 501},  //U1
+{"month-upload",     1, 0, 502},  //U2
+{"month-download",   1, 0, 503},  //U3
+
+{"user-data",        1, 0, 700},  //UserData
 
 {"prepaid",     1, 0, 'e'},  //prepaid traff
 {"create",      1, 0, 'n'},  //create
@@ -170,40 +308,33 @@ struct option long_options_set[] = {
 {"email",       1, 0, 'L'},  //emaiL
 {"phone",       1, 0, 'P'},  //phone
 {"group",       1, 0, 'G'},  //Group
-{"ip",         0, 0, 'I'},  //IP-address of user
+{"ip",          0, 0, 'I'},  //IP-address of user
 
 {0, 0, 0, 0}};
 
 //-----------------------------------------------------------------------------
-double ParseCash(const char * c, string * message)
+CASH_INFO ParseCash(const char * str)
 {
 //-c 123.45:log message
-double cash;
-char * msg;
-char * str;
-str = new char[strlen(c) + 1];
-
-strncpy(str, c, strlen(c));
-str[strlen(c)] = 0;
-
-msg = strchr(str, ':');
-
-if (msg)
+std::string cashString;
+std::string message;
+const char * pos = strchr(str, ':');
+if (pos != NULL)
     {
-    *message =  msg + 1;
-    str[msg - str] = 0;
+    cashString.append(str, pos);
+    message.append(pos + 1);
     }
 else
-    *message = "";
+    cashString = str;
 
-if (strtodouble2(str, cash) != 0)
+double cash = 0;
+if (strtodouble2(cashString, cash) != 0)
     {
-    printf("Incorrect cash value %s\n", c);
+    printf("Incorrect cash value %s\n", str);
     exit(PARAMETER_PARSING_ERR_CODE);
     }
 
-delete[] str;
-return cash;
+return CASH_INFO(cash, message);
 }
 //-----------------------------------------------------------------------------
 double ParseCredit(const char * c)
@@ -253,63 +384,24 @@ if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0')))
 return dp[0] - '0';
 }
 //-----------------------------------------------------------------------------
-string ParseTariff(const char * t, int &chgType)
+void ParseTariff(const char * str, RESETABLE<std::string> & tariffName, RESETABLE<std::string> & nextTariff)
 {
-int l = strlen(t);
-char * s;
-s = new char[l];
-char * s1, * s2;
-string ss;
-
-strcpy(s, t);
-
-s1 = strtok(s, ":");
-
-if (strlen(s1) >= TARIFF_NAME_LEN)
-    {
-    printf("Tariff name too big %s\n", s1);
-    exit(PARAMETER_PARSING_ERR_CODE);
-    }
-
-//*tariff = s;
-
-if (CheckLogin(s1))
-    {
-    printf("Incorrect tariff value %s\n", t);
-    exit(PARAMETER_PARSING_ERR_CODE);
-    }
-
-s2 = strtok(NULL, ":");
-
-chgType = -1;
-
-if (s2 == NULL)
+const char * pos = strchr(str, ':');
+if (pos != NULL)
     {
-    chgType = TARIFF_NOW;
-    ss = s;
-    delete[] s;
-    return ss;
-    }
-
-
-if (strcmp(s2, "now") == 0)
-    chgType = TARIFF_NOW;
-
-if (strcmp(s2, "delayed") == 0)
-    chgType = TARIFF_DEL;
-
-if (strcmp(s2, "recalc") == 0)
-    chgType = TARIFF_REC;
-
-if (chgType < 0)
-    {
-    printf("Incorrect tariff value %s\n", t);
-    exit(PARAMETER_PARSING_ERR_CODE);
+    std::string tariff(str, pos);
+    if (strcmp(pos + 1, "now") == 0)
+        tariffName = tariff;
+    else if (strcmp(pos + 1, "delayed") == 0)
+        nextTariff = tariff;
+    else
+        {
+        printf("Incorrect tariff value '%s'. Should be '<tariff>', '<tariff>:now' or '<tariff>:delayed'.\n", str);
+        exit(PARAMETER_PARSING_ERR_CODE);
+        }
     }
-
-ss = s;
-delete[] s;
-return ss;
+else
+    tariffName = str;
 }
 //-----------------------------------------------------------------------------
 time_t ParseCreditExpire(const char * str)
@@ -400,10 +492,10 @@ memset(str, 0, strLen);
 
 r[0] = 0;
 
-if (!req->usrMsg.res_empty())
+if (!req->usrMsg.empty())
     {
     string msg;
-    Encode12str(msg, req->usrMsg);
+    Encode12str(msg, req->usrMsg.data());
     sprintf(str, "<Message login=\"%s\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"%s\"/>", req->login.const_data().c_str(), msg.c_str());
     //sprintf(str, "<message login=\"%s\" priority=\"0\" text=\"%s\"/>\n", req->login, msg);
     strcat(r, str);
@@ -429,25 +521,25 @@ if (req->createUser)
 strcat(r, "<SetUser>\n");
 sprintf(str, "<login value=\"%s\"/>\n", req->login.const_data().c_str());
 strcat(r, str);
-if (!req->credit.res_empty())
+if (!req->credit.empty())
     {
     sprintf(str, "<credit value=\"%f\"/>\n", req->credit.const_data());
     strcat(r, str);
     }
 
-if (!req->creditExpire.res_empty())
+if (!req->creditExpire.empty())
     {
     sprintf(str, "<creditExpire value=\"%ld\"/>\n", req->creditExpire.const_data());
     strcat(r, str);
     }
 
-if (!req->prepaidTraff.res_empty())
+if (!req->prepaidTraff.empty())
     {
     sprintf(str, "<FreeMb value=\"%f\"/>\n", req->prepaidTraff.const_data());
     strcat(r, str);
     }
 
-if (!req->cash.res_empty())
+if (!req->cash.empty())
     {
     string msg;
     Encode12str(msg, req->message);
@@ -455,7 +547,7 @@ if (!req->cash.res_empty())
     strcat(r, str);
     }
 
-if (!req->setCash.res_empty())
+if (!req->setCash.empty())
     {
     string msg;
     Encode12str(msg, req->message);
@@ -463,38 +555,38 @@ if (!req->setCash.res_empty())
     strcat(r, str);
     }
 
-if (!req->usrPasswd.res_empty())
+if (!req->usrPasswd.empty())
     {
     sprintf(str, "<password value=\"%s\" />\n", req->usrPasswd.const_data().c_str());
     strcat(r, str);
     }
 
-if (!req->down.res_empty())
+if (!req->down.empty())
     {
     sprintf(str, "<down value=\"%d\" />\n", req->down.const_data());
     strcat(r, str);
     }
 
-if (!req->passive.res_empty())
+if (!req->passive.empty())
     {
     sprintf(str, "<passive value=\"%d\" />\n", req->passive.const_data());
     strcat(r, str);
     }
 
-if (!req->disableDetailStat.res_empty())
+if (!req->disableDetailStat.empty())
     {
     sprintf(str, "<disableDetailStat value=\"%d\" />\n", req->disableDetailStat.const_data());
     strcat(r, str);
     }
 
-if (!req->alwaysOnline.res_empty())
+if (!req->alwaysOnline.empty())
     {
     sprintf(str, "<aonline value=\"%d\" />\n", req->alwaysOnline.const_data());
     strcat(r, str);
     }
 
 // IP-address of user
-if (!req->ips.res_empty())
+if (!req->ips.empty())
     {
     sprintf(str, "<ip value=\"%s\" />\n", req->ips.const_data().c_str());
     strcat(r, str);
@@ -504,7 +596,7 @@ int uPresent = false;
 int dPresent = false;
 for (int i = 0; i < DIR_NUM; i++)
     {
-    if (!req->u[i].res_empty())
+    if (!req->monthUpload[i].empty())
         {
         if (!uPresent && !dPresent)
             {
@@ -514,12 +606,12 @@ for (int i = 0; i < DIR_NUM; i++)
             }
 
         stringstream ss;
-        ss << req->u[i].const_data();
+        ss << req->monthUpload[i].const_data();
         //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
         sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
         strcat(r, str);
         }
-    if (!req->d[i].res_empty())
+    if (!req->monthDownload[i].empty())
         {
         if (!uPresent && !dPresent)
             {
@@ -529,7 +621,36 @@ for (int i = 0; i < DIR_NUM; i++)
             }
 
         stringstream ss;
-        ss << req->d[i].const_data();
+        ss << req->monthDownload[i].const_data();
+        sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
+        strcat(r, str);
+        }
+    if (!req->sessionUpload[i].empty())
+        {
+        if (!uPresent && !dPresent)
+            {
+            sprintf(str, "<traff ");
+            strcat(r, str);
+            uPresent = true;
+            }
+
+        stringstream ss;
+        ss << req->sessionUpload[i].const_data();
+        //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
+        sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
+        strcat(r, str);
+        }
+    if (!req->sessionDownload[i].empty())
+        {
+        if (!uPresent && !dPresent)
+            {
+            sprintf(str, "<traff ");
+            strcat(r, str);
+            dPresent = true;
+            }
+
+        stringstream ss;
+        ss << req->sessionDownload[i].const_data();
         sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
         strcat(r, str);
         }
@@ -541,7 +662,7 @@ if (uPresent || dPresent)
 
 //printf("%s\n", r);
 
-if (!req->tariff.res_empty())
+if (!req->tariff.empty())
     {
     switch (req->chgTariff)
         {
@@ -561,60 +682,60 @@ if (!req->tariff.res_empty())
 
     }
 
-if (!req->note.res_empty())
+if (!req->note.empty())
     {
     string note;
-    Encode12str(note, req->note);
+    Encode12str(note, req->note.data());
     sprintf(str, "<note value=\"%s\"/>", note.c_str());
     strcat(r, str);
     }
 
-if (!req->name.res_empty())
+if (!req->name.empty())
     {
     string name;
-    Encode12str(name, req->name);
+    Encode12str(name, req->name.data());
     sprintf(str, "<name value=\"%s\"/>", name.c_str());
     strcat(r, str);
     }
 
-if (!req->address.res_empty())
+if (!req->address.empty())
     {
     string address;
-    Encode12str(address, req->address);
+    Encode12str(address, req->address.data());
     sprintf(str, "<address value=\"%s\"/>", address.c_str());
     strcat(r, str);
     }
 
-if (!req->email.res_empty())
+if (!req->email.empty())
     {
     string email;
-    Encode12str(email, req->email);
+    Encode12str(email, req->email.data());
     sprintf(str, "<email value=\"%s\"/>", email.c_str());
     strcat(r, str);
     }
 
-if (!req->phone.res_empty())
+if (!req->phone.empty())
     {
     string phone;
-    Encode12str(phone, req->phone);
+    Encode12str(phone, req->phone.data());
     sprintf(str, "<phone value=\"%s\"/>", phone.c_str());
     strcat(r, str);
     }
 
-if (!req->group.res_empty())
+if (!req->group.empty())
     {
     string group;
-    Encode12str(group, req->group);
+    Encode12str(group, req->group.data());
     sprintf(str, "<group value=\"%s\"/>", group.c_str());
     strcat(r, str);
     }
 
 for (int i = 0; i < USERDATA_NUM; i++)
     {
-    if (!req->ud[i].res_empty())
+    if (!req->userData[i].empty())
         {
         string ud;
-        Encode12str(ud, req->ud[i]);
+        Encode12str(ud, req->userData[i].data());
         sprintf(str, "<userdata%d value=\"%s\"/>", i, ud.c_str());
         strcat(r, str);
         }
@@ -625,30 +746,32 @@ strcat(r, "</SetUser>\n");
 //-----------------------------------------------------------------------------
 int CheckParameters(REQUEST * req)
 {
-int u = false;
-int d = false;
-int ud = false;
-int a = !req->admLogin.res_empty()
-    && !req->admPasswd.res_empty()
-    && !req->server.res_empty()
-    && !req->port.res_empty()
-    && !req->login.res_empty();
-
-int b = !req->cash.res_empty()
-    || !req->setCash.res_empty()
-    || !req->credit.res_empty()
-    || !req->prepaidTraff.res_empty()
-    || !req->tariff.res_empty()
-    || !req->usrMsg.res_empty()
-    || !req->usrPasswd.res_empty()
-
-    || !req->note.res_empty()
-    || !req->name.res_empty()
-    || !req->address.res_empty()
-    || !req->email.res_empty()
-    || !req->phone.res_empty()
-    || !req->group.res_empty()
-    || !req->ips.res_empty()   // IP-address of user
+bool su = false;
+bool sd = false;
+bool mu = false;
+bool md = false;
+bool ud = false;
+bool a = !req->admLogin.empty()
+    && !req->admPasswd.empty()
+    && !req->server.empty()
+    && !req->port.empty()
+    && !req->login.empty();
+
+bool b = !req->cash.empty()
+    || !req->setCash.empty()
+    || !req->credit.empty()
+    || !req->prepaidTraff.empty()
+    || !req->tariff.empty()
+    || !req->usrMsg.empty()
+    || !req->usrPasswd.empty()
+
+    || !req->note.empty()
+    || !req->name.empty()
+    || !req->address.empty()
+    || !req->email.empty()
+    || !req->phone.empty()
+    || !req->group.empty()
+    || !req->ips.empty() // IP-address of user
 
     || !req->createUser
     || !req->deleteUser;
@@ -656,25 +779,43 @@ int b = !req->cash.res_empty()
 
 for (int i = 0; i < DIR_NUM; i++)
     {
-    if (req->u[i].res_empty())
+    if (req->sessionUpload[i].empty())
+        {
+        su = true;
+        break;
+        }
+    }
+
+for (int i = 0; i < DIR_NUM; i++)
+    {
+    if (req->sessionDownload[i].empty())
+        {
+        sd = true;
+        break;
+        }
+    }
+
+for (int i = 0; i < DIR_NUM; i++)
+    {
+    if (req->monthUpload[i].empty())
         {
-        u = true;
+        mu = true;
         break;
         }
     }
 
 for (int i = 0; i < DIR_NUM; i++)
     {
-    if (req->d[i].res_empty())
+    if (req->monthDownload[i].empty())
         {
-        d = true;
+        md = true;
         break;
         }
     }
 
 for (int i = 0; i < DIR_NUM; i++)
     {
-    if (req->ud[i].res_empty())
+    if (req->userData[i].empty())
         {
         ud = true;
         break;
@@ -683,7 +824,7 @@ for (int i = 0; i < DIR_NUM; i++)
 
 
 //printf("a=%d, b=%d, u=%d, d=%d ud=%d\n", a, b, u, d, ud);
-return a && (b || u || d || ud);
+return a && (b || su || sd || mu || md || ud);
 }
 //-----------------------------------------------------------------------------
 int CheckParametersGet(REQUEST * req)
@@ -696,7 +837,7 @@ int CheckParametersSet(REQUEST * req)
 return CheckParameters(req);
 }
 //-----------------------------------------------------------------------------
-int mainGet(int argc, char **argv)
+bool mainGet(int argc, char **argv)
 {
 int c;
 REQUEST req;
@@ -791,10 +932,10 @@ while (1)
         case 'G': //Group
             req.group = " ";
             break;
-       
-       case 'I': //IP-address of user
-           req.ips = " ";
-           break;
+
+        case 'I': //IP-address of user
+            req.ips = " ";
+            break;
 
         case 'S': //Detail stat status
             req.disableDetailStat = " ";
@@ -805,50 +946,33 @@ while (1)
             break;
 
         case 500: //U
+            SetArrayItem(req.sessionUpload, optarg, 1);
+            //req.sessionUpload[optarg] = 1;
+            break;
         case 501:
+            SetArrayItem(req.sessionDownload, optarg, 1);
+            //req.sessionDownload[optarg] = 1;
+            break;
         case 502:
+            SetArrayItem(req.monthUpload, optarg, 1);
+            //req.monthUpload[optarg] = 1;
+            break;
         case 503:
-        case 504:
-        case 505:
-        case 506:
-        case 507:
-        case 508:
-        case 509:
-            //printf("U%d\n", c - 500);
-            req.u[c - 500] = 1;
-            break;
-
-        case 600: //D
-        case 601:
-        case 602:
-        case 603:
-        case 604:
-        case 605:
-        case 606:
-        case 607:
-        case 608:
-        case 609:
-            //printf("D%d\n", c - 600);
-            req.d[c - 600] = 1;
+            SetArrayItem(req.monthDownload, optarg, 1);
+            //req.monthDownload[optarg] = 1;
             break;
 
         case 700: //UserData
-        case 701:
-        case 702:
-        case 703:
-        case 704:
-        case 705:
-        case 706:
-        case 707:
-        case 708:
-        case 709:
-            //printf("UD%d\n", c - 700);
-            req.ud[c - 700] = " ";
+            SetArrayItem(req.userData, optarg, std::string(" "));
+            //req.userData[optarg] = " ";
+            break;
+
+        case 800:
+            req.authBy = true;
             break;
 
         case '?':
         case ':':
-            //printf ("Unknown option \n");
             missedOptionArg = true;
             break;
 
@@ -873,10 +997,13 @@ if (missedOptionArg || !CheckParametersGet(&req))
     exit(PARAMETER_PARSING_ERR_CODE);
     }
 
-return ProcessGetUser(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req);
+if (req.authBy)
+    return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data());
+else
+    return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req);
 }
 //-----------------------------------------------------------------------------
-int mainSet(int argc, char **argv)
+bool mainSet(int argc, char **argv)
 {
 string str;
 
@@ -890,6 +1017,8 @@ const char * short_options_set = "s:p:a:w:u:c:r:t:m:o:d:i:e:v:nlN:A:D:L:P:G:I:S:
 
 int missedOptionArg = false;
 
+USER_CONF_RES conf;
+USER_STAT_RES stat;
 while (1)
     {
     int option_index = -1;
@@ -919,7 +1048,7 @@ while (1)
             break;
 
         case 'o': //change user password
-            req.usrPasswd = ParsePassword(optarg);
+            conf.password = ParsePassword(optarg);
             break;
 
         case 'u': //user
@@ -927,31 +1056,31 @@ while (1)
             break;
 
         case 'c': //add cash
-            req.cash = ParseCash(optarg, &req.message);
+            stat.cashAdd = ParseCash(optarg);
             break;
 
         case 'v': //set cash
-            req.setCash = ParseCash(optarg, &req.message);
+            stat.cashSet = ParseCash(optarg);
             break;
 
         case 'r': //credit
-            req.credit = ParseCredit(optarg);
+            conf.credit = ParseCredit(optarg);
             break;
 
         case 'E': //credit expire
-            req.creditExpire = ParseCreditExpire(optarg);
+            conf.creditExpire = ParseCreditExpire(optarg);
             break;
 
         case 'd': //down
-            req.down = ParseDownPassive(optarg);
+            conf.disabled = ParseDownPassive(optarg);
             break;
 
         case 'i': //passive
-            req.passive = ParseDownPassive(optarg);
+            conf.passive = ParseDownPassive(optarg);
             break;
 
         case 't': //tariff
-            req.tariff = ParseTariff(optarg, req.chgTariff);
+            ParseTariff(optarg, conf.tariffName, conf.nextTariff);
             break;
 
         case 'm': //message
@@ -961,7 +1090,7 @@ while (1)
             break;
 
         case 'e': //Prepaid Traffic
-            req.prepaidTraff = ParsePrepaidTraffic(optarg);
+            stat.freeMb = ParsePrepaidTraffic(optarg);
             break;
 
         case 'n': //Create User
@@ -974,98 +1103,70 @@ while (1)
 
         case 'N': //Note
             ParseAnyString(optarg, &str, "koi8-ru");
-            req.note = str;
+            conf.note = str;
             break;
 
         case 'A': //nAme
             ParseAnyString(optarg, &str, "koi8-ru");
-            req.name = str;
+            conf.realName = str;
             break;
 
         case 'D': //aDdress
             ParseAnyString(optarg, &str, "koi8-ru");
-            req.address = str;
+            conf.address = str;
             break;
 
         case 'L': //emaiL
             ParseAnyString(optarg, &str, "koi8-ru");
-            req.email = str;
-            //printf("EMAIL=%s\n", optarg);
+            conf.email = str;
             break;
 
         case 'P': //phone
             ParseAnyString(optarg, &str);
-            req.phone = str;
+            conf.phone = str;
             break;
 
         case 'G': //Group
             ParseAnyString(optarg, &str, "koi8-ru");
-            req.group = str;
+            conf.group = str;
             break;
 
         case 'I': //IP-address of user
             ParseAnyString(optarg, &str);
-            req.ips = str;
+            conf.ips = StrToIPS(str);
             break;
 
         case 'S':
-            req.disableDetailStat = ParseDownPassive(optarg);
+            conf.disabledDetailStat = ParseDownPassive(optarg);
             break;
 
         case 'O':
-            req.alwaysOnline = ParseDownPassive(optarg);
+            conf.alwaysOnline = ParseDownPassive(optarg);
             break;
 
         case 500: //U
+            SetArrayItem(stat.sessionUp, optarg, ParseTraff(argv[optind++]));
+            break;
         case 501:
+            SetArrayItem(stat.sessionDown, optarg, ParseTraff(argv[optind++]));
+            break;
         case 502:
+            SetArrayItem(stat.monthUp, optarg, ParseTraff(argv[optind++]));
+            break;
         case 503:
-        case 504:
-        case 505:
-        case 506:
-        case 507:
-        case 508:
-        case 509:
-            //printf("U%d\n", c - 500);
-            req.u[c - 500] = ParseTraff(optarg);
-            break;
-
-        case 600: //D
-        case 601:
-        case 602:
-        case 603:
-        case 604:
-        case 605:
-        case 606:
-        case 607:
-        case 608:
-        case 609:
-            //printf("D%d\n", c - 600);
-            req.d[c - 600] = ParseTraff(optarg);
+            SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++]));
             break;
 
         case 700: //UserData
-        case 701:
-        case 702:
-        case 703:
-        case 704:
-        case 705:
-        case 706:
-        case 707:
-        case 708:
-        case 709:
-            ParseAnyString(optarg, &str);
-            //printf("UD%d\n", c - 700);
-            req.ud[c - 700] = str;
+            ParseAnyString(argv[optind++], &str);
+            SetArrayItem(conf.userdata, optarg, str);
             break;
 
         case '?':
-            //printf("Missing option argument\n");
             missedOptionArg = true;
             break;
 
         case ':':
-            //printf("Missing option argument\n");
             missedOptionArg = true;
             break;
 
@@ -1094,12 +1195,59 @@ const int rLen = 20000;
 char rstr[rLen];
 memset(rstr, 0, rLen);
 
-CreateRequestSet(&req, rstr);
-return ProcessSetUser(req.server, req.port, req.admLogin, req.admPasswd, rstr, NULL, isMessage);
+if (isMessage)
+    return ProcessSendMessage(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req.usrMsg.data());
+
+return ProcessSetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), conf, stat);
 }
 //-----------------------------------------------------------------------------
 int main(int argc, char **argv)
 {
+SGCONF::CONFIG config;
+
+SGCONF::OPTION_BLOCKS blocks;
+blocks.Add("General options")
+      .Add("c", "config", SGCONF::MakeParamAction(config.configFile, std::string("~/.config/stg/sgconf.conf"), "<config file>"), "override default config file")
+      .Add("h", "help", SGCONF::MakeFunc0Action(bind0(Method1Adapt(&SGCONF::OPTION_BLOCKS::Help, blocks), 0)), "\t\tshow this help and exit")
+      .Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "\t\tshow full help and exit")
+      .Add("v", "version", SGCONF::MakeFunc0Action(Version), "\t\tshow version information and exit");
+blocks.Add("Connection options")
+      .Add("s", "server", SGCONF::MakeParamAction(config.server, std::string("localhost"), "<address>"), "\t\thost to connect")
+      .Add("p", "port", SGCONF::MakeParamAction(config.port, uint16_t(5555), "<port>"), "\t\tport to connect")
+      .Add("u", "username", SGCONF::MakeParamAction(config.userName, std::string("admin"), "<username>"), "\tadministrative login")
+      .Add("w", "userpass", SGCONF::MakeParamAction(config.userPass, "<password>"), "\tpassword for the administrative login")
+      .Add("a", "address", SGCONF::MakeParamAction(config, "<connection string>"), "connection params as a single string in format: <login>:<password>@<host>:<port>");
+
+
+SGCONF::PARSER_STATE state(false, argc, argv);
+
+try
+{
+state = blocks.Parse(--argc, ++argv); // Skipping self name
+}
+catch (const SGCONF::OPTION::ERROR& ex)
+{
+std::cerr << ex.what() << "\n";
+return -1;
+}
+
+if (state.stop)
+    return 0;
+
+if (state.argc > 0)
+    {
+    std::cerr << "Unknown option: '" << *state.argv << "'\n";
+    return -1;
+    }
+
+return 0;
+
+if (argc < 2)
+    {
+    Usage();
+    return 1;
+    }
+
 if (argc <= 2)
     {
     UsageConf();
@@ -1114,7 +1262,9 @@ if (strcmp(argv[1], "get") == 0)
 else if (strcmp(argv[1], "set") == 0)
     {
     //printf("set\n");
-    return mainSet(argc - 1, argv + 1);
+    if (mainSet(argc - 1, argv + 1) )
+        return 0;
+    return -1;
     }
 else
     {
@@ -1125,3 +1275,213 @@ return UNKNOWN_ERR_CODE;
 }
 //-----------------------------------------------------------------------------
 
+namespace
+{
+
+void Usage()
+{
+UsageImpl(false);
+}
+
+void UsageAll()
+{
+UsageImpl(true);
+}
+
+void UsageImpl(bool full)
+{
+std::cout << "sgconf is the Stargazer management utility.\n\n"
+          << "Usage:\n"
+          << "\tsgconf [options]\n\n"
+          << "General options:\n"
+          << "\t-c, --config <config file>\t\toverride default config file (default: \"~/.config/stg/sgconf.conf\")\n"
+          << "\t-h, --help\t\t\t\tshow this help and exit\n"
+          << "\t--help-all\t\t\t\tshow full help and exit\n"
+          << "\t-v, --version\t\t\t\tshow version information and exit\n\n";
+UsageConnection();
+UsageAdmins(full);
+UsageTariffs(full);
+UsageUsers(full);
+UsageServices(full);
+UsageCorporations(full);
+}
+//-----------------------------------------------------------------------------
+void UsageConnection()
+{
+std::cout << "Connection options:\n"
+          << "\t-s, --server <address>\t\t\thost to connect (ip or domain name, default: \"localhost\")\n"
+          << "\t-p, --port <port>\t\t\tport to connect (default: \"5555\")\n"
+          << "\t-u, --username <username>\t\tadministrative login (default: \"admin\")\n"
+          << "\t-w, --userpass <password>\t\tpassword for administrative login\n"
+          << "\t-a, --address <connection string>\tconnection params as a single string in format: <login>:<password>@<host>:<port>\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageAdmins(bool full)
+{
+std::cout << "Admins management options:\n"
+          << "\t--get-admins\t\t\t\tget a list of admins (subsequent options will define what to show)\n";
+if (full)
+    std::cout << "\t\t--login\t\t\t\tshow admin's login\n"
+              << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
+std::cout << "\t--get-admin\t\t\t\tget the information about admin\n";
+if (full)
+    std::cout << "\t\t--login <login>\t\t\tlogin of the admin to show\n"
+              << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
+std::cout << "\t--add-admin\t\t\t\tadd a new admin\n";
+if (full)
+    std::cout << "\t\t--login <login>\t\t\tlogin of the admin to add\n"
+              << "\t\t--password <password>\t\tpassword of the admin to add\n"
+              << "\t\t--priv <priv number>\t\tpriviledges of the admin to add\n\n";
+std::cout << "\t--del-admin\t\t\t\tdelete an existing admin\n";
+if (full)
+    std::cout << "\t\t--login <login>\t\t\tlogin of the admin to delete\n\n";
+std::cout << "\t--chg-admin\t\t\t\tchange an existing admin\n";
+if (full)
+    std::cout << "\t\t--login <login>\t\t\tlogin of the admin to change\n"
+              << "\t\t--priv <priv number>\t\tnew priviledges\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageTariffs(bool full)
+{
+std::cout << "Tariffs management options:\n"
+          << "\t--get-tariffs\t\t\t\tget a list of tariffs (subsequent options will define what to show)\n";
+if (full)
+    std::cout << "\t\t--name\t\t\t\tshow tariff's name\n"
+              << "\t\t--fee\t\t\t\tshow tariff's fee\n"
+              << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
+              << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
+              << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
+              << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
+std::cout << "\t--get-tariff\t\t\t\tget the information about tariff\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the tariff to show\n"
+              << "\t\t--fee\t\t\t\tshow tariff's fee\n"
+              << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
+              << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
+              << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
+              << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
+std::cout << "\t--add-tariff\t\t\t\tadd a new tariff\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the tariff to add\n"
+              << "\t\t--fee <fee>\t\t\tstariff's fee\n"
+              << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
+              << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
+              << "\t\t--traff-type <type>\t\twhat type of traffi will be accounted by the tariff\n"
+              << "\t\t--times <times>\t\t\tslash-separated list of \"day\" time-spans (in form \"hh:mm-hh:mm\") for each direction\n"
+              << "\t\t--prices-day-a <prices>\t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n"
+              << "\t\t--prices-night-a <prices>\tslash-separated list of prices for \"night\" traffic before threshold for each direction\n"
+              << "\t\t--prices-day-b <prices>\t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n"
+              << "\t\t--prices-night-b <prices>\tslash-separated list of prices for \"night\" traffic after threshold for each direction\n"
+              << "\t\t--single-prices <yes|no>\tslash-separated list of \"single price\" flags for each direction\n"
+              << "\t\t--no-discounts <yes|no>\t\tslash-separated list of \"no discount\" flags for each direction\n"
+              << "\t\t--thresholds <thresholds>\tslash-separated list of thresholds (in Mb) for each direction\n\n";
+std::cout << "\t--del-tariff\t\t\t\tdelete an existing tariff\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the tariff to delete\n\n";
+std::cout << "\t--chg-tariff\t\t\t\tchange an existing tariff\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the tariff to change\n"
+              << "\t\t--fee <fee>\t\t\tstariff's fee\n"
+              << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
+              << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
+              << "\t\t--traff-type <type>\t\twhat type of traffix will be accounted by the tariff\n"
+              << "\t\t--dir <N>\t\t\tnumber of direction data to change\n"
+              << "\t\t\t--time <time>\t\t\"day\" time-span (in form \"hh:mm-hh:mm\")\n"
+              << "\t\t\t--price-day-a <price>\tprice for \"day\" traffic before threshold\n"
+              << "\t\t\t--price-night-a <price>\tprice for \"night\" traffic before threshold\n"
+              << "\t\t\t--price-day-b <price>\tprice for \"day\" traffic after threshold\n"
+              << "\t\t\t--price-night-b <price>\tprice for \"night\" traffic after threshold\n"
+              << "\t\t\t--single-price <yes|no>\t\"single price\" flag\n"
+              << "\t\t\t--no-discount <yes|no>\t\"no discount\" flag\n"
+              << "\t\t\t--threshold <threshold>\tthreshold (in Mb)\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageUsers(bool full)
+{
+std::cout << "Users management options:\n"
+          << "\t--get-users\t\t\t\tget a list of users (subsequent options will define what to show)\n";
+if (full)
+    std::cout << "\n\n";
+std::cout << "\t--get-user\t\t\t\tget the information about user\n";
+if (full)
+    std::cout << "\n\n";
+std::cout << "\t--add-user\t\t\t\tadd a new user\n";
+if (full)
+    std::cout << "\n\n";
+std::cout << "\t--del-user\t\t\t\tdelete an existing user\n";
+if (full)
+    std::cout << "\n\n";
+std::cout << "\t--chg-user\t\t\t\tchange an existing user\n";
+if (full)
+    std::cout << "\n\n";
+std::cout << "\t--check-user\t\t\t\tcheck credentials is valid\n";
+if (full)
+    std::cout << "\n\n";
+std::cout << "\t--send-message\t\t\t\tsend a message to a user\n";
+if (full)
+    std::cout << "\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageServices(bool full)
+{
+std::cout << "Services management options:\n"
+          << "\t--get-services\t\t\t\tget a list of services (subsequent options will define what to show)\n";
+if (full)
+    std::cout << "\t\t--name\t\t\t\tshow service's name\n"
+              << "\t\t--comment\t\t\tshow a comment to the service\n"
+              << "\t\t--cost\t\t\t\tshow service's cost\n"
+              << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
+std::cout << "\t--get-service\t\t\t\tget the information about service\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the service to show\n"
+              << "\t\t--comment\t\t\tshow a comment to the service\n"
+              << "\t\t--cost\t\t\t\tshow service's cost\n"
+              << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
+std::cout << "\t--add-service\t\t\t\tadd a new service\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the service to add\n"
+              << "\t\t--comment <comment>\t\ta comment to the service\n"
+              << "\t\t--cost <cost>\t\t\tservice's cost\n"
+              << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
+std::cout << "\t--del-service\t\t\t\tdelete an existing service\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the service to delete\n\n";
+std::cout << "\t--chg-service\t\t\t\tchange an existing service\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the service to change\n"
+              << "\t\t--comment <comment>\t\ta comment to the service\n"
+              << "\t\t--cost <cost>\t\t\tservice's cost\n"
+              << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageCorporations(bool full)
+{
+std::cout << "Corporations management options:\n"
+          << "\t--get-corporations\t\t\tget a list of corporations (subsequent options will define what to show)\n";
+if (full)
+    std::cout << "\t\t--name\t\t\t\tshow corporation's name\n"
+              << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
+std::cout << "\t--get-corp\t\t\t\tget the information about corporation\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the corporation to show\n"
+              << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
+std::cout << "\t--add-corp\t\t\t\tadd a new corporation\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the corporation to add\n"
+              << "\t\t--cash <cash>\t\t\tinitial corporation's cash (default: \"0\")\n\n";
+std::cout << "\t--del-corp\t\t\t\tdelete an existing corporation\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the corporation to delete\n\n";
+std::cout << "\t--chg-corp\t\t\t\tchange an existing corporation\n";
+if (full)
+    std::cout << "\t\t--name <name>\t\t\tname of the corporation to change\n"
+              << "\t\t--add-cash <amount>[:<message>]\tadd cash to the corporation's account and optional comment message\n"
+              << "\t\t--set-cash <cash>[:<message>]\tnew corporation's cash and optional comment message\n\n";
+}
+
+void Version()
+{
+std::cout << "sgconf, version: 2.0.0-alpha.\n";
+}
+
+} // namespace anonymous
diff --git a/projects/sgconf/options.cpp b/projects/sgconf/options.cpp
new file mode 100644 (file)
index 0000000..6fddaf3
--- /dev/null
@@ -0,0 +1,176 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "options.h"
+
+#include "action.h"
+#include "parser_state.h"
+
+#include <iostream>
+#include <functional>
+#include <algorithm>
+
+using SGCONF::OPTION;
+using SGCONF::OPTION_BLOCK;
+using SGCONF::OPTION_BLOCKS;
+using SGCONF::ACTION;
+using SGCONF::PARSER_STATE;
+
+OPTION::OPTION(const std::string & shortName,
+               const std::string & longName,
+               ACTION * action,
+               const std::string & description)
+    : m_shortName(shortName),
+      m_longName(longName),
+      m_action(action),
+      m_description(description)
+{
+}
+
+OPTION::OPTION(const std::string & longName,
+               ACTION * action,
+               const std::string & description)
+    : m_longName(longName),
+      m_action(action),
+      m_description(description)
+{
+}
+
+OPTION::OPTION(const OPTION & rhs)
+    : m_shortName(rhs.m_shortName),
+      m_longName(rhs.m_longName),
+      m_action(rhs.m_action->Clone()),
+      m_description(rhs.m_description)
+{
+}
+
+OPTION::~OPTION()
+{
+delete m_action;
+}
+
+void OPTION::Help(size_t level) const
+{
+if (!m_action)
+    throw ERROR("Option is not defined.");
+std::string indent(level, '\t');
+std::cout << indent << "\t";
+if (!m_shortName.empty())
+    std::cout << "-" << m_shortName << ", ";
+std::cout << "--" << m_longName << " " << m_action->ParamDescription()
+          << "\t" << m_description << m_action->DefaultDescription() << "\n";
+m_action->Suboptions().Help(level + 1);
+}
+
+bool OPTION::Check(const char * arg) const
+{
+if (arg == NULL)
+    return false;
+
+if (*arg++ != '-')
+    return false;
+
+if (*arg == '-')
+    return m_longName == arg + 1;
+
+return m_shortName == arg;
+}
+
+PARSER_STATE OPTION::Parse(int argc, char ** argv)
+{
+if (!m_action)
+    throw ERROR("Option is not defined.");
+try
+    {
+    return m_action->Parse(argc, argv);
+    }
+catch (const ACTION::ERROR & ex)
+    {
+    if (m_longName.empty())
+        throw ERROR("-" + m_shortName + ": " + ex.what());
+    else
+        throw ERROR("--" + m_longName + ", -" + m_shortName + ": " + ex.what());
+    }
+}
+
+OPTION_BLOCK & OPTION_BLOCK::Add(const std::string & shortName,
+                                 const std::string & longName,
+                                 ACTION * action,
+                                 const std::string & description)
+{
+m_options.push_back(OPTION(shortName, longName, action, description));
+return *this;
+}
+
+OPTION_BLOCK & OPTION_BLOCK::Add(const std::string & longName,
+                                 ACTION * action,
+                                 const std::string & description)
+{
+m_options.push_back(OPTION(longName, action, description));
+return *this;
+}
+
+void OPTION_BLOCK::Help(size_t level) const
+{
+if (m_options.empty())
+    return;
+std::cout << m_description << ":\n";
+std::for_each(m_options.begin(),
+              m_options.end(),
+              std::bind2nd(std::mem_fun_ref(&OPTION::Help), level + 1));
+}
+
+PARSER_STATE OPTION_BLOCK::Parse(int argc, char ** argv)
+{
+PARSER_STATE state(false, argc, argv);
+while (state.argc > 0 && !state.stop)
+    {
+    std::vector<OPTION>::iterator it = std::find_if(m_options.begin(), m_options.end(), std::bind2nd(std::mem_fun_ref(&OPTION::Check), *state.argv));
+    if (it != m_options.end())
+        state = it->Parse(--state.argc, ++state.argv);
+    else
+        break;
+    ++it;
+    }
+return state;
+}
+
+void OPTION_BLOCKS::Help(size_t level) const
+{
+std::list<OPTION_BLOCK>::const_iterator it(m_blocks.begin());
+while (it != m_blocks.end())
+    {
+    it->Help(level);
+    std::cout << "\n";
+    ++it;
+    }
+}
+
+PARSER_STATE OPTION_BLOCKS::Parse(int argc, char ** argv)
+{
+PARSER_STATE state(false, argc, argv);
+std::list<OPTION_BLOCK>::iterator it(m_blocks.begin());
+while (!state.stop && it != m_blocks.end())
+    {
+    state = it->Parse(state.argc, state.argv);
+    ++it;
+    }
+return state;
+}
diff --git a/projects/sgconf/options.h b/projects/sgconf/options.h
new file mode 100644 (file)
index 0000000..3d4bdd6
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_OPTIONS_H__
+#define __STG_SGCONF_OPTIONS_H__
+
+#include <string>
+#include <vector>
+#include <list>
+#include <stdexcept>
+#include <cstddef> // size_t
+
+namespace SGCONF
+{
+
+class ACTION;
+struct PARSER_STATE;
+
+class OPTION
+{
+    public:
+        OPTION(const std::string & shortName,
+               const std::string & longName,
+               ACTION * action,
+               const std::string & description);
+        OPTION(const std::string & longName,
+               ACTION * action,
+               const std::string & description);
+        OPTION(const OPTION & rhs);
+        ~OPTION();
+
+        OPTION & operator=(const OPTION & rhs);
+
+        void Help(size_t level = 0) const;
+        PARSER_STATE Parse(int argc, char ** argv);
+        bool Check(const char * arg) const;
+
+        class ERROR : public std::runtime_error
+        {
+            public:
+                ERROR(const std::string & message)
+                    : std::runtime_error(message.c_str()) {}
+        };
+
+    private:
+        std::string m_shortName;
+        std::string m_longName;
+        ACTION * m_action;
+        std::string m_description;
+};
+
+class OPTION_BLOCK
+{
+    public:
+        OPTION_BLOCK() {}
+        OPTION_BLOCK(const std::string & description)
+            : m_description(description) {}
+        OPTION_BLOCK & Add(const std::string & shortName,
+                           const std::string & longName,
+                           ACTION * action,
+                           const std::string & description);
+        OPTION_BLOCK & Add(const std::string & longName,
+                           ACTION * action,
+                           const std::string & description);
+
+        void Help(size_t level) const;
+
+        PARSER_STATE Parse(int argc, char ** argv);
+
+    private:
+        std::vector<OPTION> m_options;
+        std::string m_description;
+};
+
+class OPTION_BLOCKS
+{
+    public:
+        OPTION_BLOCK & Add(const std::string & description)
+        { m_blocks.push_back(OPTION_BLOCK(description)); return m_blocks.back(); }
+        void Help(size_t level) const;
+        PARSER_STATE Parse(int argc, char ** argv);
+
+    private:
+        std::list<OPTION_BLOCK> m_blocks;
+};
+
+} // namespace SGCONF
+
+#endif
diff --git a/projects/sgconf/parser_state.h b/projects/sgconf/parser_state.h
new file mode 100644 (file)
index 0000000..22ad794
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_PARSER_STATE_H__
+#define __STG_SGCONF_PARSER_STATE_H__
+
+namespace SGCONF
+{
+
+struct PARSER_STATE
+{
+    PARSER_STATE(bool s, int c, char ** v) : stop(s), argc(c), argv(v) {}
+    bool stop;
+    int argc;
+    char ** argv;
+};
+
+}
+
+#endif
index daddec1d3401f6d2eec33d1a2678a98823bd922a..bca3c148e1892f1e0306c2683a3aec8cbb6b81e7 100644 (file)
@@ -49,16 +49,19 @@ struct REQUEST
 REQUEST()
     : chgTariff(false),
       createUser(false),
-      deleteUser(false)
+      deleteUser(false),
+      authBy(false)
 {
     for (int i = 0; i < DIR_NUM; i++)
         {
-        u[i].reset();
-        d[i].reset();
+        sessionUpload[i].reset();
+        sessionDownload[i].reset();
+        monthUpload[i].reset();
+        monthDownload[i].reset();
         }
 
     for (int i = 0; i < USERDATA_NUM; i++)
-        ud[i].reset();
+        userData[i].reset();
 }
 
 RESETABLE<string>   server;
@@ -75,6 +78,7 @@ RESETABLE<double>   setCash;
 string              message;
 bool                createUser;
 bool                deleteUser;
+bool                authBy;
 
 RESETABLE<string>   usrMsg;
 RESETABLE<double>   credit;
@@ -86,10 +90,13 @@ RESETABLE<bool>     disableDetailStat;
 RESETABLE<bool>     alwaysOnline;
 RESETABLE<double>   prepaidTraff;
 
-RESETABLE<int64_t>  u[DIR_NUM];
-RESETABLE<int64_t>  d[DIR_NUM];
+RESETABLE<int64_t>  sessionUpload[DIR_NUM];
+RESETABLE<int64_t>  sessionDownload[DIR_NUM];
 
-RESETABLE<string>   ud[USERDATA_NUM];
+RESETABLE<int64_t>  monthUpload[DIR_NUM];
+RESETABLE<int64_t>  monthDownload[DIR_NUM];
+
+RESETABLE<string>   userData[USERDATA_NUM];
 
 RESETABLE<string>   note;
 RESETABLE<string>   name;
index b7ebca0addfb67ba8950e00ba94087d9383ea135..b953bb526cd9b059958e19cb37dfda8c6e78a5cd 100644 (file)
@@ -66,7 +66,11 @@ distclean: clean
 install: install-bin install-data
 
 install-bin:
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG)
+endif
        $(MAKE) -C $(DIR_LIBSRC) install
 
 uninstall: uninstall-bin uninstall-data
index f78e6f70ccbf41c58dd25f26030ac699b31d3c25..e9cfb40b478eaba32419daefc104d171a0187e9d 100755 (executable)
@@ -16,18 +16,15 @@ DATA_MODE=0644
 DIR_MODE=0755
 OWNER=root
 
-if [ -z $1 ]
+if [ "$1" = "debug" ]
 then
-    MAKEOPTS="-j1"
+   DEFS="$DEFS -DDEBUG"
+   MAKEOPTS="$MAKEOPTS -j1"
+   CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+   DEBUG="yes"
 else
-    if [ "$1" = "debug" ]
-    then
-        DEFS="-DDEBUG"
-        MAKEOPTS="-j1"
-        CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
-    else
-        MAKEOPTS="-j1"
-    fi
+   DEFS="$DEFS -DNDEBUG"
+   DEBUG="no"
 fi
 
 CXXFLAGS="$CXXFLAGS -I/usr/local/include"
@@ -56,15 +53,15 @@ fi
 
 if [ "$OS" = "unknown" ]
 then 
-    echo "#############################################################################"
-    echo "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
+    printf "#############################################################################\n"
+    printf "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #\n"
+    printf "#############################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building sgconf for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building sgconf for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="conffiles.lib
          crypto.lib 
@@ -100,32 +97,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -134,60 +131,61 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 
-echo -n "Checking for -lexpat... "
-echo "int main() { return 0; }" > build_check.c
+printf "Checking for -lexpat... "
+printf "int main() { return 0; }\n" > build_check.c
 $CC $CXXFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
     CHECK_EXPAT=no
-    echo "no"
+    printf "no\n"
 else
     CHECK_EXPAT=yes
-    echo "yes"
+    printf "yes\n"
 fi
 rm -f fake
 rm -f build_check.c
 
 if [ "$CHECK_EXPAT" != "yes" ]
 then
-    echo "-lexpat not found!"
+    printf "-lexpat not found!\n"
     exit 1
 fi
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
 
 $MAKE $MAKEOPTS
 
diff --git a/projects/sgconv/Makefile b/projects/sgconv/Makefile
new file mode 100644 (file)
index 0000000..794114c
--- /dev/null
@@ -0,0 +1,97 @@
+###############################################################################
+# $Id: Makefile,v 1.12 2009/03/03 15:49:34 faust Exp $
+###############################################################################
+
+include ../../Makefile.conf
+
+PROG = sgconv
+
+SRCS = ./main.cpp \
+       ./settings_impl.cpp
+
+STGLIBS = dotconfpp \
+         conffiles \
+         logger \
+         crypto \
+          common
+
+STGLIBS_INCS = $(addprefix -I ../../stglibs/,$(addsuffix .lib/include,$(STGLIBS)))
+STGLIBS_LIBS = $(addprefix -L ../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
+
+LIBS += $(addprefix -lstg,$(STGLIBS)) $(LIB_THREAD)
+
+ifeq ($(OS),linux)
+LIBS += -ldl
+else
+LIBS += -lc -liconv
+endif
+
+SEARCH_DIRS = -I ../../include
+
+OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
+
+CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
+CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
+LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
+
+.PHONY: all clean distclean libs plugins install uninstall
+all: libs plugins $(PROG) ../../Makefile.conf
+
+libs:
+       $(MAKE) -C $(DIR_LIBSRC)
+
+plugins: libs 
+       $(MAKE) -C $(DIR_PLUGINS)
+
+$(PROG): $(OBJS)
+       $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG)
+
+clean:
+       rm -f deps $(PROG) *.o tags *.*~ .OS
+       rm -f .OS
+       rm -f .store
+       rm -f .db.sql
+       rm -f core*
+       $(MAKE) -C $(DIR_LIBSRC) clean
+       $(MAKE) -C $(DIR_PLUGINS) clean
+
+distclean: clean
+       rm -f ../../Makefile.conf
+
+install: install-bin
+
+install-bin:
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG)
+endif
+       $(MAKE) -C $(DIR_PLUGINS) install
+
+uninstall: uninstall-bin
+
+uninstall-bin:
+       rm -f $(PREFIX)/usr/bin/$(PROG)
+
+ifneq ($(MAKECMDGOALS),distclean)
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(MAKECMDGOALS),uninstall)
+-include deps
+endif
+endif
+endif
+
+deps:  $(SRCS) ../../Makefile.conf
+       $(MAKE) -C $(DIR_LIBSRC)
+       @>deps ;\
+       for file in $(SRCS); do\
+         echo "$$file" | grep ".c$$" > /dev/null;\
+         if [ $$? -eq 0 ];\
+         then\
+           echo "`$(CC) $(CFLAGS) -MM $$file` Makefile" >> deps ;\
+           printf '%b\n' '\t$$(CC) $(CFLAGS) -c $$<' >> deps ;\
+         else\
+           echo "`$(CXX) $(CXXFLAGS) -MM $$file` Makefile" >> deps ;\
+           printf '%b\n' '\t$$(CXX) $(CXXFLAGS) -c $$<' >> deps ;\
+         fi;\
+       done
diff --git a/projects/sgconv/build b/projects/sgconv/build
new file mode 100755 (executable)
index 0000000..7e430be
--- /dev/null
@@ -0,0 +1,300 @@
+#!/bin/sh
+
+#   $Revision: 1.20 $
+#   $Author: faust $
+#   $Date: 2010/04/14 08:58:43 $
+######################################################
+
+OS=unknown
+sys=`uname -s`
+release=`uname -r | cut -b1`
+BUILD_DIR=`pwd`
+CONFFILE="../../Makefile.conf"
+PREFIX="/"
+BIN_MODE=0755
+DATA_MODE=0644
+DIR_MODE=0755
+OWNER=root
+VAR_DIR="./inst/var/stargazer"
+
+if [ "$1" = "debug" ]
+then
+   DEFS="$DEFS -DDEBUG"
+   MAKEOPTS="$MAKEOPTS -j1"
+   CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+   DEBUG="yes"
+else
+   DEFS="$DEFS -DNDEBUG"
+   DEBUG="no"
+fi
+
+CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -I/usr/local/include"
+LDFLAGS="$LDFLAGS -L/usr/local/lib"
+
+if [ "$sys" = "Linux" ]
+then
+    OS=linux
+    release=""
+    MAKE="make"
+fi
+
+if [ "$sys" = "FreeBSD" ]
+then
+    case $release in
+        4) OS=bsd;;
+        5) OS=bsd5;;
+        6) OS=bsd5;;
+        7) OS=bsd7;;
+        8) OS=bsd7;;
+        9) OS=bsd7;;
+        *) OS=unknown;;
+    esac
+    MAKE="gmake"
+fi
+
+if [ "$OS" = "unknown" ]
+then 
+    printf "#############################################################################\n"
+    printf "# Sorry, but sgconv currently supported by Linux, FreeBSD 4.x, 5.x, 6.x     #\n"
+    printf "#############################################################################\n"
+    exit 1
+fi
+
+printf "#############################################################################\n"
+printf "       Building sgconv for $sys $release\n"
+printf "#############################################################################\n"
+
+STG_LIBS="logger.lib 
+          locker.lib
+         crypto.lib 
+         common.lib 
+         conffiles.lib
+         dotconfpp.lib"
+
+PLUGINS="store/files"
+
+if [ "$OS" = "linux" ]
+then
+    DEFS="$DEFS -DLINUX"
+    LIB_THREAD=-lpthread
+else
+    if [ "$OS" = "bsd" ]
+    then
+        DEFS="$DEFS -DFREE_BSD"
+        LIB_THREAD=-lc_r
+    else
+        DEFS="$DEFS -DFREE_BSD5"
+        if [ "$OS" = "bsd7" ]
+        then
+            LIB_THREAD=-lpthread
+        else
+            LIB_THREAD=-lc_r
+        fi
+    fi
+fi
+
+if [ -z "$CC" ]
+then
+    CC=gcc
+fi
+
+if [ -z "$CXX" ]
+then
+    CXX=g++
+fi
+
+printf "Checking CC... "
+$CC --version > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+    printf "FAIL!\n"
+    printf "$CC not found\n"
+    exit;
+fi
+printf "found\n"
+printf "Checking CXX... "
+$CXX --version > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
+    exit;
+fi
+printf "found\n"
+
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
+$CC $CFLAGS $LDFLAGS -L/usr/lib/mysql -L/usr/local/lib/mysql build_check.c -o fake > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
+    exit;
+else
+    ./fake
+    if [ $? = 1 ]
+    then
+        ARCH=le
+        CXXFLAGS="$CXXFLAGS -DARCH_LE"
+        CFLAGS="$CFLAGS -DARCH_LE"
+        printf "Little Endian\n"
+    else
+        ARCH=be
+        CXXFLAGS="$CXXFLAGS -DARCH_BE"
+        CFLAGS="$CFLAGS -DARCH_BE"
+        printf "Big Endian\n"
+    fi
+fi
+rm -f fake
+
+printf "Checking for -lfbclient... "
+$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+    CHECK_FBCLIENT=no
+    printf "no\n"
+else
+    CHECK_FBCLIENT=yes
+    printf "yes\n"
+fi
+rm -f fake
+
+printf "Checking for mysql_config... "
+MYSQL_VERSION=`mysql_config --version 2> /dev/null`
+if [ $? != 0 ]
+then
+    printf "no\n";
+    printf "Checking for -lmysqlclient... "
+    $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
+    if [ $? != 0 ]
+    then
+        CHECK_MYSQLCLIENT=no
+        printf "no\n"
+    else
+        CHECK_MYSQLCLIENT=yes
+        printf "yes\n"
+    fi
+    rm -f fake
+else
+    printf "yes\n"
+    printf "Checking for mysql_config --cflags... "
+    MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
+    if [ $? != 0 ]
+    then
+        CHECK_MYSQLCLIENT=no
+        printf "no\n"
+    else
+        printf "[$MYSQL_CFLAGS]\n"
+        printf "Checking for mysql_config --libs_r... "
+        MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
+        if [ $? != 0 ]
+        then
+            CHECK_MYSQLCLIENT=no
+            printf "no\n"
+        else
+            CHECK_MYSQLCLIENT=yes
+            printf "[$MYSQL_LDFLAGS]\n"
+        fi
+    fi
+fi
+
+printf "Checking for pg_config... "
+PG_VERSION=`pg_config --version 2> /dev/null`
+if [ $? != 0 ]
+then
+    printf "no\n";
+    printf "Checking for -lpq... "
+    $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
+    if [ $? != 0 ]
+    then
+        CHECK_PQ=no
+        printf "no\n"
+    else
+        CHECK_PQ=yes
+        printf "yes\n"
+    fi
+    rm -f fake
+else
+    printf "yes\n";
+    printf "Checking for pg_config --includedir... "
+    PG_CFLAGS=`pg_config --includedir 2> /dev/null`
+    if [ $? != 0 ]
+    then
+        CHECK_PQ=no
+        printf "no\n"
+    else
+        printf "[$PG_CFLAGS]\n"
+        printf "Checking for pg_config --libdir... "
+        PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
+        if [ $? != 0 ]
+        then
+            CHECK_PQ=no
+            printf "no\n"
+        else
+            CHECK_PQ=yes
+            printf "[$PG_LDFLAGS]\n"
+        fi
+    fi
+fi
+
+rm -f build_check.c
+
+if [ "$CHECK_FBCLIENT" = "yes" ]
+then
+    STG_LIBS="$STG_LIBS
+          ibpp.lib"
+    PLUGINS="$PLUGINS
+         store/firebird"
+fi
+
+if [ "$CHECK_PQ" = "yes" ]
+then
+    PLUGINS="$PLUGINS
+             store/postgresql"
+fi
+
+if [ "$CHECK_MYSQLCLIENT" = "yes" ]
+then
+    PLUGINS="$PLUGINS
+         store/mysql"
+fi
+
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules\n" >> $CONFFILE
+printf "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_FBCLIENT=$CHECK_FBCLIENT\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
+for lib in $STG_LIBS
+do
+    printf "$lib " >> $CONFFILE
+done
+printf "\n" >> $CONFFILE
+printf "PLUGINS=" >> $CONFFILE
+for plugin in $PLUGINS
+do
+    printf "$plugin " >> $CONFFILE
+done
+printf "\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
+printf "VAR_DIR=$VAR_DIR\n" >> $CONFFILE
+
+mkdir -p ../stargazer/modules
+
+$MAKE $MAKEOPTS
+
diff --git a/projects/sgconv/main.cpp b/projects/sgconv/main.cpp
new file mode 100644 (file)
index 0000000..e0679d0
--- /dev/null
@@ -0,0 +1,446 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+ /*
+ $Revision: 1.11 $
+ $Date: 2010/03/25 12:32:30 $
+ $Author: faust $
+ */
+
+#include <dlfcn.h>
+
+#include <string>
+#include <vector>
+#include <iostream>
+#include <ctime>
+#include <algorithm>
+
+#include "stg/common.h"
+#include "stg/store.h"
+#include "stg/conffiles.h"
+
+#include "stg/user_stat.h"
+#include "stg/user_conf.h"
+#include "stg/corp_conf.h"
+#include "stg/service_conf.h"
+#include "stg/admin_conf.h"
+#include "stg/tariff_conf.h"
+#include "stg/settings.h"
+#include "stg/message.h"
+
+#include "settings_impl.h"
+
+using namespace std;
+
+volatile time_t stgTime = time(NULL);
+
+int main(int argc, char **argv)
+{
+printfd(__FILE__, "Start\n");
+
+STORE * fromStore = NULL;
+STORE * toStore = NULL;
+
+SETTINGS_IMPL * settings = NULL;
+
+string modulePath;
+
+MODULE_SETTINGS fromStoreSettings;
+MODULE_SETTINGS toStoreSettings;
+
+ADMIN_CONF ac;
+USER_CONF uc;
+USER_STAT us;
+STG_MSG msg;
+TARIFF_DATA td;
+CORP_CONF cc;
+SERVICE_CONF sc;
+vector<STG_MSG_HDR> hdrs;
+
+if (argc == 2)
+    settings = new SETTINGS_IMPL(argv[1]);
+else
+    settings = new SETTINGS_IMPL();
+
+if (settings->ReadSettings())
+    {
+    printfd(__FILE__, "Error reading settings\n");
+    delete settings;
+    return -1;
+    }
+
+fromStoreSettings = settings->GetSourceStoreModuleSettings();
+toStoreSettings = settings->GetDestStoreModuleSettings();
+modulePath = settings->GetModulesPath();
+
+string sourcePlugin(modulePath + "/mod_" + fromStoreSettings.moduleName + ".so");
+string destPlugin(modulePath + "/mod_" + toStoreSettings.moduleName + ".so");
+
+void * src_lh = dlopen(sourcePlugin.c_str(), RTLD_NOW);
+if (!src_lh)
+    {
+    printfd(__FILE__, "Source storage plugin loading failed: %s\n", dlerror());
+    delete settings;
+    return -1;
+    }
+
+void * dst_lh = dlopen(destPlugin.c_str(), RTLD_NOW);
+if (!dst_lh)
+    {
+    printfd(__FILE__, "Destination storage plugin loading failed: %s\n", dlerror());
+    delete settings;
+    return -1;
+    }
+
+STORE * (*GetSourceStore)();
+STORE * (*GetDestStore)();
+GetSourceStore = (STORE * (*)())dlsym(src_lh, "GetStore");
+if (!GetSourceStore)
+    {
+    printfd(__FILE__, "Source storage plugin loading failed. GetStore not found: %s\n", dlerror());
+    delete settings;
+    return -1;
+    }
+GetDestStore = (STORE * (*)())dlsym(dst_lh, "GetStore");
+if (!GetDestStore)
+    {
+    printfd(__FILE__, "Storage plugin (firebird) loading failed. GetStore not found: %s\n", dlerror());
+    delete settings;
+    return -1;
+    }
+
+fromStore = GetSourceStore();
+toStore = GetDestStore();
+
+vector<string> entities;
+vector<string> ready;
+fromStore->SetSettings(fromStoreSettings);
+fromStore->ParseSettings();
+toStore->SetSettings(toStoreSettings);
+toStore->ParseSettings();
+
+printfd(__FILE__, "Importing admins:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetAdminsList(&entities))
+    {
+    printfd(__FILE__, "Error getting admins list: %s\n", fromStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+if (toStore->GetAdminsList(&ready))
+    {
+    printfd(__FILE__, "Error getting admins list: %s\n", toStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+
+vector<string>::const_iterator it;
+for (it = entities.begin(); it != entities.end(); ++it)
+    {
+    printfd(__FILE__, "\t - %s\n", it->c_str());
+    if (find(ready.begin(), ready.end(), *it) == ready.end())
+        if (toStore->AddAdmin(*it))
+            {
+            printfd(__FILE__, "Error adding admin: %s\n", toStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+    if (fromStore->RestoreAdmin(&ac, *it))
+        {
+        printfd(__FILE__, "Error getting admin's confi: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    ac.login = *it;
+    if (toStore->SaveAdmin(ac))
+        {
+        printfd(__FILE__, "Error saving admin's conf: %s\n", toStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    }
+
+printfd(__FILE__, "Importing tariffs:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetTariffsList(&entities))
+    {
+    printfd(__FILE__, "Error getting tariffs list: %s\n", fromStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+if (toStore->GetTariffsList(&ready))
+    {
+    printfd(__FILE__, "Error getting tariffs list: %s\n", toStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+
+for (it = entities.begin(); it != entities.end(); ++it)
+    {
+    printfd(__FILE__, "\t - %s\n", it->c_str());
+    if (find(ready.begin(), ready.end(), *it) == ready.end())
+        if (toStore->AddTariff(*it))
+            {
+            printfd(__FILE__, "Error adding tariff: %s\n", toStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+    if (fromStore->RestoreTariff(&td, *it))
+        {
+        printfd(__FILE__, "Error getting tariff's data: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    if (toStore->SaveTariff(td, *it))
+        {
+        printfd(__FILE__, "Error saving tariff's data: %s\n", toStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    }
+
+printfd(__FILE__, "Importing services:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetServicesList(&entities))
+    {
+    printfd(__FILE__, "Error getting service list: %s\n", fromStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+if (toStore->GetServicesList(&ready))
+    {
+    printfd(__FILE__, "Error getting service list: %s\n", toStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+
+for (it = entities.begin(); it != entities.end(); ++it)
+    {
+    printfd(__FILE__, "\t - %s\n", it->c_str());
+    if (find(ready.begin(), ready.end(), *it) == ready.end())
+        if (toStore->AddService(*it))
+            {
+            printfd(__FILE__, "Error adding service: %s\n", toStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+    if (fromStore->RestoreService(&sc, *it))
+        {
+        printfd(__FILE__, "Error getting service's data: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    if (toStore->SaveService(sc))
+        {
+        printfd(__FILE__, "Error saving service's data: %s\n", toStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    }
+
+printfd(__FILE__, "Importing corporations:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetCorpsList(&entities))
+    {
+    printfd(__FILE__, "Error getting corporations list: %s\n", fromStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+if (toStore->GetCorpsList(&ready))
+    {
+    printfd(__FILE__, "Error getting corporations list: %s\n", toStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+
+for (it = entities.begin(); it != entities.end(); ++it)
+    {
+    printfd(__FILE__, "\t - %s\n", it->c_str());
+    if (find(ready.begin(), ready.end(), *it) == ready.end())
+        if (toStore->AddCorp(*it))
+            {
+            printfd(__FILE__, "Error adding corporation: %s\n", toStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+    if (fromStore->RestoreCorp(&cc, *it))
+        {
+        printfd(__FILE__, "Error getting corporation's data: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    if (toStore->SaveCorp(cc))
+        {
+        printfd(__FILE__, "Error saving corporation's data: %s\n", toStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    }
+
+printfd(__FILE__, "Importing users:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetUsersList(&entities))
+    {
+    printfd(__FILE__, "Error getting users list: %s\n", fromStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+if (toStore->GetUsersList(&ready))
+    {
+    printfd(__FILE__, "Error getting users list: %s\n", toStore->GetStrError().c_str());
+    dlclose(src_lh);
+    dlclose(dst_lh);
+    delete settings;
+    return -1;
+    }
+
+sort(ready.begin(), ready.end());
+for (it = entities.begin(); it != entities.end(); ++it)
+    {
+    printfd(__FILE__, "\t - %s\n", it->c_str());
+    if (!binary_search(ready.begin(), ready.end(), *it)) {
+        if (toStore->AddUser(*it))
+            {
+            printfd(__FILE__, "Error adding user: %s\n", toStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+    } else {
+        printfd(__FILE__, "\t\t(adding passed)\n");
+    }
+    if (fromStore->RestoreUserConf(&uc, *it))
+        {
+        printfd(__FILE__, "Error getting user's conf: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    if (fromStore->RestoreUserStat(&us, *it))
+        {
+        printfd(__FILE__, "Error getting user's stat: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    if (toStore->SaveUserConf(uc, *it))
+        {
+        printfd(__FILE__, "Error saving user's conf: %s\n", toStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    if (toStore->SaveUserStat(us, *it))
+        {
+        printfd(__FILE__, "Error saving user's stat: %s\n", toStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    hdrs.erase(hdrs.begin(), hdrs.end());
+    if (fromStore->GetMessageHdrs(&hdrs, *it))
+        {
+        printfd(__FILE__, "Error getting user's messages: %s\n", fromStore->GetStrError().c_str());
+        dlclose(src_lh);
+        dlclose(dst_lh);
+        delete settings;
+        return -1;
+        }
+    vector<STG_MSG_HDR>::iterator mit;
+    for (mit = hdrs.begin(); mit != hdrs.end(); ++mit)
+        {
+        if (fromStore->GetMessage(mit->id, &msg, *it))
+            {
+            printfd(__FILE__, "Error getting message for a user: %s\n", fromStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+        printfd(__FILE__, "\t\t * %s\n", msg.text.c_str());
+        if (toStore->AddMessage(&msg, *it))
+            {
+            printfd(__FILE__, "Error adding message to a user: %s\n", toStore->GetStrError().c_str());
+            dlclose(src_lh);
+            dlclose(dst_lh);
+            delete settings;
+            return -1;
+            }
+        }
+    }
+
+dlclose(src_lh);
+dlclose(dst_lh);
+printfd(__FILE__, "Done\n");
+delete settings;
+return 0;
+}
diff --git a/projects/sgconv/settings_impl.cpp b/projects/sgconv/settings_impl.cpp
new file mode 100644 (file)
index 0000000..645865c
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Date: 27.10.2002
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ */
+
+/*
+$Revision: 1.6 $
+$Date: 2009/06/22 16:26:54 $
+*/
+
+#include "stg/dotconfpp.h"
+#include "stg/module_settings.h"
+#include "stg/common.h"
+
+#include "settings_impl.h"
+
+int SETTINGS_IMPL::ParseModuleSettings(const DOTCONFDocumentNode * node, std::vector<PARAM_VALUE> * params)
+{
+if (!node)
+    return 0;
+
+PARAM_VALUE pv;
+
+pv.param = node->getName();
+
+if (node->getValue(1))
+    {
+    strError = "Unexpected value \'" + std::string(node->getValue(1)) + "\'.";
+    printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
+    return -1;
+    }
+
+const char * value = node->getValue(0);
+
+if (!value)
+    {
+    strError = "Module name expected.";
+    printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
+    return -1;
+    }
+
+const DOTCONFDocumentNode * childNode = node->getChildNode();
+while (childNode)
+    {
+    pv.param = childNode->getName();
+    int i = 0;
+    while ((value = childNode->getValue(i)) != NULL)
+        {
+        pv.value.push_back(value);
+        ++i;
+        }
+    params->push_back(pv);
+    pv.value.clear();
+    childNode = childNode->getNextNode();
+    }
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+int SETTINGS_IMPL::ReadSettings()
+{
+const char * requiredOptions[] = {
+    "ModulesPath",
+    "SourceStoreModule",
+    "DestStoreModule",
+    NULL
+    };
+int sourceStoreModulesCount = 0;
+int destStoreModulesCount = 0;
+
+DOTCONFDocument conf(DOTCONFDocument::CASEINSENSITIVE);
+conf.setRequiredOptionNames(requiredOptions);
+
+if(conf.setContent(confFile.c_str()) != 0)
+    {
+    strError = "Cannot read file " + confFile + ".";
+    printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+    return -1;
+    }
+
+const DOTCONFDocumentNode * node = conf.getFirstNode();
+
+while (node)
+    {
+    if (strcasecmp(node->getName(), "ModulesPath") == 0)
+        {
+        modulesPath = node->getValue(0);
+        }
+
+    if (strcasecmp(node->getName(), "SourceStoreModule") == 0)
+        {
+        if (node->getValue(1))
+            {
+            strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
+            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+            return -1;
+            }
+
+        if (sourceStoreModulesCount)
+            {
+            strError = "Should be only one source StoreModule.";
+            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+            return -1;
+            }
+        ++sourceStoreModulesCount;
+
+        sourceStoreModuleSettings.moduleName = node->getValue(0);
+        ParseModuleSettings(node, &sourceStoreModuleSettings.moduleParams);
+        }
+
+    if (strcasecmp(node->getName(), "DestStoreModule") == 0)
+        {
+        if (node->getValue(1))
+            {
+            strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
+            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+            return -1;
+            }
+
+        if (destStoreModulesCount)
+            {
+            strError = "Should be only one dest StoreModule.";
+            printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+            return -1;
+            }
+        ++destStoreModulesCount;
+
+        destStoreModuleSettings.moduleName = node->getValue(0);
+        ParseModuleSettings(node, &destStoreModuleSettings.moduleParams);
+        }
+
+    node = node->getNextNode();
+    }
+
+return 0;
+}
+//-----------------------------------------------------------------------------
diff --git a/projects/sgconv/settings_impl.h b/projects/sgconv/settings_impl.h
new file mode 100644 (file)
index 0000000..3dfb959
--- /dev/null
@@ -0,0 +1,65 @@
+ /*
+ $Revision: 1.6 $
+ $Date: 2009/06/22 16:26:54 $
+ */
+
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Date: 27.10.2002
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ */
+
+#ifndef SETTINGS_IMPL_H
+#define SETTINGS_IMPL_H
+
+#include <string>
+#include <vector>
+
+struct MODULE_SETTINGS;
+class DOTCONFDocumentNode;
+
+class SETTINGS_IMPL {
+public:
+    SETTINGS_IMPL() : confFile("./sgconv.conf") {}
+    SETTINGS_IMPL(const std::string & cf) : confFile(cf) {}
+    ~SETTINGS_IMPL() {}
+    int ReadSettings();
+
+    std::string GetStrError() const { return strError; }
+
+    const std::string & GetConfDir() const;
+
+    const std::string & GetModulesPath() const { return modulesPath; }
+    const MODULE_SETTINGS & GetSourceStoreModuleSettings() const { return sourceStoreModuleSettings; }
+    const MODULE_SETTINGS & GetDestStoreModuleSettings() const { return destStoreModuleSettings; }
+
+private:
+    int ParseModuleSettings(const DOTCONFDocumentNode * dirNameNode, std::vector<PARAM_VALUE> * params);
+
+    std::string strError;
+    std::string modulesPath;
+    std::string confFile;
+
+    MODULE_SETTINGS sourceStoreModuleSettings;
+    MODULE_SETTINGS destStoreModuleSettings;
+};
+
+#endif
diff --git a/projects/sgconv/sgconv.conf b/projects/sgconv/sgconv.conf
new file mode 100644 (file)
index 0000000..25298b0
--- /dev/null
@@ -0,0 +1,124 @@
+################################################################################
+#                   Stargazer Convertor Configuration file                     #
+################################################################################
+
+# The path to directory with server modules
+# Parameter: required
+# Value: directory path
+# Default: /usr/lib/stg
+ModulesPath = /usr/lib/stg
+
+#################################################################################
+Store module
+# Configure the module that works with the database server
+# Option - the name of the module without 'mod_' at the beginning and '.so'
+# in the end ie full name of the module mod_store_files.so
+<SourceStoreModule store_files>
+
+    # Working server directory, provides data on tariffs, users, administrators.
+    # Parameter: required
+    # Value: directory path
+    WorkDir = /var/stargazer
+
+    # Owner, group and permissions of the files of user statistics (stat)
+    # Parameter: required
+    # Values: any, supported by OS
+    ConfOwner = root
+    ConfGroup = root
+    ConfMode = 600
+
+    # Owner, group and permissions on user configuration files (conf)
+    # Parameter: required
+    # Values: any, supported by OS
+    StatOwner = root
+    StatGroup = root
+    StatMode = 640
+
+    # Owner, group and permissions for user log files (log)
+    # Parameter: required
+    # Values: any, supported by OS
+    UserLogOwner = root
+    UserLogGroup = root
+    UserLogMode = 640
+
+</SourceStoreModule>
+
+#<DestStoreModule store_firebird>
+    # Database server address
+    # Parameter: required
+    # Value: IP address or DNS name
+    # Default: localhost
+    # Server = localhost
+
+    # Path to the database on the server or its alias
+    # Parameter: required
+    # Value: file path
+    # Default: /var/stg/stargazer.fdb
+    # Database = /var/stg/stargazer.fdb
+
+    # Database username
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: stg
+    # User = stg
+
+    # Database password
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: 123456
+    # Password = 123456
+#</DestStoreModule>
+
+<DestStoreModule store_postgresql>
+    # Database server address
+    # Parameter: required
+    # Value: IP address or DNS name
+    # Default: localhost
+    Server = localhost
+
+    # Database name
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: stargazer
+    Database = stargazer
+
+    # Database username
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: stg
+    User = stg
+
+    # Database password
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: 123456
+    Password = 123456
+
+</DestStoreModule>
+
+#<DestStoreModule store_mysql>
+    # Database server address
+    # Parameter: required
+    # Value: IP address or DNS name
+    # Default: localhost
+    # Server = localhost
+
+    # Database name
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: stg
+    # Database = stg
+
+    # Database username
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: stg
+    # User = stg
+
+    # Database password
+    # Parameter: required
+    # Value: any, supported by database
+    # Default: 123456
+    # Password = 123456
+
+#</DestStoreModule>
index 44ae35ec3007ebae87f6cef197526972043ae013..aa2b6f90d65f74fa309c3140035a3f52c95c1a82 100644 (file)
@@ -47,7 +47,12 @@ OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
 
 CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
 CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
+
+ifneq ($(OS),darwin)
 LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
+endif
+
+LDFLAGS += $(STGLIBS_LIBS)
 
 .PHONY: all clean distclean libs plugins install uninstall install-bin install-data
 all: libs plugins $(PROG)
@@ -77,7 +82,11 @@ distclean: clean
 install: install-bin install-data
 
 install-bin: $(PROG)
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+endif
        $(MAKE) -C $(DIR_INCLUDE) install
        $(MAKE) -C $(DIR_LIBSRC) install
        $(MAKE) -C $(DIR_PLUGINS) install
index 6c1fc8a8c671ea9c7ed24781af0ff867990d09bb..66b8556d1144ab43344378865ecbbc18261fc043 100644 (file)
@@ -41,7 +41,7 @@ public:
     ACTION(ACTIVE_CLASS & ac,
            typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
            DATA_TYPE d)
-        : activeClass(ac), actor(a), data(d) {};
+        : activeClass(ac), actor(a), data(d) {}
     void Invoke();
 private:
     ACTION(const ACTION<ACTIVE_CLASS, DATA_TYPE> & rvalue);
index 6a608e11ef4d9ca8822779796d8882652c98f5f6..9a2b9781242a62eec4a06e8d82b776fec6a2732b 100644 (file)
@@ -43,9 +43,9 @@ public:
       ADMIN_IMPL();
       ADMIN_IMPL(const ADMIN_CONF & ac);
       ADMIN_IMPL(const PRIV & priv,
-            const std::string & login,
-            const std::string & password);
-      virtual ~ADMIN_IMPL() {};
+                 const std::string & login,
+                 const std::string & password);
+      virtual ~ADMIN_IMPL() {}
 
       ADMIN_IMPL & operator=(const ADMIN_IMPL &);
       ADMIN_IMPL & operator=(const ADMIN_CONF &);
@@ -54,15 +54,15 @@ public:
       bool         operator<(const ADMIN_IMPL & rhs) const;
       bool         operator<=(const ADMIN_IMPL & rhs) const;
 
-      const std::string & GetPassword() const { return conf.password; };
-      const std::string & GetLogin() const { return conf.login; };
-      PRIV const *        GetPriv() const { return &conf.priv; };
-      uint16_t            GetPrivAsInt() const { return conf.priv.ToInt(); };
-      const ADMIN_CONF &  GetConf() const { return conf; };
+      const std::string & GetPassword() const { return conf.password; }
+      const std::string & GetLogin() const { return conf.login; }
+      PRIV const *        GetPriv() const { return &conf.priv; }
+      uint32_t            GetPrivAsInt() const { return conf.priv.ToInt(); }
+      const ADMIN_CONF &  GetConf() const { return conf; }
       void                Print() const;
-      uint32_t            GetIP() const { return ip; };
+      uint32_t            GetIP() const { return ip; }
       std::string         GetIPStr() const;
-      void                SetIP(uint32_t ip) { ADMIN_IMPL::ip = ip; };
+      void                SetIP(uint32_t v) { ip = v; }
       const std::string   GetLogStr() const;
 
 private:
index cef8682dd2fda9e32eb470147849579011b730dd..7d73dde1834cde8481ddeee2fde6f3cc78d3de66 100644 (file)
@@ -219,7 +219,7 @@ assert(admin != NULL && "Pointer to admin is not null");
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 if (data.empty())
     {
-    printfd(__FILE__, "no admin in system!\n");
+    printfd(__FILE__, "No admin in system!\n");
     *admin = &noAdmin;
     return false;
     }
index cb00368c18543d75c9a72e596d8f6d6b993f6587..48435b75d56f49c5a58c9b2aeb78fb82aa62382d 100644 (file)
@@ -73,8 +73,8 @@ private:
     ADMINS_IMPL(const ADMINS_IMPL & rvalue);
     ADMINS_IMPL & operator=(const ADMINS_IMPL & rvalue);
 
-    typedef list<ADMIN_IMPL>::iterator admin_iter;
-    typedef list<ADMIN_IMPL>::const_iterator const_admin_iter;
+    typedef std::list<ADMIN_IMPL>::iterator admin_iter;
+    typedef std::list<ADMIN_IMPL>::const_iterator const_admin_iter;
 
     int             Read();
 
index 60c8e1ff035e4c07008c3cec1c62146fbf9f084a..2061d538b189e2f517b948fad8fda182025f680a 100755 (executable)
@@ -35,20 +35,15 @@ MIN_XMLRPCC_VERSION="1.06.27"
 XMLRPC_FEATURES="c++2 abyss-server"
 
 
-if [ -z "$1" ]
+if [ "$1" = "debug" ]
 then
-    DEFS="$DEFS -DNDEBUG"
-    MAKEOPTS="-j1"
+    DEFS="$DEFS -DDEBUG"
+    MAKEOPTS="$MAKEOPTS -j1"
+    CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
+    DEBUG="yes"
 else
-    if [ "$1" = "debug" ]
-    then
-        DEFS="$DEFS -DDEBUG"
-        MAKEOPTS="-j1"
-        CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
-    else
-        DEFS="$DEFS -DNDEBUG"
-        MAKEOPTS="-j1"
-    fi
+    DEFS="$DEFS -DNDEBUG"
+    DEBUG="no"
 fi
 
 CXXFLAGS="$CXXFLAGS -I/usr/local/include"
@@ -77,17 +72,24 @@ then
     MAKE="gmake"
 fi
 
+if [ "$sys" = "Darwin" ]
+then
+    OS=darwin
+    ETC_DIR="./inst/freebsd/etc/stargazer"
+    MAKE="gmake"
+fi
+
 if [ "$OS" = "unknown" ]
 then 
-    echo "#############################################################################"
-    echo "# Sorry, but stargazer currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #"
-    echo "#############################################################################"
+    printf "#############################################################################\n"
+    printf "# Sorry, but stargazer currently supported by Linux, FreeBSD 4.x, 5.x, 6.x  #\n"
+    printf "#############################################################################\n"
     exit 1
 fi
 
-echo "#############################################################################"
-echo "       Building STG 2.4 for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf "       Building STG 2.4 for $sys $release\n"
+printf "#############################################################################\n"
 
 STG_LIBS="logger.lib 
           locker.lib
@@ -113,8 +115,7 @@ if [ "$OS" = "linux" ]
 then
     DEFS="$DEFS -DLINUX"
     PLUGINS="$PLUGINS
-             capture/ether_linux
-             capture/ipq_linux"
+             capture/ether_linux"
     LIB_THREAD=-lpthread
 else
     if [ "$OS" = "bsd" ]
@@ -122,12 +123,18 @@ else
         DEFS="$DEFS -DFREE_BSD"
         LIB_THREAD=-lc_r
     else
-        DEFS="$DEFS -DFREE_BSD5"
         if [ "$OS" = "bsd7" ]
         then
+            DEFS="$DEFS -DFREE_BSD5"
             LIB_THREAD=-lpthread
         else
-            LIB_THREAD=-lc_r
+            if [ "$OS" == "darwin" ]
+            then
+                DEFS="$DEFS -DDARWIN"
+                LIB_THREAD=-lpthread
+            else
+                LIB_THREAD=-lc_r
+            fi
         fi
     fi
     PLUGINS="$PLUGINS
@@ -145,32 +152,32 @@ then
     CXX=g++
 fi
 
-echo -n "Checking CC... "
+printf "Checking CC... "
 $CC --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CC not found"
+    printf "FAIL!\n"
+    printf "$CC not found\n"
     exit;
 fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
 $CXX --version > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "$CXX not found"
+    printf "FAIL!\n"
+    printf "$CXX not found\n"
     exit;
 fi
-echo "found"
+printf "found\n"
 
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -o fake
 if [ $? != 0 ]
 then
-    echo "FAIL!"
-    echo "Endianess checking failed"
+    printf "FAIL!\n"
+    printf "Endianess checking failed\n"
     exit;
 else
     ./fake
@@ -179,167 +186,188 @@ else
         ARCH=le
         CXXFLAGS="$CXXFLAGS -DARCH_LE"
         CFLAGS="$CFLAGS -DARCH_LE"
-        echo "Little Endian"
+        printf "Little Endian\n"
     else
         ARCH=be
         CXXFLAGS="$CXXFLAGS -DARCH_BE"
         CFLAGS="$CFLAGS -DARCH_BE"
-        echo "Big Endian"
+        printf "Big Endian\n"
     fi
 fi
 rm -f fake
 
-echo -n "Checking for -lexpat... "
-echo "int main() { return 0; }" > build_check.c
+printf "Checking for -lexpat... "
+printf "int main() { return 0; }\n" > build_check.c
 $CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
     CHECK_EXPAT=no
-    echo "no"
+    printf "no\n"
 else
     CHECK_EXPAT=yes
-    echo "yes"
+    printf "yes\n"
 fi
 rm -f fake
 
-echo -n "Checking for -lfbclient... "
+printf "Checking for -lfbclient... "
 $CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
 if [ $? != 0 ]
 then
     CHECK_FBCLIENT=no
-    echo "no"
+    printf "no\n"
 else
     CHECK_FBCLIENT=yes
-    echo "yes"
+    printf "yes\n"
 fi
 rm -f fake
 
-echo -n "Checking for mysql_config... "
+printf "Checking for mysql_config... "
 MYSQL_VERSION=`mysql_config --version 2> /dev/null`
 if [ $? != 0 ]
 then
-    echo "no";
-    echo -n "Checking for -lmysqlclient... "
+    printf "no\n";
+    printf "Checking for -lmysqlclient... "
     $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
     if [ $? != 0 ]
     then
         CHECK_MYSQLCLIENT=no
-        echo "no"
+        printf "no\n"
     else
         CHECK_MYSQLCLIENT=yes
-        echo "yes"
+        printf "yes\n"
     fi
     rm -f fake
 else
-    echo "yes"
-    echo -n "Checking for mysql_config --cflags... "
+    printf "yes\n"
+    printf "Checking for mysql_config --cflags... "
     MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
     if [ $? != 0 ]
     then
         CHECK_MYSQLCLIENT=no
-        echo "no"
+        printf "no\n"
     else
-        echo "[$MYSQL_CFLAGS]"
-        echo -n "Checking for mysql_config --libs_r... "
+        printf "[$MYSQL_CFLAGS]\n"
+        printf "Checking for mysql_config --libs_r... "
         MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
         if [ $? != 0 ]
         then
             CHECK_MYSQLCLIENT=no
-            echo "no"
+            printf "no\n"
         else
             CHECK_MYSQLCLIENT=yes
-            echo "[$MYSQL_LDFLAGS]"
+            printf "[$MYSQL_LDFLAGS]\n"
         fi
     fi
 fi
 
-echo -n "Checking for pg_config... "
+printf "Checking for pg_config... "
 PG_VERSION=`pg_config --version 2> /dev/null`
 if [ $? != 0 ]
 then
-    echo "no";
-    echo -n "Checking for -lpq... "
+    printf "no\n";
+    printf "Checking for -lpq... "
     $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
     if [ $? != 0 ]
     then
         CHECK_PQ=no
-        echo "no"
+        printf "no\n"
     else
         CHECK_PQ=yes
-        echo "yes"
+        printf "yes\n"
     fi
     rm -f fake
 else
-    echo "yes";
-    echo -n "Checking for pg_config --includedir... "
+    printf "yes\n";
+    printf "Checking for pg_config --includedir... "
     PG_CFLAGS=`pg_config --includedir 2> /dev/null`
     if [ $? != 0 ]
     then
         CHECK_PQ=no
-        echo "no"
+        printf "no\n"
     else
-        echo "[$PG_CFLAGS]"
-        echo -n "Checking for pg_config --libdir... "
+        printf "[$PG_CFLAGS]\n"
+        printf "Checking for pg_config --libdir... "
         PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
         if [ $? != 0 ]
         then
             CHECK_PQ=no
-            echo "no"
+            printf "no\n"
         else
             CHECK_PQ=yes
-            echo "[$PG_LDFLAGS]"
+            printf "[$PG_LDFLAGS]\n"
         fi
     fi
 fi
 
-echo -n "Checking for xmlrpc-c-config... "
+printf "Checking for xmlrpc-c-config... "
 XMLRPCC_VERSION=`xmlrpc-c-config $XMLRPC_FEATURES --version 2> /dev/null`
 if [ $? != 0 ]
 then
-    echo "no";
-    echo -n "Checking for -lxmlrpc... "
+    printf "no\n";
+    printf "Checking for -lxmlrpc... "
     $CC $CFLAGS $LDFLAGS build_check.c -lxmlrpc $LIB_THREAD -o fake > /dev/null 2> /dev/null
     if [ $? != 0 ]
     then
         CHECK_XMLRPC=no
-        echo "no"
+        printf "no\n"
     else
         CHECK_XMLRPC=yes
-        echo "yes"
+        printf "yes\n"
     fi
     rm -f fake
 elif [ "$XMLRPCC_VERSION" \< "$MIN_XMLRPCC_VERSION" ]
 then
-    echo "no (need at least $MIN_XMLRPCC_VERSION, actual $XMLRPCC_VERSION)";
+    printf "no (need at least $MIN_XMLRPCC_VERSION, actual $XMLRPCC_VERSION)\n";
     CHECK_XMLRPC=no
 else
-    echo "yes (version $XMLRPCC_VERSION)";
-    echo -n "Checking for xmlrpc-c-config --cflags... "
+    printf "yes (version $XMLRPCC_VERSION)\n";
+    printf "Checking for xmlrpc-c-config --cflags... "
     XMLRPC_CFLAGS=`xmlrpc-c-config $XMLRPC_FEATURES --cflags 2> /dev/null`
     if [ $? != 0 ]
     then
         CHECK_XMLRPC=no
-        echo "no"
+        printf "no\n"
     else
-        echo "[$XMLRPC_CFLAGS]"
-        echo -n "Checking for xmlrpc-c-config --libs... "
+        printf "[$XMLRPC_CFLAGS]\n"
+        printf "Checking for xmlrpc-c-config --libs... "
         XMLRPC_LDFLAGS=`xmlrpc-c-config $XMLRPC_FEATURES --libs 2> /dev/null`
         if [ $? != 0 ]
         then
             CHECK_XMLRPC=no
-            echo "no"
+            printf "no\n"
         else
             CHECK_XMLRPC=yes
-            echo "[$XMLRPC_LDFLAGS]"
+            printf "[$XMLRPC_LDFLAGS]\n"
         fi
     fi
 fi
 
+if [ "$OS" = "linux" ]
+then
+    printf "Checking for linux/netfilter_ipv4/ip_queue.h... "
+    printf "#include <linux/types.h>\n" > build_check.c
+    printf "#include <linux/netfilter_ipv4/ip_queue.h>\n" >> build_check.c
+    printf "int main() { return 0; }\n" >> build_check.c
+    $CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
+    if [ $? != 0 ]
+    then
+        CHECK_IP_QUEUE_H=no
+        printf "no\n"
+    else
+        CHECK_IP_QUEUE_H=yes
+        DEFS="$DEFS -DHAS_IP_QUEUE_H"
+        PLUGINS="$PLUGINS
+                 capture/ipq_linux"
+        printf "yes\n"
+    fi
+    rm -f fake
+fi
+
 rm -f build_check.c
 
 if [ "$CHECK_EXPAT" != "yes" ]
 then
-    echo "-lexpat not found!"
+    printf "-lexpat not found!\n"
     exit 1
 fi
 
@@ -369,44 +397,45 @@ then
              configuration/rpcconfig"
 fi
 
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "DIR_MOD=\$(DIR_BUILD)/modules" >> $CONFFILE
-echo "DIR_PLUGINS=\$(DIR_BUILD)/plugins" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE
-echo "CHECK_FBCLIENT=$CHECK_FBCLIENT" >> $CONFFILE
-echo "CHECK_MYSQLCLIENT=$CHECK_MYSQLCLIENT" >> $CONFFILE
-echo "CHECK_PQ=$CHECK_PQ" >> $CONFFILE
-echo "CHECK_XMLRPC=$CHECK_XMLRPC" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "DIR_MOD=\$(DIR_BUILD)/modules\n" >> $CONFFILE
+printf "DIR_PLUGINS=\$(DIR_BUILD)/plugins\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE
+printf "CHECK_FBCLIENT=$CHECK_FBCLIENT\n" >> $CONFFILE
+printf "CHECK_MYSQLCLIENT=$CHECK_MYSQLCLIENT\n" >> $CONFFILE
+printf "CHECK_PQ=$CHECK_PQ\n" >> $CONFFILE
+printf "CHECK_XMLRPC=$CHECK_XMLRPC\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
 for lib in $STG_LIBS
 do
-    echo -n "$lib " >> $CONFFILE
+    printf "$lib " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo -n "PLUGINS=" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "PLUGINS=" >> $CONFFILE
 for plugin in $PLUGINS
 do
-    echo -n "$plugin " >> $CONFFILE
+    printf "$plugin " >> $CONFFILE
 done
-echo "" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
-echo "VAR_DIR=$VAR_DIR" >> $CONFFILE
-echo "ETC_DIR=$ETC_DIR" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
+printf "VAR_DIR=$VAR_DIR\n" >> $CONFFILE
+printf "ETC_DIR=$ETC_DIR\n" >> $CONFFILE
 
 mkdir -p modules
 
@@ -414,5 +443,5 @@ if [ "$1" != "debug" ]
 then
     $MAKE $MAKEOPTS
 else
-    echo -e "\n\n\nDebug build. Type $MAKE explicitly"
+    printf "\n\n\nDebug build. Type $MAKE explicitly\n"
 fi
index f926d23a9276b2f9f8cb04104796f07f3b01b188..a366f46674635dc29cb332396f419ff567630902 100644 (file)
@@ -48,7 +48,7 @@ const PRIV * priv = admin->GetPriv();
 
 if (!priv->corpChg)
     {
-    string s = admin->GetLogStr() + " Add corporation \'" + corp.name + "\'. Access denied.";
+    std::string s = admin->GetLogStr() + " Add corporation \'" + corp.name + "\'. Access denied.";
     strError = "Access denied.";
     WriteServLog(s.c_str());
     return -1;
@@ -79,14 +79,14 @@ WriteServLog("%s %s", admin->GetLogStr().c_str(), strError.c_str());
 return -1;
 }
 //-----------------------------------------------------------------------------
-int CORPORATIONS_IMPL::Del(const string & name, const ADMIN * admin)
+int CORPORATIONS_IMPL::Del(const std::string & name, const ADMIN * admin)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 const PRIV * priv = admin->GetPriv();
 
 if (!priv->corpChg)
     {
-    string s = admin->GetLogStr() + " Delete corporation \'" + name + "\'. Access denied.";
+    std::string s = admin->GetLogStr() + " Delete corporation \'" + name + "\'. Access denied.";
     strError = "Access denied.";
     WriteServLog(s.c_str());
     return -1;
@@ -101,7 +101,7 @@ if (si == data.end())
     return -1;
     }
 
-map<int, const_crp_iter>::iterator csi;
+std::map<int, const_crp_iter>::iterator csi;
 csi = searchDescriptors.begin();
 while (csi != searchDescriptors.end())
     {
@@ -130,7 +130,7 @@ const PRIV * priv = admin->GetPriv();
 
 if (!priv->corpChg)
     {
-    string s = admin->GetLogStr() + " Change corporation \'" + corp.name + "\'. Access denied.";
+    std::string s = admin->GetLogStr() + " Change corporation \'" + corp.name + "\'. Access denied.";
     strError = "Access denied.";
     WriteServLog(s.c_str());
     return -1;
@@ -162,7 +162,7 @@ return 0;
 bool CORPORATIONS_IMPL::Read()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-vector<string> corpsList;
+std::vector<std::string> corpsList;
 if (store->GetCorpsList(&corpsList) < 0)
     {
     WriteServLog(store->GetStrError().c_str());
@@ -184,7 +184,7 @@ for (size_t i = 0; i < corpsList.size(); i++)
 return false;
 }
 //-----------------------------------------------------------------------------
-bool CORPORATIONS_IMPL::Find(const string & name, CORP_CONF * corp)
+bool CORPORATIONS_IMPL::Find(const std::string & name, CORP_CONF * corp)
 {
 assert(corp != NULL && "Pointer to corporation is not null");
 
@@ -203,7 +203,7 @@ if (si != data.end())
 return true;
 }
 //-----------------------------------------------------------------------------
-bool CORPORATIONS_IMPL::Exists(const string & name) const
+bool CORPORATIONS_IMPL::Exists(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 if (data.empty())
index e4552424219c72e3aab74b25dacb69649456451f..7bde401b1a3655ba6ab77849ed7ac790e0abb643 100644 (file)
@@ -58,8 +58,8 @@ private:
     CORPORATIONS_IMPL(const CORPORATIONS_IMPL & rvalue);
     CORPORATIONS_IMPL & operator=(const CORPORATIONS_IMPL & rvalue);
 
-    typedef list<CORP_CONF>::iterator       crp_iter;
-    typedef list<CORP_CONF>::const_iterator const_crp_iter;
+    typedef std::list<CORP_CONF>::iterator       crp_iter;
+    typedef std::list<CORP_CONF>::const_iterator const_crp_iter;
 
     bool Read();
 
index 71602795626fdc82b40e703781e955eb9f4fcb3d..35de3675b290b7a2c8a2fbb5f110fa00006b7a52 100644 (file)
@@ -12,7 +12,7 @@ class EVENT_LOOP : private NONCOPYABLE,
     public:
         bool Start();
         bool Stop();
-        bool IsRunning() const { return _running; };
+        bool IsRunning() const { return _running; }
 
         template <class ACTIVE_CLASS, typename DATA_TYPE>
         void Enqueue(ACTIVE_CLASS & ac,
@@ -44,8 +44,8 @@ class EVENT_LOOP_SINGLETON : private NONCOPYABLE
         static EVENT_LOOP * _instance;
         static void CreateInstance();
 
-        EVENT_LOOP_SINGLETON() {};
-        ~EVENT_LOOP_SINGLETON() {};
+        EVENT_LOOP_SINGLETON() {}
+        ~EVENT_LOOP_SINGLETON() {}
 };
 
 template <class ACTIVE_CLASS, typename DATA_TYPE>
index ab0ddfb5765a38ba27e3bed3892d5da767b6d4ff..acd15e0712975bcd61abb6ba811bebe33fe970bd 100644 (file)
@@ -1,8 +1,14 @@
 # Enable the traffic capture module "mod_cap_divert.so" using Divert-sockets
 <Module cap_divert>
    # Port for traffic
-   # Parameter: required
+   # Parameter: optional
    # Value: 1 ... 65535
    # Default: 15701
    Port = 15701
-</Module>
\ No newline at end of file
+
+   # Disable packet forwarding
+   # Parameter: optional
+   # Value: yes, no
+   # Default: no
+   DisableForwarding = no
+</Module>
index f3cbc40c644e95d4ad5f7b0a6918aa971e1dc994..948674cacafc68583f527bcd604d17cc2077f7e8 100644 (file)
@@ -3,14 +3,14 @@
     # Port for TCP connections
     # Note: Parameters TCPPort and UDPPort can be equal
     # Parameter: optional
-    # Value: 1 ... 65534
+    # Value: 1 ... 65535
     # Default: 9996
     #TCPPort = 9996
 
     # Port for UDP connections
     # Note: Parameters TCPPort and UDPPort can be equal
     # Parameter: optional
-    # Value: 1 ... 65536
+    # Value: 1 ... 65535
     # Default: 9996
     UDPPort = 9996
-</Module>
\ No newline at end of file
+</Module>
index aa18309a40bd9f0b8c2ae3386acd5280f2f62910..df170dd089203f1e806d100cbe468b732c6c57da 100644 (file)
@@ -2,20 +2,20 @@
 <Module auth_ia>
     # Port on which the server interacts with authorizator
     # Parameter: required
-    # Value: 1 ... 65534
+    # Value: 1 ... 65535
     # Default: 5555
     Port = 5555
 
     # The time interval between sending an alive query to the user
     # and updating statistics
-    # Parameter: required 
+    # Parameter: required
     # Values: 5 ... 600 (seconds)
     # Default: 60
     UserDelay = 60
 
-    # User timeout. If authorizer does not respond during this time, 
+    # User timeout. If authorizer does not respond during this time,
     # the user will be disconnected
-    # Parameter: required 
+    # Parameter: required
     # Values: 5 ... 600
     # Default: 60
     UserTimeout = 65
     # FreeMb = cash - amount of money for which the user can download for free
     # FreeMb = none - no transfer
     # Default: cash
-    # Parameter: required 
+    # Parameter: required
     # Values: different, see above
     # Default: cash
     FreeMb = cash
-</Module>
\ No newline at end of file
+
+    # Enable protocol errors logging
+    # Parameter: optional
+    # Values: yes, no
+    # Default: no
+    # LogProtocolErrors = no
+</Module>
index b3d0ab7619111b953837b5ac57de76fb9c00a5ef..a71350c868093994373161f6b1712b9418bd46c1 100644 (file)
@@ -14,7 +14,7 @@
     # 192.168.3.0/24 192.168.3.5
     # 192.168.4.0/24 192.168.4.5
     # Parametr: required
-    # Values: filename
+    # Values: file path
     # Default: subnets
     SubnetFile = subnets
 
@@ -39,4 +39,4 @@
     # Value: 1...65535
     # Default: 9999
     Port = 9999
-</Module>
\ No newline at end of file
+</Module>
index 06eeba4ed5a65f198bbfeaa84af661c3c33117b0..b05695a75e0b16b0b4542eafe329824b81ae88fc 100644 (file)
@@ -6,9 +6,9 @@
     # Default:
     Port = 8080
 
-    # Session timeout
+    # Session timeout in seconds
     # Parameter: required
-    # Value: any numeric
+    # Value: positive integer
     # Default: 1800
     CookieTimeout = 1800
-</Module>
\ No newline at end of file
+</Module>
index 924cc636ab63fc4714ef909ce9063761fbcf5de1..84ce24bb130467457c48f658382d5fcf2e732683 100644 (file)
@@ -1,3 +1,4 @@
+# Enables SMUX-peer for SNMPd.
 <Module smux>
     # IP-address of a server to connect to
     # Parameter: required
@@ -12,7 +13,7 @@
     Port = 199
 
     # Password for authentication on a server
-    # Parameter: optional
-    # 
-    # Password = 123456
+    # Parameter: required
+    # Value: any text
+    Password =
 </Module>
index 068d4abaeb8e98c597a48c90d2d0cf438cc80d12..f7e0f23da47773ae6c059338726ea44b41fd8970 100644 (file)
@@ -1,5 +1,4 @@
-# Option - the name of the module without 'mod_' at the beginning and '.so'
-# in the end ie full name of the module mod_store_files.so
+# Enables plain file backend.
 <StoreModule store_files>
 
     # Working server directory, provides data on tariffs, users, administrators.
index 738d75ccf4c02553d01a307547a23e27a7af210d..39e4ad3d9333f0fda49beed07fad397b1c1e6203 100644 (file)
@@ -1,37 +1,38 @@
+# Enables Firebird backend.
 <StoreModule store_firebird>
     # Database server address
-    # Parameter: required
+    # Parameter: optional
     # Value: IP address or DNS name
     # Default: localhost
-    Server = localhost
+    Server = localhost
 
     # Path to the database on the server or its alias
-    # Parameter: required
+    # Parameter: optional
     # Value: file path
     # Default: /var/stg/stargazer.fdb
-    Database = /var/stg/stargazer.fdb
+    Database = /var/stg/stargazer.fdb
 
     # Database username
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: stg
-    User = stg
+    User = stg
 
     # Database password
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: 123456
-    Password = 123456
+    Password = 123456
 
     # The transaction isolation level
     # Parameter: optional
     # Values: concurrency, dirtyread, readcommitted, consistency
     # Defalt: concurrency
-    IsolationLevel = concurrency
+    IsolationLevel = concurrency
 
     # Responding to lock (optional, defaults to wait):
     # Parameter: optional
     # Values: wait, nowait
     # Defalt: wait
-    LockResolution = wait
+    LockResolution = wait
 </StoreModule>
index a5cc418046d9d56cb7543f2451eab761548ae407..a5b2126d5b3ca3d4669ec3a361ff457265dac154 100644 (file)
@@ -1,3 +1,4 @@
+# Enables MySQL backend.
 <StoreModule store_mysql>
     # Database server address
     # Parameter: required
index 153265845091dfe2d52b4296ba4c0b95c7fa4720..8a52c75b994eeca8a5800e8b42a2c6e8137eacb2 100644 (file)
@@ -1,27 +1,28 @@
+# Enables PostgreSQL backend.
 <StoreModule store_postgresql>
     # Database server address
-    # Parameter: required
+    # Parameter: optional
     # Value: IP address or DNS name
     # Default: localhost
-    Server = localhost
+    Server = localhost
 
     # Database name
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: stargazer
-    Database = stargazer
+    Database = stargazer
 
     # Database username
-    # Parameter: mandatory
+    # Parameter: optional
     # Value: any, supported by database
     # Default: stg
-    User = stg
+    User = stg
 
     # Database password
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: 123456
-    Password = 123456
+    Password = 123456
 
     # Number of tries to reconnect
     # Parameter: optional
index 699e331030aa5a8222fd2e97dba68279df95e502..daa0fd679ca74720beb10d58de6ef5a22edfcc11 100755 (executable)
@@ -1,6 +1,6 @@
 #!/sbin/runscript
 
-opts="reload"
+extra_commands="reload"
 
 DAEMON=/usr/sbin/stargazer
 STARGAZER_OPTS=""
index 8cb10961764441a9735f1a9b7db40400c5bd76cb..c1ad6a64641445f2a1b11f82274b0f715a6d46af 100755 (executable)
@@ -1,8 +1,20 @@
 #! /bin/sh
 
-login=$1
-param=$2
-oldValue=$3
-newValue=$4
+# About: This script is called when user account is changed.
+# Common Task: Notify about various events.
+# Priority: optional
 
-#echo "User: '$login'. Parameter $param changed from '$oldValue' to '$newValue'" >> /var/stargazer/users.chg.log
\ No newline at end of file
+# User login
+LOGIN=$1
+
+# User parameter
+PARAMETER=$2
+
+# User parameter old value
+OLDVALUE=$3
+
+# User parameter new value
+NEWVALUE=$4
+
+# Usage examples:
+#echo "User: '$LOGIN'. Parameter $PARAMETER changed from '$OLDVALUE' to '$NEWVALUE'" >> /var/stargazer/user.change.log
\ No newline at end of file
index 912ed7d983a83312e0a8012dfd202d34ebc5dcfb..cb1f64f4179237c683be777702d463d462eccf46 100755 (executable)
@@ -1,24 +1,23 @@
 #! /bin/sh
 
-#Этот скрипт вызывается в момент, когда пользователь
-#успешно прошел авторизацию на сервере. Задача скрипта - перестроить 
-#файрвол так, что бы пользователь получил доступ в интернет
+# About: This script is called when the user successfully authenticated on the server.
+# Common Task: Rebuild firewall to allow user to access the Internet.
+# Priority: required
 
-# Login
+# User login
 LOGIN=$1
 
-#user IP
+# User IP
 IP=$2
 
-#cash
+# User cash
 CASH=$3
 
-#user ID
+# User ID
 ID=$4
 
-#Selected dirs to connect
+# Selected DIRs (from rules file) to connect
 DIRS=$5
 
-
-#echo "C `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
-
+# Usage examples:
+#echo "Connected `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
\ No newline at end of file
index 6169ddc83cdfcb25b83b52cf291f7e9024a116a1..64a6c519daa79255d73e77561d19e15fa4c203dd 100755 (executable)
@@ -1,24 +1,23 @@
 #! /bin/sh
 
-# Этот скрипт вызывается в момент, когда пользователь
-# желает отключится от интернета или вышел таймаут у пользователя
-# и сервер сам отключает пользователя
-# Задача скрипта подобна задаче скрипта OnConnect - перестроить 
-# файрвол так, что бы пользователю закрыть доступ в интернет
+# About: This script is called when the user wants to disconnect or authorization timeout has passed.
+# Common task: Rebuild firewall to disallow user to access the Internet.
+# Priority: required
 
-# Login
+# User login
 LOGIN=$1
 
-#user IP
+# User IP
 IP=$2
 
-#cash
+# User cash
 CASH=$3
 
-#user ID
+# User ID
 ID=$4
 
-#Selected dirs to disconnect
+# Selected DIRs (from rules file) to disconnect
 DIRS=$5
 
-#echo "D `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
+# Usage examples:
+#echo "Disconnected `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
index 22d321cc02300c89c7a566e897efa07fbd4a56bc..2dcc0562fca25a067daf5e14b961b9ab73d24fc4 100755 (executable)
@@ -1,14 +1,12 @@
 #! /bin/sh
 
-# Использование (неиспользование) этого скрипта дело вкуса.
-# Он не выполняет критических функций. Его задача автматизировать
-# действия характерные при добавлении пользователя сети, например добавлекние 
-# пользователю почты
-
-# Login
-login=$1
-
-#echo "added user $login" >> /var/stargazer/add_del.log
-
+# About: This script is called when the user is added to the Stargazer.
+# Common task: Automate typical actions on adding user to the network,
+#              such as creating email or IM account.
+# Priority: optional
 
+# User login
+LOGIN=$1
 
+# Usage examples:
+#echo "Added user $login" >> /var/stargazer/add_del.log
\ No newline at end of file
index 248e5b36b86425dedf5623f311a358f3b106621f..a72da15be2b23ba6c61a722615b76221987599b1 100755 (executable)
@@ -1,7 +1,13 @@
 #! /bin/sh
 
-# Login
-login=$1
+# About: This script is called when the user is removed from the Stargazer.
+# Common task: Automate typical actions on removing user from the network,
+#              such as removing email or IM account.
+# Priority: optional
 
-#echo "deleted user $login" >> /var/stargazer/add_del.log
+# User login
+LOGIN=$1
+
+# Usage examples:
+#echo "Deleted user $LOGIN" >> /var/stargazer/add_del.log
 
index f3cbc40c644e95d4ad5f7b0a6918aa971e1dc994..948674cacafc68583f527bcd604d17cc2077f7e8 100644 (file)
@@ -3,14 +3,14 @@
     # Port for TCP connections
     # Note: Parameters TCPPort and UDPPort can be equal
     # Parameter: optional
-    # Value: 1 ... 65534
+    # Value: 1 ... 65535
     # Default: 9996
     #TCPPort = 9996
 
     # Port for UDP connections
     # Note: Parameters TCPPort and UDPPort can be equal
     # Parameter: optional
-    # Value: 1 ... 65536
+    # Value: 1 ... 65535
     # Default: 9996
     UDPPort = 9996
-</Module>
\ No newline at end of file
+</Module>
index aa18309a40bd9f0b8c2ae3386acd5280f2f62910..df170dd089203f1e806d100cbe468b732c6c57da 100644 (file)
@@ -2,20 +2,20 @@
 <Module auth_ia>
     # Port on which the server interacts with authorizator
     # Parameter: required
-    # Value: 1 ... 65534
+    # Value: 1 ... 65535
     # Default: 5555
     Port = 5555
 
     # The time interval between sending an alive query to the user
     # and updating statistics
-    # Parameter: required 
+    # Parameter: required
     # Values: 5 ... 600 (seconds)
     # Default: 60
     UserDelay = 60
 
-    # User timeout. If authorizer does not respond during this time, 
+    # User timeout. If authorizer does not respond during this time,
     # the user will be disconnected
-    # Parameter: required 
+    # Parameter: required
     # Values: 5 ... 600
     # Default: 60
     UserTimeout = 65
     # FreeMb = cash - amount of money for which the user can download for free
     # FreeMb = none - no transfer
     # Default: cash
-    # Parameter: required 
+    # Parameter: required
     # Values: different, see above
     # Default: cash
     FreeMb = cash
-</Module>
\ No newline at end of file
+
+    # Enable protocol errors logging
+    # Parameter: optional
+    # Values: yes, no
+    # Default: no
+    # LogProtocolErrors = no
+</Module>
index b3d0ab7619111b953837b5ac57de76fb9c00a5ef..a71350c868093994373161f6b1712b9418bd46c1 100644 (file)
@@ -14,7 +14,7 @@
     # 192.168.3.0/24 192.168.3.5
     # 192.168.4.0/24 192.168.4.5
     # Parametr: required
-    # Values: filename
+    # Values: file path
     # Default: subnets
     SubnetFile = subnets
 
@@ -39,4 +39,4 @@
     # Value: 1...65535
     # Default: 9999
     Port = 9999
-</Module>
\ No newline at end of file
+</Module>
index 06eeba4ed5a65f198bbfeaa84af661c3c33117b0..b05695a75e0b16b0b4542eafe329824b81ae88fc 100644 (file)
@@ -6,9 +6,9 @@
     # Default:
     Port = 8080
 
-    # Session timeout
+    # Session timeout in seconds
     # Parameter: required
-    # Value: any numeric
+    # Value: positive integer
     # Default: 1800
     CookieTimeout = 1800
-</Module>
\ No newline at end of file
+</Module>
index 924cc636ab63fc4714ef909ce9063761fbcf5de1..84ce24bb130467457c48f658382d5fcf2e732683 100644 (file)
@@ -1,3 +1,4 @@
+# Enables SMUX-peer for SNMPd.
 <Module smux>
     # IP-address of a server to connect to
     # Parameter: required
@@ -12,7 +13,7 @@
     Port = 199
 
     # Password for authentication on a server
-    # Parameter: optional
-    # 
-    # Password = 123456
+    # Parameter: required
+    # Value: any text
+    Password =
 </Module>
index 068d4abaeb8e98c597a48c90d2d0cf438cc80d12..f7e0f23da47773ae6c059338726ea44b41fd8970 100644 (file)
@@ -1,5 +1,4 @@
-# Option - the name of the module without 'mod_' at the beginning and '.so'
-# in the end ie full name of the module mod_store_files.so
+# Enables plain file backend.
 <StoreModule store_files>
 
     # Working server directory, provides data on tariffs, users, administrators.
index 738d75ccf4c02553d01a307547a23e27a7af210d..39e4ad3d9333f0fda49beed07fad397b1c1e6203 100644 (file)
@@ -1,37 +1,38 @@
+# Enables Firebird backend.
 <StoreModule store_firebird>
     # Database server address
-    # Parameter: required
+    # Parameter: optional
     # Value: IP address or DNS name
     # Default: localhost
-    Server = localhost
+    Server = localhost
 
     # Path to the database on the server or its alias
-    # Parameter: required
+    # Parameter: optional
     # Value: file path
     # Default: /var/stg/stargazer.fdb
-    Database = /var/stg/stargazer.fdb
+    Database = /var/stg/stargazer.fdb
 
     # Database username
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: stg
-    User = stg
+    User = stg
 
     # Database password
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: 123456
-    Password = 123456
+    Password = 123456
 
     # The transaction isolation level
     # Parameter: optional
     # Values: concurrency, dirtyread, readcommitted, consistency
     # Defalt: concurrency
-    IsolationLevel = concurrency
+    IsolationLevel = concurrency
 
     # Responding to lock (optional, defaults to wait):
     # Parameter: optional
     # Values: wait, nowait
     # Defalt: wait
-    LockResolution = wait
+    LockResolution = wait
 </StoreModule>
index a5cc418046d9d56cb7543f2451eab761548ae407..a5b2126d5b3ca3d4669ec3a361ff457265dac154 100644 (file)
@@ -1,3 +1,4 @@
+# Enables MySQL backend.
 <StoreModule store_mysql>
     # Database server address
     # Parameter: required
index 153265845091dfe2d52b4296ba4c0b95c7fa4720..8a52c75b994eeca8a5800e8b42a2c6e8137eacb2 100644 (file)
@@ -1,27 +1,28 @@
+# Enables PostgreSQL backend.
 <StoreModule store_postgresql>
     # Database server address
-    # Parameter: required
+    # Parameter: optional
     # Value: IP address or DNS name
     # Default: localhost
-    Server = localhost
+    Server = localhost
 
     # Database name
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: stargazer
-    Database = stargazer
+    Database = stargazer
 
     # Database username
-    # Parameter: mandatory
+    # Parameter: optional
     # Value: any, supported by database
     # Default: stg
-    User = stg
+    User = stg
 
     # Database password
-    # Parameter: required
+    # Parameter: optional
     # Value: any, supported by database
     # Default: 123456
-    Password = 123456
+    Password = 123456
 
     # Number of tries to reconnect
     # Parameter: optional
index 4fff88a16de7c82a094ca54ba2c3f094c2223bf6..1e4c677e255133503bbc25c61721874cf3891d95 100644 (file)
@@ -60,8 +60,6 @@
 #include "pidfile.h"
 #include "eventloop.h"
 
-using namespace std;
-
 #ifdef DEBUG
     #define MAIN_DEBUG (1)
     #define NO_DAEMON  (1)
@@ -69,7 +67,16 @@ using namespace std;
 
 #define START_FILE "/._ST_ART_ED_"
 
-set<pid_t> executersPid;
+namespace
+{
+std::set<pid_t> executersPid;
+
+bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs);
+bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs);
+void StartTimer();
+int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings);
+int ForkAndWait(const std::string & confDir);
+void KillExecuters();
 
 //-----------------------------------------------------------------------------
 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
@@ -82,7 +89,7 @@ bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
 return lhs.GetStopPosition() > rhs.GetStopPosition();
 }
 //-----------------------------------------------------------------------------
-static void StartTimer()
+void StartTimer()
 {
 STG_LOGGER & WriteServLog = GetStgLogger();
 
@@ -99,7 +106,7 @@ else
     }
 }
 //-----------------------------------------------------------------------------
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
 #else
 int StartScriptExecuter(char *, int msgKey, int * msgID, SETTINGS_IMPL * settings)
@@ -144,7 +151,7 @@ switch (executerPid)
 
     case 0:
         delete settings;
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
         Executer(*msgID, executerPid, procName);
 #else
         Executer(*msgID, executerPid);
@@ -153,7 +160,7 @@ switch (executerPid)
 
     default:
         if (executersPid.empty()) {
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
             Executer(*msgID, executerPid, NULL);
 #else
             Executer(*msgID, executerPid);
@@ -165,14 +172,14 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 #ifndef NO_DAEMON
-int ForkAndWait(const string & confDir)
+int ForkAndWait(const std::string & confDir)
 #else
-int ForkAndWait(const string &)
+int ForkAndWait(const std::string &)
 #endif
 {
 #ifndef NO_DAEMON
 pid_t childPid = fork();
-string startFile = confDir + START_FILE;
+std::string startFile = confDir + START_FILE;
 unlink(startFile.c_str());
 
 switch (childPid)
@@ -209,7 +216,7 @@ return 0;
 //-----------------------------------------------------------------------------
 void KillExecuters()
 {
-set<pid_t>::iterator pid;
+std::set<pid_t>::iterator pid;
 pid = executersPid.begin();
 while (pid != executersPid.end())
     {
@@ -219,6 +226,8 @@ while (pid != executersPid.end())
     }
 }
 //-----------------------------------------------------------------------------
+} // namespace anonymous
+//-----------------------------------------------------------------------------
 int main(int argc, char * argv[])
 {
 SETTINGS_IMPL * settings = NULL;
@@ -236,10 +245,10 @@ int msgID = -11;
     WriteServLog.SetLogFileName("/var/log/stargazer.log");
     }
 
-vector<MODULE_SETTINGS> modSettings;
-list<PLUGIN_RUNNER> modules;
+std::vector<MODULE_SETTINGS> modSettings;
+std::list<PLUGIN_RUNNER> modules;
 
-list<PLUGIN_RUNNER>::iterator modIter;
+std::list<PLUGIN_RUNNER>::iterator modIter;
 
 if (getuid())
     {
@@ -262,9 +271,8 @@ if (settings->ReadSettings())
     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
     exit(1);
     }
-
 #ifndef NO_DAEMON
-string startFile(settings->GetConfDir() + START_FILE);
+std::string startFile(settings->GetConfDir() + START_FILE);
 #endif
 
 if (ForkAndWait(settings->GetConfDir()) < 0)
@@ -338,7 +346,7 @@ modSettings = settings->GetModulesSettings();
 
 for (size_t i = 0; i < modSettings.size(); i++)
     {
-    string modulePath = settings->GetModulesPath();
+    std::string modulePath = settings->GetModulesPath();
     modulePath += "/mod_";
     modulePath += modSettings[i].moduleName;
     modulePath += ".so";
@@ -363,7 +371,8 @@ while (modIter != modules.end())
     {
     if (modIter->Load())
         {
-        WriteServLog("Error: %s",
+        WriteServLog("Error loading module '%s': %s",
+                     modIter->GetPlugin()->GetVersion().c_str(),
                      modIter->GetStrError().c_str());
         goto exitLblNotStarted;
         }
@@ -390,7 +399,8 @@ while (modIter != modules.end())
     {
     if (modIter->Start())
         {
-        WriteServLog("Error: %s",
+        WriteServLog("Error starting module '%s': %s",
+                     modIter->GetPlugin()->GetVersion().c_str(),
                      modIter->GetStrError().c_str());
         goto exitLbl;
         }
@@ -398,7 +408,7 @@ while (modIter != modules.end())
     ++modIter;
     }
 
-srandom(stgTime);
+srandom(static_cast<unsigned int>(stgTime));
 
 WriteServLog("Stg started successfully.");
 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
@@ -415,7 +425,7 @@ while (true)
     bool stop = false;
     int status;
     pid_t childPid;
-    set<pid_t>::iterator it;
+    std::set<pid_t>::iterator it;
     switch (sig)
         {
         case SIGHUP:
@@ -425,9 +435,9 @@ while (true)
                 {
                 if (modIter->Reload())
                     {
-                    WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
+                    WriteServLog("Error reloading module '%s': '%s'", modIter->GetPlugin()->GetVersion().c_str(),
                                                               modIter->GetStrError().c_str());
-                    printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
+                    printfd(__FILE__, "Error reloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(),
                                                                      modIter->GetStrError().c_str());
                     }
                 }
@@ -453,7 +463,7 @@ while (true)
                 }
             break;
         default:
-            WriteServLog("Ignore signel %d", sig);
+            WriteServLog("Ignore signal %d", sig);
             break;
         }
     if (stop)
@@ -473,14 +483,14 @@ while (modIter != modules.end())
     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
     if (modIter->Stop())
         {
-        WriteServLog("Module \'%s\': Error: %s",
+        WriteServLog("Error stopping module '%s': %s",
                      modIter->GetPlugin()->GetVersion().c_str(),
                      modIter->GetStrError().c_str());
-        printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
+        printfd(__FILE__, "Error stopping module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str());
         }
     else
         {
-        WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
+        WriteServLog("Module: '%s'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
         }
     ++modIter;
     }
@@ -505,10 +515,10 @@ while (modIter != modules.end())
         printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
         if (modIter->Unload())
             {
-            WriteServLog("Module \'%s\': Error: %s",
-                         name.c_str(),
+            WriteServLog("Error unloading module '%s': '%s'",
+                         modIter->GetPlugin()->GetVersion().c_str(),
                          modIter->GetStrError().c_str());
-            printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
+            printfd(__FILE__, "Error unloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str());
             }
         }
     ++modIter;
index 17e10ace9d0845932ecc6f22860c52c1e514d7f7..dd1e124a32a1e01407d872605a4d490476ed7785 100644 (file)
@@ -9,18 +9,23 @@ OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
 LN = ln
 
 STGLIBS_INCS = $(addprefix -I ../../../../../stglibs/,$(addsuffix .lib/include,$(STGLIBS)))
-STGLIBS_LIBS = $(addprefix -L ../../../../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
+STGLIBS_PATHS = $(addprefix -L ../../../../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
 
-LIBS += $(addprefix -lstg,$(STGLIBS))
+STGLIBS_LIBS = $(addprefix -lstg,$(STGLIBS))
 
 CXXFLAGS += -fPIC $(STGLIBS_INCS)
 CFLAGS += -fPIC $(STGLIBS_INCS)
-LDFLAGS += -shared -Wl,-rpath,$(PREFIX)/usr/lib/stg $(STGLIBS_LIBS)
+
+ifneq ($(OS),darwin)
+LDFLAGS += -shared -Wl,-rpath,$(PREFIX)/usr/lib/stg
+else
+LDFLAGS += -dynamiclib -undefined suppress -flat_namespace -Wl,-rpath,$(PREFIX)/usr/lib/stg
+endif
 
 all: $(PROG)
 
 $(PROG): $(OBJS)
-       $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG)
+       $(CXX) $^ $(STGLIBS_PATHS) $(STGLIBS_LIBS) $(LIBS) $(LDFLAGS) -o $(PROG)
        $(LN) -fs "`pwd`/$(PROG)" $(DIR_MOD)/$(PROG)
 
 clean:
@@ -28,7 +33,11 @@ clean:
 
 install: $(PROG)
        mkdir -m $(DIR_MODE) -p $(PREFIX)/usr/lib/stg
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+endif
 
 uninstall:
        rm -f $(PREFIX)/usr/lib/stg/$(PROG)
index 1a7697e36972a0f6b6169306d2b6c990b71c0cc5..0e356aa1831a4fc659a4ed471483a20cf16c2397 100644 (file)
@@ -8,10 +8,10 @@ PROG = mod_auth_ao.so
 
 SRCS = ./ao.cpp
 
-STGLIBS = common \
+STGLIBS = scriptexecuter \
          logger \
          locker \
-         scriptexecuter
+         common
 
 include ../../Makefile.in
 
index cef272c0b9bca72ecb75f2601ae6c8cf3fe54995..100e0557603f16faed29d1da098e9d48450868f8 100644 (file)
@@ -41,7 +41,7 @@ $Author: faust $
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-PLUGIN_CREATOR<AUTH_AO> aoc;
+static PLUGIN_CREATOR<AUTH_AO> aoc;
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -53,18 +53,18 @@ return aoc.GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 template <typename varType>
-class IS_CONTAINS_USER: public binary_function<varType, USER_PTR, bool>
+class IS_CONTAINS_USER: public std::binary_function<varType, USER_PTR, bool>
 {
 public:
     bool operator()(varType notifier, USER_PTR user) const
         {
         return notifier.GetUser() == user;
-        };
+        }
 };
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-const string AUTH_AO::GetVersion() const
+std::string AUTH_AO::GetVersion() const
 {
 return "Always Online authorizator v.1.0";
 }
@@ -80,7 +80,8 @@ AUTH_AO::AUTH_AO()
       BeforeChgIPNotifierList(),
       AfterChgIPNotifierList(),
       onAddUserNotifier(*this),
-      onDelUserNotifier(*this)
+      onDelUserNotifier(*this),
+      logger(GetPluginLogger(GetStgLogger(), "auth_ao"))
 {
 }
 //-----------------------------------------------------------------------------
@@ -108,7 +109,7 @@ if (!isRunning)
 users->DelNotifierUserAdd(&onAddUserNotifier);
 users->DelNotifierUserDel(&onDelUserNotifier);
 
-list<USER_PTR>::iterator users_iter;
+std::list<USER_PTR>::iterator users_iter;
 users_iter = usersList.begin();
 while (users_iter != usersList.end())
     {
@@ -152,8 +153,8 @@ void AUTH_AO::UnSetUserNotifiers(USER_PTR u)
 IS_CONTAINS_USER<CHG_BEFORE_NOTIFIER<int> > IsContainsUserAOB;
 IS_CONTAINS_USER<CHG_AFTER_NOTIFIER<int> > IsContainsUserAOA;
 
-list<CHG_BEFORE_NOTIFIER<int> >::iterator aoBIter;
-list<CHG_AFTER_NOTIFIER<int> >::iterator  aoAIter;
+std::list<CHG_BEFORE_NOTIFIER<int> >::iterator aoBIter;
+std::list<CHG_AFTER_NOTIFIER<int> >::iterator  aoAIter;
 
 aoBIter = find_if(BeforeChgAONotifierList.begin(),
                   BeforeChgAONotifierList.end(),
@@ -180,12 +181,12 @@ if (aoAIter != AfterChgAONotifierList.end())
 IS_CONTAINS_USER<CHG_BEFORE_NOTIFIER<USER_IPS> > IsContainsUserIPB;
 IS_CONTAINS_USER<CHG_AFTER_NOTIFIER<USER_IPS> >  IsContainsUserIPA;
 
-list<CHG_BEFORE_NOTIFIER<USER_IPS> >::iterator ipBIter;
-list<CHG_AFTER_NOTIFIER<USER_IPS> >::iterator  ipAIter;
+std::list<CHG_BEFORE_NOTIFIER<USER_IPS> >::iterator ipBIter;
+std::list<CHG_AFTER_NOTIFIER<USER_IPS> >::iterator  ipAIter;
 
-ipBIter = find_if(BeforeChgIPNotifierList.begin(),
-                  BeforeChgIPNotifierList.end(),
-                  bind2nd(IsContainsUserIPB, u));
+ipBIter = std::find_if(BeforeChgIPNotifierList.begin(),
+                       BeforeChgIPNotifierList.end(),
+                       bind2nd(IsContainsUserIPB, u));
 
 if (ipBIter != BeforeChgIPNotifierList.end())
     {
@@ -241,7 +242,8 @@ UpdateUserAuthorization(u);
 //-----------------------------------------------------------------------------
 void AUTH_AO::DelUser(USER_PTR u)
 {
-users->Unauthorize(u->GetLogin(), this);
+if (u->IsAuthorizedBy(this))
+    users->Unauthorize(u->GetLogin(), this);
 UnSetUserNotifiers(u);
 usersList.remove(u);
 }
index 205ebf5a841a5eded5e9d1bc40d86faa8c2ce9da..d8b6dc88bf48719a7504a9f08328bdfb08c25973 100644 (file)
@@ -37,6 +37,7 @@
 #include "stg/notifer.h"
 #include "stg/user_ips.h"
 #include "stg/user.h"
+#include "stg/logger.h"
 
 extern "C" PLUGIN * GetPlugin();
 
@@ -82,7 +83,7 @@ private:
 class AUTH_AO : public AUTH {
 public:
     AUTH_AO();
-    virtual ~AUTH_AO(){};
+    virtual ~AUTH_AO(){}
 
     void                SetUsers(USERS * u) { users = u; }
 
@@ -93,7 +94,7 @@ public:
     void                SetSettings(const MODULE_SETTINGS &) {}
     int                 ParseSettings() { return 0; }
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const;
+    std::string         GetVersion() const;
     uint16_t            GetStartPosition() const { return 30; }
     uint16_t            GetStopPosition() const { return 30; }
 
@@ -117,11 +118,11 @@ private:
     bool                isRunning;
     MODULE_SETTINGS     settings;
 
-    list<CHG_BEFORE_NOTIFIER<int> >      BeforeChgAONotifierList;
-    list<CHG_AFTER_NOTIFIER<int> >       AfterChgAONotifierList;
+    std::list<CHG_BEFORE_NOTIFIER<int> >      BeforeChgAONotifierList;
+    std::list<CHG_AFTER_NOTIFIER<int> >       AfterChgAONotifierList;
 
-    list<CHG_BEFORE_NOTIFIER<USER_IPS> > BeforeChgIPNotifierList;
-    list<CHG_AFTER_NOTIFIER<USER_IPS> >  AfterChgIPNotifierList;
+    std::list<CHG_BEFORE_NOTIFIER<USER_IPS> > BeforeChgIPNotifierList;
+    std::list<CHG_AFTER_NOTIFIER<USER_IPS> >  AfterChgIPNotifierList;
 
     class ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
     public:
@@ -148,6 +149,7 @@ private:
 
         AUTH_AO & auth;
     } onDelUserNotifier;
+    PLUGIN_LOGGER logger;
 
     friend class CHG_BEFORE_NOTIFIER<int>;
     friend class CHG_AFTER_NOTIFIER<int>;
index a6d2073abe709b4457f186f0e6bf4d2b3d58d25a..5a15a10aea91cfee72d1614d068c73bab3d61a4c 100644 (file)
@@ -36,6 +36,7 @@
 #include <cstdlib>
 #include <cstdio> // snprintf
 #include <cerrno>
+#include <cmath>
 #include <algorithm>
 
 #include "stg/common.h"
 #include "stg/plugin_creator.h"
 #include "inetaccess.h"
 
-extern volatile const time_t stgTime;
-
-void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
+extern volatile time_t stgTime;
 
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<AUTH_IA> iac;
+
+void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
+}
+
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -79,7 +85,7 @@ int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
 {
 int p;
 PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 ///////////////////////////
 pv.param = "Port";
 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -95,7 +101,7 @@ if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
     return -1;
     }
-port = p;
+port = static_cast<uint16_t>(p);
 ///////////////////////////
 pv.param = "UserDelay";
 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -128,8 +134,19 @@ if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
     printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
     return -1;
     }
+///////////////////////////
+pv.param = "LogProtocolErrors";
+pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
+if (pvi == s.moduleParams.end())
+    logProtocolErrors = false;
+else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
+    {
+    errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
+    printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
+    return -1;
+    }
 /////////////////////////////////////////////////////////////
-string freeMbType;
+std::string freeMbType;
 int n = 0;
 pv.param = "FreeMb";
 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -321,9 +338,9 @@ AUTH_IA::AUTH_IA()
       fin6(),
       fin8(),
       packetTypes(),
-      WriteServLog(GetStgLogger()),
       enabledDirs(0xFFffFFff),
-      onDelUserNotifier(*this)
+      onDelUserNotifier(*this),
+      logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
 {
 InitEncrypt(&ctxS, "pr7Hhen");
 
@@ -393,6 +410,7 @@ if (!isRunningRun)
         {
         errorStr = "Cannot create thread.";
         printfd(__FILE__, "Cannot create recv thread\n");
+        logger("Cannot create recv thread.");
         return -1;
         }
     }
@@ -403,6 +421,7 @@ if (!isRunningRunTimeouter)
         {
         errorStr = "Cannot create thread.";
         printfd(__FILE__, "Cannot create timeouter thread\n");
+        logger("Cannot create timeouter thread.");
         return -1;
         }
     }
@@ -474,7 +493,7 @@ while (ia->nonstop)
     if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
         {
         touchTime = stgTime;
-        string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
+        std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
         TouchFile(monFile.c_str());
         }
     }
@@ -494,7 +513,7 @@ AUTH_IA * ia = static_cast<AUTH_IA *>(d);
 ia->isRunningRunTimeouter = true;
 
 int a = -1;
-string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
+std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
 while (ia->nonstop)
     {
     struct timespec ts = {0, 20000000};
@@ -528,16 +547,18 @@ listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
 if (listenSocket < 0)
     {
     errorStr = "Cannot create socket.";
+    logger("Cannot create a socket: %s", strerror(errno));
     return -1;
     }
 
 listenAddr.sin_family = AF_INET;
-listenAddr.sin_port = htons(iaSettings.GetUserPort());
+listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
 
 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
     {
     errorStr = "AUTH_IA: Bind failed.";
+    logger("Cannot bind the socket: %s", strerror(errno));
     return -1;
     }
 
@@ -559,7 +580,7 @@ if (!WaitPackets(listenSocket)) // Timeout
 
 struct sockaddr_in outerAddr;
 socklen_t outerAddrLen(sizeof(outerAddr));
-int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
+ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
 
 if (!dataLen) // EOF
     {
@@ -571,6 +592,7 @@ if (dataLen <= 0) // Error
     if (errno != EINTR)
         {
         printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
+        logger("recvfrom error: %s", strerror(errno));
         return -1;
         }
     return 0;
@@ -579,8 +601,11 @@ if (dataLen <= 0) // Error
 if (dataLen > 256)
     return -1;
 
+uint32_t sip = outerAddr.sin_addr.s_addr;
+uint16_t sport = htons(outerAddr.sin_port);
+
 int protoVer;
-if (CheckHeader(buffer, &protoVer))
+if (CheckHeader(buffer, sip, &protoVer))
     return -1;
 
 char login[PASSWD_LEN];  //TODO why PASSWD_LEN ?
@@ -588,15 +613,12 @@ memset(login, 0, PASSWD_LEN);
 
 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
 
-uint32_t sip = outerAddr.sin_addr.s_addr;
-uint16_t sport = htons(outerAddr.sin_port);
-
 USER_PTR user;
 if (users->FindByName(login, &user))
     {
-    WriteServLog("User's connect failed: user '%s' not found. IP %s",
-                 login,
-                 inet_ntostring(sip).c_str());
+    logger("User's connect failed: user '%s' not found. IP %s",
+           login,
+           inet_ntostring(sip).c_str());
     printfd(__FILE__, "User '%s' NOT found!\n", login);
     SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
     return -1;
@@ -606,12 +628,14 @@ printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
 
 if (user->GetProperty().disabled.Get())
     {
+    logger("Cannont authorize '%s', user is disabled.", login);
     SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
     return 0;
     }
 
 if (user->GetProperty().passive.Get())
     {
+    logger("Cannont authorize '%s', user is passive.", login);
     SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
     return 0;
     }
@@ -620,8 +644,8 @@ if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
     {
     printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
             user->GetLogin().c_str(), inet_ntostring(sip).c_str());
-    WriteServLog("User %s. IP address is incorrect. IP %s",
-                 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
+    logger("User %s. IP address is incorrect. IP %s",
+           user->GetLogin().c_str(), inet_ntostring(sip).c_str());
     SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
     return 0;
     }
@@ -629,12 +653,14 @@ if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
+int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
 {
 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
     {
     //SendError(userIP, updateMsg);
     printfd(__FILE__, "update needed - IA_ID\n");
+    if (iaSettings.LogProtocolErrors())
+        logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
     //SendError(userIP, "Incorrect header!");
     return -1;
     }
@@ -642,6 +668,8 @@ if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
 if (buffer[6] != 0) //proto[0] shoud be 0
     {
     printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
+    if (iaSettings.LogProtocolErrors())
+        logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
     //SendError(userIP, updateMsg);
     return -1;
     }
@@ -651,6 +679,8 @@ if (buffer[7] < 6)
     // need update
     //SendError(userIP, updateMsg);
     printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
+    if (iaSettings.LogProtocolErrors())
+        logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
     return -1;
     }
 else
@@ -664,7 +694,7 @@ int AUTH_IA::Timeouter()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-map<uint32_t, IA_USER>::iterator it;
+std::map<uint32_t, IA_USER>::iterator it;
 it = ip2user.begin();
 uint32_t sip;
 
@@ -678,6 +708,8 @@ while (it != ip2user.end())
     if ((it->second.phase.GetPhase() == 2)
         && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
         {
+        if (iaSettings.LogProtocolErrors())
+            logger("User '%s'. Protocol version: %d. Phase 2: connect request timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserDelay());
         it->second.phase.SetPhase1();
         printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
         ip2user.erase(it++);
@@ -720,6 +752,8 @@ while (it != ip2user.end())
 
         if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
             {
+            if (iaSettings.LogProtocolErrors())
+                logger("User '%s'. Protocol version: %d. Phase 3: alive timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserTimeout());
             users->Unauthorize(it->second.user->GetLogin(), this);
             ip2user.erase(it++);
             continue;
@@ -729,6 +763,8 @@ while (it != ip2user.end())
     if ((it->second.phase.GetPhase() == 4)
         && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
         {
+        if (iaSettings.LogProtocolErrors())
+            logger("User '%s'. Protocol version: %d. Phase 4: disconnect request timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserDelay());
         it->second.phase.SetPhase3();
         printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
         }
@@ -739,13 +775,13 @@ while (it != ip2user.end())
 return 0;
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
+int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
 {
 std::string login(user->GetLogin());
-const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
+const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
 
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
+std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
 
 if (it == ip2user.end())
     {
@@ -758,10 +794,10 @@ if (it == ip2user.end())
                     userPtr->GetLogin().c_str(),
                     inet_ntostring(sip).c_str(),
                    login.c_str());
-            WriteServLog("IP address already in use by user '%s'. IP %s, login: '%s'",
-                         userPtr->GetLogin().c_str(),
-                         inet_ntostring(sip).c_str(),
-                         login.c_str());
+            logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
+                   userPtr->GetLogin().c_str(),
+                   inet_ntostring(sip).c_str(),
+                   login.c_str());
             SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
             return 0;
             }
@@ -783,10 +819,10 @@ else if (user->GetID() != it->second.user->GetID())
             it->second.user->GetLogin().c_str(),
             inet_ntostring(sip).c_str(),
             user->GetLogin().c_str());
-    WriteServLog("IP address already in use by user '%s'. IP %s, login: '%s'",
-                 it->second.user->GetLogin().c_str(),
-                 inet_ntostring(sip).c_str(),
-                 user->GetLogin().c_str());
+    logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
+           it->second.user->GetLogin().c_str(),
+           inet_ntostring(sip).c_str(),
+           user->GetLogin().c_str());
     SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
     return 0;
     }
@@ -799,21 +835,20 @@ if (iaUser->password != user->GetProperty().password.Get())
     iaUser->password = user->GetProperty().password.Get();
     }
 
-buff += offset;
-Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
+Decrypt(&iaUser->ctx, static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset) / 8);
 
 char packetName[IA_MAX_TYPE_LEN];
-strncpy(packetName,  buff + 4, IA_MAX_TYPE_LEN);
+strncpy(packetName,  static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
 packetName[IA_MAX_TYPE_LEN - 1] = 0;
 
-map<string, int>::iterator pi(packetTypes.find(packetName));
+std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
 if (pi == packetTypes.end())
     {
     SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉΠÉÌÉ ÐÁÒÏÌØ!");
     printfd(__FILE__, "Login or password is wrong!\n");
-    WriteServLog("User's connect failed. User: '%s', ip %s. Wrong login or password",
-                 login.c_str(),
-                 inet_ntostring(sip).c_str());
+    logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
+           login.c_str(),
+           inet_ntostring(sip).c_str());
     ip2user.erase(it);
     return 0;
     }
@@ -823,10 +858,10 @@ if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
     printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
             login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
             inet_ntostring(sip).c_str());
-    WriteServLog("Login %s already in use from ip %s. IP %s",
-                 login.c_str(),
-                 inet_ntostring(user->GetCurrIP()).c_str(),
-                 inet_ntostring(sip).c_str());
+    logger("Login '%s' is already in use from ip %s. IP %s",
+           login.c_str(),
+           inet_ntostring(user->GetCurrIP()).c_str(),
+           inet_ntostring(sip).c_str());
     SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉΠÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
     ip2user.erase(it);
     return 0;
@@ -838,15 +873,15 @@ switch (pi->second)
         switch (protoVer)
             {
             case 6:
-                if (Process_CONN_SYN_6((CONN_SYN_6 *)(buff - offset), &(it->second), sip))
+                if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
                     return -1;
                 return Send_CONN_SYN_ACK_6(iaUser, sip);
             case 7:
-                if (Process_CONN_SYN_7((CONN_SYN_7 *)(buff - offset), &(it->second), sip))
+                if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
                     return -1;
                 return Send_CONN_SYN_ACK_7(iaUser, sip);
             case 8:
-                if (Process_CONN_SYN_8((CONN_SYN_8 *)(buff - offset), &(it->second), sip))
+                if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
                     return -1;
                 return Send_CONN_SYN_ACK_8(iaUser, sip);
             }
@@ -856,15 +891,15 @@ switch (pi->second)
         switch (protoVer)
             {
             case 6:
-                if (Process_CONN_ACK_6((CONN_ACK_6 *)(buff - offset), iaUser, sip))
+                if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
                     return -1;
                 return Send_ALIVE_SYN_6(iaUser, sip);
             case 7:
-                if (Process_CONN_ACK_7((CONN_ACK_6 *)(buff - offset), iaUser, sip))
+                if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
                     return -1;
                 return Send_ALIVE_SYN_7(iaUser, sip);
             case 8:
-                if (Process_CONN_ACK_8((CONN_ACK_8 *)(buff - offset), iaUser, sip))
+                if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
                     return -1;
                 return Send_ALIVE_SYN_8(iaUser, sip);
             }
@@ -874,11 +909,11 @@ switch (pi->second)
         switch (protoVer)
             {
             case 6:
-                return Process_ALIVE_ACK_6((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
+                return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
             case 7:
-                return Process_ALIVE_ACK_7((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
+                return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
             case 8:
-                return Process_ALIVE_ACK_8((ALIVE_ACK_8 *)(buff - offset), iaUser, sip);
+                return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
             }
         break;
 
@@ -886,15 +921,15 @@ switch (pi->second)
         switch (protoVer)
             {
             case 6:
-                if (Process_DISCONN_SYN_6((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
+                if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
                     return -1;
                 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
             case 7:
-                if (Process_DISCONN_SYN_7((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
+                if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
                     return -1;
                 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
             case 8:
-                if (Process_DISCONN_SYN_8((DISCONN_SYN_8 *)(buff - offset), iaUser, sip))
+                if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
                     return -1;
                 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
             }
@@ -904,15 +939,15 @@ switch (pi->second)
         switch (protoVer)
             {
             case 6:
-                if (Process_DISCONN_ACK_6((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
+                if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
                     return -1;
                 return Send_FIN_6(iaUser, sip, it);
             case 7:
-                if (Process_DISCONN_ACK_7((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
+                if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
                     return -1;
                 return Send_FIN_7(iaUser, sip, it);
             case 8:
-                if (Process_DISCONN_ACK_8((DISCONN_ACK_8 *)(buff - offset), iaUser, sip, it))
+                if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
                     return -1;
                 return Send_FIN_8(iaUser, sip, it);
             }
@@ -930,7 +965,7 @@ uint32_t ip = u->GetCurrIP();
 if (!ip)
     return;
 
-map<uint32_t, IA_USER>::iterator it;
+std::map<uint32_t, IA_USER>::iterator it;
 
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 it = ip2user.find(ip);
@@ -949,12 +984,12 @@ if (it->second.user == u)
     }
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
+int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
 {
 struct sockaddr_in sendAddr;
+ssize_t res;
 switch (protoVer)
     {
-    int res;
     case 6:
     case 7:
         ERR err;
@@ -1000,7 +1035,7 @@ switch (protoVer)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
+int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
 {
 struct sockaddr_in sendAddr;
 
@@ -1008,9 +1043,7 @@ sendAddr.sin_family = AF_INET;
 sendAddr.sin_port = htons(port);
 sendAddr.sin_addr.s_addr = ip;
 
-int res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
-
-if (res == len)
+if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
     return 0;
 
 return -1;
@@ -1020,7 +1053,7 @@ int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
 {
 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
 
-map<uint32_t, IA_USER>::iterator it;
+std::map<uint32_t, IA_USER>::iterator it;
 
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 it = ip2user.find(ip);
@@ -1066,8 +1099,8 @@ memset(&info, 0, sizeof(INFO_7));
 
 info.len = 264;
 strncpy((char*)info.type, "INFO_7", 16);
-info.infoType = msg.header.type;
-info.showTime = msg.header.showTime;
+info.infoType = static_cast<int8_t>(msg.header.type);
+info.showTime = static_cast<int8_t>(msg.header.showTime);
 info.sendTime = msg.header.creationTime;
 
 size_t len = info.len;
@@ -1095,8 +1128,8 @@ memset(&info, 0, sizeof(INFO_8));
 
 info.len = 1056;
 strncpy((char*)info.type, "INFO_8", 16);
-info.infoType = msg.header.type;
-info.showTime = msg.header.showTime;
+info.infoType = static_cast<int8_t>(msg.header.type);
+info.showTime = static_cast<int8_t>(msg.header.showTime);
 info.sendTime = msg.header.creationTime;
 
 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
@@ -1164,6 +1197,8 @@ if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
     else
         {
         errorStr = iaUser->user->GetStrError();
+        if (iaSettings.LogProtocolErrors())
+            logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: phase 2, authorization error ('%s').", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, errorStr.c_str());
         iaUser->phase.SetPhase1();
         ip2user.erase(sip);
         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
@@ -1171,6 +1206,13 @@ if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
         }
     }
 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
+if (iaSettings.LogProtocolErrors())
+    {
+    if (iaUser->phase.GetPhase() != 2)
+        logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid phase, expected 2, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
+    if (connAck->rnd != iaUser->rnd + 1)
+        logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), connAck->rnd);
+    }
 return -1;
 }
 //-----------------------------------------------------------------------------
@@ -1200,6 +1242,8 @@ if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
     else
         {
         errorStr = iaUser->user->GetStrError();
+        if (iaSettings.LogProtocolErrors())
+            logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: phase 2, authorization error ('%s').", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, errorStr.c_str());
         iaUser->phase.SetPhase1();
         ip2user.erase(sip);
         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
@@ -1207,6 +1251,13 @@ if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
         }
     }
 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
+if (iaSettings.LogProtocolErrors())
+    {
+    if (iaUser->phase.GetPhase() != 2)
+        logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid phase, expected 2, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
+    if (connAck->rnd != iaUser->rnd + 1)
+        logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), connAck->rnd);
+    }
 return -1;
 }
 //-----------------------------------------------------------------------------
@@ -1249,11 +1300,13 @@ if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
+int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
 {
 printfd(__FILE__, "DISCONN_SYN_6\n");
 if (iaUser->phase.GetPhase() != 3)
     {
+    if (iaSettings.LogProtocolErrors())
+        logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
     errorStr = "Incorrect request DISCONN_SYN";
     return -1;
@@ -1270,10 +1323,12 @@ int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser,
 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
+int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
 {
 if (iaUser->phase.GetPhase() != 3)
     {
+    if (iaSettings.LogProtocolErrors())
+        logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
     errorStr = "Incorrect request DISCONN_SYN";
     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
     return -1;
@@ -1287,8 +1342,8 @@ return 0;
 //-----------------------------------------------------------------------------
 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
                                    IA_USER * iaUser,
-                                   uint32_t,
-                                   map<uint32_t, IA_USER>::iterator)
+                                   uint32_t sip,
+                                   std::map<uint32_t, IA_USER>::iterator)
 {
 #ifdef ARCH_BE
 SwapBytes(disconnAck->len);
@@ -1297,6 +1352,13 @@ SwapBytes(disconnAck->rnd);
 printfd(__FILE__, "DISCONN_ACK_6\n");
 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
     {
+    if (iaSettings.LogProtocolErrors())
+        {
+        if (iaUser->phase.GetPhase() != 4)
+            logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid phase, expected 4, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
+        if (disconnAck->rnd != iaUser->rnd + 1)
+            logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), disconnAck->rnd);
+        }
     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
     return -1;
     }
@@ -1304,12 +1366,12 @@ if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
 {
 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_tmap<uint32_t, IA_USER>::iterator)
+int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
 {
 #ifdef ARCH_BE
 SwapBytes(disconnAck->len);
@@ -1318,6 +1380,13 @@ SwapBytes(disconnAck->rnd);
 printfd(__FILE__, "DISCONN_ACK_8\n");
 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
     {
+    if (iaSettings.LogProtocolErrors())
+        {
+        if (iaUser->phase.GetPhase() != 4)
+            logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid phase, expected 4, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
+        if (disconnAck->rnd != iaUser->rnd + 1)
+            logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), disconnAck->rnd);
+        }
     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
     return -1;
     }
@@ -1341,7 +1410,7 @@ for (int j = 0; j < DIR_NUM; j++)
     }
 //--- Fill static data in connSynAck ---
 
-iaUser->rnd = random();
+iaUser->rnd = static_cast<uint32_t>(random());
 connSynAck6.rnd = iaUser->rnd;
 
 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
@@ -1383,7 +1452,7 @@ for (int j = 0; j < DIR_NUM; j++)
     }
 //--- Fill static data in connSynAck ---
 
-iaUser->rnd = random();
+iaUser->rnd = static_cast<uint32_t>(random());
 connSynAck8.rnd = iaUser->rnd;
 
 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
@@ -1403,7 +1472,7 @@ return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))
 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
 {
 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
-aliveSyn6.rnd = iaUser->rnd = random();
+aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
 
 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
 
@@ -1426,8 +1495,8 @@ if (dn < DIR_NUM)
                                          aliveSyn6.md[dn],
                                          dn,
                                          stgTime);
-    p *= (1024 * 1024);
-    if (p == 0)
+    p *= 1024 * 1024;
+    if (std::fabs(p) < 1.0e-3)
         {
         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
         }
@@ -1493,7 +1562,7 @@ aliveSyn8.hdr.protoVer[0] = 0;
 aliveSyn8.hdr.protoVer[1] = 8;
 
 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
-aliveSyn8.rnd = iaUser->rnd = random();
+aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
 
 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
 
@@ -1516,8 +1585,8 @@ if (dn < DIR_NUM)
                                          aliveSyn8.md[dn],
                                          dn,
                                          stgTime);
-    p *= (1024 * 1024);
-    if (p == 0)
+    p *= 1024 * 1024;
+    if (std::fabs(p) < 1.0e-3)
         {
         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
         }
@@ -1578,7 +1647,7 @@ int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
 {
 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
-disconnSynAck6.rnd = iaUser->rnd = random();
+disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
 
 #ifdef ARCH_BE
 SwapBytes(disconnSynAck6.len);
@@ -1602,7 +1671,7 @@ disconnSynAck8.hdr.protoVer[1] = 8;
 
 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
-disconnSynAck8.rnd = iaUser->rnd = random();
+disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
 
 #ifdef ARCH_BE
 SwapBytes(disconnSynAck8.len);
@@ -1613,7 +1682,7 @@ Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeo
 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
 {
 fin6.len = Min8(sizeof(FIN_6));
 strcpy((char*)fin6.type, "FIN");
@@ -1634,12 +1703,12 @@ ip2user.erase(it);
 return res;
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
 {
 return Send_FIN_6(iaUser, sip, it);
 }
 //-----------------------------------------------------------------------------
-int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
 {
 strcpy((char*)fin8.hdr.magic, IA_ID);
 fin8.hdr.protoVer[0] = 0;
@@ -1663,9 +1732,11 @@ ip2user.erase(it);
 
 return res;
 }
+namespace
+{
 //-----------------------------------------------------------------------------
 inline
-void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
+void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
 {
 unsigned char keyL[PASSWD_LEN];
 memset(keyL, 0, PASSWD_LEN);
@@ -1674,15 +1745,17 @@ Blowfish_Init(ctx, keyL, PASSWD_LEN);
 }
 //-----------------------------------------------------------------------------
 inline
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
 {
-for (int i = 0; i < len8; i++)
-    DecodeString(dst + i * 8, src + i * 8, ctx);
+for (size_t i = 0; i < len8; i++)
+    DecodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
 }
 //-----------------------------------------------------------------------------
 inline
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
 {
-for (int i = 0; i < len8; i++)
-    EncodeString(dst + i * 8, src + i * 8, ctx);
+for (size_t i = 0; i < len8; i++)
+    EncodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
+}
+//-----------------------------------------------------------------------------
 }
index d0f6b5ac271691a6cad1b5c8186a8aaf6088a69d..873505566c8e699458d4eaf27324b956844774b6 100644 (file)
@@ -49,8 +49,7 @@
 #include "stg/blowfish.h"
 #include "stg/logger.h"
 #include "stg/utime.h"
-
-extern "C" PLUGIN * GetPlugin();
+#include "stg/logger.h"
 
 #define IA_PROTO_VER    (6)
 
@@ -122,7 +121,7 @@ struct IA_USER {
           user(NULL),
           phase(),
           lastSendAlive(0),
-          rnd(random()),
+          rnd(static_cast<uint32_t>(random())),
           port(0),
           ctx(),
           messagesToSend(),
@@ -137,7 +136,7 @@ struct IA_USER {
     #ifdef IA_DEBUG
     aliveSent = false;
     #endif
-    };
+    }
 
     IA_USER(const IA_USER & u)
         : login(u.login),
@@ -155,7 +154,7 @@ struct IA_USER {
     aliveSent  = u.aliveSent;
     #endif
     memcpy(&ctx, &u.ctx, sizeof(BLOWFISH_CTX));
-    };
+    }
 
     IA_USER(const std::string & l,
             CONST_USER_PTR u,
@@ -165,7 +164,7 @@ struct IA_USER {
           user(u),
           phase(),
           lastSendAlive(0),
-          rnd(random()),
+          rnd(static_cast<uint32_t>(random())),
           port(p),
           ctx(),
           messagesToSend(),
@@ -203,13 +202,14 @@ private:
 class AUTH_IA_SETTINGS {
 public:
                     AUTH_IA_SETTINGS();
-    virtual         ~AUTH_IA_SETTINGS() {};
-    const std::string & GetStrError() const { return errorStr; };
+    virtual         ~AUTH_IA_SETTINGS() {}
+    const std::string & GetStrError() const { return errorStr; }
     int             ParseSettings(const MODULE_SETTINGS & s);
-    int             GetUserDelay() const { return userDelay; };
-    int             GetUserTimeout() const { return userTimeout; };
-    int             GetUserPort() const { return port; };
-    FREEMB          GetFreeMbShowType() const { return freeMbShowType; };
+    int             GetUserDelay() const { return userDelay; }
+    int             GetUserTimeout() const { return userTimeout; }
+    uint16_t        GetUserPort() const { return port; }
+    FREEMB          GetFreeMbShowType() const { return freeMbShowType; }
+    bool            LogProtocolErrors() const { return logProtocolErrors; }
 
 private:
     int             userDelay;
@@ -217,6 +217,7 @@ private:
     uint16_t        port;
     std::string     errorStr;
     FREEMB          freeMbShowType;
+    bool            logProtocolErrors;
 };
 //-----------------------------------------------------------------------------
 class AUTH_IA;
@@ -251,7 +252,7 @@ public:
     bool                IsRunning() { return isRunningRunTimeouter || isRunningRun; }
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const { return "InetAccess authorization plugin v.1.4"; }
+    std::string         GetVersion() const { return "InetAccess authorization plugin v.1.4"; }
     uint16_t            GetStartPosition() const { return 30; }
     uint16_t            GetStopPosition() const { return 30; }
 
@@ -267,8 +268,8 @@ private:
     int                 FinalizeNet();
     void                DelUser(USER_PTR u);
     int                 RecvData(char * buffer, int bufferSize);
-    int                 CheckHeader(const char * buffer, int * protoVer);
-    int                 PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user);
+    int                 CheckHeader(const char * buffer, uint32_t sip, int * protoVer);
+    int                 PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user);
 
     int                 Process_CONN_SYN_6(CONN_SYN_6 * connSyn, IA_USER * iaUser, uint32_t sip);
     int                 Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip);
@@ -289,15 +290,15 @@ private:
     int                 Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnSyn,
                                               IA_USER * iaUser,
                                               uint32_t sip,
-                                              map<uint32_t, IA_USER>::iterator it);
+                                              std::map<uint32_t, IA_USER>::iterator it);
     int                 Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnSyn,
                                               IA_USER * iaUser,
                                               uint32_t sip,
-                                              map<uint32_t, IA_USER>::iterator it);
+                                              std::map<uint32_t, IA_USER>::iterator it);
     int                 Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnSyn,
                                               IA_USER * iaUser,
                                               uint32_t sip,
-                                              map<uint32_t, IA_USER>::iterator it);
+                                              std::map<uint32_t, IA_USER>::iterator it);
 
     int                 Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip);
     int                 Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip);
@@ -311,14 +312,14 @@ private:
     int                 Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip);
     int                 Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip);
 
-    int                 Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it);
-    int                 Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it);
-    int                 Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it);
+    int                 Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it);
+    int                 Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it);
+    int                 Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it);
 
     int                 Timeouter();
 
     int                 SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text);
-    int                 Send(uint32_t ip, uint16_t port, const char * buffer, int len);
+    int                 Send(uint32_t ip, uint16_t port, const char * buffer, size_t len);
     int                 RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user);
     int                 RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user);
     int                 RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user);
@@ -358,12 +359,12 @@ private:
 
     std::map<std::string, int> packetTypes;
 
-    STG_LOGGER &        WriteServLog;
-
     uint32_t            enabledDirs;
 
     DEL_USER_NOTIFIER   onDelUserNotifier;
 
+    PLUGIN_LOGGER       logger;
+
     friend class UnauthorizeUser;
 };
 //-----------------------------------------------------------------------------
index 85fd602bd18412e165f2ab3dce3143296a75f820..6ec8c3420e1dc3dd91d9f25bc848f2403c7e60f6 100644 (file)
@@ -56,7 +56,12 @@ fclose(f);
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<DEBUG_CAP> cdc;
+}
+
+extern "C" BASE_PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -74,7 +79,7 @@ RAW_PACKET MakeTCPPacket(const char * src,
                          uint16_t sport,
                          uint16_t dport,
                          uint16_t len);
-const string DEBUG_CAP::GetVersion() const
+std::string DEBUG_CAP::GetVersion() const
 {
 return "Debug_cap v.0.01a";
 }
@@ -90,7 +95,7 @@ void DEBUG_CAP::SetTraffcounter(TRAFFCOUNTER * tc)
 traffCnt = tc;
 }
 //-----------------------------------------------------------------------------
-const string & DEBUG_CAP::GetStrError() const
+const std::string & DEBUG_CAP::GetStrError() const
 {
 return errorStr;
 }
index d0aad7646f5177fb72128685dbcc0af828424c74..6bea457fbe79d4d4a41944aba10b5e933bda02ff 100644 (file)
@@ -36,9 +36,6 @@ $Author: faust $
 #include "stg/plugin.h"
 #include "stg/module_settings.h"
 
-using namespace std;
-extern "C" PLUGIN * GetPlugin();
-
 //-----------------------------------------------------------------------------
 struct iphdr_eth {
     uint8_t     ihl:4,
@@ -58,8 +55,8 @@ struct iphdr_eth {
 //-----------------------------------------------------------------------------
 class CAP_SETTINGS {
 public:
-    const string &  GetStrError() const { static string s; return s; }
-    int             ParseSettings(const MODULE_SETTINGS & s) { return 0; }
+    const std::string & GetStrError() const { static std::string s; return s; }
+    int                 ParseSettings(const MODULE_SETTINGS & s) { return 0; }
 };
 //-----------------------------------------------------------------------------
 class DEBUG_CAP :public PLUGIN
@@ -75,15 +72,15 @@ public:
     int                 Reload() { return 0; }
     int                 ParseSettings() { return 0; }
     bool                IsRunning();
-    const string &      GetStrError() const;
-    const string        GetVersion() const;
+    const std::string & GetStrError() const;
+    std::string         GetVersion() const;
     uint16_t            GetStartPosition() const;
     uint16_t            GetStopPosition() const;
 private:
     static void *       Run1(void *);
     static void *       Run2(void *);
     static void *       Run3(void *);
-    mutable string      errorStr;
+    mutable std::string errorStr;
     CAP_SETTINGS        capSettings;
     pthread_t           thread;
     bool                nonstop;
index 481862dd23db24a6199c8edad24bf685cb8f256e..f9412802de25c739eee8a186b6f7c0838a600cbf 100644 (file)
@@ -10,7 +10,8 @@ SRCS = ./cap_nf.cpp
 
 LIBS += $(LIB_THREAD)
 
-STGLIBS = common
+STGLIBS = common \
+          logger
 
 include ../../Makefile.in
 
index 51ba49546d26fb7a4d8c9ee3be18b9be1b9750ac..41ad9faed1ab4d769ba4359e11c3fac673cb642f 100644 (file)
@@ -45,7 +45,12 @@ $Author: faust $
 #include "stg/plugin_creator.h"
 #include "cap_nf.h"
 
+namespace
+{
 PLUGIN_CREATOR<NF_CAP> cnc;
+}
+
+extern "C" PLUGIN * GetPlugin();
 
 PLUGIN * GetPlugin()
 {
@@ -65,7 +70,8 @@ NF_CAP::NF_CAP()
       portU(0),
       sockTCP(-1),
       sockUDP(-1),
-      errorStr()
+      errorStr(),
+      logger(GetPluginLogger(GetStgLogger(), "cap_nf"))
 {
 }
 
@@ -117,6 +123,7 @@ if (portU > 0)
         runningUDP = false;
         CloseUDP();
         errorStr = "Cannot create UDP thread";
+       logger("Cannot create UDP thread.");
         printfd(__FILE__, "Error: Cannot create UDP thread\n");
         return -1;
         }
@@ -132,6 +139,7 @@ if (portT > 0)
         {
         runningTCP = false;
         CloseTCP();
+       logger("Cannot create TCP thread.");
         errorStr = "Cannot create TCP thread";
         printfd(__FILE__, "Error: Cannot create TCP thread\n");
         return -1;
@@ -160,10 +168,12 @@ if (portU && !stoppedUDP)
         if (pthread_kill(tidUDP, SIGUSR1))
             {
             errorStr = "Error sending signal to UDP thread";
+           logger("Error sending sugnal to UDP thread.");
             printfd(__FILE__, "Error: Error sending signal to UDP thread\n");
             return -1;
             }
         printfd(__FILE__, "UDP thread NOT stopped\n");
+        logger("Cannot stop UDP thread.");
         }
     }
 if (portT && !stoppedTCP)
@@ -183,10 +193,12 @@ if (portT && !stoppedTCP)
         if (pthread_kill(tidTCP, SIGUSR1))
             {
             errorStr = "Error sending signal to TCP thread";
+           logger("Error sending signal to TCP thread.");
             printfd(__FILE__, "Error: Error sending signal to TCP thread\n");
             return -1;
             }
         printfd(__FILE__, "TCP thread NOT stopped\n");
+       logger("Cannot stop TCP thread.");
         }
     }
 return 0;
@@ -199,6 +211,7 @@ sockUDP = socket(PF_INET, SOCK_DGRAM, 0);
 if (sockUDP <= 0)
     {
     errorStr = "Error opening UDP socket";
+    logger("Cannot create UDP socket: %s", strerror(errno));
     printfd(__FILE__, "Error: Error opening UDP socket\n");
     return true;
     }
@@ -208,6 +221,7 @@ sin.sin_addr.s_addr = inet_addr("0.0.0.0");
 if (bind(sockUDP, (struct sockaddr *)&sin, sizeof(sin)))
     {
     errorStr = "Error binding UDP socket";
+    logger("Cannot bind UDP socket: %s", strerror(errno));
     printfd(__FILE__, "Error: Error binding UDP socket\n");
     return true;
     }
@@ -221,6 +235,7 @@ sockTCP = socket(PF_INET, SOCK_STREAM, 0);
 if (sockTCP <= 0)
     {
     errorStr = "Error opening TCP socket";
+    logger("Cannot create TCP socket: %s", strerror(errno));
     printfd(__FILE__, "Error: Error opening TCP socket\n");
     return true;
     }
@@ -230,12 +245,14 @@ sin.sin_addr.s_addr = inet_addr("0.0.0.0");
 if (bind(sockTCP, (struct sockaddr *)&sin, sizeof(sin)))
     {
     errorStr = "Error binding TCP socket";
+    logger("Cannot bind TCP socket: %s", strerror(errno));
     printfd(__FILE__, "Error: Error binding TCP socket\n");
     return true;
     }
 if (listen(sockTCP, 1))
     {
     errorStr = "Error listening on TCP socket";
+    logger("Cannot listen on TCP socket: %s", strerror(errno));
     printfd(__FILE__, "Error: Error listening TCP socket\n");
     return true;
     }
@@ -249,10 +266,6 @@ sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
 NF_CAP * cap = static_cast<NF_CAP *>(c);
-uint8_t buf[BUF_SIZE];
-int res;
-struct sockaddr_in sin;
-socklen_t slen;
 cap->stoppedUDP = false;
 while (cap->runningUDP)
     {
@@ -262,11 +275,19 @@ while (cap->runningUDP)
         }
 
     // Data
-    slen = sizeof(sin);
-    res = recvfrom(cap->sockUDP, buf, BUF_SIZE, 0, reinterpret_cast<struct sockaddr *>(&sin), &slen);
+    struct sockaddr_in sin;
+    socklen_t slen = sizeof(sin);
+    uint8_t buf[BUF_SIZE];
+    ssize_t res = recvfrom(cap->sockUDP, buf, BUF_SIZE, 0, reinterpret_cast<struct sockaddr *>(&sin), &slen);
     if (!cap->runningUDP)
         break;
 
+    if (res < 0)
+       {
+       cap->logger("recvfrom error: %s", strerror(errno));
+       continue;
+       }
+
     if (res == 0) // EOF
         {
         continue;
@@ -295,11 +316,6 @@ sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
 NF_CAP * cap = static_cast<NF_CAP *>(c);
-uint8_t buf[BUF_SIZE];
-int res;
-int sd;
-struct sockaddr_in sin;
-socklen_t slen;
 cap->stoppedTCP = false;
 while (cap->runningTCP)
     {
@@ -309,18 +325,16 @@ while (cap->runningTCP)
         }
 
     // Data
-    slen = sizeof(sin);
-    sd = accept(cap->sockTCP, reinterpret_cast<struct sockaddr *>(&sin), &slen);
+    struct sockaddr_in sin;
+    socklen_t slen = sizeof(sin);
+    int sd = accept(cap->sockTCP, reinterpret_cast<struct sockaddr *>(&sin), &slen);
     if (!cap->runningTCP)
         break;
 
     if (sd <= 0)
         {
-        if (errno != EINTR)
-            {
-            cap->errorStr = "Error accepting connection";
-            printfd(__FILE__, "Error: Error accepting connection\n");
-            }
+        if (sd < 0)
+           cap->logger("accept error: %s", strerror(errno));
         continue;
         }
 
@@ -330,7 +344,12 @@ while (cap->runningTCP)
         continue;
         }
 
-    res = recv(sd, buf, BUF_SIZE, MSG_WAITALL);
+    uint8_t buf[BUF_SIZE];
+    ssize_t res = recv(sd, buf, BUF_SIZE, MSG_WAITALL);
+
+    if (res < 0)
+        cap->logger("recv error: %s", strerror(errno));
+
     close(sd);
 
     if (!cap->runningTCP)
@@ -345,11 +364,6 @@ while (cap->runningTCP)
     // Need to check actual data length and wait all data to receive
     if (res < 24)
         {
-        if (errno != EINTR)
-            {
-            cap->errorStr = "Invalid data received";
-            printfd(__FILE__, "Error: Invalid data received through TCP\n");
-            }
         continue;
         }
 
@@ -359,7 +373,7 @@ cap->stoppedTCP = true;
 return NULL;
 }
 
-void NF_CAP::ParseBuffer(uint8_t * buf, int size)
+void NF_CAP::ParseBuffer(uint8_t * buf, ssize_t size)
 {
 RAW_PACKET ip;
 NF_HEADER * hdr = reinterpret_cast<NF_HEADER *>(buf);
index 43d6e0987a77521b82d7b92691e970ccf39ba56a..23f7d7db2e18fc4f4f176581dce105c507b65949 100644 (file)
@@ -37,6 +37,7 @@ $Author: faust $
 #include "stg/os_int.h"
 #include "stg/plugin.h"
 #include "stg/module_settings.h"
+#include "stg/logger.h"
 
 #define VERSION "CAP_NF v. 0.4"
 #define START_POS 40
@@ -60,7 +61,7 @@ struct NF_HEADER {
     uint8_t  eType;     // Engine type
     uint8_t  eID;       // Engine ID
     uint16_t sInterval; // Sampling mode and interval
-} __attribute__ ((packed));
+};
 
 struct NF_DATA {
     uint32_t srcAddr;   // Flow source address
@@ -83,7 +84,7 @@ struct NF_DATA {
     uint8_t  srcMask;   // Source address mask in "slash" notation
     uint8_t  dstMask;   // Destination address mask in "slash" notation
     uint16_t pad2;      // 2-byte padding
-} __attribute__ ((packed));
+};
 
 #define BUF_SIZE (sizeof(NF_HEADER) + 30 * sizeof(NF_DATA))
 
@@ -101,7 +102,7 @@ public:
     int             Reload() { return 0; }
     bool            IsRunning() { return runningTCP || runningUDP; }
     const std::string & GetStrError() const { return errorStr; }
-    const std::string GetVersion() const { return VERSION; }
+    std::string     GetVersion() const { return VERSION; }
     uint16_t        GetStartPosition() const { return START_POS; }
     uint16_t        GetStopPosition() const { return STOP_POS; }
 
@@ -122,10 +123,11 @@ private:
     int sockTCP;
     int sockUDP;
     mutable std::string errorStr;
+    PLUGIN_LOGGER logger;
 
     static void * RunUDP(void *);
     static void * RunTCP(void *);
-    void ParseBuffer(uint8_t *, int);
+    void ParseBuffer(uint8_t * buf, ssize_t size);
 
     bool OpenTCP();
     bool OpenUDP();
@@ -133,6 +135,4 @@ private:
     void CloseUDP() { close(sockUDP); }
 };
 
-extern "C" PLUGIN * GetPlugin();
-
 #endif
index 48e24826c8132415d005fceadfbd569d5c60eff3..555ec8b18a5f9ef55ba4fed8563f6698e3e8e627 100644 (file)
@@ -10,7 +10,8 @@ SRCS = ./divert_cap.cpp
 
 LIBS += $(LIB_THREAD)
 
-STGLIBS = common
+STGLIBS = common \
+          logger
 
 include ../../Makefile.in
 
index a949433e762dab509be7475f348d3d567fdb378c..96476d4e204027ee8f1d556f7dc54544a52489d8 100644 (file)
@@ -62,7 +62,12 @@ DIVERT_DATA cddiv;  //capture data
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<DIVERT_CAP> dcc;
+}
+
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -73,7 +78,7 @@ return dcc.GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-const std::string DIVERT_CAP::GetVersion() const
+std::string DIVERT_CAP::GetVersion() const
 {
 return "Divert_cap v.1.0";
 }
@@ -81,11 +86,13 @@ return "Divert_cap v.1.0";
 DIVERT_CAP::DIVERT_CAP()
     : settings(),
       port(0),
+      disableForwarding(false),
       errorStr(),
       thread(),
       nonstop(false),
       isRunning(false),
-      traffCnt(NULL)
+      traffCnt(NULL),
+      logger(GetPluginLogger(GetStgLogger(), "cap_divert"))
 {
 }
 //-----------------------------------------------------------------------------
@@ -103,14 +110,15 @@ if (DivertCapOpen() < 0)
 
 nonstop = true;
 
-if (pthread_create(&thread, NULL, Run, this) == 0)
+if (pthread_create(&thread, NULL, Run, this))
     {
-    return 0;
+    errorStr = "Cannot create thread.";
+    logger("Cannot create thread.");
+    printfd(__FILE__, "Cannot create thread\n");
+    return -1;
     }
 
-errorStr = "Cannot create thread.";
-printfd(__FILE__, "Cannot create thread\n");
-return -1;
+return 0;
 }
 //-----------------------------------------------------------------------------
 int DIVERT_CAP::Stop()
@@ -139,6 +147,7 @@ if (isRunning)
     if (pthread_kill(thread, SIGINT))
         {
         errorStr = "Cannot kill thread.";
+       logger("Cannot send signal to thread.");
         printfd(__FILE__, "Cannot kill thread\n");
         return -1;
         }
@@ -196,6 +205,7 @@ cddiv.sock = socket(PF_INET, SOCK_RAW, IPPROTO_DIVERT);
 if (cddiv.sock < 0)
     {
     errorStr = "Create divert socket error.";
+    logger("Cannot create a socket: %s", strerror(errno));
     printfd(__FILE__, "Cannot create divert socket\n");
     return -1;
     }
@@ -213,6 +223,7 @@ ret = bind(cddiv.sock, (struct sockaddr *)&divAddr, sizeof(divAddr));
 if (ret < 0)
     {
     errorStr = "Bind divert socket error.";
+    logger("Cannot bind the scoket: %s", strerror(errno));
     printfd(__FILE__, "Cannot bind divert socket\n");
     return -1;
     }
@@ -250,7 +261,16 @@ if ((bytes = recvfrom (cddiv.sock, buf, BUFF_LEN,
     if (iface)
         *iface = cddiv.iface;
 
-    sendto(cddiv.sock, buf, bytes, 0, (struct sockaddr*)&divertaddr, divertaddrSize);
+    if (!disableForwarding)
+       {
+        if (sendto(cddiv.sock, buf, bytes, 0, (struct sockaddr*)&divertaddr, divertaddrSize) < 0)
+           logger("sendto error: %s", strerror(errno));
+       }
+    }
+else
+    {
+    if (bytes < 0)
+        logger("recvfrom error: %s", strerror(errno));
     }
 
 return 0;
@@ -272,11 +292,9 @@ pv.param = "Port";
 pvi = std::find(settings.moduleParams.begin(), settings.moduleParams.end(), pv);
 if (pvi == settings.moduleParams.end())
     {
-    port = 15701;
-    return 0;
+    p = 15701;
     }
-
-if (ParseIntInRange(pvi->value[0], 1, 65535, &p))
+else if (ParseIntInRange(pvi->value[0], 1, 65535, &p))
     {
     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
@@ -285,6 +303,22 @@ if (ParseIntInRange(pvi->value[0], 1, 65535, &p))
 
 port = p;
 
+bool d = false;
+pv.param = "DisableForwarding";
+pvi = std::find(settings.moduleParams.begin(), settings.moduleParams.end(), pv);
+if (pvi == settings.moduleParams.end())
+    {
+    disableForwarding = false;
+    }
+else if (ParseYesNo(pvi->value[0], &d))
+    {
+    errorStr = "Cannot parse parameter \'DisableForwarding\': " + errorStr;
+    printfd(__FILE__, "Cannot parse parameter 'DisableForwarding'\n");
+    return -1;
+    }
+
+disableForwarding = d;
+
 return 0;
 }
 //-----------------------------------------------------------------------------
index 62a78a439c0430497bc69dfbb6870027c12444d1..b34f832e5ea5b7706a762edb7ba92b38aeb3b84c 100644 (file)
@@ -33,6 +33,7 @@ $Date: 2009/06/23 11:32:27 $
 
 #include "stg/plugin.h"
 #include "stg/module_settings.h"
+#include "stg/logger.h"
 
 class USERS;
 class TARIFFS;
@@ -40,8 +41,6 @@ class ADMINS;
 class TRAFFCOUNTER;
 class SETTINGS;
 
-extern "C" PLUGIN * GetPlugin();
-
 //-----------------------------------------------------------------------------
 class DIVERT_CAP : public PLUGIN {
 public:
@@ -58,7 +57,7 @@ public:
     void                SetSettings(const MODULE_SETTINGS & s) { settings = s; }
     int                 ParseSettings();
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const;
+    std::string         GetVersion() const;
     uint16_t            GetStartPosition() const { return 40; }
     uint16_t            GetStopPosition() const { return 40; }
 
@@ -77,6 +76,7 @@ private:
     MODULE_SETTINGS     settings;
 
     int                 port;
+    bool                disableForwarding;
 
     mutable std::string errorStr;
 
@@ -86,6 +86,8 @@ private:
     bool                isRunning;
 
     TRAFFCOUNTER *      traffCnt;
+
+    PLUGIN_LOGGER       logger;
 };
 //-----------------------------------------------------------------------------
 
index d108789680c85a17e274c0943d0d79ba9c1541bf..aeb77636b65b2577a1ee649360ed682108d26981 100644 (file)
@@ -10,7 +10,8 @@ SRCS = ./ether_cap.cpp
 
 LIBS += $(LIB_THREAD)
 
-STGLIBS = common
+STGLIBS = common \
+          logger
 
 include ../../Makefile.in
 
index 247051114511f74801fab94dc600cc07e8597428..72e7f73bdcad694183f5cb94c03fe9dd33d1e241 100644 (file)
@@ -60,7 +60,12 @@ $Author: faust $
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<BPF_CAP> bcc;
+}
+
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -110,7 +115,7 @@ return iface[num];
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-const std::string BPF_CAP::GetVersion() const
+std::string BPF_CAP::GetVersion() const
 {
 return "bpf_cap v.1.0";
 }
@@ -125,7 +130,8 @@ BPF_CAP::BPF_CAP()
       isRunning(false),
       capSock(-1),
       settings(),
-      traffCnt(NULL)
+      traffCnt(NULL),
+      logger(GetPluginLogger(GetStgLogger(), "cap_ether"))
 {
 }
 //-----------------------------------------------------------------------------
@@ -153,14 +159,15 @@ if (BPFCapOpen() < 0)
 
 nonstop = true;
 
-if (pthread_create(&thread, NULL, Run, this) == 0)
+if (pthread_create(&thread, NULL, Run, this))
     {
-    return 0;
+    errorStr = "Cannot create thread.";
+    logger("Cannot create thread.");
+    printfd(__FILE__, "Cannot create thread\n");
+    return -1;
     }
 
-errorStr = "Cannot create thread.";
-printfd(__FILE__, "Cannot create thread\n");
-return -1;
+return 0;
 }
 //-----------------------------------------------------------------------------
 int BPF_CAP::Stop()
@@ -190,6 +197,7 @@ if (isRunning)
     if (pthread_kill(thread, SIGINT))
         {
         errorStr = "Cannot kill thread.";
+       logger("Cannot send signal to thread.");
         printfd(__FILE__, "Cannot kill thread\n");
         return -1;
         }
@@ -271,6 +279,7 @@ do
 if (bd->fd < 0)
     {
     errorStr = "Can't capture packets. Open bpf device for " + bd->iface + " error.";
+    logger("Cannot open device for interface '%s': %s", bd->iface.c_str(), strerror(errno));
     printfd(__FILE__, "Cannot open BPF device\n");
     return -1;
     }
@@ -280,6 +289,7 @@ strncpy(ifr.ifr_name, bd->iface.c_str(), sizeof(ifr.ifr_name));
 if (ioctl(bd->fd, BIOCSBLEN, (caddr_t)&l) < 0)
     {
     errorStr = bd->iface + " BIOCSBLEN " + std::string(strerror(errno));
+    logger("ioctl (BIOCSBLEN) error for interface '%s': %s", bd->iface.c_str(), strerror(errno));
     printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str());
     return -1;
     }
@@ -287,6 +297,7 @@ if (ioctl(bd->fd, BIOCSBLEN, (caddr_t)&l) < 0)
 if (ioctl(bd->fd, BIOCSETIF, (caddr_t)&ifr) < 0)
     {
     errorStr = bd->iface + " BIOCSETIF " + std::string(strerror(errno));
+    logger("ioctl (BIOCSETIF) error for interface '%s': %s", bd->iface.c_str(), strerror(errno));
     printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str());
     return -1;
     }
@@ -294,6 +305,7 @@ if (ioctl(bd->fd, BIOCSETIF, (caddr_t)&ifr) < 0)
 if (ioctl(bd->fd, BIOCIMMEDIATE, &im) < 0)
     {
     errorStr = bd->iface + " BIOCIMMEDIATE " + std::string(strerror(errno));
+    logger("ioctl (BIOCIMMEDIATE) error for interface '%s': %s", bd->iface.c_str(), strerror(errno));
     printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str());
     return -1;
     }
@@ -335,6 +347,7 @@ if (bd->canRead)
     bd->r = read(bd->fd, bd->buffer, BUFF_LEN);
     if (bd->r < 0)
         {
+       logger("read error: %s", strerror(errno));
         struct timespec ts = {0, 20000000};
         nanosleep(&ts, NULL);
         return -1;
index ad9ff9f15ae817f7754dff0d0dc8a6ff7869f27b..76785ed293ebb55f2116cf2549920371cc21ed39 100644 (file)
@@ -35,8 +35,7 @@
 #include "stg/os_int.h"
 #include "stg/plugin.h"
 #include "stg/module_settings.h"
-
-extern "C" PLUGIN * GetPlugin();
+#include "stg/logger.h"
 
 #define BUFF_LEN (128)
 
@@ -106,7 +105,7 @@ public:
     int                 ParseSettings();
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const;
+    std::string         GetVersion() const;
     uint16_t            GetStartPosition() const { return 40; }
     uint16_t            GetStopPosition() const { return 40; }
 
@@ -135,6 +134,8 @@ private:
     MODULE_SETTINGS       settings;
 
     TRAFFCOUNTER *        traffCnt;
+
+    PLUGIN_LOGGER         logger;
 };
 //-----------------------------------------------------------------------------
 
index 873ba6f06d9869d3d5741ecc0750bfeafa06990a..c89ea6530d9896d02d8a8155166b739f98e6b749 100644 (file)
@@ -10,7 +10,8 @@ SRCS = ./ether_cap.cpp
 
 LIBS += $(LIB_THREAD)
 
-STGLIBS = common
+STGLIBS = common \
+          logger
 
 include ../../Makefile.in
 
index 093aea7231d425d9666a53a63cec3d15d83e637f..a97fa8e7d07e5490569f7f9c73e14d6107776717 100644 (file)
@@ -56,7 +56,12 @@ $Date: 2009/12/13 13:45:13 $
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<ETHER_CAP> ecc;
+}
+
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -67,7 +72,7 @@ return ecc.GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------        
-const std::string ETHER_CAP::GetVersion() const
+std::string ETHER_CAP::GetVersion() const
 {
 return "Ether_cap v.1.2";
 }
@@ -78,7 +83,8 @@ ETHER_CAP::ETHER_CAP()
       nonstop(false),
       isRunning(false),
       capSock(-1),
-      traffCnt(NULL)
+      traffCnt(NULL),
+      logger(GetPluginLogger(GetStgLogger(), "cap_ether"))
 {
 }
 //-----------------------------------------------------------------------------
@@ -96,14 +102,15 @@ if (EthCapOpen() < 0)
 
 nonstop = true;
 
-if (pthread_create(&thread, NULL, Run, this) == 0)
+if (pthread_create(&thread, NULL, Run, this))
     {
-    return 0;
+    errorStr = "Cannot create thread.";
+    logger("Cannot create thread.");
+    printfd(__FILE__, "Cannot create thread\n");
+    return -1;
     }
 
-errorStr = "Cannot create thread.";
-printfd(__FILE__, "Cannot create thread\n");
-return -1;
+return 0;
 }
 //-----------------------------------------------------------------------------
 int ETHER_CAP::Stop()
@@ -125,6 +132,7 @@ if (isRunning)
     if (pthread_kill(thread, SIGUSR1))
         {
         errorStr = "Cannot kill thread.";
+       logger("Cannot send signal to thread.");
         return -1;
         }
     for (int i = 0; i < 25 && isRunning; ++i)
@@ -135,6 +143,7 @@ if (isRunning)
     if (isRunning)
         {
         errorStr = "ETHER_CAP not stopped.";
+       logger("Cannot stop thread.");
         printfd(__FILE__, "Cannot stop thread\n");
         return -1;
         }
@@ -165,13 +174,11 @@ char        padding[4];
 char        padding1[8];
 };
 
-ETH_IP * ethIP;
-
 char ethip[sizeof(ETH_IP)];
 
 memset(&ethip, 0, sizeof(ETH_IP));
 
-ethIP = (ETH_IP *)&ethip;
+ETH_IP * ethIP = static_cast<ETH_IP *>(static_cast<void *>(&ethip));
 ethIP->rp.dataLen = -1;
 
 char * iface = NULL;
@@ -196,6 +203,8 @@ return NULL;
 int ETHER_CAP::EthCapOpen()
 {
 capSock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
+if (capSock < 0)
+    logger("Cannot create socket: %s", strerror(errno));
 return capSock;
 }
 //-----------------------------------------------------------------------------
@@ -208,7 +217,7 @@ return 0;
 int ETHER_CAP::EthCapRead(void * buffer, int blen, char **)
 {
 struct sockaddr_ll  addr;
-int addrLen, res;
+int addrLen;
 
 if (!WaitPackets(capSock))
     {
@@ -217,14 +226,9 @@ if (!WaitPackets(capSock))
 
 addrLen = sizeof(addr);
 
-res = recvfrom(capSock, ((char*)buffer) + 2, blen, 0, (struct sockaddr *)&addr, (socklen_t*)&addrLen);
-
-if (-1 == res)
+if (recvfrom(capSock, ((char*)buffer) + 2, blen, 0, (struct sockaddr *)&addr, (socklen_t*)&addrLen) < 0)
     {
-    if (errno != EINTR)
-        {
-        printfd(__FILE__, "Error on recvfrom: '%s'\n", strerror(errno));
-        }
+    logger("recvfrom error: %s", strerror(errno));
     return ENODATA;
     }
 
index 44c4ae7e7e83cbabf844a94e0ec90360c975b709..8dfb6c043e741dd7dbbb80ee2ff661becbfdce1c 100644 (file)
@@ -32,6 +32,7 @@
 
 #include "stg/plugin.h"
 #include "stg/module_settings.h"
+#include "stg/logger.h"
 
 class USERS;
 class TARIFFS;
@@ -39,8 +40,6 @@ class ADMINS;
 class TRAFFCOUNTER;
 class SETTINGS;
 
-extern "C" PLUGIN * GetPlugin();
-
 class TRAFFCOUNTER;
 
 //-----------------------------------------------------------------------------
@@ -58,7 +57,7 @@ public:
 
     int                 ParseSettings() { return 0; }
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const;
+    std::string         GetVersion() const;
     uint16_t            GetStartPosition() const { return 40; }
     uint16_t            GetStopPosition() const { return 40; }
 
@@ -79,6 +78,8 @@ private:
     int                 capSock;
 
     TRAFFCOUNTER *      traffCnt;
+
+    PLUGIN_LOGGER       logger;
 };
 //-----------------------------------------------------------------------------
 
index 548f589c62825de49af45c5fe054ddfa11815ffc..48dc3449cc23ad41ec600a0447ae5770961bb79a 100644 (file)
@@ -11,7 +11,8 @@ SRCS = ./ipq_cap.cpp \
 
 LIBS += $(LIB_THREAD)
 
-STGLIBS = common
+STGLIBS = common \
+          logger
 
 include ../../Makefile.in
 
index 1dc22b4cff9e330579a902c693fe83e1bf05ec12..055993063d44b96d617f2b164ce89a11f9663aca 100644 (file)
@@ -23,6 +23,7 @@
 
 #include <csignal>
 #include <cerrno>
+#include <cstring>
 
 #include "stg/raw_ip_packet.h"
 #include "stg/traffcounter.h"
@@ -39,7 +40,12 @@ extern "C"
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<IPQ_CAP> icc;
+}
+
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -50,7 +56,7 @@ return icc.GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-const std::string IPQ_CAP::GetVersion() const
+std::string IPQ_CAP::GetVersion() const
 {
 return "ipq_cap v.1.2";
 }
@@ -63,7 +69,8 @@ IPQ_CAP::IPQ_CAP()
       isRunning(false),
       capSock(-1),
       traffCnt(NULL),
-      buf()
+      buf(),
+      logger(GetPluginLogger(GetStgLogger(), "cap_ipq"))
 {
 memset(buf, 0, BUFSIZE);
 }
@@ -159,6 +166,7 @@ ipq_h = ipq_create_handle(0, PF_INET);
 if (ipq_h == NULL)
     {
     ipq_destroy_handle(ipq_h);
+    logger("Cannot create IPQ handle. Error: '%s', '%s'", ipq_errstr(), strerror(errno));
     errorStr = "Cannot create ipq handle!";
     return -1;
     }
@@ -166,6 +174,7 @@ int status = ipq_set_mode(ipq_h, IPQ_COPY_PACKET, PAYLOAD_LEN);
 if (status < 0)
     {
     ipq_destroy_handle(ipq_h);
+    logger("Cannot set IPQ_COPY_PACKET mode.");
     errorStr = "Cannot set IPQ_COPY_PACKET mode!";
     return -1;
     }
index 7c78da8935345c417d80be6511da1a2dc00ad3c7..39ed5766401bac4228c48dea191f096f4082100a 100644 (file)
@@ -26,6 +26,7 @@
 #include "stg/plugin.h"
 #include "stg/module_settings.h"
 #include "stg/os_int.h"
+#include "stg/logger.h"
 
 #define BUFSIZE     (256)
 #define PAYLOAD_LEN (96)
@@ -36,8 +37,6 @@ class ADMINS;
 class TRAFFCOUNTER;
 class SETTINGS;
 
-extern "C" PLUGIN * GetPlugin();
-
 //-----------------------------------------------------------------------------
 class IPQ_CAP :public PLUGIN {
 public:
@@ -53,7 +52,7 @@ public:
 
     int  ParseSettings() { return 0; }
     const std::string & GetStrError() const { return errorStr; }
-    const std::string GetVersion() const;
+    std::string GetVersion() const;
     uint16_t GetStartPosition() const { return 40; }
     uint16_t GetStopPosition() const { return 40; }
 
@@ -76,6 +75,8 @@ private:
 
     TRAFFCOUNTER * traffCnt;
     unsigned char buf[BUFSIZE];
+
+    PLUGIN_LOGGER logger;
 };
 
 #endif
index 798faebbdc3d53c343ae76813eaa063f175b714a..a7ed5745d6c8de07adef83c9a43e739127295b3f 100644 (file)
@@ -61,7 +61,7 @@ enum
     };
 #define IPQ_MAXERR IPQ_ERR_PROTOCOL
 
-/*struct ipq_errmap_t
+struct ipq_errmap_t
     {
     int errcode;
     char *message;
@@ -83,7 +83,7 @@ enum
     { IPQ_ERR_RECVBUF, "Receive buffer size invalid"},
     { IPQ_ERR_TIMEOUT, "Timeout"},
     { IPQ_ERR_PROTOCOL, "Invalid protocol specified"}
-};*/
+};
 
 static int ipq_errno = IPQ_ERR_NONE;
 
@@ -205,12 +205,12 @@ static ssize_t ipq_netlink_recvfrom(const struct ipq_handle *h,
     return status;
 }
 //-----------------------------------------------------------------------------
-/*static char *ipq_strerror(int errcode)
+static char *ipq_strerror(int errcode)
 {
     if (errcode < 0 || errcode > IPQ_MAXERR)
         errcode = IPQ_ERR_IMPL;
     return ipq_errmap[errcode].message;
-}*/
+}
 
 /****************************************************************************
  *
@@ -386,10 +386,10 @@ int ipq_ctl(const struct ipq_handle __attribute__((unused)) * handle, int __attr
     return 1;
 }
 //-----------------------------------------------------------------------------
-/*char *ipq_errstr(void)
+char *ipq_errstr(void)
 {
     return ipq_strerror(ipq_errno);
-}*/
+}
 //-----------------------------------------------------------------------------
 /*void ipq_perror(const char *s)
 {
index 41cca57e3cf91a747d93faf9127fc99e50f66e86..58a715876b2964ca73975243b67d004cf7f986f3 100644 (file)
 #include <asm/types.h>
 #include <linux/netlink.h>
 
+#include <linux/netfilter_ipv4/ip_queue.h>
 #ifdef KERNEL_64_USERSPACE_32
-#include "ip_queue_64.h"
 typedef u_int64_t ipq_id_t;
 #else
-#include <linux/netfilter_ipv4/ip_queue.h>
 typedef unsigned long ipq_id_t;
 #endif
 
@@ -82,8 +81,8 @@ int ipq_set_verdict(const struct ipq_handle *h,
 
 int ipq_ctl(const struct ipq_handle *h, int request, ...);
 
-/*char *ipq_errstr(void);
-void ipq_perror(const char *s);*/
+char *ipq_errstr(void);
+//void ipq_perror(const char *s);
 
 #endif /* _LIBIPQ_H */
 
index 0016babe440f209812fd06499bfb32028a5e1ab8..ad9c032491adacc5fa30a2b4934f83982d5edb89 100644 (file)
@@ -223,14 +223,14 @@ void METHOD_ADMINS_GET::execute(xmlrpc_c::paramList const & paramList,
 std::string cookie = paramList.getString(0);
 paramList.verifyEnd(1);
 
-std::map<std::string, xmlrpc_c::value> structVal;
+std::map<std::string, xmlrpc_c::value> mainStructVal;
 std::vector<xmlrpc_c::value> retval;
 ADMIN_INFO adminInfo;
 
 if (config->GetAdminInfo(cookie, &adminInfo))
     {
-    structVal["result"] = xmlrpc_c::value_boolean(false);
-    *retvalPtr = xmlrpc_c::value_struct(structVal);
+    mainStructVal["result"] = xmlrpc_c::value_boolean(false);
+    *retvalPtr = xmlrpc_c::value_struct(mainStructVal);
     return;
     }
 
index c4684c1bdea4f535ef6543822376eff7f6df497d..895088dc3482dcbc9c3a21c26697bebb3eb70bbe 100644 (file)
@@ -28,12 +28,12 @@ un += " ";
 un += utsn.nodename;
 
 structVal["version"] = xmlrpc_c::value_string(SERVER_VERSION);
-structVal["tariff_num"] = xmlrpc_c::value_int(tariffs->Count());
+structVal["tariff_num"] = xmlrpc_c::value_int(static_cast<int>(tariffs->Count()));
 structVal["tariff"] = xmlrpc_c::value_int(2);
-structVal["users_num"] = xmlrpc_c::value_int(users->Count());
+structVal["users_num"] = xmlrpc_c::value_int(static_cast<int>(users->Count()));
 structVal["uname"] = xmlrpc_c::value_string(un);
 structVal["dir_num"] = xmlrpc_c::value_int(DIR_NUM);
-structVal["day_fee"] = xmlrpc_c::value_int(dayFee);
+structVal["day_fee"] = xmlrpc_c::value_int(static_cast<int>(dayFee));
 
 std::vector<xmlrpc_c::value> dirnameVal;
 
index e4d05636f67a0015c7641b46546eca9c37c46940..917961484cfe5014356e11fe5af8b272605dd052 100644 (file)
@@ -2,11 +2,10 @@
 
 #include "stg/message.h"
 #include "stg/common.h"
-#include "utils.h"
 #include "messages_methods.h"
 #include "rpcconfig.h"
 
-extern const volatile time_t stgTime;
+extern volatile time_t stgTime;
 
 //------------------------------------------------------------------------------
 
@@ -76,7 +75,7 @@ if ((it = msgInfo.find("text")) == msgInfo.end())
     }
 message.text = IconvString(xmlrpc_c::value_string(it->second), "UTF-8", "CP1251");
 
-message.header.creationTime = stgTime;
+message.header.creationTime = static_cast<int>(stgTime);
 message.header.lastSendTime = 0;
 
 std::vector<xmlrpc_c::value>::iterator lit;
index 56a188f1cbb2aa8bb1af2cef1b9320de81a8dd8f..dca87fbee34ce8a65eb0bc85997c6e57b54ec6cc 100644 (file)
 #include "admins_methods.h"
 #include "messages_methods.h"
 
+namespace
+{
 PLUGIN_CREATOR<RPC_CONFIG> rpcc;
+}
+
+extern "C" PLUGIN * GetPlugin();
 
 RPC_CONFIG_SETTINGS::RPC_CONFIG_SETTINGS()
     : errorStr(),
@@ -36,11 +41,9 @@ RPC_CONFIG_SETTINGS::RPC_CONFIG_SETTINGS()
 
 int RPC_CONFIG_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
 {
-int p;
 PARAM_VALUE pv;
-std::vector<PARAM_VALUE>::const_iterator pvi;
-
 pv.param = "Port";
+std::vector<PARAM_VALUE>::const_iterator pvi;
 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
 if (pvi == s.moduleParams.end())
     {
@@ -48,13 +51,14 @@ if (pvi == s.moduleParams.end())
     printfd(__FILE__, "Parameter 'Port' not found\n");
     return -1;
     }
+int p;
 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
     {
     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
     return -1;
     }
-port = p;
+port = static_cast<uint16_t>(p);
 
 pv.param = "CookieTimeout";
 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -96,7 +100,8 @@ RPC_CONFIG::RPC_CONFIG()
       tid(),
       cookies(),
       dayFee(0),
-      dirNames()
+      dirNames(),
+      logger(GetPluginLogger(GetStgLogger(), "conf_rpc"))
 {
 }
 
@@ -116,12 +121,12 @@ if (ret)
 return ret;
 }
 
-void RPC_CONFIG::SetStgSettings(const SETTINGS * settings)
+void RPC_CONFIG::SetStgSettings(const SETTINGS * s)
 {
-    dayFee = settings->GetDayFee();
+    dayFee = s->GetDayFee();
     dirNames.erase(dirNames.begin(), dirNames.end());
     for (size_t i = 0; i < DIR_NUM; ++i) {
-        dirNames.push_back(settings->GetDirName(i));
+        dirNames.push_back(s->GetDirName(i));
     }
 }
 
@@ -134,6 +139,7 @@ fd = socket(AF_INET, SOCK_STREAM, 0);
 if (fd < 0)
     {
     errorStr = "Failed to create socket";
+    logger("Cannot create a socket: %s", strerror(errno));
     printfd(__FILE__, "Failed to create listening socket: %s\n", strerror(errno));
     return -1;
     }
@@ -143,6 +149,7 @@ int flag = 1;
 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)))
     {
     errorStr = "Setsockopt failed.";
+    logger("setsockopt error: %s", strerror(errno));
     printfd(__FILE__, "Setsockopt failed: %s\n", strerror(errno));
     return -1;
     }
@@ -154,6 +161,7 @@ addr.sin_addr.s_addr = inet_addr("0.0.0.0");
 
 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)))
     {
+    logger("Cannot bind the socket: %s", strerror(errno));
     errorStr = "Failed to bind socket";
     printfd(__FILE__, "Failed to bind listening socket: %s\n", strerror(errno));
     return -1;
@@ -161,6 +169,7 @@ if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)))
 
 if (listen(fd, 10))
     {
+    logger("Cannot listen the socket: %s", strerror(errno));
     errorStr = "Failed to listen socket";
     printfd(__FILE__, "Failed to listen listening socket: %s\n", strerror(errno));
     return -1;
@@ -176,6 +185,7 @@ rpcServer = new xmlrpc_c::serverAbyss(
 if (pthread_create(&tid, NULL, Run, this))
     {
     errorStr = "Failed to create RPC thread";
+    logger("Cannot create RPC thread.");
     printfd(__FILE__, "Failed to crate RPC thread\n");
     return -1;
     }
@@ -195,6 +205,7 @@ for (int i = 0; i < 5 && !stopped; ++i)
 if (!stopped)
     {
     running = true;
+    logger("Cannot stop RPC thread.");
     printfd(__FILE__, "Failed to stop RPC thread\n");
     errorStr = "Failed to stop RPC thread";
     return -1;
@@ -262,6 +273,7 @@ ADMIN * admin = NULL;
 
 if (!admins->Correct(login, password, &admin))
     {
+    logger("Attempt to connect with invalid credentials. Login: %s", login.c_str());
     return true;
     }
 
@@ -461,5 +473,11 @@ xmlrpc_c::methodPtr const methodGetOnlinIPsPtr(new METHOD_GET_ONLINE_IPS(
             users
             ));
 rpcRegistry.addMethod("stargazer.get_online_ips", methodGetOnlinIPsPtr);
+
+xmlrpc_c::methodPtr const methodGetUserAuthByPtr(new METHOD_GET_USER_AUTH_BY(
+            this,
+            users
+            ));
+rpcRegistry.addMethod("stargazer.get_user_auth_by", methodGetUserAuthByPtr);
 }
 
index 8525f8890adf7cae6fc1f36787281495f8d28c65..72a14f21e028238c558657b2e70c8932aa81e4fc 100644 (file)
 #include "stg/plugin.h"
 #include "stg/admin_conf.h"
 #include "stg/module_settings.h"
+#include "stg/logger.h"
 
 #define RPC_CONFIG_VERSION "Stargazer RPC v. 0.2"
 
-extern "C" PLUGIN * GetPlugin();
-
 class ADMINS;
 class TARIFFS;
 class USERS;
@@ -38,7 +37,7 @@ public:
 
 private:
     std::string  errorStr;
-    int          port;
+    uint16_t     port;
     double       cookieTimeout;
 };
 
@@ -55,7 +54,7 @@ struct ADMIN_INFO
     PRIV        priviledges;
 };
 
-class RPC_CONFIG :public PLUGIN
+class RPC_CONFIG : public PLUGIN
 {
 public:
     RPC_CONFIG();
@@ -75,7 +74,7 @@ public:
     bool                IsRunning() { return running && !stopped; }
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const { return RPC_CONFIG_VERSION; }
+    std::string         GetVersion() const { return RPC_CONFIG_VERSION; }
     uint16_t            GetStartPosition() const { return 20; }
     uint16_t            GetStopPosition() const { return 20; }
 
@@ -111,6 +110,7 @@ private:
              ADMIN_INFO>    cookies;
     size_t                  dayFee;
     std::vector<std::string> dirNames;
+    PLUGIN_LOGGER           logger;
 };
 
 #endif
index fceaa3abe8f8f7e102dcc4cd1277da5ee3025a10..89c41587f8527862de5932bbc4cbe52e63ab0c37 100644 (file)
@@ -1,3 +1,5 @@
+#include <cmath>
+
 #include "stg/tariffs.h"
 #include "stg/admin.h"
 #include "stg/store.h"
@@ -5,7 +7,6 @@
 #include "stg/common.h"
 #include "stg/user_property.h"
 #include "user_helper.h"
-#include "utils.h"
 
 //------------------------------------------------------------------------------
 
@@ -73,7 +74,7 @@ structVal["group"] = xmlrpc_c::value_string(IconvString(ptr->GetProperty().group
 structVal["status"] = xmlrpc_c::value_boolean(ptr->GetConnected());
 structVal["aonline"] = xmlrpc_c::value_boolean(ptr->GetProperty().alwaysOnline.Get());
 structVal["currip"] = xmlrpc_c::value_string(inet_ntostring(ptr->GetCurrIP()));
-structVal["pingtime"] = xmlrpc_c::value_int(ptr->GetPingTime());
+structVal["pingtime"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetPingTime()));
 structVal["ips"] = xmlrpc_c::value_string(ptr->GetProperty().ips.Get().GetIpStr());
 
 std::map<std::string, xmlrpc_c::value> traffInfo;
@@ -115,9 +116,9 @@ structVal["down"] = xmlrpc_c::value_boolean(ptr->GetProperty().disabled.Get());
 structVal["disableddetailstat"] = xmlrpc_c::value_boolean(ptr->GetProperty().disabledDetailStat.Get());
 structVal["passive"] = xmlrpc_c::value_boolean(ptr->GetProperty().passive.Get());
 structVal["lastcash"] = xmlrpc_c::value_double(ptr->GetProperty().lastCashAdd.Get());
-structVal["lasttimecash"] = xmlrpc_c::value_int(ptr->GetProperty().lastCashAddTime.Get());
-structVal["lastactivitytime"] = xmlrpc_c::value_int(ptr->GetProperty().lastActivityTime.Get());
-structVal["creditexpire"] = xmlrpc_c::value_int(ptr->GetProperty().creditExpire.Get());
+structVal["lasttimecash"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetProperty().lastCashAddTime.Get()));
+structVal["lastactivitytime"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetProperty().lastActivityTime.Get()));
+structVal["creditexpire"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetProperty().creditExpire.Get()));
 
 *info = xmlrpc_c::value_struct(structVal);
 }
@@ -136,21 +137,42 @@ std::map<std::string, xmlrpc_c::value> structVal(
 
 std::map<std::string, xmlrpc_c::value>::iterator it;
 
-if ((it = structVal.find("password")) != structVal.end())
+bool check = false;
+bool alwaysOnline = ptr->GetProperty().alwaysOnline;
+if ((it = structVal.find("aonline")) != structVal.end())
     {
-    std::string value(xmlrpc_c::value_string(it->second));
-    if (ptr->GetProperty().password.Get() != value)
-        if (!ptr->GetProperty().password.Set(value,
-                                         admin,
-                                         login,
-                                         &store))
-            return true;
+    check = true;
+    alwaysOnline = xmlrpc_c::value_boolean(it->second);
+    }
+bool onlyOneIP = ptr->GetProperty().ips.ConstData().OnlyOneIP();
+if ((it = structVal.find("ips")) != structVal.end())
+    {
+    check = true;
+    onlyOneIP = StrToIPS(xmlrpc_c::value_string(it->second)).OnlyOneIP();
+    }
+
+if (check && alwaysOnline && !onlyOneIP)
+    {
+    printfd(__FILE__, "Requested change leads to a forbidden state: AlwaysOnline with multiple IP's\n");
+    return true;
     }
 
 if ((it = structVal.find("ips")) != structVal.end())
     {
     USER_IPS ips;
     ips = StrToIPS(xmlrpc_c::value_string(it->second));
+
+    for (size_t i = 0; i < ips.Count(); ++i)
+        {
+        CONST_USER_PTR user;
+        uint32_t ip = ips[i].ip;
+        if (users.IsIPInUse(ip, login, &user))
+            {
+            printfd(__FILE__, "Trying to assign an IP %s to '%s' that is already in use by '%s'\n", inet_ntostring(ip).c_str(), login.c_str(), user->GetLogin().c_str());
+            return true;
+            }
+        }
+
     if (!ptr->GetProperty().ips.Set(ips,
                                 admin,
                                 login,
@@ -158,6 +180,28 @@ if ((it = structVal.find("ips")) != structVal.end())
         return true;
     }
 
+if ((it = structVal.find("aonline")) != structVal.end())
+    {
+    bool value(xmlrpc_c::value_boolean(it->second));
+    if (ptr->GetProperty().alwaysOnline.Get() != value)
+        if (!ptr->GetProperty().alwaysOnline.Set(value,
+                                             admin,
+                                             login,
+                                             &store))
+            return true;
+    }
+
+if ((it = structVal.find("password")) != structVal.end())
+    {
+    std::string value(xmlrpc_c::value_string(it->second));
+    if (ptr->GetProperty().password.Get() != value)
+        if (!ptr->GetProperty().password.Set(value,
+                                         admin,
+                                         login,
+                                         &store))
+            return true;
+    }
+
 if ((it = structVal.find("address")) != structVal.end())
     {
     std::string value(IconvString(xmlrpc_c::value_string(it->second), "UTF-8", "KOI8-RU"));
@@ -194,7 +238,7 @@ if ((it = structVal.find("email")) != structVal.end())
 if ((it = structVal.find("cash")) != structVal.end())
     {
     double value(xmlrpc_c::value_double(it->second));
-    if (ptr->GetProperty().cash.Get() != value)
+    if (std::fabs(ptr->GetProperty().cash.Get() - value) > 1.0e-3)
         if (!ptr->GetProperty().cash.Set(value,
                                      admin,
                                      login,
@@ -216,7 +260,7 @@ if ((it = structVal.find("creditexpire")) != structVal.end())
 if ((it = structVal.find("credit")) != structVal.end())
     {
     double value(xmlrpc_c::value_double(it->second));
-    if (ptr->GetProperty().credit.Get() != value)
+    if (std::fabs(ptr->GetProperty().credit.Get() - value) > 1.0e-3)
         if (!ptr->GetProperty().credit.Set(value,
                                        admin,
                                        login,
@@ -227,7 +271,7 @@ if ((it = structVal.find("credit")) != structVal.end())
 if ((it = structVal.find("freemb")) != structVal.end())
     {
     double value(xmlrpc_c::value_double(it->second));
-    if (ptr->GetProperty().freeMb.Get() != value)
+    if (std::fabs(ptr->GetProperty().freeMb.Get() - value) > 1.0e-3)
         if (!ptr->GetProperty().freeMb.Set(value,
                                        admin,
                                        login,
@@ -257,17 +301,6 @@ if ((it = structVal.find("passive")) != structVal.end())
             return true;
     }
 
-if ((it = structVal.find("aonline")) != structVal.end())
-    {
-    bool value(xmlrpc_c::value_boolean(it->second));
-    if (ptr->GetProperty().alwaysOnline.Get() != value)
-        if (!ptr->GetProperty().alwaysOnline.Set(value,
-                                             admin,
-                                             login,
-                                             &store))
-            return true;
-    }
-
 if ((it = structVal.find("disableddetailstat")) != structVal.end())
     {
     bool value(xmlrpc_c::value_boolean(it->second));
@@ -314,7 +347,7 @@ if ((it = structVal.find("note")) != structVal.end())
 
 if ((it = structVal.find("userdata")) != structVal.end())
     {
-    std::vector<USER_PROPERTY_LOGGED<string> *> userdata;
+    std::vector<USER_PROPERTY_LOGGED<std::string> *> userdata;
     userdata.push_back(ptr->GetProperty().userdata0.GetPointer());
     userdata.push_back(ptr->GetProperty().userdata1.GetPointer());
     userdata.push_back(ptr->GetProperty().userdata2.GetPointer());
index 83f70b5c4df2428cfabb48a296688c1ff2618604..4e1dd7966f0a584be40ffc972779d2cdc9bfd525 100644 (file)
@@ -14,8 +14,9 @@ class TARIFFS;
 class USER_HELPER
 {
 public:
-    USER_HELPER(USER_PTR & p)
-        : ptr(p)
+    USER_HELPER(USER_PTR & p, USERS & us)
+        : ptr(p),
+          users(us)
     {
     }
 
@@ -28,6 +29,7 @@ public:
                      TARIFFS * tariffs);
 private:
     USER_PTR & ptr;
+    USERS & users;
 };
 
 #endif
index 48ef3103123515633614d073fa2b0f9b445cefc7..5adbf44131905750cfa52fefbf1398b0842b2dd0 100644 (file)
@@ -10,7 +10,6 @@
 #include "users_methods.h"
 #include "rpcconfig.h"
 #include "user_helper.h"
-#include "utils.h"
 
 //------------------------------------------------------------------------------
 
@@ -40,7 +39,7 @@ if (users->FindByName(login, &u))
     return;
     }
 
-USER_HELPER uhelper(u);
+USER_HELPER uhelper(u, *users);
 
 if (!adminInfo.priviledges.userConf || !adminInfo.priviledges.userPasswd)
     {
@@ -173,7 +172,7 @@ while (1)
 
     xmlrpc_c::value info;
 
-    USER_HELPER uhelper(u);
+    USER_HELPER uhelper(u, *users);
 
     uhelper.GetUserInfo(&info, hidePassword);
 
@@ -217,7 +216,7 @@ if (users->FindByName(login, &u))
     return;
     }
 
-USER_HELPER uhelper(u);
+USER_HELPER uhelper(u, *users);
 
 if (!adminInfo.priviledges.userConf || !adminInfo.priviledges.userPasswd)
     {
@@ -405,14 +404,13 @@ void METHOD_GET_ONLINE_IPS::execute(xmlrpc_c::paramList const & paramList,
                                     xmlrpc_c::value *   const   retvalPtr)
 {
 std::string cookie = paramList.getString(0);
-std::vector<xmlrpc_c::value> subnetsStr = paramList.getArray(1);
+typedef std::vector<xmlrpc_c::value> ValueVector;
+ValueVector subnetsStr = paramList.getArray(1);
 paramList.verifyEnd(2);
 
 std::vector<IP_MASK> subnets;
 
-std::vector<xmlrpc_c::value>::iterator it;
-
-for (it = subnetsStr.begin(); it != subnetsStr.end(); ++it)
+for (ValueVector::const_iterator it(subnetsStr.begin()); it != subnetsStr.end(); ++it)
     {
     IP_MASK ipm;
     if (ParseNet(xmlrpc_c::value_string(*it), ipm))
@@ -435,7 +433,7 @@ if (config->GetAdminInfo(cookie, &adminInfo))
     return;
     }
 
-std::vector<xmlrpc_c::value> ips;
+ValueVector ips;
 
 USER_PTR u;
 
@@ -458,8 +456,7 @@ while (1)
         {
         uint32_t ip = u->GetCurrIP();
 
-        std::vector<IP_MASK>::iterator it;
-        for (it = subnets.begin(); it != subnets.end(); ++it)
+        for (std::vector<IP_MASK>::const_iterator it(subnets.begin()); it != subnets.end(); ++it)
             {
             if ((it->ip & it->mask) == (ip & it->mask))
                 {
@@ -512,3 +509,36 @@ ipm.mask = htonl(0xffFFffFF << (32 - ipm.mask));
 
 return false;
 }
+
+void METHOD_GET_USER_AUTH_BY::execute(xmlrpc_c::paramList const & paramList,
+                                      xmlrpc_c::value *   const   retvalPtr)
+{
+std::string cookie = paramList.getString(0);
+std::string login = paramList.getString(1);
+paramList.verifyEnd(2);
+
+std::map<std::string, xmlrpc_c::value> structVal;
+ADMIN_INFO adminInfo;
+
+if (config->GetAdminInfo(cookie, &adminInfo))
+    {
+    structVal["result"] = xmlrpc_c::value_boolean(false);
+    *retvalPtr = xmlrpc_c::value_struct(structVal);
+    return;
+    }
+
+USER_PTR u;
+
+if (users->FindByName(login, &u))
+    {
+    structVal["result"] = xmlrpc_c::value_boolean(false);
+    *retvalPtr = xmlrpc_c::value_struct(structVal);
+    return;
+    }
+
+std::vector<std::string> list(u->GetAuthorizers());
+std::vector<xmlrpc_c::value> authList;
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+    authList.push_back(xmlrpc_c::value_string(*it));
+*retvalPtr = xmlrpc_c::value_array(authList);
+}
index 413e9aaf8b418578f374a056383207489dcdc4a1..d1ec33a4ade340f07e1612e1b9641de38417db8d 100644 (file)
@@ -229,4 +229,24 @@ private:
     bool ParseNet(const std::string & net, IP_MASK & ipm) const;
 };
 
+class METHOD_GET_USER_AUTH_BY : public xmlrpc_c::method {
+public:
+    METHOD_GET_USER_AUTH_BY(RPC_CONFIG * c,
+                            USERS * u)
+        : config(c),
+          users(u)
+    {
+    }
+
+    void execute(xmlrpc_c::paramList const & paramList,
+                 xmlrpc_c::value *   const   retvalP);
+
+private:
+    METHOD_GET_USER_AUTH_BY(const METHOD_GET_ONLINE_IPS & rvalue);
+    METHOD_GET_USER_AUTH_BY & operator=(const METHOD_GET_ONLINE_IPS & rvalue);
+
+    RPC_CONFIG * config;
+    USERS * users;
+};
+
 #endif
diff --git a/projects/stargazer/plugins/configuration/rpcconfig/utils.cpp b/projects/stargazer/plugins/configuration/rpcconfig/utils.cpp
deleted file mode 100644 (file)
index 18999aa..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-#include <string>
-#include <cerrno>
-#include <cstring>
-#include <iconv.h>
-
-#include "utils.h"
-#include "common.h"
-
-//-----------------------------------------------------------------------------
-std::string IconvString(const std::string & src,
-                        const std::string & from,
-                        const std::string & to)
-{
-if (src.empty())
-    return std::string();
-
-size_t inBytesLeft = src.length() + 1;
-size_t outBytesLeft = src.length() * 2 + 1;
-
-char * inBuf = new char[inBytesLeft];
-char * outBuf = new char[outBytesLeft];
-
-strncpy(inBuf, src.c_str(), src.length());
-
-inBuf[src.length()] = 0;
-
-#if defined(FREE_BSD) || defined(FREE_BSD5)
-const char * srcPos = inBuf;
-#else
-char * srcPos = inBuf;
-#endif
-char * dstPos = outBuf;
-
-iconv_t handle = iconv_open(to.c_str(),
-                            from.c_str());
-
-if (handle == iconv_t(-1))
-    {
-    if (errno == EINVAL)
-        {
-        printfd(__FILE__, "IconvString(): iconv from %s to %s failed\n", from.c_str(), to.c_str());
-        delete[] outBuf;
-        delete[] inBuf;
-        return src;
-        }
-    else
-        printfd(__FILE__, "IconvString(): iconv_open error\n");
-
-    delete[] outBuf;
-    delete[] inBuf;
-    return src;
-    }
-
-size_t res = iconv(handle,
-                   &srcPos, &inBytesLeft,
-                   &dstPos, &outBytesLeft);
-
-if (res == size_t(-1))
-    {
-    printfd(__FILE__, "IconvString(): '%s'\n", strerror(errno));
-
-    iconv_close(handle);
-    delete[] outBuf;
-    delete[] inBuf;
-    return src;
-    }
-
-dstPos = 0;
-
-std::string dst(outBuf);
-
-iconv_close(handle);
-
-delete[] outBuf;
-delete[] inBuf;
-
-return dst;
-}
diff --git a/projects/stargazer/plugins/configuration/rpcconfig/utils.h b/projects/stargazer/plugins/configuration/rpcconfig/utils.h
deleted file mode 100644 (file)
index d273e3d..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-#ifndef __UTILS_H__
-#define __UTILS_H__
-
-#include <string>
-
-std::string IconvString(const std::string & src,
-                        const std::string & from = "UTF-8",
-                        const std::string & to = "KOI8-R");
-
-#endif
index b6f4938a632095cfcdf505f4fb950e39d65845e6..1b59f5cfa844da7c643e85e7318c58771fb01338 100644 (file)
@@ -11,7 +11,9 @@ SRCS = ./stgconfig.cpp \
        ./configproto.cpp \
        ./parser.cpp \
        ./parser_tariff.cpp \
-       ./parser_admin.cpp
+       ./parser_admin.cpp \
+       ./parser_auth_by.cpp \
+       ./parser_user_info.cpp
 
 LIBS += -lexpat \
        $(LIB_THREAD)
index 07c319a0c9e0cf0849cee2853db291192692bbab..ec3e3ee3c86e765a5a048e3fe8fe920e596091b4 100644 (file)
  $Author: faust $
  */
 
+#include "configproto.h"
 
 #include <unistd.h>
 
-#include "configproto.h"
-
 //-----------------------------------------------------------------------------
 void ParseXMLStart(void *data, const char *el, const char **attr)
 {
@@ -86,39 +85,16 @@ else
     }
 }
 //-----------------------------------------------------------------------------
-CONFIGPROTO::CONFIGPROTO()
-    : answerList(),
-      requestList(),
-      adminIP(0),
-      adminLogin(),
+CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l)
+    : adminIP(0),
       port(0),
-      thrReciveSendConf(),
       nonstop(true),
       state(0),
       currAdmin(NULL),
-      WriteServLog(GetStgLogger()),
+      logger(l),
       listenSocket(-1),
-      parserGetServInfo(),
-      parserGetUsers(),
-      parserGetUser(),
-      parserChgUser(),
-      parserAddUser(),
-      parserDelUser(),
-      parserCheckUser(),
-      parserSendMessage(),
-      parserGetAdmins(),
-      parserAddAdmin(),
-      parserDelAdmin(),
-      parserChgAdmin(),
-      parserGetTariffs(),
-      parserAddTariff(),
-      parserDelTariff(),
-      parserChgTariff(),
       admins(NULL),
-      currParser(NULL),
-      dataParser(),
-      xmlParser(),
-      errorStr()
+      currParser(NULL)
 {
 dataParser.push_back(&parserGetServInfo);
 
@@ -129,6 +105,8 @@ dataParser.push_back(&parserAddUser);
 dataParser.push_back(&parserDelUser);
 dataParser.push_back(&parserCheckUser);
 dataParser.push_back(&parserSendMessage);
+dataParser.push_back(&parserAuthBy);
+dataParser.push_back(&parserUserInfo);
 
 dataParser.push_back(&parserGetTariffs);
 dataParser.push_back(&parserAddTariff);
@@ -144,7 +122,7 @@ xmlParser = XML_ParserCreate(NULL);
 
 if (!xmlParser)
     {
-    WriteServLog("Couldn't allocate memory for parser.");
+    logger("Couldn't allocate memory for parser.");
     exit(1);
     }
 
@@ -157,10 +135,9 @@ XML_ParserFree(xmlParser);
 //-----------------------------------------------------------------------------
 int CONFIGPROTO::ParseCommand()
 {
-list<string>::iterator n;
+std::list<std::string>::iterator n;
 int done = 0;
 char str[9];
-int len;
 
 if (requestList.empty())
     return 0;
@@ -178,16 +155,16 @@ while(nonstop)
     {
     strncpy(str, (*n).c_str(), 8);
     str[8] = 0;
-    len = strlen(str);
+    size_t len = strlen(str);
 
     ++n;
     if (n == requestList.end())
         done = 1;
     --n;
 
-    if (XML_Parse(xmlParser, (*n).c_str(), len, done) == XML_STATUS_ERROR)
+    if (XML_Parse(xmlParser, (*n).c_str(), static_cast<int>(len), done) == XML_STATUS_ERROR)
         {
-        WriteServLog("Invalid configuration request");
+        logger("Invalid configuration request");
         printfd(__FILE__, "Parse error at line %d:\n%s\n",
            XML_GetCurrentLineNumber(xmlParser),
            XML_ErrorString(XML_GetErrorCode(xmlParser)));
@@ -210,51 +187,34 @@ while(nonstop)
 return 0;
 }
 //-----------------------------------------------------------------------------
-void CONFIGPROTO::SetPort(uint16_t p)
-{
-port = p;
-}
-//-----------------------------------------------------------------------------
 void CONFIGPROTO::SetAdmins(ADMINS * a)
 {
 admins = a;
 for (size_t i = 0; i < dataParser.size(); i++)
-    {
     dataParser[i]->SetAdmins(a);
-    }
-
 }
 //-----------------------------------------------------------------------------
 void CONFIGPROTO::SetUsers(USERS * u)
 {
 for (size_t i = 0; i < dataParser.size(); i++)
-    {
     dataParser[i]->SetUsers(u);
-    }
-
 }
 //-----------------------------------------------------------------------------
 void CONFIGPROTO::SetTariffs(TARIFFS * t)
 {
 for (size_t i = 0; i < dataParser.size(); i++)
-    {
     dataParser[i]->SetTariffs(t);
-    }
 }
 //-----------------------------------------------------------------------------
 void CONFIGPROTO::SetStore(STORE * s)
 {
 for (size_t i = 0; i < dataParser.size(); i++)
-    {
     dataParser[i]->SetStore(s);
-    }
 }
 //-----------------------------------------------------------------------------
 void CONFIGPROTO::SetStgSettings(const SETTINGS * s)
 {
 for (size_t i = 0; i < dataParser.size(); i++)
-    {
     dataParser[i]->SetStgSettings(s);
-    }
 }
 //-----------------------------------------------------------------------------
index 15809c3c7fd9a6e9848b505691e230c64930f862..4adba09758afae9345de7104f1e4236160a55de9 100644 (file)
 #ifndef CONFIGPROTO_H
 #define CONFIGPROTO_H
 
-#include <expat.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <string>
-#include <list>
+#include "parser_auth_by.h"
+#include "parser_user_info.h"
 
 #include "stg/users.h"
 #include "stg/admins.h"
 #include "stg/logger.h"
 #include "parser.h"
 
+#include <string>
+#include <list>
+
+#include <expat.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
 #define  STG_HEADER     "SG04"
 #define  OK_HEADER      "OKHD"
 #define  ERR_HEADER     "ERHD"
 //-----------------------------------------------------------------------------
 class CONFIGPROTO {
 public:
-    CONFIGPROTO();
+    CONFIGPROTO(PLUGIN_LOGGER & l);
     ~CONFIGPROTO();
 
-    void            SetPort(uint16_t port);
+    void            SetPort(uint16_t p) { port = p; }
     void            SetAdmins(ADMINS * a);
     void            SetUsers(USERS * u);
     void            SetTariffs(TARIFFS * t);
@@ -88,12 +91,13 @@ private:
     std::list<std::string>      requestList;
     uint32_t                    adminIP;
     std::string                 adminLogin;
+    std::string                 adminPassword;
     uint16_t                    port;
     pthread_t                   thrReciveSendConf;
     bool                        nonstop;
     int                         state;
     ADMIN *                     currAdmin;
-    STG_LOGGER &                WriteServLog;
+    PLUGIN_LOGGER &             logger;
 
     int                         listenSocket;
 
@@ -106,6 +110,8 @@ private:
     PARSER_DEL_USER             parserDelUser;
     PARSER_CHECK_USER           parserCheckUser;
     PARSER_SEND_MESSAGE         parserSendMessage;
+    PARSER_AUTH_BY              parserAuthBy;
+    PARSER_USER_INFO            parserUserInfo;
 
     PARSER_GET_ADMINS           parserGetAdmins;
     PARSER_ADD_ADMIN            parserAddAdmin;
@@ -120,7 +126,7 @@ private:
     ADMINS *                    admins;
 
     BASE_PARSER *               currParser;
-    vector<BASE_PARSER *>       dataParser;
+    std::vector<BASE_PARSER *>  dataParser;
 
     XML_Parser                  xmlParser;
 
index c63edfe0d16f4af11dbb31e3ebe0e6cd67e45ae6..a7c79c00d5df90f09685a7a7f535882eff233db9 100644 (file)
@@ -13,6 +13,7 @@
 #include "stg/tariffs.h"
 #include "stg/user_property.h"
 #include "stg/settings.h"
+#include "stg/logger.h"
 #include "parser.h"
 
 #define  UNAME_LEN      (256)
@@ -63,13 +64,13 @@ answerList->push_back("<ServerInfo>");
 sprintf(s, "<version value=\"%s\"/>", SERVER_VERSION);
 answerList->push_back(s);
 
-sprintf(s, "<tariff_num value=\"%llu\"/>", (unsigned long long)tariffs->Count());
+sprintf(s, "<tariff_num value=\"%llu\"/>", static_cast<unsigned long long>(tariffs->Count()));
 answerList->push_back(s);
 
 sprintf(s, "<tariff value=\"%d\"/>", 2);
 answerList->push_back(s);
 
-sprintf(s, "<users_num value=\"%llu\"/>", (unsigned long long)users->Count());
+sprintf(s, "<users_num value=\"%llu\"/>", static_cast<unsigned long long>(users->Count()));
 answerList->push_back(s);
 
 sprintf(s, "<uname value=\"%s\"/>", un);
@@ -83,7 +84,7 @@ answerList->push_back(s);
 
 for (int i = 0; i< DIR_NUM; i++)
     {
-    string dn2e;
+    std::string dn2e;
     Encode12str(dn2e, settings->GetDirName(i));
     sprintf(s, "<dir_name_%d value=\"%s\"/>", i, dn2e.c_str());
     answerList->push_back(s);
@@ -123,8 +124,8 @@ return -1;
 //-----------------------------------------------------------------------------
 void PARSER_GET_USER::CreateAnswer()
 {
-string s;
-string enc;
+std::string s;
+std::string enc;
 
 USER_PTR u;
 
@@ -132,8 +133,7 @@ answerList->erase(answerList->begin(), answerList->end());
 
 if (users->FindByName(login, &u))
     {
-    s = "<user result=\"error\"/>";
-    answerList->push_back(s);
+    answerList->push_back("<user result=\"error\" reason=\"User not found.\"/>");
     return;
     }
 
@@ -189,7 +189,7 @@ s = "<email value=\"" + enc + "\" />";
 answerList->push_back(s);
 
 
-vector<USER_PROPERTY_LOGGED<string> *> userdata;
+std::vector<USER_PROPERTY_LOGGED<std::string> *> userdata;
 userdata.push_back(u->GetProperty().userdata0.GetPointer());
 userdata.push_back(u->GetProperty().userdata1.GetPointer());
 userdata.push_back(u->GetProperty().userdata2.GetPointer());
@@ -201,7 +201,7 @@ userdata.push_back(u->GetProperty().userdata7.GetPointer());
 userdata.push_back(u->GetProperty().userdata8.GetPointer());
 userdata.push_back(u->GetProperty().userdata9.GetPointer());
 
-string tmpI;
+std::string tmpI;
 for (unsigned i = 0; i < userdata.size(); i++)
     {
     Encode12str(enc, userdata[i]->Get());
@@ -229,7 +229,7 @@ answerList->push_back(s);
 strprintf(&s, "<PingTime value=\"%lu\" />", u->GetPingTime());
 answerList->push_back(s);
 
-stringstream sstr;
+std::ostringstream sstr;
 sstr << u->GetProperty().ips.Get();
 strprintf(&s, "<ip value=\"%s\" />", sstr.str().c_str());
 answerList->push_back(s);
@@ -245,7 +245,7 @@ upload = u->GetProperty().up.Get();
 
 for (int j = 0; j < DIR_NUM; j++)
     {
-    string s;
+    std::string s;
     x2str(upload[j], s);
     sprintf(st, " MU%d=\"%s\"", j, s.c_str());
     strcat(ss, st);
@@ -285,6 +285,13 @@ answerList->push_back(s);
 strprintf(&s, "<CreditExpire value=\"%ld\" />", u->GetProperty().creditExpire.Get());
 answerList->push_back(s);
 
+s = "<AuthorizedBy>";
+std::vector<std::string> list(u->GetAuthorizers());
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+    s += "<Auth name=\"" + *it + "\"/>";
+s += "</AuthorizedBy>";
+answerList->push_back(s);
+
 strprintf(&s, "</user>");
 answerList->push_back(s);
 }
@@ -341,16 +348,16 @@ void PARSER_GET_USERS::CreateAnswer()
 {
 answerList->erase(answerList->begin(), answerList->end());
 
-string s;
-string userStart;
-string traffStart;
-string traffMiddle;
-string traffFinish;
-string middle;
-string userFinish;
+std::string s;
+std::string userStart;
+std::string traffStart;
+std::string traffMiddle;
+std::string traffFinish;
+std::string middle;
+std::string userFinish;
 
 
-string enc;
+std::string enc;
 
 USER_PTR u;
 
@@ -361,7 +368,7 @@ if (!h)
     users->CloseSearch(h);
     return;
     }
-string updateTime;
+std::string updateTime;
 x2str(time(NULL), updateTime);
 
 if (lastUpdateFound)
@@ -457,7 +464,7 @@ while (1)
         middle += s;
         }
 
-    vector<USER_PROPERTY_LOGGED<string> *> userdata;
+    std::vector<USER_PROPERTY_LOGGED<std::string> *> userdata;
     userdata.push_back(u->GetProperty().userdata0.GetPointer());
     userdata.push_back(u->GetProperty().userdata1.GetPointer());
     userdata.push_back(u->GetProperty().userdata2.GetPointer());
@@ -469,7 +476,7 @@ while (1)
     userdata.push_back(u->GetProperty().userdata8.GetPointer());
     userdata.push_back(u->GetProperty().userdata9.GetPointer());
 
-    string tmpI;
+    std::string tmpI;
     for (unsigned i = 0; i < userdata.size(); i++)
         {
         if (userdata[i]->ModificationTime() > lastUserUpdateTime)
@@ -521,7 +528,7 @@ while (1)
 
     if (u->GetProperty().ips.ModificationTime() > lastUserUpdateTime)
         {
-        stringstream sstr;
+        std::ostringstream sstr;
         sstr << u->GetProperty().ips.Get();
         strprintf(&s, "<ip value=\"%s\" />", sstr.str().c_str());
         middle += s;
@@ -539,7 +546,7 @@ while (1)
         {
         for (int j = 0; j < DIR_NUM; j++)
             {
-            string s;
+            std::string s;
             x2str(upload[j], s);
             sprintf(st, " MU%d=\"%s\" ", j, s.c_str());
             traffMiddle += st;
@@ -741,11 +748,11 @@ ucr = new USER_CONF_RES;
 
 upr = new RESETABLE<uint64_t>[DIR_NUM];
 downr = new RESETABLE<uint64_t>[DIR_NUM];
-};
+}
 //-----------------------------------------------------------------------------
-string PARSER_CHG_USER::EncChar2String(const char * strEnc)
+std::string PARSER_CHG_USER::EncChar2String(const char * strEnc)
 {
-string str;
+std::string str;
 Decode21str(str, strEnc);
 return str;
 }
@@ -916,7 +923,7 @@ else
         int dir;
         DIR_TRAFF dtu;
         DIR_TRAFF dtd;
-        unsigned long long t = 0;
+        uint64_t t = 0;
         while (attr[j])
             {
             dir = attr[j][2] - '0';
@@ -935,8 +942,6 @@ else
                 }
             j+=2;
             }
-        usr->down = dtd;
-        usr->up = dtu;
         return 0;
         }
 
@@ -996,6 +1001,7 @@ switch (res)
 //-----------------------------------------------------------------------------
 int PARSER_CHG_USER::AplayChanges()
 {
+printfd(__FILE__, "PARSER_CHG_USER::AplayChanges()\n");
 USER_PTR u;
 
 res = 0;
@@ -1005,53 +1011,88 @@ if (users->FindByName(login, &u))
     return -1;
     }
 
-if (!ucr->ips.res_empty())
-    if (!u->GetProperty().ips.Set(ucr->ips.const_data(), currAdmin, login, store))
+bool check = false;
+bool alwaysOnline = u->GetProperty().alwaysOnline;
+if (!ucr->alwaysOnline.empty())
+    {
+    check = true;
+    alwaysOnline = ucr->alwaysOnline.const_data();
+    }
+bool onlyOneIP = u->GetProperty().ips.ConstData().OnlyOneIP();
+if (!ucr->ips.empty())
+    {
+    check = true;
+    onlyOneIP = ucr->ips.const_data().OnlyOneIP();
+    }
+
+if (check && alwaysOnline && !onlyOneIP)
+    {
+    printfd(__FILE__, "Requested change leads to a forbidden state: AlwaysOnline with multiple IP's\n");
+    GetStgLogger()("%s Requested change leads to a forbidden state: AlwaysOnline with multiple IP's", currAdmin->GetLogStr().c_str());
+    res = -1;
+    return -1;
+    }
+
+for (size_t i = 0; i < ucr->ips.const_data().Count(); ++i)
+    {
+    CONST_USER_PTR user;
+    uint32_t ip = ucr->ips.const_data().operator[](i).ip;
+    if (users->IsIPInUse(ip, login, &user))
+        {
+        printfd(__FILE__, "Trying to assign an IP %s to '%s' that is already in use by '%s'\n", inet_ntostring(ip).c_str(), login.c_str(), user->GetLogin().c_str());
+        GetStgLogger()("%s trying to assign an IP %s to '%s' that is currently in use by '%s'", currAdmin->GetLogStr().c_str(), inet_ntostring(ip).c_str(), login.c_str(), user->GetLogin().c_str());
         res = -1;
+        return -1;
+        }
+    }
 
-if (!ucr->address.res_empty())
-    if (!u->GetProperty().address.Set(ucr->address.const_data(), currAdmin, login, store))
+if (!ucr->ips.empty())
+    if (!u->GetProperty().ips.Set(ucr->ips.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->alwaysOnline.res_empty())
+if (!ucr->alwaysOnline.empty())
     if (!u->GetProperty().alwaysOnline.Set(ucr->alwaysOnline.const_data(),
                                       currAdmin, login, store))
         res = -1;
 
-if (!ucr->creditExpire.res_empty())
+if (!ucr->address.empty())
+    if (!u->GetProperty().address.Set(ucr->address.const_data(), currAdmin, login, store))
+        res = -1;
+
+if (!ucr->creditExpire.empty())
     if (!u->GetProperty().creditExpire.Set(ucr->creditExpire.const_data(),
                                       currAdmin, login, store))
         res = -1;
 
-if (!ucr->credit.res_empty())
+if (!ucr->credit.empty())
     if (!u->GetProperty().credit.Set(ucr->credit.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!usr->freeMb.res_empty())
+if (!usr->freeMb.empty())
     if (!u->GetProperty().freeMb.Set(usr->freeMb.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->disabled.res_empty())
+if (!ucr->disabled.empty())
     if (!u->GetProperty().disabled.Set(ucr->disabled.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->disabledDetailStat.res_empty())
+if (!ucr->disabledDetailStat.empty())
     if (!u->GetProperty().disabledDetailStat.Set(ucr->disabledDetailStat.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->email.res_empty())
+if (!ucr->email.empty())
     if (!u->GetProperty().email.Set(ucr->email.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->group.res_empty())
+if (!ucr->group.empty())
     if (!u->GetProperty().group.Set(ucr->group.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->note.res_empty())
+if (!ucr->note.empty())
     if (!u->GetProperty().note.Set(ucr->note.const_data(), currAdmin, login, store))
         res = -1;
 
-vector<USER_PROPERTY_LOGGED<string> *> userdata;
+std::vector<USER_PROPERTY_LOGGED<std::string> *> userdata;
 userdata.push_back(u->GetProperty().userdata0.GetPointer());
 userdata.push_back(u->GetProperty().userdata1.GetPointer());
 userdata.push_back(u->GetProperty().userdata2.GetPointer());
@@ -1065,31 +1106,31 @@ userdata.push_back(u->GetProperty().userdata9.GetPointer());
 
 for (int i = 0; i < (int)userdata.size(); i++)
     {
-    if (!ucr->userdata[i].res_empty())
+    if (!ucr->userdata[i].empty())
         {
         if(!userdata[i]->Set(ucr->userdata[i].const_data(), currAdmin, login, store))
             res = -1;
         }
     }
 
-if (!ucr->passive.res_empty())
+if (!ucr->passive.empty())
     if (!u->GetProperty().passive.Set(ucr->passive.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->password.res_empty())
+if (!ucr->password.empty())
     if (!u->GetProperty().password.Set(ucr->password.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->phone.res_empty())
+if (!ucr->phone.empty())
     if (!u->GetProperty().phone.Set(ucr->phone.const_data(), currAdmin, login, store))
         res = -1;
 
-if (!ucr->realName.res_empty())
+if (!ucr->realName.empty())
     if (!u->GetProperty().realName.Set(ucr->realName.const_data(), currAdmin, login, store))
         res = -1;
 
 
-if (!usr->cash.res_empty())
+if (!usr->cash.empty())
     {
     //if (*currAdmin->GetPriv()->userCash)
         {
@@ -1111,7 +1152,7 @@ if (!usr->cash.res_empty())
     }
 
 
-if (!ucr->tariffName.res_empty())
+if (!ucr->tariffName.empty())
     {
     if (tariffs->FindByName(ucr->tariffName.const_data()))
         {
@@ -1126,7 +1167,7 @@ if (!ucr->tariffName.res_empty())
         }
     }
 
-if (!ucr->nextTariff.res_empty())
+if (!ucr->nextTariff.empty())
     {
     if (tariffs->FindByName(ucr->nextTariff.const_data()))
         {
@@ -1146,14 +1187,14 @@ int upCount = 0;
 int downCount = 0;
 for (int i = 0; i < DIR_NUM; i++)
     {
-    if (!upr[i].res_empty())
+    if (!upr[i].empty())
         {
-        up[i] = upr[i];
+        up[i] = upr[i].data();
         upCount++;
         }
-    if (!downr[i].res_empty())
+    if (!downr[i].empty())
         {
-        down[i] = downr[i];
+        down[i] = downr[i].data();
         downCount++;
         }
     }
@@ -1166,15 +1207,6 @@ if (downCount)
     if (!u->GetProperty().down.Set(down, currAdmin, login, store))
         res = -1;
 
-/*if (!usr->down.res_empty())
-    {
-    u->GetProperty().down.Set(usr->down.const_data(), currAdmin, login, store);
-    }
-if (!usr->up.res_empty())
-    {
-    u->GetProperty().up.Set(usr->up.const_data(), currAdmin, login, store);
-    }*/
-
 u->WriteConf();
 u->WriteStat();
 
@@ -1265,7 +1297,7 @@ if (strcasecmp(el, "Message") == 0)
             printfd(__FILE__, "User not found. %s\n", logins[i].c_str());
             continue;
             }
-        msg.header.creationTime = stgTime;
+        msg.header.creationTime = static_cast<unsigned int>(stgTime);
         u->AddMessage(&msg);
         result = res_ok;
         }
@@ -1319,11 +1351,11 @@ switch (result)
         break;
     case res_params_error:
         printfd(__FILE__, "res_params_error\n");
-        answerList->push_back("<SendMessageResult value=\"Parameters error\"/>");
+        answerList->push_back("<SendMessageResult value=\"Parameters error.\"/>");
         break;
     case res_unknown:
         printfd(__FILE__, "res_unknown\n");
-        answerList->push_back("<SendMessageResult value=\"Unknown user\"/>");
+        answerList->push_back("<SendMessageResult value=\"Unknown user.\"/>");
         break;
     default:
         printfd(__FILE__, "res_default\n");
@@ -1377,30 +1409,17 @@ else
     answerList->push_back("<DelUser value=\"ok\"/>");
 }
 //-----------------------------------------------------------------------------
-/*void PARSERDELUSER::CreateAnswer(char * mes)
-{
-//answerList->clear();
-answerList->erase(answerList->begin(), answerList->end());
-
-char str[255];
-sprintf(str, "<DelUser value=\"%s\"/>", mes);
-answerList->push_back(str);
-}*/
-//-----------------------------------------------------------------------------
 //  CHECK USER
 // <checkuser login="vasya" password=\"123456\"/>
 //-----------------------------------------------------------------------------
 int PARSER_CHECK_USER::ParseStart(void *, const char *el, const char **attr)
 {
-result = false;
-
 if (strcasecmp(el, "CheckUser") == 0)
     {
     if (attr[0] == NULL || attr[1] == NULL
      || attr[2] == NULL || attr[3] == NULL)
         {
-        result = false;
-        CreateAnswer();
+        CreateAnswer("Invalid parameters.");
         printfd(__FILE__, "PARSER_CHECK_USER - attr err\n");
         return 0;
         }
@@ -1408,22 +1427,19 @@ if (strcasecmp(el, "CheckUser") == 0)
     USER_PTR user;
     if (users->FindByName(attr[1], &user))
         {
-        result = false;
-        CreateAnswer();
+        CreateAnswer("User not found.");
         printfd(__FILE__, "PARSER_CHECK_USER - login err\n");
         return 0;
         }
 
     if (strcmp(user->GetProperty().password.Get().c_str(), attr[3]))
         {
-        result = false;
-        CreateAnswer();
+        CreateAnswer("Wrong password.");
         printfd(__FILE__, "PARSER_CHECK_USER - passwd err\n");
         return 0;
         }
 
-    result = true;
-    CreateAnswer();
+    CreateAnswer(NULL);
     return 0;
     }
 return -1;
@@ -1438,12 +1454,12 @@ if (strcasecmp(el, "CheckUser") == 0)
 return -1;
 }
 //-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::CreateAnswer()
+void PARSER_CHECK_USER::CreateAnswer(const char * error)
 {
-if (result)
-    answerList->push_back("<CheckUser value=\"Ok\"/>");
+if (error)
+    answerList->push_back(std::string("<CheckUser value=\"Err\" reason=\"") + error + "\"/>");
 else
-    answerList->push_back("<CheckUser value=\"Err\"/>");
+    answerList->push_back("<CheckUser value=\"Ok\"/>");
 }
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
index df3d7155872b56f3a08aaad57e6d750ce6b0853c..e76d8f4ca9b36ec5122bcd12a68f958f2c1ed431 100644 (file)
@@ -7,10 +7,6 @@
 #ifndef PARSER_H
 #define PARSER_H
 
-#include <list>
-#include <string>
-#include <vector>
-
 #include "stg/resetable.h"
 #include "stg/const.h"
 #include "stg/store.h"
 #include "stg/users.h"
 #include "stg/message.h"
 
+#include <list>
+#include <string>
+#include <vector>
+
 class TARIFFS;
 class SETTINGS;
 
@@ -39,18 +39,18 @@ public:
     virtual ~BASE_PARSER() {}
     virtual int ParseStart(void *data, const char *el, const char **attr) = 0;
     virtual int ParseEnd(void *data, const char *el) = 0;
-    virtual void CreateAnswer() = 0;
-    virtual void SetAnswerList(std::list<std::string> * ansList) { answerList = ansList; }
 
-    virtual void SetUsers(USERS * u) { users = u; }
-    virtual void SetAdmins(ADMINS * a) { admins = a; }
-    virtual void SetTariffs(TARIFFS * t) { tariffs = t; }
-    virtual void SetStore(STORE * s) { store = s; }
-    virtual void SetStgSettings(const SETTINGS * s) { settings = s; }
+    void SetAnswerList(std::list<std::string> * ansList) { answerList = ansList; }
+
+    void SetUsers(USERS * u) { users = u; }
+    void SetAdmins(ADMINS * a) { admins = a; }
+    void SetTariffs(TARIFFS * t) { tariffs = t; }
+    void SetStore(STORE * s) { store = s; }
+    void SetStgSettings(const SETTINGS * s) { settings = s; }
 
-    virtual void SetCurrAdmin(ADMIN & cua) { currAdmin = &cua; }
-    virtual std::string & GetStrError() { return strError; }
-    virtual void Reset() { answerList->clear(); depth = 0; }
+    void SetCurrAdmin(ADMIN & cua) { currAdmin = &cua; }
+    std::string & GetStrError() { return strError; }
+    void Reset() { answerList->clear(); depth = 0; }
 
 protected:
     BASE_PARSER(const BASE_PARSER & rvalue);
@@ -71,6 +71,8 @@ class PARSER_GET_ADMINS: public BASE_PARSER {
 public:
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
+
+private:
     void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
@@ -79,9 +81,11 @@ public:
         PARSER_ADD_ADMIN() : BASE_PARSER(), adminToAdd() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
     std::string adminToAdd;
+
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_DEL_ADMIN: public BASE_PARSER {
@@ -89,10 +93,12 @@ public:
         PARSER_DEL_ADMIN() : BASE_PARSER(), adminToDel() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
-    int CheckAttr(const char **attr);
     std::string adminToDel;
+
+    int CheckAttr(const char **attr);
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_CHG_ADMIN: public BASE_PARSER {
@@ -100,17 +106,21 @@ public:
         PARSER_CHG_ADMIN() : BASE_PARSER(), login(), password(), privAsString() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
     RESETABLE<std::string> login;
     RESETABLE<std::string> password;
     RESETABLE<std::string> privAsString;
+
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_GET_SERVER_INFO: public BASE_PARSER {
 public:
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
+
+private:
     void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
@@ -120,9 +130,11 @@ public:
         ~PARSER_GET_USER() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
     std::string login;
+
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_GET_USERS: public BASE_PARSER {
@@ -130,16 +142,20 @@ public:
         PARSER_GET_USERS() : BASE_PARSER(), lastUserUpdateTime(0), lastUpdateFound(false) {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
     time_t lastUserUpdateTime;
     bool lastUpdateFound;
+
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_GET_TARIFFS: public BASE_PARSER {
 public:
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
+
+private:
     void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
@@ -148,9 +164,11 @@ public:
         PARSER_ADD_TARIFF() : BASE_PARSER(), tariffToAdd() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
     std::string tariffToAdd;
+
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_DEL_TARIFF: public BASE_PARSER {
@@ -158,9 +176,11 @@ public:
         PARSER_DEL_TARIFF() : BASE_PARSER(), tariffToDel() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
     std::string tariffToDel;
+
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_CHG_TARIFF: public BASE_PARSER {
@@ -168,14 +188,15 @@ public:
         PARSER_CHG_TARIFF() : BASE_PARSER(), td() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
+    TARIFF_DATA_RES td;
+
     int ParseSlashedIntParams(int paramsNum, const std::string & s, int * params);
     int ParseSlashedDoubleParams(int paramsNum, const std::string & s, double * params);
     int CheckTariffData();
     int AplayChanges();
-
-    TARIFF_DATA_RES td;
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------/
 class PARSER_ADD_USER: public BASE_PARSER {
@@ -184,11 +205,13 @@ public:
         ~PARSER_ADD_USER() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
-    void Reset();
+
 private:
-    int CheckUserData();
     std::string login;
+
+    int CheckUserData();
+    void CreateAnswer();
+    void Reset();
 };
 //-----------------------------------------------------------------------------
 class PARSER_CHG_USER: public BASE_PARSER {
@@ -197,15 +220,8 @@ public:
         ~PARSER_CHG_USER();
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
-    void Reset();
-private:
-    PARSER_CHG_USER(const PARSER_CHG_USER & rvalue);
-    PARSER_CHG_USER & operator=(const PARSER_CHG_USER & rvalue);
-
-    std::string EncChar2String(const char *);
-    int AplayChanges();
 
+private:
     USER_STAT_RES * usr;
     USER_CONF_RES * ucr;
     RESETABLE<uint64_t> * upr;
@@ -214,6 +230,14 @@ private:
     std::string login;
     bool cashMustBeAdded;
     int res;
+
+    PARSER_CHG_USER(const PARSER_CHG_USER & rvalue);
+    PARSER_CHG_USER & operator=(const PARSER_CHG_USER & rvalue);
+
+    std::string EncChar2String(const char *);
+    int AplayChanges();
+    void CreateAnswer();
+    void Reset();
 };
 //-----------------------------------------------------------------------------
 class PARSER_DEL_USER: public BASE_PARSER {
@@ -221,24 +245,25 @@ public:
         PARSER_DEL_USER() : BASE_PARSER(), res(0), u(NULL) {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
 
 private:
+    int res;
+    USER * u;
+
     PARSER_DEL_USER(const PARSER_DEL_USER & rvalue);
     PARSER_DEL_USER & operator=(const PARSER_DEL_USER & rvalue);
 
-    int res;
-    USER * u;
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 class PARSER_CHECK_USER: public BASE_PARSER {
 public:
-        PARSER_CHECK_USER() : BASE_PARSER(), result(false) {}
+        PARSER_CHECK_USER() : BASE_PARSER() {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
+
 private:
-    bool result;
+    void CreateAnswer(const char * error);
 };
 //-----------------------------------------------------------------------------
 class PARSER_SEND_MESSAGE: public BASE_PARSER {
@@ -246,18 +271,19 @@ public:
         PARSER_SEND_MESSAGE() : BASE_PARSER(), logins(), result(0), msg(), u(NULL) {}
     int ParseStart(void *data, const char *el, const char **attr);
     int ParseEnd(void *data, const char *el);
-    void CreateAnswer();
-private:
-    PARSER_SEND_MESSAGE(const PARSER_SEND_MESSAGE & rvalue);
-    PARSER_SEND_MESSAGE & operator=(const PARSER_SEND_MESSAGE & rvalue);
-
-    int ParseLogins(const char * logins);
 
+private:
     enum {res_ok, res_params_error, res_unknown};
     std::vector<std::string> logins;
     int result;
     STG_MSG msg;
     USER * u;
+
+    PARSER_SEND_MESSAGE(const PARSER_SEND_MESSAGE & rvalue);
+    PARSER_SEND_MESSAGE & operator=(const PARSER_SEND_MESSAGE & rvalue);
+
+    int ParseLogins(const char * logins);
+    void CreateAnswer();
 };
 //-----------------------------------------------------------------------------
 #endif //PARSER_H
index a87c1dbfd765127462866f908b2bb62f724babdf..b1285a772441d3facc49cd96937c05f11ba9c24d 100644 (file)
@@ -37,7 +37,7 @@ if (!priv->adminChg)
     return;
     }
 
-string s;
+std::string s;
 //answerList->clear();
 answerList->erase(answerList->begin(), answerList->end());
 
@@ -99,7 +99,7 @@ if (admins->Del(adminToDel, currAdmin) == 0)
     }
 else
     {
-    string s;
+    std::string s;
     strprintf(&s, "<DelAdmin Result=\"Error. %s\"/>", admins->GetStrError().c_str());
     answerList->push_back(s);
     }
@@ -155,7 +155,7 @@ if (admins->Add(adminToAdd, currAdmin) == 0)
     }
 else
     {
-    string s;
+    std::string s;
     strprintf(&s, "<AddAdmin Result=\"Error. %s\"/>", admins->GetStrError().c_str());
     answerList->push_back(s);
     }
@@ -212,49 +212,44 @@ void PARSER_CHG_ADMIN::CreateAnswer()
 {
 answerList->erase(answerList->begin(), answerList->end());
 
-ADMIN_CONF conf;
-conf.login = login;
-if (!login.res_empty())
+
+if (!login.empty())
     {
-    string s;
-    //if (admins->FindAdmin(login.data()) != NULL)
-    //    {
-        if (!password.res_empty())
-            conf.password = password.data();
+    ADMIN * origAdmin = NULL;
 
-        if (!privAsString.res_empty())
-            {
-            int p = 0;
-            if (str2x(privAsString.data().c_str(), p) < 0)
-                {
-                strprintf(&s, "<ChgAdmin Result = \"Incorrect parameter Priv.\"/>" );
-                answerList->push_back(s);
-                return;
-                }
-            //memcpy(&conf.priv, &p, sizeof(conf.priv));
-            conf.priv.userStat      = (p & 0x0003) >> 0x00; // 1+2
-            conf.priv.userConf      = (p & 0x000C) >> 0x02; // 4+8
-            conf.priv.userCash      = (p & 0x0030) >> 0x04; // 10+20
-            conf.priv.userPasswd    = (p & 0x00C0) >> 0x06; // 40+80
-            conf.priv.userAddDel    = (p & 0x0300) >> 0x08; // 100+200
-            conf.priv.adminChg      = (p & 0x0C00) >> 0x0A; // 400+800
-            conf.priv.tariffChg     = (p & 0x3000) >> 0x0C; // 1000+2000
-            }
+    if (admins->Find(login.data(), &origAdmin))
+        {
+        answerList->push_back(std::string("<ChgAdmin Result = \"Admin '") + login.data() + "' is not found.\"/>");
+        return;
+        }
 
-        if (admins->Change(conf, currAdmin) != 0)
-            {
-            strprintf(&s, "<ChgAdmin Result = \"%s\"/>", admins->GetStrError().c_str());
-            answerList->push_back(s);
-            }
-        else
+    ADMIN_CONF conf(origAdmin->GetConf());
+
+    if (!password.empty())
+        conf.password = password.data();
+
+    if (!privAsString.empty())
+        {
+        int p = 0;
+        if (str2x(privAsString.data().c_str(), p) < 0)
             {
-            answerList->push_back("<ChgAdmin Result = \"Ok\"/>");
+            answerList->push_back("<ChgAdmin Result = \"Incorrect parameter Priv.\"/>");
+            return;
             }
-        return;
-    //    }
-    //strprintf(&s, "<ChgAdmin Result = \"%s\"/>", admins->GetStrError().c_str());
-    //answerList->push_back(s);
-    //return;
+
+        conf.priv.FromInt(p);
+        }
+
+    if (admins->Change(conf, currAdmin) != 0)
+        {
+        std::string s;
+        strprintf(&s, "<ChgAdmin Result = \"%s\"/>", admins->GetStrError().c_str());
+        answerList->push_back(s);
+        }
+    else
+        {
+        answerList->push_back("<ChgAdmin Result = \"Ok\"/>");
+        }
     }
 else
     {
diff --git a/projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp b/projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp
new file mode 100644 (file)
index 0000000..5492157
--- /dev/null
@@ -0,0 +1,46 @@
+#include "parser_auth_by.h"
+
+int PARSER_AUTH_BY::ParseStart(void * /*data*/, const char *el, const char **attr)
+{
+if (strcasecmp(el, "GetUserAuthBy") == 0)
+    {
+    if (attr[0] && attr[1])
+        login = attr[1];
+    else
+        {
+        login.erase(login.begin(), login.end());
+        return -1;
+        }
+    return 0;
+    }
+return -1;
+}
+
+int PARSER_AUTH_BY::ParseEnd(void * /*data*/, const char *el)
+{
+if (strcasecmp(el, "GetUserAuthBy") == 0)
+    {
+    CreateAnswer();
+    return 0;
+    }
+return -1;
+}
+
+void PARSER_AUTH_BY::CreateAnswer()
+{
+answerList->erase(answerList->begin(), answerList->end());
+
+USER_PTR u;
+if (users->FindByName(login, &u))
+    {
+    answerList->push_back("<AuthorizedBy result=\"error\" reason=\"User not found.\"/>");
+    return;
+    }
+
+std::string s = "<AuthorizedBy result=\"ok\">";
+std::vector<std::string> list(u->GetAuthorizers());
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+    s += "<Auth name=\"" + *it + "\"/>";
+s += "</AuthorizedBy>";
+answerList->push_back(s);
+}
diff --git a/projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.h b/projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.h
new file mode 100644 (file)
index 0000000..c34586c
--- /dev/null
@@ -0,0 +1,18 @@
+#ifndef __STG_PARSER_AUTH_BY_H__
+#define __STG_PARSER_AUTH_BY_H__
+
+#include <string>
+
+#include "parser.h"
+
+class PARSER_AUTH_BY : public BASE_PARSER {
+public:
+    int ParseStart(void *data, const char *el, const char **attr);
+    int ParseEnd(void *data, const char *el);
+    void CreateAnswer();
+
+private:
+    std::string login;
+};
+
+#endif
index bb855fafc07ba679c057b7bfbda772ae8424f0c6..0e001b224a559fdfee6f94411275387e7ec62926 100644 (file)
@@ -29,7 +29,7 @@ return -1;
 //-----------------------------------------------------------------------------
 void PARSER_GET_TARIFFS::CreateAnswer()
 {
-string s;
+std::string s;
 char vs[100];
 int hd, hn, md, mn;
 
@@ -188,7 +188,7 @@ if (tariffs->Add(tariffToAdd, currAdmin) == 0)
     }
 else
     {
-    string s;
+    std::string s;
     strprintf(&s, "<AddTariff Result=\"Error. %s\"/>", tariffs->GetStrError().c_str());
     answerList->push_back(s);
     }
@@ -224,7 +224,7 @@ answerList->erase(answerList->begin(), answerList->end());
 
 if (users->TariffInUse(tariffToDel))
     {
-    string s;
+    std::string s;
     strprintf(&s, "<DelTariff Result=\"Error. Tariff \'%s\' cannot be deleted. Tariff in use.\"/>", tariffToDel.c_str());
     answerList->push_back(s);
     return;
@@ -236,7 +236,7 @@ if (tariffs->Del(tariffToDel, currAdmin) == 0)
     }
 else
     {
-    string s;
+    std::string s;
     strprintf(&s, "<DelTariff Result=\"Error. %s\"/>", tariffs->GetStrError().c_str());
     answerList->push_back(s);
     }
@@ -246,7 +246,7 @@ else
 //  CHG TARIFF
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-int PARSER_CHG_TARIFF::ParseSlashedIntParams(int paramsNum, const string & s, int * params)
+int PARSER_CHG_TARIFF::ParseSlashedIntParams(int paramsNum, const std::string & s, int * params)
 {
 char * str = new char[s.size() + 1];
 char * p;
@@ -274,7 +274,7 @@ delete[] str;
 return 0;
 }
 //-----------------------------------------------------------------------------
-int PARSER_CHG_TARIFF::ParseSlashedDoubleParams(int paramsNum, const string & s, double * params)
+int PARSER_CHG_TARIFF::ParseSlashedDoubleParams(int paramsNum, const std::string & s, double * params)
 {
 char * str = new char[s.size() + 1];
 char * p;
@@ -319,7 +319,7 @@ if (depth == 1)
     }
 else
     {
-    string s;
+    std::string s;
 
     if (strcasecmp(el, "PriceDayA") == 0)
         {
@@ -493,7 +493,7 @@ if (!td.tariffConf.name.data().empty())
         }
     else
         {
-        string s;
+        std::string s;
         strprintf(&s, "<SetTariff Result=\"Change tariff error! %s\"/>", tariffs->GetStrError().c_str());
         answerList->push_back(s);
         return;
diff --git a/projects/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp b/projects/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp
new file mode 100644 (file)
index 0000000..72c3c6e
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "parser_user_info.h"
+
+#include "stg/user.h"
+#include "stg/common.h"
+
+#include <strings.h> // strcasecmp
+
+int PARSER_USER_INFO::ParseStart(void * /*data*/, const char *el, const char **attr)
+{
+login.clear();
+if (strcasecmp(el, "GetUserInfo") != 0)
+    return -1;
+
+if (!attr[0] || !attr[1] || strcasecmp(attr[0], "login") != 0)
+    return -1;
+
+login = attr[1];
+return 0;
+}
+
+int PARSER_USER_INFO::ParseEnd(void * /*data*/, const char *el)
+{
+if (strcasecmp(el, "GetUserInfo") != 0)
+    return -1;
+
+CreateAnswer();
+return 0;
+}
+
+void PARSER_USER_INFO::CreateAnswer()
+{
+answerList->clear();
+
+CONST_USER_PTR u;
+if (users->FindByName(login, &u))
+    {
+    answerList->push_back("<UserInfo result=\"error\"/>");
+    return;
+    }
+
+std::string s = "<UserInfo lastAuthTime=\"" + x2str(u->GetAuthorizedModificationTime()) + "\"" +
+                " lastDisconnectTime=\"" + x2str(u->GetConnectedModificationTime()) + "\"" +
+                " connected=\"" + (u->GetConnected() ? "true" : "false") + "\"" +
+                " lastDisconnectReason=\"" + u->GetLastDisconnectReason() + "\">";
+std::vector<std::string> list(u->GetAuthorizers());
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+    s += "<Auth name=\"" + *it + "\"/>";
+s += "</UserInfo>";
+answerList->push_back(s);
+}
diff --git a/projects/stargazer/plugins/configuration/sgconfig/parser_user_info.h b/projects/stargazer/plugins/configuration/sgconfig/parser_user_info.h
new file mode 100644 (file)
index 0000000..ccd1d94
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_PARSER_USER_INFO_H__
+#define __STG_PARSER_USER_INFO_H__
+
+#include "parser.h"
+
+#include <string>
+
+class PARSER_USER_INFO : public BASE_PARSER {
+public:
+    int ParseStart(void *data, const char *el, const char **attr);
+    int ParseEnd(void *data, const char *el);
+
+private:
+    std::string login;
+
+    void CreateAnswer();
+};
+
+#endif
index c0b7b325ba8659123ea9f4d2224ef6bf9cc71029..6ca2b3da41de956ebe9442c726c2b9e17b2f6e53 100644 (file)
 *
 *******************************************************************/
 
-#include <unistd.h> // close
+#include "configproto.h"
+
+#include "stg/blowfish.h"
 
 #include <cerrno>
 #include <csignal>
 #include <cstdio> // snprintf
 
-#include "stg/blowfish.h"
-#include "configproto.h"
+#include <unistd.h> // close
 
 #ifndef ENODATA
 // FreeBSD 4.* - suxx
@@ -57,7 +58,7 @@ enum
 //-----------------------------------------------------------------------------
 int CONFIGPROTO::Prepare()
 {
-list<string> ansList; //óÀÄÁ ÂÕÄÅÔ ÐÏÍÅÝÅΠÏÔ×ÅÔ ÄÌÑ ÍÅÎÅÄÖÅÒÁ ËÌÉÅÎÔÏ×
+std::list<std::string> ansList; //óÀÄÁ ÂÕÄÅÔ ÐÏÍÅÝÅΠÏÔ×ÅÔ ÄÌÑ ÍÅÎÅÄÖÅÒÁ ËÌÉÅÎÔÏ×
 int res;
 struct sockaddr_in listenAddr;
 
@@ -74,6 +75,7 @@ listenSocket = socket(PF_INET, SOCK_STREAM, 0);
 if (listenSocket < 0)
     {
     errorStr = "Create NET_CONFIGURATOR socket failed.";
+    logger("Cannot create a socket: %s", strerror(errno));
     return -1;
     }
 
@@ -85,7 +87,8 @@ int lng = 1;
 
 if (0 != setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4))
     {
-    errorStr = "Setsockopt failed. " + string(strerror(errno));
+    errorStr = "Setsockopt failed. " + std::string(strerror(errno));
+    logger("setsockopt error: %s", strerror(errno));
     return -1;
     }
 
@@ -94,6 +97,7 @@ res = bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr));
 if (res == -1)
     {
     errorStr = "Bind admin socket failed";
+    logger("Cannot bind the socket: %s", strerror(errno));
     return -1;
     }
 
@@ -101,6 +105,7 @@ res = listen(listenSocket, 0);
 if (res == -1)
     {
     errorStr = "Listen admin socket failed";
+    logger("Cannot listen the socket: %s", strerror(errno));
     return -1;
     }
 
@@ -143,20 +148,17 @@ while (nonstop)
                              &outerAddrLen);
 
     if (!nonstop)
-        {
         break;
-        }
 
-    if (outerSocket == -1)
+    if (outerSocket < 0)
         {
+        logger("accept error: %s", strerror(errno));
         printfd(__FILE__, "accept failed\n");
         continue;
         }
 
     adminIP = *(unsigned int*)&(outerAddr.sin_addr);
 
-    printfd(__FILE__, "Connection accepted from %s\n", inet_ntostring(outerAddr.sin_addr.s_addr).c_str());
-
     if (state == confHdr)
         {
         if (RecvHdr(outerSocket) < 0)
@@ -231,6 +233,7 @@ while (nonstop)
         {
         WriteLogAccessFailed(adminIP);
         }
+    printfd(__FILE__, "Successfull connection from %s\n", inet_ntostring(outerAddr.sin_addr.s_addr).c_str());
     close(outerSocket);
     }
 }
@@ -249,9 +252,11 @@ while (pos < stgHdrLen)
         SendError("Bad request");
         return -1;
         }
-    int ret = recv(sock, &buf[pos], stgHdrLen - pos, 0);
+    ssize_t ret = recv(sock, &buf[pos], static_cast<int>(stgHdrLen) - static_cast<int>(pos), 0);
     if (ret <= 0)
         {
+        if (ret < 0)
+            logger("recv error: %s", strerror(errno));
         state = confHdr;
         return -1;
         }
@@ -278,7 +283,7 @@ if (err)
     {
     if (send(sock, ERR_HEADER, sizeof(ERR_HEADER) - 1, 0) < 0)
         {
-        WriteServLog("send ERR_HEADER error in SendHdrAnswer.");
+        logger("send error: %s", strerror(errno));
         return -1;
         }
     }
@@ -286,7 +291,7 @@ else
     {
     if (send(sock, OK_HEADER, sizeof(OK_HEADER) - 1, 0) < 0)
         {
-        WriteServLog("send OK_HEADER error in SendHdrAnswer.");
+        logger("send error: %s", strerror(errno));
         return -1;
         }
     }
@@ -308,11 +313,12 @@ while (pos < ADM_LOGIN_LEN) {
         return ENODATA;
         }
 
-    int ret = recv(sock, &login[pos], ADM_LOGIN_LEN - pos, 0);
+    ssize_t ret = recv(sock, &login[pos], ADM_LOGIN_LEN - static_cast<int>(pos), 0);
 
     if (ret <= 0)
         {
         // Error in network
+        logger("recv error: %s", strerror(errno));
         state = confHdr;
         return ENODATA;
         }
@@ -337,7 +343,7 @@ int CONFIGPROTO::SendLoginAnswer(int sock)
 {
 if (send(sock, OK_LOGIN, sizeof(OK_LOGIN) - 1, 0) < 0)
     {
-    WriteServLog("Send OK_LOGIN error in SendLoginAnswer.");
+    logger("Send OK_LOGIN error in SendLoginAnswer.");
     return -1;
     }
 return 0;
@@ -357,12 +363,13 @@ while (pos < ADM_LOGIN_LEN)
         return ENODATA;
         }
 
-    int ret = recv(sock, &loginS[pos], ADM_LOGIN_LEN - pos, 0);
+    ssize_t ret = recv(sock, &loginS[pos], ADM_LOGIN_LEN - static_cast<int>(pos), 0);
 
     if (ret <= 0)
         {
         // Network error
         printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
+        logger("recv error: %s", strerror(errno));
         state = confHdr;
         return ENODATA;
         }
@@ -381,9 +388,7 @@ EnDecodeInit(currAdmin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
 
 char login[ADM_LOGIN_LEN + 1];
 for (size_t i = 0; i < ADM_LOGIN_LEN / 8; i++)
-    {
     DecodeString(login + i * 8, loginS + i * 8, &ctx);
-    }
 
 if (currAdmin == admins->GetNoAdmin())
     {
@@ -399,6 +404,7 @@ if (strncmp(currAdmin->GetLogin().c_str(), login, ADM_LOGIN_LEN) != 0)
     }
 
 state = confData;
+adminPassword = currAdmin->GetPassword();
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -408,7 +414,7 @@ if (err)
     {
     if (send(sock, ERR_LOGINS, sizeof(ERR_LOGINS) - 1, 0) < 0)
         {
-        WriteServLog("send ERR_LOGIN error in SendLoginAnswer.");
+        logger("send error: %s", strerror(errno));
         return -1;
         }
     }
@@ -416,7 +422,7 @@ else
     {
     if (send(sock, OK_LOGINS, sizeof(OK_LOGINS) - 1, 0) < 0)
         {
-        WriteServLog("send OK_LOGINS error in SendLoginSAnswer.");
+        logger("send error: %s", strerror(errno));
         return -1;
         }
     }
@@ -443,10 +449,11 @@ while (1)
             break;
             }
 
-        int ret = recv(sock, &bufferS[pos], sizeof(bufferS) - pos, 0);
+        ssize_t ret = recv(sock, &bufferS[pos], sizeof(bufferS) - static_cast<int>(pos), 0);
         if (ret < 0)
             {
             // Network error
+            logger("recv error: %s", strerror(errno));
             printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
             return -1;
             }
@@ -476,12 +483,12 @@ while (1)
         return SendDataAnswer(sock);
         }
     }
-return 0;
+//return 0;
 }
 //-----------------------------------------------------------------------------
 int CONFIGPROTO::SendDataAnswer(int sock)
 {
-list<string>::iterator li;
+std::list<std::string>::iterator li;
 li = answerList.begin();
 
 BLOWFISH_CTX ctx;
@@ -491,7 +498,7 @@ char buffS[8];
 int n = 0;
 int k = 0;
 
-EnDecodeInit(currAdmin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
+EnDecodeInit(adminPassword.c_str(), ADM_PASSWD_LEN, &ctx);
 
 while (li != answerList.end())
     {
@@ -504,11 +511,8 @@ while (li != answerList.end())
         if (n % 8 == 0)
             {
             EncodeString(buffS, buff, &ctx);
-            int ret = send(sock, buffS, 8, 0);
-            if (ret < 0)
-                {
+            if (send(sock, buffS, 8, 0) < 0)
                 return -1;
-                }
             }
         }
     k = 0;// new node
@@ -524,7 +528,7 @@ EncodeString(buffS, buff, &ctx);
 
 answerList.clear();
 
-return send(sock, buffS, 8, 0);
+return static_cast<int>(send(sock, buffS, 8, 0));
 }
 //-----------------------------------------------------------------------------
 void CONFIGPROTO::SendError(const char * text)
@@ -537,6 +541,6 @@ answerList.push_back(s);
 //-----------------------------------------------------------------------------
 void CONFIGPROTO::WriteLogAccessFailed(uint32_t ip)
 {
-WriteServLog("Admin's connect failed. IP %s", inet_ntostring(ip).c_str());
+logger("Admin's connection failed. IP %s", inet_ntostring(ip).c_str());
 }
 //-----------------------------------------------------------------------------
index ea71a117b7bb925c1e753d00cf3665d5aea1c962..06381144944a8d04abbcb53d2fab44a8cdadcb99 100644 (file)
@@ -12,7 +12,7 @@
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-PLUGIN_CREATOR<STG_CONFIG> stgc;
+static PLUGIN_CREATOR<STG_CONFIG> stgc;
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -20,7 +20,7 @@ int STG_CONFIG_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
 {
 int p;
 PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 ///////////////////////////
 pv.param = "Port";
 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -36,7 +36,7 @@ if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
     printfd(__FILE__, "%s\n", errorStr.c_str());
     return -1;
     }
-port = p;
+port = static_cast<uint16_t>(p);
 
 return 0;
 }
@@ -50,7 +50,7 @@ return stgc.GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-const std::string STG_CONFIG::GetVersion() const
+std::string STG_CONFIG::GetVersion() const
 {
 return "Stg configurator v.0.08";
 }
@@ -61,7 +61,8 @@ STG_CONFIG::STG_CONFIG()
       thread(),
       nonstop(false),
       isRunning(false),
-      config(),
+      logger(GetPluginLogger(GetStgLogger(), "conf_sg")),
+      config(logger),
       users(NULL),
       admins(NULL),
       tariffs(NULL),
@@ -103,6 +104,7 @@ if (pthread_create(&thread, NULL, Run, this))
     {
     errorStr = "Cannot create thread.";
     printfd(__FILE__, "Cannot create thread\n");
+    logger("Cannot create thread.");
     return -1;
     }
 errorStr = "";
index cdce9668bf6931c34ecbdf622b31cbf678e3ff28..8fa4dc7691abd3584242c306f403c451b9e3f131 100644 (file)
@@ -7,6 +7,7 @@
 
 #include "stg/plugin.h"
 #include "stg/store.h"
+#include "stg/logger.h"
 #include "configproto.h"
 
 extern "C" PLUGIN * GetPlugin();
@@ -22,13 +23,13 @@ public:
     uint16_t        GetPort() const { return port; }
 private:
     std::string errorStr;
-    int     port;
+    uint16_t    port;
 };
 //-----------------------------------------------------------------------------
 class STG_CONFIG :public PLUGIN {
 public:
     STG_CONFIG();
-    virtual ~STG_CONFIG(){};
+    virtual ~STG_CONFIG(){}
 
     void                SetUsers(USERS * u) { users = u; }
     void                SetTariffs(TARIFFS * t) { tariffs = t; }
@@ -44,7 +45,7 @@ public:
     bool                IsRunning() { return isRunning; }
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const;
+    std::string         GetVersion() const;
     uint16_t            GetStartPosition() const { return 20; }
     uint16_t            GetStopPosition() const { return 20; }
 
@@ -59,6 +60,7 @@ private:
     pthread_t           thread;
     bool                nonstop;
     bool                isRunning;
+    PLUGIN_LOGGER       logger;
     CONFIGPROTO         config;
     USERS *             users;
     ADMINS *            admins;
index f0868e1225d21bd5a333094c412e9e4856d75861..7c4050abb035d9f55108ed306b02d5b51e869a3d 100644 (file)
 #include "stg/plugin_creator.h"
 #include "ping.h"
 
-PLUGIN_CREATOR<PING> pc;
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+namespace
 {
-return pc.GetPlugin();
-}
+PLUGIN_CREATOR<PING> pc;
+
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 // ëÌÁÓÓ ÄÌÑ ÐÏÉÓËÁ ÀÚÅÒÁ × ÓÐÉÓËÅ ÎÏÔÉÆÉËÁÔÏÒÏ×
 template <typename varType>
-class IS_CONTAINS_USER: public binary_function<varType, USER_PTR, bool>
+class IS_CONTAINS_USER: public std::binary_function<varType, USER_PTR, bool>
 {
 public:
     IS_CONTAINS_USER(const USER_PTR & u) : user(u) {}
     bool operator()(varType notifier) const
         {
         return notifier.GetUser() == user;
-        };
+        }
 private:
     const USER_PTR & user;
 };
+}
+
+extern "C" PLUGIN * GetPlugin();
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+PLUGIN * GetPlugin()
+{
+return pc.GetPlugin();
+}
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 int PING_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
 {
 PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 
 pv.param = "PingDelay";
 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -74,7 +80,8 @@ PING::PING()
       ChgCurrIPNotifierList(),
       ChgIPNotifierList(),
       onAddUserNotifier(*this),
-      onDelUserNotifier(*this)
+      onDelUserNotifier(*this),
+      logger(GetPluginLogger(GetStgLogger(), "ping"))
 {
 pthread_mutex_init(&mutex, NULL);
 }
@@ -107,6 +114,7 @@ pinger.Start();
 if (pthread_create(&thread, NULL, Run, this))
     {
     errorStr = "Cannot start thread.";
+    logger("Cannot create thread.");
     printfd(__FILE__, "Cannot start thread\n");
     return -1;
     }
@@ -136,7 +144,7 @@ for (int i = 0; i < 25; i++)
 users->DelNotifierUserAdd(&onAddUserNotifier);
 users->DelNotifierUserDel(&onDelUserNotifier);
 
-list<USER_PTR>::iterator users_iter;
+std::list<USER_PTR>::iterator users_iter;
 users_iter = usersList.begin();
 while (users_iter != usersList.end())
     {
@@ -168,7 +176,7 @@ long delay = (10000000 * ping->pingSettings.GetPingDelay()) / 3 + 50000000;
  
 while (ping->nonstop)
     {
-    list<USER_PTR>::iterator iter = ping->usersList.begin();
+    std::list<USER_PTR>::iterator iter = ping->usersList.begin();
         {
         STG_LOCKER lock(&ping->mutex, __FILE__, __LINE__);
         while (iter != ping->usersList.end())
@@ -231,8 +239,8 @@ void PING::UnSetUserNotifiers(USER_PTR u)
 IS_CONTAINS_USER<CHG_CURRIP_NOTIFIER_PING> IsContainsUserCurrIP(u);
 IS_CONTAINS_USER<CHG_IPS_NOTIFIER_PING> IsContainsUserIP(u);
 
-list<CHG_CURRIP_NOTIFIER_PING>::iterator currIPter;
-list<CHG_IPS_NOTIFIER_PING>::iterator IPIter;
+std::list<CHG_CURRIP_NOTIFIER_PING>::iterator currIPter;
+std::list<CHG_IPS_NOTIFIER_PING>::iterator IPIter;
 
 currIPter = find_if(ChgCurrIPNotifierList.begin(),
                     ChgCurrIPNotifierList.end(),
@@ -301,7 +309,7 @@ STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 UnSetUserNotifiers(u);
 
-list<USER_PTR>::iterator users_iter;
+std::list<USER_PTR>::iterator users_iter;
 users_iter = usersList.begin();
 
 while (users_iter != usersList.end())
index 6c31eb9589facd72454d132b07fc027b7bc9d456..29e4974ef4be2779c286ff36dfd82dcc2661e328 100644 (file)
@@ -19,6 +19,7 @@
 #include "stg/user_ips.h"
 #include "stg/pinger.h"
 #include "stg/users.h"
+#include "stg/logger.h"
 
 extern "C" PLUGIN * GetPlugin();
 
@@ -115,7 +116,7 @@ public:
     bool IsRunning();
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string GetVersion() const { return "Pinger v.1.01"; }
+    std::string GetVersion() const { return "Pinger v.1.01"; }
     uint16_t GetStartPosition() const { return 10; }
     uint16_t GetStopPosition() const { return 10; }
 
@@ -148,6 +149,8 @@ private:
 
     ADD_USER_NONIFIER_PING onAddUserNotifier;
     DEL_USER_NONIFIER_PING onDelUserNotifier;
+
+    PLUGIN_LOGGER logger;
 };
 //-----------------------------------------------------------------------------
 
index 480e6f16252aaab31d279a02e5e0ce43971294cf..90ec1891ea7c0602f9dfa24b9f568a259cc3afe3 100644 (file)
 #include "stg/plugin_creator.h"
 #include "radius.h"
 
-extern volatile const time_t stgTime;
-
-void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
+extern volatile time_t stgTime;
 
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<RADIUS> radc;
+
+void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8);
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8);
+}
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -89,7 +93,7 @@ if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
     return -1;
     }
-port = p;
+port = static_cast<uint16_t>(p);
 ///////////////////////////
 pv.param = "Password";
 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -136,7 +140,8 @@ RADIUS::RADIUS()
       thread(),
       mutex(),
       sock(-1),
-      packet()
+      packet(),
+      logger(GetPluginLogger(GetStgLogger(), "radius"))
 {
 InitEncrypt(&ctx, "");
 }
@@ -156,6 +161,7 @@ sock = socket(AF_INET, SOCK_DGRAM, 0);
 if (sock < 0)
     {
     errorStr = "Cannot create socket.";
+    logger("Cannot create a socket: %s", strerror(errno));
     printfd(__FILE__, "Cannot create socket\n");
     return -1;
     }
@@ -168,6 +174,7 @@ inAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
 if (bind(sock, (struct sockaddr*)&inAddr, sizeof(inAddr)) < 0)
     {
     errorStr = "RADIUS: Bind failed.";
+    logger("Cannot bind the socket: %s", strerror(errno));
     printfd(__FILE__, "Cannot bind socket\n");
     return -1;
     }
@@ -202,6 +209,7 @@ if (!isRunning)
     if (pthread_create(&thread, NULL, Run, this))
         {
         errorStr = "Cannot create thread.";
+       logger("Cannot create thread.");
         printfd(__FILE__, "Cannot create thread\n");
         return -1;
         }
@@ -288,25 +296,36 @@ int RADIUS::RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr)
 {
     int8_t buf[RAD_MAX_PACKET_LEN];
     socklen_t outerAddrLen = sizeof(struct sockaddr_in);
-    int dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast<struct sockaddr *>(outerAddr), &outerAddrLen);
-    if (dataLen > 0) {
-        Decrypt(&ctx, (char *)packet, (const char *)buf, dataLen / 8);
-    }
+    ssize_t dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast<struct sockaddr *>(outerAddr), &outerAddrLen);
+    if (dataLen < 0)
+       {
+       logger("recvfrom error: %s", strerror(errno));
+       return -1;
+       }
+    if (dataLen == 0)
+       return -1;
+
+    Decrypt(&ctx, (char *)packet, (const char *)buf, dataLen / 8);
+
     if (strncmp((char *)packet->magic, RAD_ID, RAD_MAGIC_LEN))
         {
         printfd(__FILE__, "RADIUS::RecvData Error magic. Wanted: '%s', got: '%s'\n", RAD_ID, packet->magic);
         return -1;
         }
+
     return 0;
 }
 //-----------------------------------------------------------------------------
-int RADIUS::Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr)
+ssize_t RADIUS::Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr)
 {
 size_t len = sizeof(RAD_PACKET);
 char buf[1032];
 
 Encrypt(&ctx, buf, (char *)&packet, len / 8);
-return sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
+ssize_t res = sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
+if (res < 0)
+    logger("sendto error: %s", strerror(errno));
+return res;
 }
 //-----------------------------------------------------------------------------
 int RADIUS::ProcessData(RAD_PACKET * packet)
@@ -336,7 +355,6 @@ switch (packet->packetType)
         printfd(__FILE__, "RADIUS::ProcessData Unsupported packet type: %d\n", packet->packetType);
         return -1;
     };
-return 0;
 }
 //-----------------------------------------------------------------------------
 int RADIUS::ProcessAutzPacket(RAD_PACKET * packet)
@@ -553,6 +571,9 @@ bool RADIUS::IsAllowedService(const std::string & svc) const
 return CanAuthService(svc) || CanAcctService(svc);
 }
 //-----------------------------------------------------------------------------
+namespace
+{
+
 inline
 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
 {
@@ -563,23 +584,25 @@ Blowfish_Init(ctx, keyL, RAD_PASSWORD_LEN);
 }
 //-----------------------------------------------------------------------------
 inline
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8)
 {
 // len8 - длина в 8-ми байтовых блоках
 if (dst != src)
     memcpy(dst, src, len8 * 8);
 
-for (int i = 0; i < len8; i++)
-    Blowfish_Encrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
+for (size_t i = 0; i < len8; i++)
+    Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
 }
 //-----------------------------------------------------------------------------
 inline
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8)
 {
 // len8 - длина в 8-ми байтовых блоках
 if (dst != src)
     memcpy(dst, src, len8 * 8);
 
-for (int i = 0; i < len8; i++)
-    Blowfish_Decrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
+for (size_t i = 0; i < len8; i++)
+    Blowfish_Decrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
 }
+
+} // namespace anonymous
index 92cfcab2d157dd16f007b5c7fbf497034b261ea1..c424c007dcefe0958bc3cebef0cc2c2b9f64dcd4 100644 (file)
@@ -47,6 +47,7 @@
 #include "stg/users.h"
 #include "stg/blowfish.h"
 #include "stg/rad_packets.h"
+#include "stg/logger.h"
 
 extern "C" PLUGIN * GetPlugin();
 
@@ -61,12 +62,12 @@ public:
           authServices(), acctServices()
     {}
     virtual ~RAD_SETTINGS() {}
-    const string & GetStrError() const { return errorStr; }
+    const std::string & GetStrError() const { return errorStr; }
     int ParseSettings(const MODULE_SETTINGS & s);
     uint16_t GetPort() const { return port; }
     const std::string & GetPassword() const { return password; }
-    const std::list<string> & GetAuthServices() const { return authServices; }
-    const std::list<string> & GetAcctServices() const { return acctServices; }
+    const std::list<std::string> & GetAuthServices() const { return authServices; }
+    const std::list<std::string> & GetAcctServices() const { return acctServices; }
 
 private:
     int ParseServices(const std::vector<std::string> & str, std::list<std::string> * lst);
@@ -101,7 +102,7 @@ public:
     bool                IsRunning() { return isRunning; }
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const { return "RADIUS data access plugin v 0.6"; }
+    std::string         GetVersion() const { return "RADIUS data access plugin v 0.6"; }
     uint16_t            GetStartPosition() const { return 30; }
     uint16_t            GetStopPosition() const { return 30; }
 
@@ -115,7 +116,7 @@ private:
     int                 PrepareNet();
     int                 FinalizeNet();
 
-    int                 Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr);
+    ssize_t             Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr);
     int                 RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr);
     int                 ProcessData(RAD_PACKET * packet);
 
@@ -134,19 +135,19 @@ private:
 
     void                PrintServices(const std::list<std::string> & svcs);
 
-    struct Printer : public unary_function<std::string, void>
+    struct Printer : public std::unary_function<std::string, void>
     { 
         void operator()(const std::string & line)
         { 
             printfd("radius.cpp", "'%s'\n", line.c_str()); 
-        }; 
+        } 
     };
-    struct SPrinter : public unary_function<std::pair<std::string, RAD_SESSION>, void>
+    struct SPrinter : public std::unary_function<std::pair<std::string, RAD_SESSION>, void>
     { 
         void operator()(const std::pair<std::string, RAD_SESSION> & it)
         { 
             printfd("radius.cpp", "%s - ('%s', '%s')\n", it.first.c_str(), it.second.userName.c_str(), it.second.serviceType.c_str()); 
-        }; 
+        } 
     };
 
     BLOWFISH_CTX        ctx;
@@ -172,6 +173,7 @@ private:
 
     RAD_PACKET          packet;
 
+    PLUGIN_LOGGER       logger;
 };
 //-----------------------------------------------------------------------------
 
index e7cb44c2988640710d756c6a7ee0a7622a2cdfe1..240ce349b6d12a0d74e66e876b99122db3e90f21 100644 (file)
@@ -60,8 +60,8 @@ public:
     ~NRMapParser() {}
 
     bool ReadFile(const std::string & fileName);
-    const std::vector<NET_ROUTER> & GetMap() const { return nrmap; };
-    const std::string & GetErrorStr() const { return errorStr; };
+    const std::vector<NET_ROUTER> & GetMap() const { return nrmap; }
+    const std::string & GetErrorStr() const { return errorStr; }
 
 private:
     NRMapParser(const NRMapParser & rvalue);
index 3a557a3088a1ec7c32b48260a5dfa1db1564b5bb..3bc90792276152606e274fb5258b2554ff956198 100644 (file)
  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
  */
 
-/*
- $Revision: 1.33 $
- $Date: 2010/04/16 12:30:37 $
- $Author: faust $
-*/
-
 #include <sys/time.h>
 
 #include <csignal>
 #include <cassert>
 #include <cstdlib>
+#include <cerrno>
+#include <cstring>
 #include <algorithm>
 
 #include "stg/common.h"
 #include "stg/locker.h"
+#include "stg/users.h"
 #include "stg/user_property.h"
 #include "stg/plugin_creator.h"
+#include "stg/logger.h"
 #include "rscript.h"
 #include "ur_functor.h"
 #include "send_functor.h"
 
-extern volatile const time_t stgTime;
+extern volatile time_t stgTime;
+
+using RS::REMOTE_SCRIPT;
+
+namespace {
+
+template<typename T>
+struct USER_IS
+{
+    USER_IS(USER_PTR u) : user(u) {}
+    bool operator()(const T & notifier) { return notifier.GetUser() == user; }
+
+    USER_PTR user;
+};
+
+PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
 
-#define RS_MAX_ROUTERS  (100)
+} // namespace anonymous
 
+extern "C" PLUGIN * GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -58,16 +71,7 @@ return rsc.GetPlugin();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-RS_USER & RS_USER::operator=(const RS_USER & rvalue)
-{
-lastSentTime = rvalue.lastSentTime;
-user = rvalue.user;
-routers = rvalue.routers;
-shortPacketsCount = rvalue.shortPacketsCount;
-return *this;
-}
-//-----------------------------------------------------------------------------
-RS_SETTINGS::RS_SETTINGS()
+RS::SETTINGS::SETTINGS()
     : sendPeriod(0),
       port(0),
       errorStr(),
@@ -78,11 +82,11 @@ RS_SETTINGS::RS_SETTINGS()
 {
 }
 //-----------------------------------------------------------------------------
-int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
+int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
 {
 int p;
 PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 netRouters.clear();
 ///////////////////////////
 pv.param = "Port";
@@ -99,7 +103,7 @@ if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
     return -1;
     }
-port = p;
+port = static_cast<uint16_t>(p);
 ///////////////////////////
 pv.param = "SendPeriod";
 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -149,13 +153,14 @@ subnetFile = pvi->value[0];
 
 NRMapParser nrMapParser;
 
-if (nrMapParser.ReadFile(subnetFile))
+if (!nrMapParser.ReadFile(subnetFile))
     {
-    errorStr = nrMapParser.GetErrorStr();
-    return -1;
+    netRouters = nrMapParser.GetMap();
+    }
+else
+    {
+    GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
     }
-
-netRouters = nrMapParser.GetMap();
 
 return 0;
 }
@@ -164,7 +169,8 @@ return 0;
 //-----------------------------------------------------------------------------
 REMOTE_SCRIPT::REMOTE_SCRIPT()
     : ctx(),
-      afterChgIPNotifierList(),
+      ipNotifierList(),
+      connNotifierList(),
       authorizedUsers(),
       errorStr(),
       rsSettings(),
@@ -179,7 +185,8 @@ REMOTE_SCRIPT::REMOTE_SCRIPT()
       mutex(),
       sock(0),
       onAddUserNotifier(*this),
-      onDelUserNotifier(*this)
+      onDelUserNotifier(*this),
+      logger(GetPluginLogger(GetStgLogger(), "rscript"))
 {
 pthread_mutex_init(&mutex, NULL);
 }
@@ -227,9 +234,6 @@ netRouters = rsSettings.GetSubnetsMap();
 
 InitEncrypt(&ctx, rsSettings.GetPassword());
 
-//onAddUserNotifier.SetRemoteScript(this);
-//onDelUserNotifier.SetRemoteScript(this);
-
 users->AddNotifierUserAdd(&onAddUserNotifier);
 users->AddNotifierUserDel(&onDelUserNotifier);
 
@@ -250,6 +254,7 @@ if (!isRunning)
     if (pthread_create(&thread, NULL, Run, this))
         {
         errorStr = "Cannot create thread.";
+       logger("Cannot create thread.");
         printfd(__FILE__, "Cannot create thread\n");
         return -1;
         }
@@ -288,7 +293,10 @@ users->DelNotifierUserDel(&onDelUserNotifier);
 users->DelNotifierUserAdd(&onAddUserNotifier);
 
 if (isRunning)
+    {
+    logger("Cannot stop thread.");
     return -1;
+    }
 
 return 0;
 }
@@ -300,6 +308,7 @@ NRMapParser nrMapParser;
 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
     {
     errorStr = nrMapParser.GetErrorStr();
+    logger("Map file reading error: %s", errorStr.c_str());
     return -1;
     }
 
@@ -315,6 +324,9 @@ std::for_each(authorizedUsers.begin(),
               authorizedUsers.end(),
               UpdateRouter(*this));
 
+logger("%s reloaded successfully.", rsSettings.GetMapFileName().c_str());
+printfd(__FILE__, "REMOTE_SCRIPT::Reload() %s reloaded successfully.\n");
+
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -325,6 +337,7 @@ sock = socket(AF_INET, SOCK_DGRAM, 0);
 if (sock < 0)
     {
     errorStr = "Cannot create socket.";
+    logger("Canot create a socket: %s", strerror(errno));
     printfd(__FILE__, "Cannot create socket\n");
     return true;
     }
@@ -342,25 +355,24 @@ void REMOTE_SCRIPT::PeriodicSend()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
+std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
 while (it != authorizedUsers.end())
     {
     if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
-    //if (stgTime - it->second.lastSentTime > sendPeriod)
         {
-        Send(it->first, it->second);
+        Send(it->second);
         }
     ++it;
     }
 }
 //-----------------------------------------------------------------------------
 #ifdef NDEBUG
-bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
+bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
 #else
-bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
+bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
 #endif
 {
-RS_PACKET_HEADER packetHead;
+RS::PACKET_HEADER packetHead;
 
 memset(packetHead.padding, 0, sizeof(packetHead.padding));
 strcpy((char*)packetHead.magic, RS_ID);
@@ -369,6 +381,7 @@ packetHead.protoVer[1] = '2';
 if (forceDisconnect)
     {
     packetHead.packetType = RS_DISCONNECT_PACKET;
+    printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
     }
 else
     {
@@ -376,17 +389,25 @@ else
         {
         //SendLong
         packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
+        if (rsu.user->IsInetable())
+            printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
+        else
+            printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
         }
     else
         {
         //SendShort
         packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
+        if (rsu.user->IsInetable())
+            printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
+        else
+            printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
         }
     }
 rsu.shortPacketsCount++;
 rsu.lastSentTime = stgTime;
 
-packetHead.ip = htonl(ip);
+packetHead.ip = htonl(rsu.ip);
 packetHead.id = htonl(rsu.user->GetID());
 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
 packetHead.login[RS_LOGIN_LEN - 1] = 0;
@@ -398,11 +419,11 @@ if (packetHead.packetType == RS_ALIVE_PACKET)
     return false;
     }
 
-RS_PACKET_TAIL packetTail;
+RS::PACKET_TAIL packetTail;
 
 memset(packetTail.padding, 0, sizeof(packetTail.padding));
 strcpy((char*)packetTail.magic, RS_ID);
-vector<string>::const_iterator it;
+std::vector<std::string>::const_iterator it;
 std::string params;
 for(it = rsSettings.GetUserParams().begin();
     it != rsSettings.GetUserParams().end();
@@ -423,13 +444,13 @@ Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail)
 return false;
 }
 //-----------------------------------------------------------------------------
-bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
+bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
 {
 char buffer[RS_MAX_PACKET_LEN];
 
 memset(buffer, 0, sizeof(buffer));
 
-if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
+if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
     {
     printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
     return true;
@@ -438,17 +459,17 @@ if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
 std::for_each(
         rsu.routers.begin(),
         rsu.routers.end(),
-        PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
+        PacketSender(sock, buffer, sizeof(buffer), static_cast<uint16_t>(htons(rsSettings.GetPort())))
         );
 
 return false;
 }
 //-----------------------------------------------------------------------------
-bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
+bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
 {
 char buffer[RS_MAX_PACKET_LEN];
 
-if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
+if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
     {
     printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
     return true;
@@ -457,10 +478,13 @@ if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
 struct sockaddr_in sendAddr;
 
 sendAddr.sin_family = AF_INET;
-sendAddr.sin_port = htons(rsSettings.GetPort());
+sendAddr.sin_port = static_cast<uint16_t>(htons(rsSettings.GetPort()));
 sendAddr.sin_addr.s_addr = routerIP;
 
-int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
+ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
+
+if (res < 0)
+    logger("sendto error: %s", strerror(errno));
 
 return (res != sizeof(buffer));
 }
@@ -470,51 +494,17 @@ bool REMOTE_SCRIPT::GetUsers()
 USER_PTR u;
 
 int h = users->OpenSearch();
-if (!h)
-    {
-    errorStr = "users->OpenSearch() error.";
-    printfd(__FILE__, "OpenSearch() error\n");
-    return true;
-    }
+assert(h && "USERS::OpenSearch is always correct");
 
 while (!users->SearchNext(h, &u))
     {
-    SetUserNotifier(u);
+    SetUserNotifiers(u);
     }
 
 users->CloseSearch(h);
 return false;
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
-{
-/*
- * When ip changes process looks like:
- * old => 0, 0 => new
- *
- */
-if (newIP)
-    {
-    RS_USER rsu(IP2Routers(newIP), u);
-    Send(newIP, rsu);
-
-    STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    authorizedUsers[newIP] = rsu;
-    }
-else
-    {
-    STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    const map<uint32_t, RS_USER>::iterator it(
-            authorizedUsers.find(oldIP)
-            );
-    if (it != authorizedUsers.end())
-        {
-        Send(oldIP, it->second, true);
-        authorizedUsers.erase(it);
-        }
-    }
-}
-//-----------------------------------------------------------------------------
 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
@@ -528,9 +518,9 @@ for (size_t i = 0; i < netRouters.size(); ++i)
 return std::vector<uint32_t>();
 }
 //-----------------------------------------------------------------------------
-string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
+std::string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const std::string & paramName) const
 {
-string value = "";
+std::string value = "";
 if (strcasecmp(paramName.c_str(), "cash") == 0)
     strprintf(&value, "%f", u->GetProperty().cash.Get());
 else
@@ -608,44 +598,75 @@ else
 return value;
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
+void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u)
 {
-RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
-
-afterChgIPNotifierList.push_front(afterChgIPNotifier);
+ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u));
+connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u));
+}
+//-----------------------------------------------------------------------------
+void REMOTE_SCRIPT::UnSetUserNotifiers(USER_PTR u)
+{
+ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
+                                    ipNotifierList.end(),
+                                    USER_IS<IP_NOTIFIER>(u)),
+                     ipNotifierList.end());
+connNotifierList.erase(std::remove_if(connNotifierList.begin(),
+                                      connNotifierList.end(),
+                                      USER_IS<CONNECTED_NOTIFIER>(u)),
+                       connNotifierList.end());
 
-u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
+void REMOTE_SCRIPT::AddRSU(USER_PTR user)
 {
-list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator  ipAIter;
-std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
+RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
+Send(rsu);
 
-for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
+STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
+}
+//-----------------------------------------------------------------------------
+void REMOTE_SCRIPT::DelRSU(USER_PTR user)
+{
+STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
+while (it != authorizedUsers.end())
     {
-    if (ipAIter->GetUser() == u)
+    if (it->second.user == user)
         {
-        u->DelCurrIPAfterNotifier(&(*ipAIter));
-        toErase.push_back(ipAIter);
+        Send(it->second, true);
+        authorizedUsers.erase(it);
+        return;
         }
+    ++it;
     }
-
-std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
-
-for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
+/*const std::map<uint32_t, RS::USER>::iterator it(
+        authorizedUsers.find(user->GetCurrIP())
+        );
+if (it != authorizedUsers.end())
     {
-    afterChgIPNotifierList.erase(*eIter);
-    }
+    Send(it->second, true);
+    authorizedUsers.erase(it);
+    }*/
+}
+//-----------------------------------------------------------------------------
+void RS::IP_NOTIFIER::Notify(const uint32_t & /*oldValue*/, const uint32_t & newValue)
+{
+if (newValue)
+    rs.AddRSU(user);
+else
+    rs.DelRSU(user);
 }
 //-----------------------------------------------------------------------------
-template <typename varParamType>
-void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
+void RS::CONNECTED_NOTIFIER::Notify(const bool & /*oldValue*/, const bool & newValue)
 {
-rs.ChangedIP(user, oldValue, newValue);
+if (newValue)
+    rs.AddRSU(user);
+else
+    rs.DelRSU(user);
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
+void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const
 {
 unsigned char keyL[PASSWD_LEN];  // Пароль для шифровки
 memset(keyL, 0, PASSWD_LEN);
@@ -653,11 +674,11 @@ strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
 Blowfish_Init(ctx, keyL, PASSWD_LEN);
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
+void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const
 {
 if (dst != src)
     memcpy(dst, src, len8 * 8);
 for (size_t i = 0; i < len8; ++i)
-    Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
+    Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
 }
 //-----------------------------------------------------------------------------
index 794c4c2b82e8c28e0f6524cc3d3fa548e9c4e013..8d22b458c870d72fba63ea61f3f7651134389ca7 100644 (file)
  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
  */
 
-/*
- $Revision: 1.16 $
- $Date: 2010/09/10 06:43:59 $
- $Author: faust $
-*/
-
 #ifndef RSCRIPT_H
 #define RSCRIPT_H
 
 #include <pthread.h>
 
-#include <cstring>
 #include <string>
 #include <list>
 #include <map>
 #include <utility>
 
 #include "stg/plugin.h"
-#include "stg/store.h"
 #include "stg/module_settings.h"
 #include "stg/os_int.h"
 #include "stg/notifer.h"
-#include "stg/user_ips.h"
 #include "stg/user.h"
-#include "stg/users.h"
 #include "stg/blowfish.h"
 #include "stg/rs_packets.h"
+#include "stg/logger.h"
+
 #include "nrmap_parser.h"
 
 extern "C" PLUGIN * GetPlugin();
@@ -55,90 +47,117 @@ extern "C" PLUGIN * GetPlugin();
 
 #define MAX_SHORT_PCKT  (3)
 
-class REMOTE_SCRIPT;
 class SETTINGS;
+class USERS;
+
+namespace RS
+{
+
+class REMOTE_SCRIPT;
+class UpdateRouter;
+class DisconnectUser;
+
 //-----------------------------------------------------------------------------
-class RS_ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
+class ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
 public:
-    RS_ADD_USER_NONIFIER(REMOTE_SCRIPT & r)
+    ADD_USER_NONIFIER(REMOTE_SCRIPT & r)
         : NOTIFIER_BASE<USER_PTR>(), rs(r) {}
-    virtual ~RS_ADD_USER_NONIFIER() {}
+    virtual ~ADD_USER_NONIFIER() {}
     void Notify(const USER_PTR & user);
 
 private:
-    RS_ADD_USER_NONIFIER(const RS_ADD_USER_NONIFIER & rvalue);
-    RS_ADD_USER_NONIFIER & operator=(const RS_ADD_USER_NONIFIER);
+    ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rhs);
+    ADD_USER_NONIFIER & operator=(const ADD_USER_NONIFIER);
 
     REMOTE_SCRIPT & rs;
 };
 //-----------------------------------------------------------------------------
-class RS_DEL_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
+class DEL_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
 public:
-    RS_DEL_USER_NONIFIER(REMOTE_SCRIPT & r)
+    DEL_USER_NONIFIER(REMOTE_SCRIPT & r)
         : NOTIFIER_BASE<USER_PTR>(), rs(r) {}
-    virtual ~RS_DEL_USER_NONIFIER() {}
+    virtual ~DEL_USER_NONIFIER() {}
     void Notify(const USER_PTR & user);
 
 private:
-    RS_DEL_USER_NONIFIER(const RS_DEL_USER_NONIFIER & rvalue);
-    RS_DEL_USER_NONIFIER & operator=(const RS_DEL_USER_NONIFIER);
+    DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rhs);
+    DEL_USER_NONIFIER & operator=(const DEL_USER_NONIFIER);
 
     REMOTE_SCRIPT & rs;
 };
 //-----------------------------------------------------------------------------
-template <typename T>
-class RS_CHG_AFTER_NOTIFIER: public PROPERTY_NOTIFIER_BASE<T> {
+class IP_NOTIFIER: public PROPERTY_NOTIFIER_BASE<uint32_t> {
 public:
-    RS_CHG_AFTER_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
-        : PROPERTY_NOTIFIER_BASE<T>(), user(u), rs(r) {}
-    RS_CHG_AFTER_NOTIFIER(const RS_CHG_AFTER_NOTIFIER<T> & rvalue)
-        : PROPERTY_NOTIFIER_BASE<T>(), user(rvalue.user), rs(rvalue.rs) {}
-    void Notify(const T & oldValue, const T & newValue);
-    USER_PTR GetUser() { return user; }
+    IP_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
+        : PROPERTY_NOTIFIER_BASE<uint32_t>(), user(u), rs(r) { user->AddCurrIPAfterNotifier(this); }
+    IP_NOTIFIER(const IP_NOTIFIER & rhs)
+        : PROPERTY_NOTIFIER_BASE<uint32_t>(), user(rhs.user), rs(rhs.rs) { user->AddCurrIPAfterNotifier(this); }
+    ~IP_NOTIFIER() { user->DelCurrIPAfterNotifier(this); }
+
+    IP_NOTIFIER & operator=(const IP_NOTIFIER & rhs)
+    {
+        user->DelCurrIPAfterNotifier(this);
+        user = rhs.user;
+        user->AddCurrIPAfterNotifier(this);
+        return *this;
+    }
+
+    void Notify(const uint32_t & oldValue, const uint32_t & newValue);
+    USER_PTR GetUser() const { return user; }
 
 private:
-    RS_CHG_AFTER_NOTIFIER<T> & operator=(const RS_CHG_AFTER_NOTIFIER<T> & rvalue);
 
     USER_PTR user;
     REMOTE_SCRIPT & rs;
 };
 //-----------------------------------------------------------------------------
-struct RS_USER {
-    RS_USER()
-        : lastSentTime(0),
-          user(NULL),
-          routers(),
-          shortPacketsCount(0)
-    {}
-    RS_USER(const std::vector<uint32_t> & r, USER_PTR it)
-        : lastSentTime(0),
-          user(it),
+class CONNECTED_NOTIFIER: public PROPERTY_NOTIFIER_BASE<bool> {
+public:
+    CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
+        : PROPERTY_NOTIFIER_BASE<bool>(), user(u), rs(r) { user->AddConnectedAfterNotifier(this); }
+    CONNECTED_NOTIFIER(const CONNECTED_NOTIFIER & rhs)
+        : PROPERTY_NOTIFIER_BASE<bool>(), user(rhs.user), rs(rhs.rs) { user->AddConnectedAfterNotifier(this); }
+    ~CONNECTED_NOTIFIER() { user->DelConnectedAfterNotifier(this); }
+
+    CONNECTED_NOTIFIER & operator=(const CONNECTED_NOTIFIER & rhs)
+    {
+        user->DelConnectedAfterNotifier(this);
+        user = rhs.user;
+        user->AddConnectedAfterNotifier(this);
+        return *this;
+    }
+
+    void Notify(const bool & oldValue, const bool & newValue);
+    USER_PTR GetUser() const { return user; }
+
+private:
+
+    USER_PTR user;
+    REMOTE_SCRIPT & rs;
+};
+//-----------------------------------------------------------------------------
+struct USER {
+    USER(const std::vector<uint32_t> & r, USER_PTR it)
+        : user(it),
           routers(r),
-          shortPacketsCount(0)
-    {}
-    RS_USER(const RS_USER & rvalue)
-        : lastSentTime(rvalue.lastSentTime),
-          user(rvalue.user),
-          routers(rvalue.routers),
-          shortPacketsCount(rvalue.shortPacketsCount)
+          ip(user->GetCurrIP())
     {}
 
-    RS_USER & operator=(const RS_USER & rvalue);
-
     time_t lastSentTime;
     USER_PTR user;
     std::vector<uint32_t> routers;
     int shortPacketsCount;
+    uint32_t ip;
 };
 //-----------------------------------------------------------------------------
-class RS_SETTINGS {
+class SETTINGS {
 public:
-                        RS_SETTINGS();
-    virtual             ~RS_SETTINGS() {}
+                        SETTINGS();
+    virtual             ~SETTINGS() {}
     const std::string & GetStrError() const { return errorStr; }
     int                 ParseSettings(const MODULE_SETTINGS & s);
     int                 GetSendPeriod() const { return sendPeriod; }
-    int                 GetPort() const { return port; }
+    uint16_t            GetPort() const { return port; }
     const std::vector<NET_ROUTER> & GetSubnetsMap() const { return netRouters; }
     const std::vector<std::string> & GetUserParams() const { return userParams; }
     const std::string & GetPassword() const { return password; }
@@ -147,11 +166,11 @@ public:
 private:
     int                 sendPeriod;
     uint16_t            port;
-    string              errorStr;
+    std::string         errorStr;
     std::vector<NET_ROUTER> netRouters;
-    std::vector<string> userParams;
-    string              password;
-    string              subnetFile;
+    std::vector<std::string> userParams;
+    std::string         password;
+    std::string         subnetFile;
 };
 //-----------------------------------------------------------------------------
 class REMOTE_SCRIPT : public PLUGIN {
@@ -169,45 +188,47 @@ public:
     bool                IsRunning() { return isRunning; }
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string   GetVersion() const { return "Remote script v 0.3"; }
+    std::string         GetVersion() const { return "Remote script v 0.3"; }
     uint16_t            GetStartPosition() const { return 10; }
     uint16_t            GetStopPosition() const { return 10; }
 
-    void                DelUser(USER_PTR u) { UnSetUserNotifier(u); }
-    void                AddUser(USER_PTR u) { SetUserNotifier(u); }
+    void                DelUser(USER_PTR u) { UnSetUserNotifiers(u); }
+    void                AddUser(USER_PTR u) { SetUserNotifiers(u); }
 
-    void                ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP);
+    void                AddRSU(USER_PTR user);
+    void                DelRSU(USER_PTR user);
 
 private:
-    REMOTE_SCRIPT(const REMOTE_SCRIPT & rvalue);
-    REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rvalue);
+    REMOTE_SCRIPT(const REMOTE_SCRIPT & rhs);
+    REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rhs);
 
     static void *       Run(void *);
     bool                PrepareNet();
     bool                FinalizeNet();
 
-    bool                Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect = false) const;
-    bool                SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect = false) const;
-    bool                PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER &rsu, bool forceDisconnect = false) const;
+    bool                Send(USER & rsu, bool forceDisconnect = false) const;
+    bool                SendDirect(USER & rsu, uint32_t routerIP, bool forceDisconnect = false) const;
+    bool                PreparePacket(char * buf, size_t bufSize, USER &rsu, bool forceDisconnect = false) const;
     void                PeriodicSend();
 
     std::vector<uint32_t> IP2Routers(uint32_t ip);
     bool                GetUsers();
     std::string         GetUserParam(USER_PTR u, const std::string & paramName) const;
 
-    void                SetUserNotifier(USER_PTR u);
-    void                UnSetUserNotifier(USER_PTR u);
+    void                SetUserNotifiers(USER_PTR u);
+    void                UnSetUserNotifiers(USER_PTR u);
 
-    void                InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const;
-    void                Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const;
+    void                InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const;
+    void                Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const;
 
     mutable BLOWFISH_CTX ctx;
 
-    std::list<RS_CHG_AFTER_NOTIFIER<uint32_t> > afterChgIPNotifierList;
-    std::map<uint32_t, RS_USER> authorizedUsers;
+    std::list<IP_NOTIFIER> ipNotifierList;
+    std::list<CONNECTED_NOTIFIER> connNotifierList;
+    std::map<uint32_t, USER> authorizedUsers;
 
     mutable std::string errorStr;
-    RS_SETTINGS         rsSettings;
+    SETTINGS         rsSettings;
     MODULE_SETTINGS     settings;
     int                 sendPeriod;
     int                 halfPeriod;
@@ -224,33 +245,38 @@ private:
 
     int                 sock;
 
-    RS_ADD_USER_NONIFIER onAddUserNotifier;
-    RS_DEL_USER_NONIFIER onDelUserNotifier;
+    ADD_USER_NONIFIER onAddUserNotifier;
+    DEL_USER_NONIFIER onDelUserNotifier;
 
-    friend class UpdateRouter;
-    friend class DisconnectUser;
+    PLUGIN_LOGGER       logger;
+
+    friend class RS::UpdateRouter;
+    friend class RS::DisconnectUser;
+    friend class RS::CONNECTED_NOTIFIER;
 };
 //-----------------------------------------------------------------------------
-class DisconnectUser : public std::unary_function<std::pair<const uint32_t, RS_USER> &, void> {
+class DisconnectUser : public std::unary_function<std::pair<const uint32_t, USER> &, void> {
     public:
         DisconnectUser(REMOTE_SCRIPT & rs) : rscript(rs) {}
-        void operator()(std::pair<const uint32_t, RS_USER> & p)
+        void operator()(std::pair<const uint32_t, USER> & p)
         {
-            rscript.Send(p.first, p.second, true);
+            rscript.Send(p.second, true);
         }
     private:
         REMOTE_SCRIPT & rscript;
 };
 //-----------------------------------------------------------------------------
-inline void RS_ADD_USER_NONIFIER::Notify(const USER_PTR & user)
+inline void ADD_USER_NONIFIER::Notify(const USER_PTR & user)
 {
 rs.AddUser(user);
 }
 //-----------------------------------------------------------------------------
-inline void RS_DEL_USER_NONIFIER::Notify(const USER_PTR & user)
+inline void DEL_USER_NONIFIER::Notify(const USER_PTR & user)
 {
 rs.DelUser(user);
 }
 //-----------------------------------------------------------------------------
 
+} // namespace RS
+
 #endif
index b9b789eaf1556ed034ae350b29b6479d96714b63..a14fe20b3e95cdf18ec602fc656d087974ab0654 100644 (file)
 
 #include "stg/os_int.h"
 
-class PacketSender : public std::unary_function<uint32_t, int> {
+class PacketSender : public std::unary_function<uint32_t, ssize_t> {
     public:
-        PacketSender(int s, char * b, int l, uint16_t p)
+        PacketSender(int s, char * b, size_t l, uint16_t p)
             : sock(s),
               buffer(b),
               length(l),
-              port(p) {};
-        int operator() (uint32_t ip)
+              port(p) {}
+        ssize_t operator() (uint32_t ip)
         {
         struct sockaddr_in sendAddr;
 
@@ -54,7 +54,7 @@ class PacketSender : public std::unary_function<uint32_t, int> {
     private:
         int sock;
         char * buffer;
-        int length;
+        size_t length;
         uint16_t port;
 };
 
index b3a5cdaca3889ca338da3985ff46905b58829b76..95382400f6403e945b3e05768ac40d718b3aece1 100644 (file)
  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
  */
 
-/*
- $Revision: 1.3 $
- $Date: 2010/03/04 12:07:03 $
- $Author: faust $
-*/
-
 #ifndef __UR_FUNCTOR_H__
 #define __UR_FUNCTOR_H__
 
 
 #include "rscript.h"
 
-class UpdateRouter : public std::unary_function<std::pair<const uint32_t, RS_USER>, void>
+namespace RS
+{
+
+class UpdateRouter : public std::unary_function<std::pair<const uint32_t, RS::USER>, void>
 {
 public:
     UpdateRouter(REMOTE_SCRIPT & t)
-        : obj(t) {};
+        : obj(t) {}
 
-    void operator() (std::pair<const uint32_t, RS_USER> & val)
+    void operator() (std::pair<const uint32_t, USER> & val)
         {
-        std::vector<uint32_t> newRouters = obj.IP2Routers(val.first);
+        std::vector<uint32_t> newRouters = obj.IP2Routers(val.second.ip);
         std::vector<uint32_t>::const_iterator oldIt(val.second.routers.begin());
         std::vector<uint32_t>::const_iterator newIt(newRouters.begin());
         val.second.shortPacketsCount = 0;
@@ -55,26 +52,23 @@ public:
                 {
                 if (newIt != newRouters.end())
                     {
-                    obj.SendDirect(val.first, val.second, *newIt); // Connect on new router
+                    obj.SendDirect(val.second, *newIt); // Connect on new router
                     ++newIt;
                     }
                 }
             else if (newIt == newRouters.end())
                 {
-                //if (oldIt != newRouters.end())
-                    //{ // Already checked it
-                    obj.SendDirect(val.first, val.second, *oldIt, true); // Disconnect on old router
-                    ++oldIt;
-                    //}
+                obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router
+                ++oldIt;
                 } 
             else if (*oldIt < *newIt)
                 {
-                obj.SendDirect(val.first, val.second, *oldIt, true); // Disconnect on old router
+                obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router
                 ++oldIt;
                 }
             else if (*oldIt > *newIt)
                 {
-                obj.SendDirect(val.first, val.second, *newIt); // Connect on new router
+                obj.SendDirect(val.second, *newIt); // Connect on new router
                 ++newIt;
                 }
             else
@@ -86,16 +80,11 @@ public:
                 }
             }
         val.second.routers = newRouters;
-        /*if (val.second.souters != newRouters)
-            {
-            obj.Send(val.first, val.second, true); // Disconnect on old router
-            val.second.routerIP = obj.IP2Router(val.first); // Change router
-            val.second.shortPacketsCount = 0; // Reset packets count (to prevent alive send)
-            obj.Send(val.first, val.second); // Connect on new router
-            }*/
         }
 private:
     REMOTE_SCRIPT & obj;
 };
 
+} // namespace RS
+
 #endif
index f1c94d11b2bc18023bc9b05c9ef264597dffc2ef..09cb4636795b1f72d567dc6274e2d74f788a2fad 100644 (file)
 #include "smux.h"
 #include "utils.h"
 
+namespace
+{
 PLUGIN_CREATOR<SMUX> smc;
 
-PLUGIN * GetPlugin()
-{
-return smc.GetPlugin();
-}
+bool SPrefixLess(const Sensors::value_type & a,
+                 const Sensors::value_type & b);
 
 bool SPrefixLess(const Sensors::value_type & a,
                  const Sensors::value_type & b)
@@ -33,6 +33,15 @@ bool SPrefixLess(const Sensors::value_type & a,
 return a.first.PrefixLess(b.first);
 }
 
+}
+
+extern "C" PLUGIN * GetPlugin();
+
+PLUGIN * GetPlugin()
+{
+return smc.GetPlugin();
+}
+
 SMUX_SETTINGS::SMUX_SETTINGS()
     : errorStr(),
       ip(0),
@@ -60,7 +69,7 @@ if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
     return -1;
     }
-port = p;
+port = static_cast<uint16_t>(p);
 
 pv.param = "Password";
 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -103,6 +112,9 @@ SMUX::SMUX()
       mutex(),
       running(false),
       stopped(true),
+      needReconnect(false),
+      lastReconnectTry(0),
+      reconnectTimeout(1),
       sock(-1),
       smuxHandlers(),
       pdusHandlers(),
@@ -111,7 +123,8 @@ SMUX::SMUX()
       notifiers(),
       addUserNotifier(*this),
       delUserNotifier(*this),
-      addDelTariffNotifier(*this)
+      addDelTariffNotifier(*this),
+      logger(GetPluginLogger(GetStgLogger(), "smux"))
 {
 pthread_mutex_init(&mutex, NULL);
 
@@ -156,7 +169,7 @@ assert(corporations != NULL && "corporations must not be NULL");
 assert(traffcounter != NULL && "traffcounter must not be NULL");
 
 if (PrepareNet())
-    return -1;
+    needReconnect = true;
 
 // Users
 sensors[OID(".1.3.6.1.4.1.38313.1.1.1")] = new TotalUsersSensor(*users);
@@ -204,6 +217,7 @@ if (!running)
     if (pthread_create(&thread, NULL, Runner, this))
         {
         errorStr = "Cannot create thread.";
+       logger("Cannot create thread.");
         printfd(__FILE__, "Cannot create thread\n");
         return -1;
         }
@@ -264,6 +278,11 @@ if (Stop())
     return -1;
 if (Start())
     return -1;
+if (!needReconnect)
+    {
+    printfd(__FILE__, "SMUX reconnected succesfully.\n");
+    logger("Reconnected successfully.");
+    }
 return 0;
 }
 
@@ -284,15 +303,15 @@ void SMUX::Run()
 {
 stopped = true;
 if (!SendOpenPDU(sock))
-    return;
+    needReconnect = true;
 if (!SendRReqPDU(sock))
-    return;
+    needReconnect = true;
 running = true;
 stopped = false;
 
 while(running)
     {
-    if (WaitPackets(sock))
+    if (WaitPackets(sock) && !needReconnect)
         {
         SMUX_PDUs_t * pdus = RecvSMUXPDUs(sock);
         if (pdus)
@@ -300,7 +319,11 @@ while(running)
             DispatchPDUs(pdus);
             ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
             }
+        else if (running)
+            Reconnect();
         }
+    else if (running && needReconnect)
+        Reconnect();
     if (!running)
         break;
     }
@@ -315,6 +338,7 @@ sock = socket(AF_INET, SOCK_STREAM, 0);
 if (sock < 0)
     {
     errorStr = "Cannot create socket.";
+    logger("Cannot create a socket: %s", strerror(errno));
     printfd(__FILE__, "Cannot create socket\n");
     return true;
     }
@@ -328,6 +352,7 @@ addr.sin_addr.s_addr = smuxSettings.GetIP();
 if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)))
     {
     errorStr = "Cannot connect.";
+    logger("Cannot connect the socket: %s", strerror(errno));
     printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno));
     return true;
     }
@@ -335,6 +360,33 @@ if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)))
 return false;
 }
 
+bool SMUX::Reconnect()
+{
+if (needReconnect && difftime(time(NULL), lastReconnectTry) < reconnectTimeout)
+    return true;
+
+time(&lastReconnectTry);
+SendClosePDU(sock);
+close(sock);
+if (!PrepareNet())
+    if (SendOpenPDU(sock))
+        if (SendRReqPDU(sock))
+            {
+            reconnectTimeout = 1;
+            needReconnect = false;
+            logger("Connected successfully");
+            printfd(__FILE__, "Connected successfully\n");
+            return false;
+            }
+
+if (needReconnect)
+    if (reconnectTimeout < 60)
+        reconnectTimeout *= 2;
+
+needReconnect = true;
+return true;
+}
+
 bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus)
 {
 SMUXHandlers::iterator it(smuxHandlers.find(pdus->present));
@@ -473,4 +525,5 @@ while (it != notifiers.end())
     it->GetUserPtr()->GetProperty().tariffName.DelAfterNotifier(&(*it));
     ++it;
     }
+notifiers.clear();
 }
index 24f7de32a384d9ede2cbc142e5303ef288e99d63..e379ea7f7f06261e4cfe64bc2612b83796c2c94b 100644 (file)
 #include "stg/module_settings.h"
 #include "stg/notifer.h"
 #include "stg/noncopyable.h"
+#include "stg/logger.h"
 
 #include "sensors.h"
 #include "tables.h"
 #include "types.h"
 
-extern "C" PLUGIN * GetPlugin();
-
 class USER;
 class SETTINGS;
 class SMUX;
@@ -65,7 +64,7 @@ public:
                    smux(rvalue.smux), userPtr(rvalue.userPtr) {}
     void     Notify(const std::string &, const std::string &);
 
-    USER_PTR GetUserPtr() { return userPtr; }
+    USER_PTR GetUserPtr() const { return userPtr; }
 
 private:
     CHG_AFTER_NOTIFIER & operator=(const CHG_AFTER_NOTIFIER & rvalue);
@@ -121,7 +120,7 @@ public:
     bool IsRunning() { return running && !stopped; }
 
     const std::string & GetStrError() const { return errorStr; }
-    const std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; }
+    std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; }
     uint16_t GetStartPosition() const { return 10; }
     uint16_t GetStopPosition() const { return 10; }
 
@@ -137,6 +136,7 @@ private:
     static void * Runner(void * d);
     void Run();
     bool PrepareNet();
+    bool Reconnect();
 
     bool DispatchPDUs(const SMUX_PDUs_t * pdus);
 
@@ -167,6 +167,10 @@ private:
     pthread_mutex_t mutex;
     bool running;
     bool stopped;
+    bool needReconnect;
+
+    time_t lastReconnectTry;
+    unsigned reconnectTimeout;
 
     int sock;
 
@@ -179,6 +183,8 @@ private:
     ADD_USER_NOTIFIER addUserNotifier;
     DEL_USER_NOTIFIER delUserNotifier;
     ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier;
+
+    PLUGIN_LOGGER logger;
 };
 //-----------------------------------------------------------------------------
 
@@ -208,6 +214,4 @@ smux.UnsetNotifier(userPtr);
 smux.UpdateTables();
 }
 
-extern "C" PLUGIN * GetPlugin();
-
 #endif
index 25b2dd85d8372b880bfa1be5e85f3b45ccafbede..c3e3ef54c48d870fee774d16ac11e3420b8b67e2 100644 (file)
@@ -51,8 +51,8 @@ OID prefixOid(prefix);
 std::map<std::string, size_t>::const_iterator it(data.begin());
 while (it != data.end())
     {
-    sensors[prefixOid.copyWithSuffix(2, idx)] = new ConstSensor<std::string>(it->first);
-    sensors[prefixOid.copyWithSuffix(3, idx)] = new ConstSensor<int>(it->second);
+    sensors[prefixOid.copyWithSuffix(2, static_cast<unsigned int>(idx))] = new ConstSensor<std::string>(it->first);
+    sensors[prefixOid.copyWithSuffix(3, static_cast<unsigned int>(idx))] = new ConstSensor<unsigned long>(it->second);
     ++idx;
     ++it;
     }
index eb09a73ce5c91d1acc074b26cb1f00ac8b6474af..4e54749287110f740fa264db4590a63fd23028b9 100644 (file)
@@ -5,6 +5,13 @@
 
 #include "types.h"
 
+namespace
+{
+
+bool ParseArcs(const char * str, ptrdiff_t length, unsigned * a, size_t * pos);
+bool StringToArcs(const char * str, size_t length, std::vector<unsigned> & arcs);
+bool AppendToArcs(const char * str, size_t length, std::vector<unsigned> & arcs);
+
 bool ParseArcs(const char * str, ptrdiff_t length, unsigned * a, size_t * pos)
 {
 if (length == 0)
@@ -16,7 +23,7 @@ size_t arcPos = 0;
 while ((left - str) < length)
     {
     char * pos = NULL;
-    unsigned arc = strtoul(left, &pos, 10);
+    unsigned arc = static_cast<unsigned int>(strtoul(left, &pos, 10));
     if (pos == left)
         return false;
     a[arcPos++] = arc;
@@ -52,6 +59,8 @@ std::copy(&a[0], &a[pos], std::back_inserter(arcs));
 return true;
 }
 
+}
+
 OID::OID(const std::string & str)
     : arcs()
 {
@@ -182,7 +191,7 @@ return stream.str();
 
 void OID::ToOID(OBJECT_IDENTIFIER_t * oid) const
 {
-OBJECT_IDENTIFIER_set_arcs(oid, &arcs.front(), sizeof(unsigned), arcs.size());
+OBJECT_IDENTIFIER_set_arcs(oid, &arcs.front(), sizeof(unsigned), static_cast<unsigned int>(arcs.size()));
 }
 
 OID & OID::operator=(const OID & rvalue)
index 18e2bf3157fec9168c7fd92d9d114f7a6eb1d265..3160bc5fcf6c33b5bc1d6729c80fb74e2a8f3f21 100644 (file)
@@ -44,7 +44,7 @@ if (left < str.length())
         }
     arcs[arcPos++] = arc;
     }
-OBJECT_IDENTIFIER_set_arcs(oi, arcs, sizeof(arcs[0]), arcPos);
+OBJECT_IDENTIFIER_set_arcs(oi, arcs, sizeof(arcs[0]), static_cast<unsigned int>(arcPos));
 return true;
 }
 
index d17cb3574ba80579bd2d27351eaf5eb241c5f917..c069affdd328b9585103cbc4996f14b385e29ea8 100644 (file)
@@ -57,7 +57,7 @@ bool ValueToOS<std::string>(const std::string & value, ObjectSyntax * objectSynt
 objectSyntax->present = ObjectSyntax_PR_simple;
 SimpleSyntax_t * simpleSyntax = &objectSyntax->choice.simple;
 simpleSyntax->present = SimpleSyntax_PR_string;
-OCTET_STRING_fromBuf(&simpleSyntax->choice.string, value.c_str(), value.length());
+OCTET_STRING_fromBuf(&simpleSyntax->choice.string, value.c_str(), static_cast<int>(value.length()));
 return true;
 }
 
index fa0483a8894213944c1215a694c8eefb4fe82343..0466b82490c97bfd576a2e477a7d0514257ab388 100644 (file)
 
 #define adm_enc_passwd "cjeifY8m3"
 
-using namespace std;
-
-int GetFileList(vector<string> * fileList, const string & directory, mode_t mode, const string & ext);
+int GetFileList(std::vector<std::string> * fileList, const std::string & directory, mode_t mode, const std::string & ext);
 
 const int pt_mega = 1024 * 1024;
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+namespace
+{
 PLUGIN_CREATOR<FILES_STORE> fsc;
+}
+
+extern "C" STORE * GetStore();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -96,11 +99,11 @@ FILES_STORE_SETTINGS::FILES_STORE_SETTINGS()
 {
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseOwner(const vector<PARAM_VALUE> & moduleParams, const string & owner, uid_t * uid)
+int FILES_STORE_SETTINGS::ParseOwner(const std::vector<PARAM_VALUE> & moduleParams, const std::string & owner, uid_t * uid)
 {
 PARAM_VALUE pv;
 pv.param = owner;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
 if (pvi == moduleParams.end())
     {
@@ -117,11 +120,11 @@ if (User2UID(pvi->value[0].c_str(), uid) < 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseGroup(const vector<PARAM_VALUE> & moduleParams, const string & group, gid_t * gid)
+int FILES_STORE_SETTINGS::ParseGroup(const std::vector<PARAM_VALUE> & moduleParams, const std::string & group, gid_t * gid)
 {
 PARAM_VALUE pv;
 pv.param = group;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
 if (pvi == moduleParams.end())
     {
@@ -138,7 +141,7 @@ if (Group2GID(pvi->value[0].c_str(), gid) < 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseYesNo(const string & value, bool * val)
+int FILES_STORE_SETTINGS::ParseYesNo(const std::string & value, bool * val)
 {
 if (0 == strcasecmp(value.c_str(), "yes"))
     {
@@ -155,11 +158,11 @@ errorStr = "Incorrect value \'" + value + "\'.";
 return -1;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseMode(const vector<PARAM_VALUE> & moduleParams, const string & modeStr, mode_t * mode)
+int FILES_STORE_SETTINGS::ParseMode(const std::vector<PARAM_VALUE> & moduleParams, const std::string & modeStr, mode_t * mode)
 {
 PARAM_VALUE pv;
 pv.param = modeStr;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
 if (pvi == moduleParams.end())
     {
@@ -199,7 +202,7 @@ if (ParseGroup(s.moduleParams, "UserLogGroup", &userLogGID) < 0)
 if (ParseMode(s.moduleParams, "UserLogMode", &userLogMode) < 0)
     return -1;
 
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 PARAM_VALUE pv;
 pv.param = "RemoveBak";
 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
@@ -252,7 +255,7 @@ adminsDir = workDir + "/admins/";
 return 0;
 }
 //-----------------------------------------------------------------------------
-const string & FILES_STORE_SETTINGS::GetStrError() const
+const std::string & FILES_STORE_SETTINGS::GetStrError() const
 {
 return errorStr;
 }
@@ -263,7 +266,7 @@ struct passwd * pw;
 pw = getpwnam(user);
 if (!pw)
     {
-    errorStr = string("User \'") + string(user) + string("\' not found in system.");
+    errorStr = std::string("User \'") + std::string(user) + std::string("\' not found in system.");
     printfd(__FILE__, "%s\n", errorStr.c_str());
     return -1;
     }
@@ -278,7 +281,7 @@ struct group * grp;
 grp = getgrnam(gr);
 if (!grp)
     {
-    errorStr = string("Group \'") + string(gr) + string("\' not found in system.");
+    errorStr = std::string("Group \'") + std::string(gr) + std::string("\' not found in system.");
     printfd(__FILE__, "%s\n", errorStr.c_str());
     return -1;
     }
@@ -294,7 +297,7 @@ char b;
 char c;
 if (strlen(str) > 3)
     {
-    errorStr = string("Error parsing mode \'") + str + string("\'");
+    errorStr = std::string("Error parsing mode \'") + str + std::string("\'");
     printfd(__FILE__, "%s\n", errorStr.c_str());
     return -1;
     }
@@ -302,7 +305,7 @@ if (strlen(str) > 3)
 for (int i = 0; i < 3; i++)
     if (str[i] > '7' || str[i] < '0')
         {
-        errorStr = string("Error parsing mode \'") + str + string("\'");
+        errorStr = std::string("Error parsing mode \'") + str + std::string("\'");
         printfd(__FILE__, "%s\n", errorStr.c_str());
         return -1;
         }
@@ -341,13 +344,14 @@ FILES_STORE::FILES_STORE()
       version("file_store v.1.04"),
       storeSettings(),
       settings(),
-      mutex()
+      mutex(),
+      logger(GetPluginLogger(GetStgLogger(), "store_files"))
 {
 pthread_mutexattr_t attr;
 pthread_mutexattr_init(&attr);
 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
 pthread_mutex_init(&mutex, &attr);
-};
+}
 //-----------------------------------------------------------------------------
 int FILES_STORE::ParseSettings()
 {
@@ -360,14 +364,14 @@ if (ret)
 return ret;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::GetUsersList(vector<string> * userList) const
+int FILES_STORE::GetUsersList(std::vector<std::string> * userList) const
 {
-vector<string> files;
+std::vector<std::string> files;
 
 if (GetFileList(&files, storeSettings.GetUsersDir(), S_IFDIR, ""))
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "Failed to open '" + storeSettings.GetUsersDir() + "': " + string(strerror(errno));
+    errorStr = "Failed to open '" + storeSettings.GetUsersDir() + "': " + std::string(strerror(errno));
     return -1;
     }
 
@@ -378,14 +382,14 @@ userList->swap(files);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::GetAdminsList(vector<string> * adminList) const
+int FILES_STORE::GetAdminsList(std::vector<std::string> * adminList) const
 {
-vector<string> files;
+std::vector<std::string> files;
 
 if (GetFileList(&files, storeSettings.GetAdminsDir(), S_IFREG, ".adm"))
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "Failed to open '" + storeSettings.GetAdminsDir() + "': " + string(strerror(errno));
+    errorStr = "Failed to open '" + storeSettings.GetAdminsDir() + "': " + std::string(strerror(errno));
     return -1;
     }
 
@@ -396,14 +400,14 @@ adminList->swap(files);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::GetTariffsList(vector<string> * tariffList) const
+int FILES_STORE::GetTariffsList(std::vector<std::string> * tariffList) const
 {
-vector<string> files;
+std::vector<std::string> files;
 
 if (GetFileList(&files, storeSettings.GetTariffsDir(), S_IFREG, ".tf"))
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "Failed to open '" + storeSettings.GetTariffsDir() + "': " + string(strerror(errno));
+    errorStr = "Failed to open '" + storeSettings.GetTariffsDir() + "': " + std::string(strerror(errno));
     return -1;
     }
 
@@ -433,8 +437,8 @@ while ((entry = readdir(d)))
     if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
         continue;
 
-    string str = path;
-    str += "/" + string(entry->d_name);
+    std::string str = path;
+    str += "/" + std::string(entry->d_name);
 
     struct stat st;
     if (stat(str.c_str(), &st))
@@ -480,16 +484,16 @@ if (rmdir(path))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::AddUser(const string & login) const
+int FILES_STORE::AddUser(const std::string & login) const
 {
-string fileName;
+std::string fileName;
 
 strprintf(&fileName, "%s%s", storeSettings.GetUsersDir().c_str(), login.c_str());
 
 if (mkdir(fileName.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = string("mkdir failed. Message: '") + strerror(errno) + "'";
+    errorStr = std::string("mkdir failed. Message: '") + strerror(errno) + "'";
     printfd(__FILE__, "FILES_STORE::AddUser - mkdir failed. Message: '%s'\n", strerror(errno));
     return -1;
     }
@@ -514,12 +518,12 @@ if (Touch(fileName))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::DelUser(const string & login) const
+int FILES_STORE::DelUser(const std::string & login) const
 {
-string dirName;
-string dirName1;
+std::string dirName;
+std::string dirName1;
 
-strprintf(&dirName, "%s/"DELETED_USERS_DIR, storeSettings.GetWorkDir().c_str());
+strprintf(&dirName, "%s/%s", storeSettings.GetWorkDir().c_str(), DELETED_USERS_DIR);
 if (access(dirName.c_str(), F_OK) != 0)
     {
     if (mkdir(dirName.c_str(), 0700) != 0)
@@ -533,7 +537,7 @@ if (access(dirName.c_str(), F_OK) != 0)
 
 if (access(dirName.c_str(), F_OK) == 0)
     {
-    strprintf(&dirName, "%s/"DELETED_USERS_DIR"/%s.%lu", storeSettings.GetWorkDir().c_str(), login.c_str(), time(NULL));
+    strprintf(&dirName, "%s/%s/%s.%lu", storeSettings.GetWorkDir().c_str(), DELETED_USERS_DIR, login.c_str(), time(NULL));
     strprintf(&dirName1, "%s/%s", storeSettings.GetUsersDir().c_str(), login.c_str());
     if (rename(dirName1.c_str(), dirName.c_str()))
         {
@@ -554,9 +558,9 @@ else
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserConf(USER_CONF * conf, const string & login) const
+int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login) const
 {
-string fileName;
+std::string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
 if (RestoreUserConf(conf, login, fileName))
     {
@@ -569,11 +573,11 @@ if (RestoreUserConf(conf, login, fileName))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserConf(USER_CONF * conf, const string & login, const string & fileName) const
+int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login, const std::string & fileName) const
 {
 CONFIGFILE cf(fileName);
 int e = cf.Error();
-string str;
+std::string str;
 
 if (e)
     {
@@ -613,21 +617,21 @@ if (conf->tariffName.empty())
     return -1;
     }
 
-string ipStr;
+std::string ipStr;
 cf.ReadString("IP", &ipStr, "?");
-USER_IPS i;
+USER_IPS ips;
 try
     {
-    i = StrToIPS(ipStr);
+    ips = StrToIPS(ipStr);
     }
-catch (const string & s)
+catch (const std::string & s)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
     errorStr = "User \'" + login + "\' data not read. Parameter IP address. " + s;
     printfd(__FILE__, "FILES_STORE::RestoreUserConf - ip read failed for user '%s'\n", login.c_str());
     return -1;
     }
-conf->ips = i;
+conf->ips = ips;
 
 if (cf.ReadInt("alwaysOnline", &conf->alwaysOnline, 0) != 0)
     {
@@ -681,9 +685,9 @@ if (cf.ReadDouble("Credit", &conf->credit, 0) != 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserStat(USER_STAT * stat, const string & login) const
+int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login) const
 {
-string fileName;
+std::string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
 
 if (RestoreUserStat(stat, login, fileName))
@@ -697,7 +701,7 @@ if (RestoreUserStat(stat, login, fileName))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserStat(USER_STAT * stat, const string & login, const string & fileName) const
+int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login, const std::string & fileName) const
 {
 CONFIGFILE cf(fileName);
 
@@ -720,21 +724,21 @@ for (int i = 0; i < DIR_NUM; i++)
     if (cf.ReadULongLongInt(s, &traff, 0) != 0)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "User \'" + login + "\' stat not read. Parameter " + string(s);
+        errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
         printfd(__FILE__, "FILES_STORE::RestoreUserStat - download stat read failed for user '%s'\n", login.c_str());
         return -1;
         }
-    stat->down[i] = traff;
+    stat->monthDown[i] = traff;
 
     snprintf(s, 22, "U%d", i);
     if (cf.ReadULongLongInt(s, &traff, 0) != 0)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr =   "User \'" + login + "\' stat not read. Parameter " + string(s);
+        errorStr =   "User \'" + login + "\' stat not read. Parameter " + std::string(s);
         printfd(__FILE__, "FILES_STORE::RestoreUserStat - upload stat read failed for user '%s'\n", login.c_str());
         return -1;
         }
-    stat->up[i] = traff;
+    stat->monthUp[i] = traff;
     }
 
 if (cf.ReadDouble("Cash", &stat->cash, 0) != 0)
@@ -788,9 +792,9 @@ if (cf.ReadTime("LastActivityTime", &stat->lastActivityTime, 0) != 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::SaveUserConf(const USER_CONF & conf, const string & login) const
+int FILES_STORE::SaveUserConf(const USER_CONF & conf, const std::string & login) const
 {
-string fileName;
+std::string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
 
 CONFIGFILE cfstat(fileName, true);
@@ -800,7 +804,7 @@ int e = cfstat.Error();
 if (e)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = string("User \'") + login + "\' conf not written\n";
+    errorStr = std::string("User \'") + login + "\' conf not written\n";
     printfd(__FILE__, "FILES_STORE::SaveUserConf - conf write failed for user '%s'\n", login.c_str());
     return -1;
     }
@@ -837,17 +841,17 @@ for (int i = 0; i < USERDATA_NUM; i++)
     }
 cfstat.WriteInt("CreditExpire",    conf.creditExpire);
 
-stringstream ipStr;
+std::ostringstream ipStr;
 ipStr << conf.ips;
 cfstat.WriteString("IP", ipStr.str());
 
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::SaveUserStat(const USER_STAT & stat, const string & login) const
+int FILES_STORE::SaveUserStat(const USER_STAT & stat, const std::string & login) const
 {
 char s[22];
-string fileName;
+std::string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
 
     {
@@ -857,7 +861,7 @@ fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
     if (e)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = string("User \'") + login + "\' stat not written\n";
+        errorStr = std::string("User \'") + login + "\' stat not written\n";
         printfd(__FILE__, "FILES_STORE::SaveUserStat - stat write failed for user '%s'\n", login.c_str());
         return -1;
         }
@@ -865,9 +869,9 @@ fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
     for (int i = 0; i < DIR_NUM; i++)
         {
         snprintf(s, 22, "D%d", i);
-        cfstat.WriteInt(s, stat.down[i]);
+        cfstat.WriteInt(s, stat.monthDown[i]);
         snprintf(s, 22, "U%d", i);
-        cfstat.WriteInt(s, stat.up[i]);
+        cfstat.WriteInt(s, stat.monthUp[i]);
         }
 
     cfstat.WriteDouble("Cash", stat.cash);
@@ -890,11 +894,11 @@ if (e)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::WriteLogString(const string & str, const string & login) const
+int FILES_STORE::WriteLogString(const std::string & str, const std::string & login) const
 {
 FILE * f;
 time_t tm = time(NULL);
-string fileName;
+std::string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/log";
 f = fopen(fileName.c_str(), "at");
 
@@ -926,11 +930,11 @@ if (e)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::WriteLog2String(const string & str, const string & login) const
+int FILES_STORE::WriteLog2String(const std::string & str, const std::string & login) const
 {
 FILE * f;
 time_t tm = time(NULL);
-string fileName;
+std::string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/log2";
 f = fopen(fileName.c_str(), "at");
 
@@ -962,48 +966,48 @@ if (e)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::WriteUserChgLog(const string & login,
-                                 const string & admLogin,
+int FILES_STORE::WriteUserChgLog(const std::string & login,
+                                 const std::string & admLogin,
                                  uint32_t       admIP,
-                                 const string & paramName,
-                                 const string & oldValue,
-                                 const string & newValue,
-                                 const string & message) const
+                                 const std::string & paramName,
+                                 const std::string & oldValue,
+                                 const std::string & newValue,
+                                 const std::string & message) const
 {
-string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
+std::string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
     + paramName + "\' parameter changed from \'" + oldValue +
     "\' to \'" + newValue + "\'. " + message;
 
 return WriteLogString(userLogMsg, login);
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int FILES_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
 {
-string logStr = "Connect, " + inet_ntostring(ip);
+std::string logStr = "Connect, " + inet_ntostring(ip);
 if (WriteLogString(logStr, login))
     return -1;
 return WriteLog2String(logStr, login);
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::WriteUserDisconnect(const string & login,
-                                     const DIR_TRAFF & up,
-                                     const DIR_TRAFF & down,
+int FILES_STORE::WriteUserDisconnect(const std::string & login,
+                                     const DIR_TRAFF & monthUp,
+                                     const DIR_TRAFF & monthDown,
                                      const DIR_TRAFF & sessionUp,
                                      const DIR_TRAFF & sessionDown,
                                      double cash,
                                      double freeMb,
                                      const std::string & reason) const
 {
-stringstream logStr;
+std::ostringstream logStr;
 logStr << "Disconnect, "
        << " session upload: \'"
        << sessionUp
        << "\' session download: \'"
        << sessionDown
        << "\' month upload: \'"
-       << up
+       << monthUp
        << "\' month download: \'"
-       << down
+       << monthDown
        << "\' cash: \'"
        << cash
        << "\'";
@@ -1021,10 +1025,10 @@ logStr << " freeMb: \'"
 return WriteLog2String(logStr.str(), login);
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
+int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
 {
 // Classic stats
-string stat1;
+std::string stat1;
 strprintf(&stat1,"%s/%s/stat.%d.%02d",
         storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
 
@@ -1039,7 +1043,7 @@ if (s.Error())
     }
 
 // New stats
-string stat2;
+std::string stat2;
 strprintf(&stat2,"%s/%s/stat2.%d.%02d",
         storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
 
@@ -1057,11 +1061,11 @@ for (size_t i = 0; i < DIR_NUM; i++)
     {
     char dirName[3];
     snprintf(dirName, 3, "U%llu", (unsigned long long)i);
-    s.WriteInt(dirName, stat.up[i]); // Classic
-    s2.WriteInt(dirName, stat.up[i]); // New
+    s.WriteInt(dirName, stat.monthUp[i]); // Classic
+    s2.WriteInt(dirName, stat.monthUp[i]); // New
     snprintf(dirName, 3, "D%llu", (unsigned long long)i);
-    s.WriteInt(dirName, stat.down[i]); // Classic
-    s2.WriteInt(dirName, stat.down[i]); // New
+    s.WriteInt(dirName, stat.monthDown[i]); // Classic
+    s2.WriteInt(dirName, stat.monthDown[i]); // New
     }
 
 // Classic
@@ -1078,9 +1082,9 @@ s2.WriteInt("LastActivityTime", stat.lastActivityTime);
 return 0;
 }
 //-----------------------------------------------------------------------------*/
-int FILES_STORE::AddAdmin(const string & login) const
+int FILES_STORE::AddAdmin(const std::string & login) const
 {
-string fileName;
+std::string fileName;
 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
 
 if (Touch(fileName))
@@ -1094,9 +1098,9 @@ if (Touch(fileName))
 return 0;
 }
 //-----------------------------------------------------------------------------*/
-int FILES_STORE::DelAdmin(const string & login) const
+int FILES_STORE::DelAdmin(const std::string & login) const
 {
-string fileName;
+std::string fileName;
 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
 if (unlink(fileName.c_str()))
     {
@@ -1115,7 +1119,7 @@ char passwordE[2 * ADM_PASSWD_LEN + 2];
 char pass[ADM_PASSWD_LEN + 1];
 char adminPass[ADM_PASSWD_LEN + 1];
 
-string fileName;
+std::string fileName;
 
 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), ac.login.c_str());
 
@@ -1164,9 +1168,9 @@ strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), ac.login
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
+int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
 {
-string fileName;
+std::string fileName;
 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
 CONFIGFILE cf(fileName);
 char pass[ADM_PASSWD_LEN + 1];
@@ -1174,7 +1178,7 @@ char password[ADM_PASSWD_LEN + 1];
 char passwordE[2 * ADM_PASSWD_LEN + 2];
 BLOWFISH_CTX ctx;
 
-string p;
+std::string p;
 
 if (cf.Error())
     {
@@ -1184,8 +1188,6 @@ if (cf.Error())
     return -1;
     }
 
-int a;
-
 if (cf.ReadString("password", &p, "*"))
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
@@ -1216,7 +1218,9 @@ else
 
 ac->password = password;
 
-if (cf.ReadInt("ChgConf", &a, 0) == 0)
+uint16_t a;
+
+if (cf.ReadUShortInt("ChgConf", &a, 0) == 0)
     ac->priv.userConf = a;
 else
     {
@@ -1226,7 +1230,7 @@ else
     return -1;
     }
 
-if (cf.ReadInt("ChgPassword", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgPassword", &a, 0) == 0)
     ac->priv.userPasswd = a;
 else
     {
@@ -1236,7 +1240,7 @@ else
     return -1;
     }
 
-if (cf.ReadInt("ChgStat", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgStat", &a, 0) == 0)
     ac->priv.userStat = a;
 else
     {
@@ -1246,7 +1250,7 @@ else
     return -1;
     }
 
-if (cf.ReadInt("ChgCash", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgCash", &a, 0) == 0)
     ac->priv.userCash = a;
 else
     {
@@ -1256,7 +1260,7 @@ else
     return -1;
     }
 
-if (cf.ReadInt("UsrAddDel", &a, 0) == 0)
+if (cf.ReadUShortInt("UsrAddDel", &a, 0) == 0)
     ac->priv.userAddDel = a;
 else
     {
@@ -1266,7 +1270,7 @@ else
     return -1;
     }
 
-if (cf.ReadInt("ChgAdmin", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgAdmin", &a, 0) == 0)
     ac->priv.adminChg = a;
 else
     {
@@ -1276,7 +1280,7 @@ else
     return -1;
     }
 
-if (cf.ReadInt("ChgTariff", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgTariff", &a, 0) == 0)
     ac->priv.tariffChg = a;
 else
     {
@@ -1286,12 +1290,12 @@ else
     return -1;
     }
 
-if (cf.ReadInt("ChgService", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgService", &a, 0) == 0)
     ac->priv.serviceChg = a;
 else
     ac->priv.serviceChg = 0;
 
-if (cf.ReadInt("ChgCorp", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgCorp", &a, 0) == 0)
     ac->priv.corpChg = a;
 else
     ac->priv.corpChg = 0;
@@ -1299,9 +1303,9 @@ else
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::AddTariff(const string & name) const
+int FILES_STORE::AddTariff(const std::string & name) const
 {
-string fileName;
+std::string fileName;
 strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
 if (Touch(fileName))
     {
@@ -1313,9 +1317,9 @@ if (Touch(fileName))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::DelTariff(const string & name) const
+int FILES_STORE::DelTariff(const std::string & name) const
 {
-string fileName;
+std::string fileName;
 strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
 if (unlink(fileName.c_str()))
     {
@@ -1328,11 +1332,11 @@ if (unlink(fileName.c_str()))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const string & tariffName) const
+int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const
 {
-string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
+std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
 CONFIGFILE conf(fileName);
-string str;
+std::string str;
 td->tariffConf.name = tariffName;
 
 if (conf.Error() != 0)
@@ -1343,7 +1347,7 @@ if (conf.Error() != 0)
     return -1;
     }
 
-string param;
+std::string param;
 for (int i = 0; i<DIR_NUM; i++)
     {
     strprintf(&param, "Time%d", i);
@@ -1487,9 +1491,9 @@ else
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const string & tariffName) const
+int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const
 {
-string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
+std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
 
     {
     CONFIGFILE cf(fileName, true);
@@ -1504,7 +1508,7 @@ string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
         return e;
         }
 
-    string param;
+    std::string param;
     for (int i = 0; i < DIR_NUM; i++)
         {
         strprintf(&param, "PriceDayA%d", i);
@@ -1522,7 +1526,7 @@ string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
         strprintf(&param, "Threshold%d", i);
         cf.WriteInt(param, td.dirPrice[i].threshold);
 
-        string s;
+        std::string s;
         strprintf(&param, "Time%d", i);
 
         strprintf(&s, "%0d:%0d-%0d:%0d",
@@ -1566,9 +1570,9 @@ string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int FILES_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
                                    time_t lastStat,
-                                   const string & login) const
+                                   const std::string & login) const
 {
 char fn[FN_STR_LEN];
 char dn[FN_STR_LEN];
@@ -1584,7 +1588,7 @@ if (access(dn, F_OK) != 0)
     if (mkdir(dn, 0700) != 0)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
+        errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
         return -1;
         }
@@ -1617,7 +1621,7 @@ if (access(dn, F_OK) != 0)
     if (mkdir(dn, 0700) != 0)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
+        errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
         return -1;
         }
@@ -1643,7 +1647,7 @@ if (access(dn, F_OK) != 0)
     if (mkdir(dn, 0700) != 0)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
+        errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
         return -1;
         }
@@ -1665,7 +1669,7 @@ statFile = fopen (fn, "at");
 if (!statFile)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "File \'" + string(fn) + "\' cannot be written.";
+    errorStr = "File \'" + std::string(fn) + "\' cannot be written.";
     printfd(__FILE__, "FILES_STORE::WriteDetailStat - fopen failed. Message: '%s'\n", strerror(errno));
     return -1;
     }
@@ -1692,18 +1696,18 @@ if (fprintf(statFile, "-> %02d.%02d.%02d - %02d.%02d.%02d\n",
             h1, m1, s1, h2, m2, s2) < 0)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = string("fprint failed. Message: '") + strerror(errno) + "'";
+    errorStr = std::string("fprint failed. Message: '") + strerror(errno) + "'";
     printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
     fclose(statFile);
     return -1;
     }
 
-map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
+std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
 stIter = statTree.begin();
 
 while (stIter != statTree.end())
     {
-    string u, d;
+    std::string u, d;
     x2str(stIter->second.up, u);
     x2str(stIter->second.down, d);
     #ifdef TRAFF_STAT_WITH_PORTS
@@ -1732,7 +1736,7 @@ while (stIter != statTree.end())
                 stIter->second.cash) < 0)
         {
         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = string("fprint failed. Message: '");
+        errorStr = std::string("fprint failed. Message: '");
         errorStr += strerror(errno);
         errorStr += "'";
         printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
@@ -1758,10 +1762,10 @@ if (e)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int FILES_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
 {
-string fn;
-string dn;
+std::string fn;
+std::string dn;
 struct timeval tv;
 
 strprintf(&dn, "%s/%s/messages", storeSettings.GetUsersDir().c_str(), login.c_str());
@@ -1798,16 +1802,16 @@ if (Touch(fn))
 return EditMessage(*msg, login);
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::EditMessage(const STG_MSG & msg, const string & login) const
+int FILES_STORE::EditMessage(const STG_MSG & msg, const std::string & login) const
 {
-string fileName;
+std::string fileName;
 
 FILE * msgFile;
 strprintf(&fileName, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), msg.header.id);
 
 if (access(fileName.c_str(), F_OK) != 0)
     {
-    string idstr;
+    std::string idstr;
     x2str(msg.header.id, idstr);
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
     errorStr = "Message for user \'";
@@ -1840,7 +1844,7 @@ res &= (fprintf(msgFile, "%s", msg.text.c_str()) >= 0);
 if (!res)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = string("fprintf failed. Message: '") + strerror(errno) + "'";
+    errorStr = std::string("fprintf failed. Message: '") + strerror(errno) + "'";
     printfd(__FILE__, "FILES_STORE::EditMessage - fprintf failed. Message: '%s'\n", strerror(errno));
     fclose(msgFile);
     return -1;
@@ -1861,32 +1865,32 @@ if (rename((fileName + ".new").c_str(), fileName.c_str()) < 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const string & login) const
+int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const
 {
-string fn;
+std::string fn;
 strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
 msg->header.id = id;
 return ReadMessage(fn, &msg->header, &msg->text);
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::DelMessage(uint64_t id, const string & login) const
+int FILES_STORE::DelMessage(uint64_t id, const std::string & login) const
 {
-string fn;
+std::string fn;
 strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
 
 return unlink(fn.c_str());
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const string & login) const
+int FILES_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const
 {
-string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
+std::string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
 
 if (access(dn.c_str(), F_OK) != 0)
     {
     return 0;
     }
 
-vector<string> messages;
+std::vector<std::string> messages;
 GetFileList(&messages, dn, S_IFREG, "");
 
 for (unsigned i = 0; i < messages.size(); i++)
@@ -1898,7 +1902,7 @@ for (unsigned i = 0; i < messages.size(); i++)
         if (unlink((dn + messages[i]).c_str()))
             {
             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-            errorStr = string("unlink failed. Message: '") + strerror(errno) + "'";
+            errorStr = std::string("unlink failed. Message: '") + strerror(errno) + "'";
             printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
             return -1;
             }
@@ -1916,7 +1920,7 @@ for (unsigned i = 0; i < messages.size(); i++)
         if (unlink((dn + messages[i]).c_str()))
             {
             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-            errorStr = string("unlink failed. Message: '") + strerror(errno) + "'";
+            errorStr = std::string("unlink failed. Message: '") + strerror(errno) + "'";
             printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
             return -1;
             }
@@ -1929,9 +1933,9 @@ for (unsigned i = 0; i < messages.size(); i++)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FILES_STORE::ReadMessage(const string & fileName,
+int FILES_STORE::ReadMessage(const std::string & fileName,
                              STG_MSG_HDR * hdr,
-                             string * text) const
+                             std::string * text) const
 {
 FILE * msgFile;
 msgFile = fopen(fileName.c_str(), "rt");
@@ -2030,7 +2034,7 @@ if (f)
 return -1;
 }
 //-----------------------------------------------------------------------------
-int GetFileList(vector<string> * fileList, const string & directory, mode_t mode, const string & ext)
+int GetFileList(std::vector<std::string> * fileList, const std::string & directory, mode_t mode, const std::string & ext)
 {
 DIR * d = opendir(directory.c_str());
 
@@ -2046,7 +2050,7 @@ while ((entry = readdir(d)))
     if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
         continue;
 
-    string str = directory + "/" + string(entry->d_name);
+    std::string str = directory + "/" + std::string(entry->d_name);
 
     struct stat st;
     if (stat(str.c_str(), &st))
index 91fb7fa80c2e9df371d9fc4dccbe90db7f7c3aed..1d72f287d01dac7e1108b4e69bf97a62db3ccd3a 100644 (file)
@@ -37,9 +37,8 @@
 #include "stg/store.h"
 #include "stg/conffiles.h"
 #include "stg/user_traff.h"
+#include "stg/logger.h"
 
-//-----------------------------------------------------------------------------
-extern "C" STORE * GetStore();
 //-----------------------------------------------------------------------------
 class FILES_STORE_SETTINGS {
 public:
@@ -198,11 +197,13 @@ private:
     int RemoveDir(const char * path) const;
     int Touch(const std::string & path) const;
 
-    mutable string errorStr;
+    mutable std::string errorStr;
     std::string version;
     FILES_STORE_SETTINGS storeSettings;
     MODULE_SETTINGS settings;
     mutable pthread_mutex_t mutex;
+
+    PLUGIN_LOGGER logger;
 };
 //-----------------------------------------------------------------------------
 
index b14858057c343739b58f45b2d1ec26aa62a777ca..0e669751c6157a5f481f28ce7330f99c3174e251 100644 (file)
@@ -23,7 +23,11 @@ STGLIBS = ibpp \
          logger \
          crypto
 
-LIBS = -lfbclient
+FB_CFLAGS = $(shell fb_config --cflags)
+FB_LDFLAGS = $(shell fb_config --libs)
+
+CXXFLAGS +=  $(FB_CFLAGS)
+LDFLAGS += $(FB_LDFLAGS)
 
 include ../../Makefile.in
 
index 8bddf9ca6c329537f614a02ae44d2c098b5b9468..8e3c9d90f0432bd70c0c716c04a1e37a14677682 100644 (file)
  *
  */
 
-#include <string>
-#include <vector>
-#include <algorithm>
+#include "firebird_store.h"
 
 #include "stg/ibpp.h"
 #include "stg/plugin_creator.h"
-#include "stg/logger.h"
-#include "firebird_store.h"
 
-using namespace std;
+#include <string>
+#include <vector>
+#include <algorithm>
+
+#include <cctype>
 
+namespace
+{
 PLUGIN_CREATOR<FIREBIRD_STORE> frsc;
+}
+
+extern "C" STORE * GetStore();
 //-----------------------------------------------------------------------------
 STORE * GetStore()
 {
@@ -58,8 +63,7 @@ FIREBIRD_STORE::FIREBIRD_STORE()
       mutex(),
       til(IBPP::ilConcurrency),
       tlr(IBPP::lrWait),
-      schemaVersion(0),
-      WriteServLog(GetStgLogger())
+      logger(GetPluginLogger(GetStgLogger(), "store_firebird"))
 {
 pthread_mutex_init(&mutex, NULL);
 }
@@ -71,61 +75,47 @@ db->Disconnect();
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::ParseSettings()
 {
-vector<PARAM_VALUE>::iterator i;
-string s;
+std::vector<PARAM_VALUE>::iterator i;
+std::string s;
 
 for(i = settings.moduleParams.begin(); i != settings.moduleParams.end(); ++i)
     {
     s = i->param;
-    transform(s.begin(), s.end(), s.begin(), ToLower());
+
+    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
+
     if (s == "server")
-        {
         db_server = *(i->value.begin());
-        }
+
     if (s == "database")
-        {
         db_database = *(i->value.begin());
-        }
+
     if (s == "user")
-        {
         db_user = *(i->value.begin());
-        }
+
     if (s == "password")
-        {
         db_password = *(i->value.begin());
-        }
 
     // Advanced settings block
 
     if (s == "isolationLevel")
         {
         if (*(i->value.begin()) == "Concurrency")
-            {
             til = IBPP::ilConcurrency;
-            }
         else if (*(i->value.begin()) == "DirtyRead")
-            {
             til = IBPP::ilReadDirty;
-            }
         else if (*(i->value.begin()) == "ReadCommitted")
-            {
             til = IBPP::ilReadCommitted;
-            }
         else if (*(i->value.begin()) == "Consistency")
-            {
             til = IBPP::ilConsistency;
-            }
         }
+
     if (s == "lockResolution")
         {
         if (*(i->value.begin()) == "Wait")
-            {
             tlr = IBPP::lrWait;
-            }
         else if (*(i->value.begin()) == "NoWait")
-            {
             tlr = IBPP::lrNoWait;
-            }
         }
     }
 
index a5905fefa8438570e7e2606cf2f9571a0c328a1c..688f0e88651da56258aad827b29d4ff92a21c6d7 100644 (file)
 #include <ctime>
 #include <string>
 #include <vector>
-#include <map>
 
 #include "stg/store.h"
 #include "stg/locker.h"
 #include "stg/ibpp.h"
+#include "stg/logger.h"
 
 struct ToLower {
-    char operator() (char c) const  { return std::tolower(c); }
+    char operator() (char c) const  { return static_cast<char>(std::tolower(c)); }
 };
 
-extern "C" STORE * GetStore();
-
-class STG_LOGGER;
-
 class FIREBIRD_STORE : public STORE {
 public:
     FIREBIRD_STORE();
@@ -94,7 +90,7 @@ public:
 
     int GetTariffsList(std::vector<std::string> * tariffsList) const;
     int AddTariff(const std::string & name) const;
-    int DelTariff(const string & name) const;
+    int DelTariff(const std::string & name) const;
     int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const;
     int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const;
 
@@ -104,12 +100,12 @@ public:
     int AddCorp(const std::string & name) const;
     int DelCorp(const std::string & name) const;
 
-    inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; };
+    inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; }
     int ParseSettings();
 
-    inline const string & GetStrError() const { return strError; };
+    inline const std::string & GetStrError() const { return strError; }
 
-    inline const string & GetVersion() const { return version; };
+    inline const std::string & GetVersion() const { return version; }
 
     int GetServicesList(std::vector<std::string> * servicesList) const;
     int SaveService(const SERVICE_CONF & sc) const;
@@ -123,14 +119,14 @@ private:
 
     std::string version;
     mutable std::string strError;
-    mutable std::string db_server, db_database, db_user, db_password;
+    std::string db_server, db_database, db_user, db_password;
     MODULE_SETTINGS settings;
     mutable IBPP::Database db;
     mutable pthread_mutex_t mutex;
-    mutable IBPP::TIL til;
-    mutable IBPP::TLR tlr;
+    IBPP::TIL til;
+    IBPP::TLR tlr;
     int schemaVersion;
-    STG_LOGGER & WriteServLog;
+    PLUGIN_LOGGER logger;
 
     int SaveStat(const USER_STAT & stat, const std::string & login, int year = 0, int month = 0) const;
     int CheckVersion();
index 026fef924b4e3e1d3b8ebd8903e3b8e067115861..6b457de02603b90690a728998bb36196585dc1e8 100644 (file)
 #include "stg/ibpp.h"
 
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetCorpsList(vector<string> * corpsList) const
+int FIREBIRD_STORE::GetCorpsList(std::vector<std::string> * corpsList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-string name;
+std::string name;
 
 try
     {
@@ -90,7 +90,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::RestoreCorp(CORP_CONF * cc, const string & name) const
+int FIREBIRD_STORE::RestoreCorp(CORP_CONF * cc, const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -128,7 +128,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddCorp(const string & name) const
+int FIREBIRD_STORE::AddCorp(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -155,7 +155,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelCorp(const string & name) const
+int FIREBIRD_STORE::DelCorp(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
index c6180c2608ff4f024b9c1e7a9c069bf6dc905ea0..e14ad356e9f6c46938dcb3db57d94827a48c031c 100644 (file)
  *
  */
 
-#include <sstream>
-
 #include "firebird_store.h"
 #include "stg/ibpp.h"
 
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int FIREBIRD_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -70,7 +68,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::EditMessage(const STG_MSG & msg,
-                                const string & login) const
+                                const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -108,7 +106,7 @@ return 0;
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::GetMessage(uint64_t id,
                                STG_MSG * msg,
-                               const string &) const
+                               const std::string &) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -154,7 +152,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelMessage(uint64_t id, const string &) const
+int FIREBIRD_STORE::DelMessage(uint64_t id, const std::string &) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -181,8 +179,8 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList,
-                                   const string & login) const
+int FIREBIRD_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList,
+                                   const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
index 84eab5fa885b66a8ad593d5a0cbd791f61824f1e..6f6bee30a01d51b1779afdcc1fe7cb98321e0144 100644 (file)
 #include "stg/ibpp.h"
 
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetServicesList(vector<string> * servicesList) const
+int FIREBIRD_STORE::GetServicesList(std::vector<std::string> * servicesList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-string name;
+std::string name;
 
 try
     {
@@ -98,7 +98,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::RestoreService(SERVICE_CONF * sc,
-                                   const string & name) const
+                                   const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -117,7 +117,7 @@ try
         st->Get(4, sc->cost);
         int16_t pd;
         st->Get(5, pd);
-        sc->payDay = pd;
+        sc->payDay = static_cast<uint8_t>(pd);
         }
     else
         {
@@ -140,7 +140,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddService(const string & name) const
+int FIREBIRD_STORE::AddService(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -168,7 +168,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelService(const string & name) const
+int FIREBIRD_STORE::DelService(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
index e6ebd45f54bfe93f815f3e90d84af9b00ed86e2f..325e7d7f10b48c79978a04f52655f65a4f9d653c 100644 (file)
  *
  */
 
+#include <cmath>
+
 #include "firebird_store.h"
 #include "stg/ibpp.h"
 
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetTariffsList(vector<string> * tariffsList) const
+int FIREBIRD_STORE::GetTariffsList(std::vector<std::string> * tariffsList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-string name;
+std::string name;
 
 try
     {
@@ -62,7 +64,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddTariff(const string & name) const
+int FIREBIRD_STORE::AddTariff(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -90,7 +92,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelTariff(const string & name) const
+int FIREBIRD_STORE::DelTariff(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -118,7 +120,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::SaveTariff(const TARIFF_DATA & td,
-                               const string & tariffName) const
+                               const std::string & tariffName) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -245,7 +247,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::RestoreTariff(TARIFF_DATA * td,
-                                  const string & tariffName) const
+                                  const std::string & tariffName) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -309,8 +311,8 @@ try
     st->Get(7, td->dirPrice[dir].priceNightB);
     td->dirPrice[dir].priceNightB /= 1024*1024;
     st->Get(8, td->dirPrice[dir].threshold);
-    if (td->dirPrice[dir].priceDayA == td->dirPrice[dir].priceNightA &&
-        td->dirPrice[dir].priceDayB == td->dirPrice[dir].priceNightB)
+    if (std::fabs(td->dirPrice[dir].priceDayA - td->dirPrice[dir].priceNightA) < 1.0e-3 &&
+        std::fabs(td->dirPrice[dir].priceDayB - td->dirPrice[dir].priceNightB) < 1.0e-3)
         {
         td->dirPrice[dir].singlePrice = true;
         }
index a31ca3f80c5c9921c77d1fadc5ed5bb667f2c63b..e48fd0d89dacb6effa5d245996b4480d9ad7265e 100644 (file)
 #include "stg/ibpp.h"
 
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetUsersList(vector<string> * usersList) const
+int FIREBIRD_STORE::GetUsersList(std::vector<std::string> * usersList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-string name;
+std::string name;
 
 try
     {
@@ -63,7 +63,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddUser(const string & name) const
+int FIREBIRD_STORE::AddUser(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -91,7 +91,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelUser(const string & login) const
+int FIREBIRD_STORE::DelUser(const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -119,7 +119,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::SaveUserStat(const USER_STAT & stat,
-                                 const string & login) const
+                                 const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -127,7 +127,7 @@ return SaveStat(stat, login);
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::SaveStat(const USER_STAT & stat,
-                                 const string & login,
+                                 const std::string & login,
                                  int year,
                                  int month) const
 {
@@ -227,7 +227,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::SaveUserConf(const USER_CONF & conf,
-                                 const string & login) const
+                                 const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -237,7 +237,7 @@ IBPP::Statement st = IBPP::StatementFactory(db, tr);
 int i;
 int32_t uid;
 IBPP::Timestamp creditExpire;
-vector<string>::const_iterator it;
+std::vector<std::string>::const_iterator it;
 
 try
     {
@@ -337,7 +337,7 @@ try
     st->Execute();
 
     st->Prepare("insert into tb_allowed_ip (fk_user, ip, mask) values (?, ?, ?)");
-    for(i = 0; i < conf.ips.Count(); i++)
+    for(size_t i = 0; i < conf.ips.Count(); i++)
         {
         st->Set(1, uid);
         st->Set(2, (int32_t)conf.ips[i].ip);
@@ -359,7 +359,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::RestoreUserStat(USER_STAT * stat,
-                                    const string & login) const
+                                    const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -444,7 +444,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int FIREBIRD_STORE::RestoreUserConf(USER_CONF * conf,
-                                    const string & login) const
+                                    const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -455,7 +455,7 @@ int32_t uid;
 int i;
 IBPP::Timestamp timestamp;
 IP_MASK im;
-string name;
+std::string name;
 bool test;
 
 try
@@ -566,13 +566,13 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteUserChgLog(const string & login,
-                                    const string & admLogin,
+int FIREBIRD_STORE::WriteUserChgLog(const std::string & login,
+                                    const std::string & admLogin,
                                     uint32_t admIP,
-                                    const string & paramName,
-                                    const string & oldValue,
-                                    const string & newValue,
-                                    const string & message = "") const
+                                    const std::string & paramName,
+                                    const std::string & oldValue,
+                                    const std::string & newValue,
+                                    const std::string & message = "") const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -581,7 +581,7 @@ IBPP::Statement st = IBPP::StatementFactory(db, tr);
 IBPP::Timestamp now;
 now.Now();
 
-string temp = ""; // Composed message for log
+std::string temp = ""; // Composed message for log
 
 try
     {
@@ -632,7 +632,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int FIREBIRD_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -662,14 +662,14 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteUserDisconnect(const string & login,
+int FIREBIRD_STORE::WriteUserDisconnect(const std::string & login,
                     const DIR_TRAFF & up,
                     const DIR_TRAFF & down,
                     const DIR_TRAFF & sessionUp,
                     const DIR_TRAFF & sessionDown,
-                    double cash,
-                    double freeMb,
-                    const std::string & reason) const
+                    double /*cash*/,
+                    double /*freeMb*/,
+                    const std::string & /*reason*/) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -717,9 +717,9 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int FIREBIRD_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
                                       time_t lastStat,
-                                      const string & login) const
+                                      const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -734,7 +734,7 @@ time_t2ts(lastStat, &statTime);
 try
     {
     tr->Start();
-    map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
+    std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
     it = statTree.begin();
     st->Prepare("insert into tb_detail_stats \
                     (till_time, from_time, fk_user, dir_num, \
@@ -769,7 +769,7 @@ catch (IBPP::Exception & ex)
 return 0;
 }
 //-----------------------------------------------------------------------------
-int FIREBIRD_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
+int FIREBIRD_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
index d38660bfebc2c6d0532403ed2ea1e102e7c57b4f..25a29798a4050ff475bc13caf046b210852f0356 100644 (file)
@@ -9,8 +9,8 @@ PROG = mod_store_mysql.so
 SRCS = ./mysql_store.cpp
 
 STGLIBS = common \
-         logger \
-         crypto
+         crypto \
+         logger
 
 MYSQL_CFLAGS = $(shell mysql_config --cflags)
 MYSQL_LDFLAGS = $(shell mysql_config --libs_r)
index 95ac298d732529891e18de18844a56df3b3518ca..11c2def3b5c1d2ca0dc3b82fb036fa6afcc00e71 100644 (file)
@@ -2,7 +2,6 @@
 #include <cerrno>
 #include <cstdio>
 #include <cstdlib>
-#include <string>
 #include <algorithm>
 
 #include <mysql.h>
 #include "mysql_store.h"
 
 #define adm_enc_passwd "cjeifY8m3"
-char qbuf[4096];
 
-using namespace std;
+namespace
+{
+char qbuf[4096];
 
 const int pt_mega = 1024 * 1024;
-const string badSyms = "'`";
+const std::string badSyms = "'`";
 const char repSym = '\"';
 const int RepitTimes = 3;
 
-int GetInt(const string & str, int * val, int defaultVal)
+template <typename T>
+int GetInt(const std::string & str, T * val, T defaultVal = T())
 {
     char *res;
     
-    *val = strtol(str.c_str(), &res, 10);
+    *val = static_cast<T>(strtoll(str.c_str(), &res, 10));
     
     if (*res != 0) 
     {
@@ -41,7 +42,7 @@ int GetInt(const string & str, int * val, int defaultVal)
     return 0;
 }
 
-int GetDouble(const string & str, double * val, double defaultVal)
+int GetDouble(const std::string & str, double * val, double defaultVal)
 {
     char *res;
     
@@ -56,7 +57,7 @@ int GetDouble(const string & str, double * val, double defaultVal)
     return 0;
 }
 
-int GetTime(const string & str, time_t * val, time_t defaultVal)
+int GetTime(const std::string & str, time_t * val, time_t defaultVal)
 {
     char *res;
     
@@ -72,17 +73,17 @@ int GetTime(const string & str, time_t * val, time_t defaultVal)
 }
 
 //-----------------------------------------------------------------------------
-string ReplaceStr(string source, const string symlist, const char chgsym)
+std::string ReplaceStr(std::string source, const std::string symlist, const char chgsym)
 {
-    string::size_type pos=0;
+    std::string::size_type pos=0;
 
-    while( (pos = source.find_first_of(symlist,pos)) != string::npos)
+    while( (pos = source.find_first_of(symlist,pos)) != std::string::npos)
         source.replace(pos, 1,1, chgsym);
 
     return source;
 }
 
-int GetULongLongInt(const string & str, uint64_t * val, uint64_t defaultVal)
+int GetULongLongInt(const std::string & str, uint64_t * val, uint64_t defaultVal)
 {
     char *res;
     
@@ -98,6 +99,9 @@ int GetULongLongInt(const string & str, uint64_t * val, uint64_t defaultVal)
 } 
 
 PLUGIN_CREATOR<MYSQL_STORE> msc;
+}
+
+extern "C" STORE * GetStore();
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
@@ -116,12 +120,12 @@ MYSQL_STORE_SETTINGS::MYSQL_STORE_SETTINGS()
 {
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE_SETTINGS::ParseParam(const vector<PARAM_VALUE> & moduleParams, 
-                        const string & name, string & result)
+int MYSQL_STORE_SETTINGS::ParseParam(const std::vector<PARAM_VALUE> & moduleParams, 
+                        const std::string & name, std::string & result)
 {
 PARAM_VALUE pv;
 pv.param = name;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
 if (pvi == moduleParams.end())
     {
@@ -159,10 +163,9 @@ MYSQL_STORE::MYSQL_STORE()
       version("mysql_store v.0.67"),
       storeSettings(),
       settings(),
-      schemaVersion(0),
-      WriteServLog(GetStgLogger())
+      logger(GetPluginLogger(GetStgLogger(), "store_mysql"))
 {
-};
+}
 //-----------------------------------------------------------------------------
 int    MYSQL_STORE::MysqlQuery(const char* sQuery,MYSQL * sock) const
 {
@@ -213,7 +216,7 @@ else
     {
          if(mysql_select_db(sock, storeSettings.GetDBName().c_str()))
          {
-             string res = "CREATE DATABASE " + storeSettings.GetDBName();
+             std::string res = "CREATE DATABASE " + storeSettings.GetDBName();
             
             if(MysqlQuery(res.c_str(),sock))
             {
@@ -249,7 +252,7 @@ else
 return ret;
 }
 //-----------------------------------------------------------------------------
-bool MYSQL_STORE::IsTablePresent(const string & str,MYSQL * sock)
+bool MYSQL_STORE::IsTablePresent(const std::string & str,MYSQL * sock)
 {
 MYSQL_RES* result;
 
@@ -261,12 +264,12 @@ if (!(result=mysql_list_tables(sock,str.c_str() )))
     return -1;
 }
 
-unsigned int num_rows =  mysql_num_rows(result);
+my_ulonglong num_rows =  mysql_num_rows(result);
 
 if(result)
     mysql_free_result(result);
 
-return (num_rows == 1);
+return num_rows == 1;
 }
 //-----------------------------------------------------------------------------
 int MYSQL_STORE::CheckAllTables(MYSQL * sock)
@@ -339,7 +342,7 @@ if(!IsTablePresent("admins",sock))
 }
 
 //tariffs-----------------------------------------------------------------------
-string param, res;
+std::string param, res;
 if(!IsTablePresent("tariffs",sock))
 {
     res = "CREATE TABLE tariffs (name VARCHAR(40) DEFAULT '' PRIMARY KEY,";
@@ -603,13 +606,13 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 
-int MYSQL_STORE::GetAllParams(vector<string> * ParamList, 
-                            const string & table, const string & name) const
+int MYSQL_STORE::GetAllParams(std::vector<std::string> * ParamList, 
+                            const std::string & table, const std::string & name) const
 {
 MYSQL_RES *res;
 MYSQL_ROW row;
 MYSQL * sock=NULL;
-unsigned int num,i;
+my_ulonglong num, i;
     
 ParamList->clear();
     
@@ -634,7 +637,7 @@ if (!(res=mysql_store_result(sock)))
 
 num = mysql_num_rows(res);
 
-for(i=0;i<num;i++)
+for(i = 0; i < num; i++)
 {
     row = mysql_fetch_row(res);    
     ParamList->push_back(row[0]);
@@ -647,7 +650,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::GetUsersList(vector<string> * usersList) const
+int MYSQL_STORE::GetUsersList(std::vector<std::string> * usersList) const
 {
 if(GetAllParams(usersList, "users", "login"))
     return -1;
@@ -655,7 +658,7 @@ if(GetAllParams(usersList, "users", "login"))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::GetAdminsList(vector<string> * adminsList) const
+int MYSQL_STORE::GetAdminsList(std::vector<std::string> * adminsList) const
 {
 if(GetAllParams(adminsList, "admins", "login"))
     return -1;
@@ -663,7 +666,7 @@ if(GetAllParams(adminsList, "admins", "login"))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::GetTariffsList(vector<string> * tariffsList) const
+int MYSQL_STORE::GetTariffsList(std::vector<std::string> * tariffsList) const
 {
 if(GetAllParams(tariffsList, "tariffs", "name"))
     return -1;
@@ -671,7 +674,7 @@ if(GetAllParams(tariffsList, "tariffs", "name"))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::AddUser(const string & login) const
+int MYSQL_STORE::AddUser(const std::string & login) const
 {
 sprintf(qbuf,"INSERT INTO users SET login='%s'", login.c_str());
     
@@ -685,7 +688,7 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::DelUser(const string & login) const
+int MYSQL_STORE::DelUser(const std::string & login) const
 {
 sprintf(qbuf,"DELETE FROM users WHERE login='%s' LIMIT 1", login.c_str());
     
@@ -699,12 +702,12 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreUserConf(USER_CONF * conf, const string & login) const
+int MYSQL_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login) const
 {
 MYSQL_RES *res;
 MYSQL_ROW row;
 MYSQL * sock;
-string query;
+std::string query;
 
 query = "SELECT login, Password, Passive, Down, DisabledDetailStat, \
          AlwaysOnline, Tariff, Address, Phone, Email, Note, \
@@ -746,7 +749,7 @@ if (mysql_num_rows(res) != 1)
 
 row = mysql_fetch_row(res);
 
-string param;
+std::string param;
 
 conf->password = row[1];
 
@@ -758,7 +761,7 @@ if (conf->password.empty())
     return -1;
     }
 
-if (GetInt(row[2],&conf->passive, 0) != 0)
+if (GetInt(row[2],&conf->passive) != 0)
     {
     mysql_free_result(res);
     errorStr = "User \'" + login + "\' data not read. Parameter Passive.";
@@ -766,7 +769,7 @@ if (GetInt(row[2],&conf->passive, 0) != 0)
     return -1;
     }
 
-if (GetInt(row[3], &conf->disabled, 0) != 0)
+if (GetInt(row[3], &conf->disabled) != 0)
     {
     mysql_free_result(res);
     errorStr = "User \'" + login + "\' data not read. Parameter Down.";
@@ -774,7 +777,7 @@ if (GetInt(row[3], &conf->disabled, 0) != 0)
     return -1;
     }
 
-if (GetInt(row[4], &conf->disabledDetailStat, 0) != 0)
+if (GetInt(row[4], &conf->disabledDetailStat) != 0)
     {
     mysql_free_result(res);
     errorStr = "User \'" + login + "\' data not read. Parameter DisabledDetailStat.";
@@ -782,7 +785,7 @@ if (GetInt(row[4], &conf->disabledDetailStat, 0) != 0)
     return -1;
     }
 
-if (GetInt(row[5], &conf->alwaysOnline, 0) != 0)
+if (GetInt(row[5], &conf->alwaysOnline) != 0)
     {
     mysql_free_result(res);
     errorStr = "User \'" + login + "\' data not read. Parameter AlwaysOnline.";
@@ -824,13 +827,13 @@ for (int i = 0; i < USERDATA_NUM; i++)
 
 GetTime(row[15+USERDATA_NUM], &conf->creditExpire, 0);
     
-string ipStr = row[16+USERDATA_NUM];
+std::string ipStr = row[16+USERDATA_NUM];
 USER_IPS i;
 try
     {
     i = StrToIPS(ipStr);
     }
-catch (const string & s)
+catch (const std::string & s)
     {
     mysql_free_result(res);
     errorStr = "User \'" + login + "\' data not read. Parameter IP address. " + s;
@@ -845,13 +848,13 @@ mysql_close(sock);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreUserStat(USER_STAT * stat, const string & login) const
+int MYSQL_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login) const
 {
 MYSQL_RES *res;
 MYSQL_ROW row;
 MYSQL * sock;
 
-string query;
+std::string query;
 
 query = "SELECT ";
 
@@ -896,7 +899,7 @@ for (int i = 0; i < DIR_NUM; i++)
     if (GetULongLongInt(row[startPos+i*2], &traff, 0) != 0)
         {
         mysql_free_result(res);
-        errorStr = "User \'" + login + "\' stat not read. Parameter " + string(s);
+        errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
         mysql_close(sock);
         return -1;
         }
@@ -906,7 +909,7 @@ for (int i = 0; i < DIR_NUM; i++)
     if (GetULongLongInt(row[startPos+i*2+1], &traff, 0) != 0)
         {
         mysql_free_result(res);
-        errorStr =   "User \'" + login + "\' stat not read. Parameter " + string(s);
+        errorStr =   "User \'" + login + "\' stat not read. Parameter " + std::string(s);
         mysql_close(sock);
         return -1;
         }
@@ -968,10 +971,10 @@ mysql_close(sock);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::SaveUserConf(const USER_CONF & conf, const string & login) const
+int MYSQL_STORE::SaveUserConf(const USER_CONF & conf, const std::string & login) const
 {
-string param;
-string res;
+std::string param;
+std::string res;
 
 strprintf(&res,"UPDATE users SET Password='%s', Passive=%d, Down=%d, DisabledDetailStat = %d, "\
     "AlwaysOnline=%d, Tariff='%s', Address='%s', Phone='%s', Email='%s', "\
@@ -1002,7 +1005,7 @@ for (int i = 0; i < USERDATA_NUM; i++)
 strprintf(&param, " CreditExpire=%d,", conf.creditExpire);
 res += param;
 
-stringstream ipStr;
+std::ostringstream ipStr;
 ipStr << conf.ips;
 
 strprintf(&param, " IP='%s'", ipStr.str().c_str());
@@ -1021,10 +1024,10 @@ if(MysqlSetQuery(res.c_str()))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::SaveUserStat(const USER_STAT & stat, const string & login) const
+int MYSQL_STORE::SaveUserStat(const USER_STAT & stat, const std::string & login) const
 {
-string param;
-string res;
+std::string param;
+std::string res;
 
 res = "UPDATE users SET";
 
@@ -1061,9 +1064,9 @@ if(MysqlSetQuery(res.c_str()))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteLogString(const string & str, const string & login) const
+int MYSQL_STORE::WriteLogString(const std::string & str, const std::string & login) const
 {
-string res, tempStr;
+std::string res, tempStr;
 time_t t;
 tm * lt;
 
@@ -1085,7 +1088,7 @@ if (!(result=mysql_list_tables(sock,tempStr.c_str() )))
     return -1;
 }
 
-unsigned int num_rows =  mysql_num_rows(result);
+my_ulonglong num_rows =  mysql_num_rows(result);
 
 mysql_free_result(result);
 
@@ -1105,7 +1108,7 @@ if (num_rows < 1)
 
 strprintf(&res, "%s -- %s",LogDate(t), str.c_str());
 
-string send;
+std::string send;
 
 strprintf(&send,"INSERT INTO logs_%02d_%4d SET login='%s', text='%s'",
         lt->tm_mon+1, lt->tm_year+1900,
@@ -1123,42 +1126,42 @@ return 0;
 
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteUserChgLog(const string & login,
-                                 const string & admLogin,
+int MYSQL_STORE::WriteUserChgLog(const std::string & login,
+                                 const std::string & admLogin,
                                  uint32_t       admIP,
-                                 const string & paramName,
-                                 const string & oldValue,
-                                 const string & newValue,
-                                 const string & message) const
+                                 const std::string & paramName,
+                                 const std::string & oldValue,
+                                 const std::string & newValue,
+                                 const std::string & message) const
 {
-string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
+std::string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
     + paramName + "\' parameter changed from \'" + oldValue +
     "\' to \'" + newValue + "\'. " + message;
 
 return WriteLogString(userLogMsg, login);
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int MYSQL_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
 {
-string logStr = "Connect, " + inet_ntostring(ip);
+std::string logStr = "Connect, " + inet_ntostring(ip);
 return WriteLogString(logStr, login);
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteUserDisconnect(const string & login,
+int MYSQL_STORE::WriteUserDisconnect(const std::string & login,
                                      const DIR_TRAFF & up,
                                      const DIR_TRAFF & down,
                                      const DIR_TRAFF & sessionUp,
                                      const DIR_TRAFF & sessionDown,
                                      double cash,
-                                     double freeMb,
-                                     const std::string & reason) const
+                                     double /*freeMb*/,
+                                     const std::string & /*reason*/) const
 {
-string logStr = "Disconnect, ";
-stringstream sssu;
-stringstream sssd;
-stringstream ssmu;
-stringstream ssmd;
-stringstream sscash;
+std::string logStr = "Disconnect, ";
+std::ostringstream sssu;
+std::ostringstream sssd;
+std::ostringstream ssmu;
+std::ostringstream ssmd;
+std::ostringstream sscash;
 
 ssmu << up;
 ssmd << down;
@@ -1184,9 +1187,9 @@ return WriteLogString(logStr, login);
 }
 //-----------------------------------------------------------------------------
 int MYSQL_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, 
-                                const string & login) const
+                                const std::string & login) const
 {
-string param, res;
+std::string param, res;
 
 strprintf(&res, "INSERT INTO stat SET login='%s', month=%d, year=%d,", 
     login.c_str(), month+1, year+1900);
@@ -1213,7 +1216,7 @@ if(MysqlSetQuery(res.c_str()))
 return 0;
 }
 //-----------------------------------------------------------------------------*/
-int MYSQL_STORE::AddAdmin(const string & login) const
+int MYSQL_STORE::AddAdmin(const std::string & login) const
 {
 sprintf(qbuf,"INSERT INTO admins SET login='%s'", login.c_str());
     
@@ -1227,7 +1230,7 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------*/
-int MYSQL_STORE::DelAdmin(const string & login) const
+int MYSQL_STORE::DelAdmin(const std::string & login) const
 {
 sprintf(qbuf,"DELETE FROM admins where login='%s' LIMIT 1", login.c_str());
     
@@ -1288,7 +1291,7 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
+int MYSQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
 {
 char pass[ADM_PASSWD_LEN + 1];
 char password[ADM_PASSWD_LEN + 1];
@@ -1299,7 +1302,7 @@ memset(pass, 0, sizeof(pass));
 memset(password, 0, sizeof(password));
 memset(passwordE, 0, sizeof(passwordE));
 
-string p;
+std::string p;
 MYSQL_RES *res;
 MYSQL_ROW row;
 MYSQL * sock;
@@ -1332,7 +1335,6 @@ if ( mysql_num_rows(res) == 0)
 row = mysql_fetch_row(res);
 
 p = row[1];
-int a;
 
 if(p.length() == 0)
 {
@@ -1364,7 +1366,9 @@ else
 
 ac->password = password;
 
-if (GetInt(row[2], &a, 0) == 0) 
+uint16_t a;
+
+if (GetInt(row[2], &a) == 0) 
     ac->priv.userConf = a;
 else
     {
@@ -1374,7 +1378,7 @@ else
     return -1;
     }
 
-if (GetInt(row[3], &a, 0) == 0) 
+if (GetInt(row[3], &a) == 0) 
     ac->priv.userPasswd = a;
 else
     {
@@ -1384,7 +1388,7 @@ else
     return -1;
     }
 
-if (GetInt(row[4], &a, 0) == 0) 
+if (GetInt(row[4], &a) == 0) 
     ac->priv.userStat = a;
 else
     {
@@ -1394,7 +1398,7 @@ else
     return -1;
     }
 
-if (GetInt(row[5], &a, 0) == 0) 
+if (GetInt(row[5], &a) == 0) 
     ac->priv.userCash = a;
 else
     {
@@ -1404,7 +1408,7 @@ else
     return -1;
     }
 
-if (GetInt(row[6], &a, 0) == 0) 
+if (GetInt(row[6], &a) == 0) 
     ac->priv.userAddDel = a;
 else
     {
@@ -1414,7 +1418,7 @@ else
     return -1;
     }
 
-if (GetInt(row[7], &a, 0) == 0) 
+if (GetInt(row[7], &a) == 0) 
     ac->priv.tariffChg = a;
 else
     {
@@ -1424,7 +1428,7 @@ else
     return -1;
     }
 
-if (GetInt(row[8], &a, 0) == 0) 
+if (GetInt(row[8], &a) == 0) 
     ac->priv.adminChg = a;
 else
     {
@@ -1439,7 +1443,7 @@ mysql_close(sock);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::AddTariff(const string & name) const
+int MYSQL_STORE::AddTariff(const std::string & name) const
 {
 sprintf(qbuf,"INSERT INTO tariffs SET name='%s'", name.c_str());
     
@@ -1453,7 +1457,7 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::DelTariff(const string & name) const
+int MYSQL_STORE::DelTariff(const std::string & name) const
 {
 sprintf(qbuf,"DELETE FROM tariffs WHERE name='%s' LIMIT 1", name.c_str());
     
@@ -1467,7 +1471,7 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreTariff(TARIFF_DATA * td, const string & tariffName) const
+int MYSQL_STORE::RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const
 {
 MYSQL_RES *res;
 MYSQL_ROW row;
@@ -1490,12 +1494,12 @@ if (!(res=mysql_store_result(sock)))
     return -1;
 }
 
-string str;
+std::string str;
 td->tariffConf.name = tariffName;
 
 row = mysql_fetch_row(res);
 
-string param;
+std::string param;
 for (int i = 0; i<DIR_NUM; i++)
     {
     strprintf(&param, "Time%d", i);
@@ -1555,7 +1559,7 @@ for (int i = 0; i<DIR_NUM; i++)
     td->dirPrice[i].priceNightB /= (1024*1024);
 
     strprintf(&param, "Threshold%d", i);
-    if (GetInt(row[5+i*8], &td->dirPrice[i].threshold, 0) < 0)
+    if (GetInt(row[5+i*8], &td->dirPrice[i].threshold) < 0)
         {
         mysql_free_result(res);
         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
@@ -1564,7 +1568,7 @@ for (int i = 0; i<DIR_NUM; i++)
         }
 
     strprintf(&param, "SinglePrice%d", i);
-    if (GetInt(row[8+i*8], &td->dirPrice[i].singlePrice, 0) < 0)
+    if (GetInt(row[8+i*8], &td->dirPrice[i].singlePrice) < 0)
         {
         mysql_free_result(res);
         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
@@ -1573,7 +1577,7 @@ for (int i = 0; i<DIR_NUM; i++)
         }
 
     strprintf(&param, "NoDiscount%d", i);
-    if (GetInt(row[7+i*8], &td->dirPrice[i].noDiscount, 0) < 0)
+    if (GetInt(row[7+i*8], &td->dirPrice[i].noDiscount) < 0)
         {
         mysql_free_result(res);
         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
@@ -1661,11 +1665,11 @@ mysql_close(sock);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::SaveTariff(const TARIFF_DATA & td, const string & tariffName) const
+int MYSQL_STORE::SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const
 {
-string param;
+std::string param;
 
-string res="UPDATE tariffs SET";
+std::string res="UPDATE tariffs SET";
 
 for (int i = 0; i < DIR_NUM; i++)
     {
@@ -1689,7 +1693,7 @@ for (int i = 0; i < DIR_NUM; i++)
         td.dirPrice[i].threshold);
     res += param;
 
-    string s;
+    std::string s;
     strprintf(&param, " Time%d", i);
 
     strprintf(&s, "%0d:%0d-%0d:%0d", 
@@ -1750,11 +1754,11 @@ if(MysqlSetQuery(res.c_str()))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree, 
+int MYSQL_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree, 
                                    time_t lastStat, 
-                                   const string & login) const
+                                   const std::string & login) const
 {
-string res, stTime, endTime, tempStr;
+std::string res, stTime, endTime, tempStr;
 time_t t;
 tm * lt;
 
@@ -1784,7 +1788,7 @@ if (!(result=mysql_list_tables(sock,tempStr.c_str() )))
     return -1;
 }
 
-unsigned int num_rows =  mysql_num_rows(result);
+my_ulonglong num_rows =  mysql_num_rows(result);
 
 mysql_free_result(result);
 
@@ -1835,7 +1839,7 @@ strprintf(&res,"INSERT INTO detailstat_%02d_%4d SET login='%s',"\
     endTime.c_str()
     );
 
-map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
+std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
 stIter = statTree.begin();
 
 while (stIter != statTree.end())
@@ -1866,17 +1870,17 @@ mysql_close(sock);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int MYSQL_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
 {
 struct timeval tv;
 
 gettimeofday(&tv, NULL);
 
-msg->header.id = ((long long)tv.tv_sec) * 1000000 + ((long long)tv.tv_usec);
+msg->header.id = static_cast<uint64_t>(tv.tv_sec) * 1000000 + static_cast<uint64_t>(tv.tv_usec);
 
 sprintf(qbuf,"INSERT INTO messages SET login='%s', id=%lld", 
     login.c_str(),
-    (long long)msg->header.id
+    static_cast<long long>(msg->header.id)
     );
     
 if(MysqlSetQuery(qbuf))
@@ -1889,9 +1893,9 @@ if(MysqlSetQuery(qbuf))
 return EditMessage(*msg, login);
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::EditMessage(const STG_MSG & msg, const string & login) const
+int MYSQL_STORE::EditMessage(const STG_MSG & msg, const std::string & login) const
 {
-string res;
+std::string res;
 
 strprintf(&res,"UPDATE messages SET type=%d, lastSendTime=%u, creationTime=%u, "\
     "showTime=%u, stgRepeat=%d, repeatPeriod=%u, text='%s' "\
@@ -1904,7 +1908,7 @@ strprintf(&res,"UPDATE messages SET type=%d, lastSendTime=%u, creationTime=%u, "
     msg.header.repeatPeriod,
     (ReplaceStr(msg.text,badSyms,repSym)).c_str(),
     login.c_str(),
-    (long long)msg.header.id
+    msg.header.id
     );
 
 if(MysqlSetQuery(res.c_str()))
@@ -1917,7 +1921,7 @@ if(MysqlSetQuery(res.c_str()))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::GetMessage(uint64_t id, STG_MSG * msg, const string & login) const
+int MYSQL_STORE::GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const
 {
 MYSQL_RES *res;
 MYSQL_ROW row;
@@ -2000,10 +2004,10 @@ mysql_close(sock);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::DelMessage(uint64_t id, const string & login) const
+int MYSQL_STORE::DelMessage(uint64_t id, const std::string & login) const
 {
 sprintf(qbuf,"DELETE FROM messages WHERE login='%s' AND id=%lld LIMIT 1", 
-    login.c_str(),(long long)id);
+        login.c_str(), static_cast<long long>(id));
     
 if(MysqlSetQuery(qbuf))
 {
@@ -2015,7 +2019,7 @@ if(MysqlSetQuery(qbuf))
 return 0;
 }
 //-----------------------------------------------------------------------------
-int MYSQL_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const string & login) const
+int MYSQL_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const
 {
 MYSQL_RES *res;
 MYSQL_ROW row;
@@ -2038,10 +2042,11 @@ if (!(res=mysql_store_result(sock)))
     return -1;
 }
 
-unsigned int i, num_rows =  mysql_num_rows(res);
-long long int unsigned id = 0;
+unsigned int i;
+my_ulonglong num_rows = mysql_num_rows(res);
+uint64_t id = 0;
 
-for (i=0; i<num_rows; i++)
+for (i = 0; i < num_rows; i++)
 {
     row = mysql_fetch_row(res);
     if (str2x(row[1], id))
index 8818f590cb603291aba8a481c1d318f6f910f0f8..4a492b3833694ece04130acf72fc81be96e78034 100644 (file)
 #include <mysql/mysql.h>
 
 #include <string>
+#include <vector>
+#include <map>
 
 #include "stg/module_settings.h"
 #include "stg/store.h"
 #include "stg/user_traff.h"
+#include "stg/logger.h"
 
-using namespace std;
-//-----------------------------------------------------------------------------
-extern "C" STORE * GetStore();
-class STG_LOGGER;
 //-----------------------------------------------------------------------------
 class MYSQL_STORE_SETTINGS
 {
@@ -26,12 +25,12 @@ public:
     MYSQL_STORE_SETTINGS();
     virtual ~MYSQL_STORE_SETTINGS() {}
     virtual int ParseSettings(const MODULE_SETTINGS & s);
-    virtual const string & GetStrError() const { return errorStr; }
+    virtual const std::string & GetStrError() const { return errorStr; }
 
-    const string & GetDBUser() const { return dbUser; }
-    const string & GetDBPassword() const { return dbPass; }
-    const string & GetDBHost() const { return dbHost; }
-    const string & GetDBName() const { return dbName; }
+    const std::string & GetDBUser() const { return dbUser; }
+    const std::string & GetDBPassword() const { return dbPass; }
+    const std::string & GetDBHost() const { return dbHost; }
+    const std::string & GetDBName() const { return dbName; }
 
 private:
     MYSQL_STORE_SETTINGS(const MYSQL_STORE_SETTINGS & rvalue);
@@ -39,15 +38,15 @@ private:
 
     const MODULE_SETTINGS * settings;
 
-    int     ParseParam(const vector<PARAM_VALUE> & moduleParams, 
-                       const string & name, string & result);
+    int     ParseParam(const std::vector<PARAM_VALUE> & moduleParams, 
+                       const std::string & name, std::string & result);
 
-    string  errorStr;
+    std::string  errorStr;
 
-    string  dbUser;
-    string  dbPass;
-    string  dbName;
-    string  dbHost;
+    std::string  dbUser;
+    std::string  dbPass;
+    std::string  dbName;
+    std::string  dbHost;
 };
 //-----------------------------------------------------------------------------
 class MYSQL_STORE: public STORE
@@ -55,25 +54,25 @@ class MYSQL_STORE: public STORE
 public:
     MYSQL_STORE();
     virtual ~MYSQL_STORE() {}
-    virtual const string & GetStrError() const { return errorStr; }
+    virtual const std::string & GetStrError() const { return errorStr; }
 
     //User
-    virtual int GetUsersList(vector<string> * usersList) const;
-    virtual int AddUser(const string & login) const;
-    virtual int DelUser(const string & login) const;
-    virtual int SaveUserStat(const USER_STAT & stat, const string & login) const;
-    virtual int SaveUserConf(const USER_CONF & conf, const string & login) const;
-    virtual int RestoreUserStat(USER_STAT * stat, const string & login) const;
-    virtual int RestoreUserConf(USER_CONF * conf, const string & login) const;
-    virtual int WriteUserChgLog(const string & login,
-                                const string & admLogin,
+    virtual int GetUsersList(std::vector<std::string> * usersList) const;
+    virtual int AddUser(const std::string & login) const;
+    virtual int DelUser(const std::string & login) const;
+    virtual int SaveUserStat(const USER_STAT & stat, const std::string & login) const;
+    virtual int SaveUserConf(const USER_CONF & conf, const std::string & login) const;
+    virtual int RestoreUserStat(USER_STAT * stat, const std::string & login) const;
+    virtual int RestoreUserConf(USER_CONF * conf, const std::string & login) const;
+    virtual int WriteUserChgLog(const std::string & login,
+                                const std::string & admLogin,
                                 uint32_t       admIP,
-                                const string & paramName,
-                                const string & oldValue,
-                                const string & newValue,
-                                const string & message = "") const;
-    virtual int WriteUserConnect(const string & login, uint32_t ip) const;
-    virtual int WriteUserDisconnect(const string & login,
+                                const std::string & paramName,
+                                const std::string & oldValue,
+                                const std::string & newValue,
+                                const std::string & message = "") const;
+    virtual int WriteUserConnect(const std::string & login, uint32_t ip) const;
+    virtual int WriteUserDisconnect(const std::string & login,
                                     const DIR_TRAFF & up,
                                     const DIR_TRAFF & down,
                                     const DIR_TRAFF & sessionUp,
@@ -82,69 +81,70 @@ public:
                                     double freeMb,
                                     const std::string & reason) const;
 
-    virtual int WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+    virtual int WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
                                   time_t lastStat,
-                                  const string & login) const;
+                                  const std::string & login) const;
 
-    virtual int AddMessage(STG_MSG * msg, const string & login) const;
-    virtual int EditMessage(const STG_MSG & msg, const string & login) const;
-    virtual int GetMessage(uint64_t id, STG_MSG * msg, const string & login) const;
-    virtual int DelMessage(uint64_t id, const string & login) const;
-    virtual int GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const string & login) const;
+    virtual int AddMessage(STG_MSG * msg, const std::string & login) const;
+    virtual int EditMessage(const STG_MSG & msg, const std::string & login) const;
+    virtual int GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const;
+    virtual int DelMessage(uint64_t id, const std::string & login) const;
+    virtual int GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const;
 
-    virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const;
+    virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const;
 
     //Admin
-    virtual int GetAdminsList(vector<string> * adminsList) const;
-    virtual int AddAdmin(const string & login) const;
-    virtual int DelAdmin(const string & login) const;
-    virtual int RestoreAdmin(ADMIN_CONF * ac, const string & login) const;
+    virtual int GetAdminsList(std::vector<std::string> * adminsList) const;
+    virtual int AddAdmin(const std::string & login) const;
+    virtual int DelAdmin(const std::string & login) const;
+    virtual int RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const;
     virtual int SaveAdmin(const ADMIN_CONF & ac) const;
 
     //Tariff
-    virtual int GetTariffsList(vector<string> * tariffsList) const;
-    virtual int AddTariff(const string & name) const;
-    virtual int DelTariff(const string & name) const;
-    virtual int SaveTariff(const TARIFF_DATA & td, const string & tariffName) const;
-    virtual int RestoreTariff(TARIFF_DATA * td, const string & tariffName) const;
+    virtual int GetTariffsList(std::vector<std::string> * tariffsList) const;
+    virtual int AddTariff(const std::string & name) const;
+    virtual int DelTariff(const std::string & name) const;
+    virtual int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const;
+    virtual int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const;
 
     //Corparation
-    virtual int GetCorpsList(vector<string> *) const {return 0;};
-    virtual int SaveCorp(const CORP_CONF &) const {return 0;};
-    virtual int RestoreCorp(CORP_CONF *, const string &) const {return 0;};
-    virtual int AddCorp(const string &) const {return 0;};
-    virtual int DelCorp(const string &) const {return 0;};
+    virtual int GetCorpsList(std::vector<std::string> *) const {return 0;}
+    virtual int SaveCorp(const CORP_CONF &) const {return 0;}
+    virtual int RestoreCorp(CORP_CONF *, const std::string &) const {return 0;}
+    virtual int AddCorp(const std::string &) const {return 0;}
+    virtual int DelCorp(const std::string &) const {return 0;}
 
     // Services
-    virtual int GetServicesList(vector<string> *) const {return 0;};
-    virtual int SaveService(const SERVICE_CONF &) const {return 0;};
-    virtual int RestoreService(SERVICE_CONF *, const string &) const {return 0;};
-    virtual int AddService(const string &) const {return 0;};
-    virtual int DelService(const string &) const {return 0;};
+    virtual int GetServicesList(std::vector<std::string> *) const {return 0;}
+    virtual int SaveService(const SERVICE_CONF &) const {return 0;}
+    virtual int RestoreService(SERVICE_CONF *, const std::string &) const {return 0;}
+    virtual int AddService(const std::string &) const {return 0;}
+    virtual int DelService(const std::string &) const {return 0;}
 
     virtual void            SetSettings(const MODULE_SETTINGS & s) { settings = s; }
     virtual int             ParseSettings();
-    virtual const string &  GetVersion() const { return version; }
+    virtual const std::string &  GetVersion() const { return version; }
 
 private:
     MYSQL_STORE(const MYSQL_STORE & rvalue);
     MYSQL_STORE & operator=(const MYSQL_STORE & rvalue);
 
-    virtual int WriteLogString(const string & str, const string & login) const;
-    int GetAllParams(vector<string> * ParamList, const string & table, const string & name) const;
+    virtual int WriteLogString(const std::string & str, const std::string & login) const;
+    int GetAllParams(std::vector<std::string> * ParamList, const std::string & table, const std::string & name) const;
     int CheckAllTables(MYSQL * sock);
     int MakeUpdates(MYSQL * sock);
-    bool IsTablePresent(const string & str,MYSQL * sock);
-    mutable string          errorStr;
-    int                     MysqlQuery(const char* sQuery,MYSQL * sock) const;
+    bool IsTablePresent(const std::string & str,MYSQL * sock);
+    mutable std::string          errorStr;
+    int                        MysqlQuery(const char* sQuery,MYSQL * sock) const;
     int                     MysqlGetQuery(const char * Query,MYSQL * & sock) const;
     int                     MysqlSetQuery(const char * Query) const;
     MYSQL  *                MysqlConnect() const ;
-    string                  version;
+    std::string                  version;
     MYSQL_STORE_SETTINGS    storeSettings;
     MODULE_SETTINGS         settings;
     int                     schemaVersion;
-    STG_LOGGER &            WriteServLog;
+
+    PLUGIN_LOGGER           logger;
 };
 //-----------------------------------------------------------------------------
 
index 990d965a62de35d9840a11f4e20f91c02720bc72..0bd8f629771d74ebf7d13e125250853367564c63 100644 (file)
@@ -17,8 +17,8 @@ SRCS =        ./postgresql_store.cpp \
 
 STGLIBS = common \
          crypto \
-         logger \
-         locker
+         locker \
+         logger
 
 PG_CFLAGS = $(shell pg_config --includedir)
 PG_LDFLAGS = $(shell pg_config --libdir)
index 51eec8f414626463cb72a99b61873e44d5309283..49f0e8088f8f5dc06370dc947beb4b56067eeaf2 100644 (file)
  *
  */
 
-#include <string>
-#include <vector>
-#include <algorithm>
-
-#include <libpq-fe.h>
+#include "postgresql_store.h"
 
 #include "stg/module_settings.h"
 #include "stg/plugin_creator.h"
-#include "stg/logger.h"
-#include "postgresql_store_utils.h"
-#include "postgresql_store.h"
 
-PLUGIN_CREATOR<POSTGRESQL_STORE> pqStoreeCreator;
+#include <libpq-fe.h>
+
+#include <string>
+#include <vector>
+
+namespace
+{
+PLUGIN_CREATOR<POSTGRESQL_STORE> pgsc;
+}
+
+extern "C" STORE * GetStore();
 
 //-----------------------------------------------------------------------------
 STORE * GetStore()
 {
-return pqStoreeCreator.GetPlugin();
+return pgsc.GetPlugin();
 }
 
 //-----------------------------------------------------------------------------
@@ -72,7 +75,7 @@ POSTGRESQL_STORE::POSTGRESQL_STORE()
       version(0),
       retries(3),
       connection(NULL),
-      WriteServLog(GetStgLogger())
+      logger(GetPluginLogger(GetStgLogger(), "store_postgresql"))
 {
 pthread_mutex_init(&mutex, NULL);
 }
@@ -89,37 +92,25 @@ pthread_mutex_destroy(&mutex);
 int POSTGRESQL_STORE::ParseSettings()
 {
 std::vector<PARAM_VALUE>::iterator i;
-string s;
 
 for(i = settings.moduleParams.begin(); i != settings.moduleParams.end(); ++i)
     {
-    s = i->param;
-    std::transform(s.begin(), s.end(), s.begin(), ToLower());
-    if (s == "server")
-        {
+    std::string param(ToLower(i->param));
+    if (param == "server")
         server = *(i->value.begin());
-        }
-    if (s == "database")
-        {
+    else if (param == "database")
         database = *(i->value.begin());
-        }
-    if (s == "user")
-        {
+    else if (param == "user")
         user = *(i->value.begin());
-        }
-    if (s == "password")
-        {
+    else if (param == "password")
         password = *(i->value.begin());
-        }
-    if (s == "retries")
-        {
+    else if (param == "retries")
         if (str2x(*(i->value.begin()), retries))
             {
             strError = "Invalid 'retries' value";
             printfd(__FILE__, "POSTGRESQL_STORE::ParseSettings(): '%s'\n", strError.c_str());
             return -1;
             }
-        }
     }
 
 clientEncoding = "KOI8";
index a88df88b93fba855bb1d4d612d39254e2e5d9012..72a2c22c01c951fbd7bed410f12189036456776b 100644 (file)
 
 #include <string>
 #include <vector>
-#include <map>
 
 #include "stg/store.h"
+#include "stg/logger.h"
 
 // Minimal DB version is 5
 // Recommended DB version is 6 (support FreeMb logging on disconnects)
 #define DB_MIN_VERSION 5
 
-extern "C" STORE * GetStore();
-
-class STG_LOGGER;
-
 class POSTGRESQL_STORE : public STORE {
 public:
     POSTGRESQL_STORE();
@@ -98,7 +94,7 @@ public:
     // Tariffs
     int GetTariffsList(std::vector<std::string> * tariffsList) const;
     int AddTariff(const std::string & name) const;
-    int DelTariff(const string & name) const;
+    int DelTariff(const std::string & name) const;
     int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const;
     int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const;
 
@@ -117,11 +113,11 @@ public:
     int DelService(const std::string & name) const;
 
     // Settings
-    inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; };
+    inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; }
     int ParseSettings();
 
-    inline const string & GetStrError() const { return strError; };
-    inline const string & GetVersion() const { return versionString; };
+    inline const std::string & GetStrError() const { return strError; }
+    inline const std::string & GetVersion() const { return versionString; }
 private:
     POSTGRESQL_STORE(const POSTGRESQL_STORE & rvalue);
     POSTGRESQL_STORE & operator=(const POSTGRESQL_STORE & rvalue);
@@ -132,8 +128,8 @@ private:
 
     int EscapeString(std::string & value) const;
 
-    std::string Int2TS(uint32_t value) const;
-    uint32_t TS2Int(const std::string & value) const;
+    std::string Int2TS(time_t value) const;
+    time_t TS2Int(const std::string & value) const;
 
     int SaveStat(const USER_STAT & stat, const std::string & login, int year = 0, int month = 0) const;
 
@@ -161,9 +157,7 @@ private:
 
     PGconn * connection;
 
-    STG_LOGGER & WriteServLog;
+    PLUGIN_LOGGER logger;
 };
 
-extern const volatile time_t stgTime;
-
 #endif //POSTGRESQL_STORE_H
index 5b27cb8034cb7996b5c2cecfc3d76e0fbe85064c..1e9db12dbd3731f05b5f2acfb71f14a6421f06cc 100644 (file)
@@ -134,10 +134,10 @@ for (int i = 0; i < ADM_PASSWD_LEN / 8; i++)
 cryptedPass[ADM_PASSWD_LEN] = 0;
 Encode12(encodedPass, cryptedPass, ADM_PASSWD_LEN);
 
-std::string password = encodedPass;
+std::string pass = encodedPass;
 std::string login = ac.login;
 
-if (EscapeString(password))
+if (EscapeString(pass))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveAdmin(): 'Failed to escape password'\n");
     if (RollbackTransaction())
@@ -159,7 +159,7 @@ if (EscapeString(login))
 
 std::stringstream query;
 query << "UPDATE tb_admins SET "
-          << "passwd = '" << password << "', "
+          << "passwd = '" << pass << "', "
           << "chg_conf = " << ac.priv.userConf << ", "
           << "chg_password = " << ac.priv.userPasswd << ", "
           << "chg_stat = " << ac.priv.userStat << ", "
@@ -195,7 +195,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
+int POSTGRESQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -234,7 +234,7 @@ if (EscapeString(elogin))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT login, passwd, \
                  chg_conf, chg_password, chg_stat, \
                  chg_cash, usr_add_del, chg_tariff, \
@@ -316,7 +316,7 @@ ac->password = adminPass;
 return 0;
 }
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddAdmin(const string & login) const
+int POSTGRESQL_STORE::AddAdmin(const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -351,7 +351,7 @@ if (EscapeString(elogin))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "INSERT INTO tb_admins \
               (login, passwd, \
               chg_conf, chg_password, chg_stat, \
@@ -386,7 +386,7 @@ if (CommitTransaction())
 return 0;
 }
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelAdmin(const string & login) const
+int POSTGRESQL_STORE::DelAdmin(const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -421,7 +421,7 @@ if (EscapeString(elogin))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "DELETE FROM tb_admins WHERE login = '" << elogin << "'";
 
 result = PQexec(connection, query.str().c_str());
index c358a4c5fb7364e0c4f1b9ff9d97e21a96bdef0e..1d33d5b0f85a3ed6fc72430aa2ca412b31ada313 100644 (file)
@@ -36,7 +36,7 @@
 #include "stg/locker.h"
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetCorpsList(vector<string> * corpsList) const
+int POSTGRESQL_STORE::GetCorpsList(std::vector<std::string> * corpsList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -127,7 +127,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "UPDATE tb_corporations SET "
           << "cash = " << cc.cash
       << "WHERE name = '" << ename << "'";
@@ -158,7 +158,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::RestoreCorp(CORP_CONF * cc, const string & name) const
+int POSTGRESQL_STORE::RestoreCorp(CORP_CONF * cc, const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -193,7 +193,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT cash FROM tb_corporations WHERE name = '" << ename << "'";
 
 result = PQexec(connection, query.str().c_str());
@@ -241,7 +241,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddCorp(const string & name) const
+int POSTGRESQL_STORE::AddCorp(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -276,7 +276,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "INSERT INTO tb_corporations \
               (name, cash) \
           VALUES \
@@ -308,7 +308,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelCorp(const string & name) const
+int POSTGRESQL_STORE::DelCorp(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -343,7 +343,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "DELETE FROM tb_corporations WHERE name = '" << ename << "'";
 
 result = PQexec(connection, query.str().c_str());
index 4260c3b4493551da4c0aef7e674b7c5e11a7839a..bccef5aa4a805ae40e9dc0831cacbead6fa4087c 100644 (file)
@@ -38,7 +38,7 @@
 #include "stg/message.h"
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int POSTGRESQL_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -84,7 +84,7 @@ if (EscapeString(etext))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT sp_add_message("
       << "'" << elogin << "', "
       << "CAST(1 AS SMALLINT), " // Here need to be a version, but, it's uninitiated actually
@@ -141,7 +141,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::EditMessage(const STG_MSG & msg,
-                                  const string & login) const
+                                  const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -187,7 +187,7 @@ if (EscapeString(etext))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "UPDATE tb_messages SET "
           << "fk_user = (SELECT pk_user FROM tb_users WHERE name = '" << elogin << "'), "
           << "ver = " << msg.header.ver << ", "
@@ -227,7 +227,7 @@ return 0;
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::GetMessage(uint64_t id,
                                STG_MSG * msg,
-                               const string &) const
+                               const std::string &) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -242,7 +242,7 @@ if (PQstatus(connection) != CONNECTION_OK)
         }
     }
 
-string login;
+std::string login;
 PGresult * result;
 
 if (StartTransaction())
@@ -251,7 +251,7 @@ if (StartTransaction())
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT ver, msg_type, last_send_time, \
                  creation_time, show_time, repeat, \
                  repeat_period, msg_text \
@@ -286,17 +286,10 @@ if (tuples != 1)
     return -1;
     }
 
-/*std::stringstream tuple;
-
-for (int i = 0; i < 8; ++i)
-    {
-    tuple << PQgetvalue(result, 0, i) << " ";
-    }*/
-
 str2x(PQgetvalue(result, 0, 0), msg->header.ver);
 str2x(PQgetvalue(result, 0, 1), msg->header.type);
-msg->header.lastSendTime = TS2Int(PQgetvalue(result, 0, 2));
-msg->header.creationTime = TS2Int(PQgetvalue(result, 0, 3));
+msg->header.lastSendTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, 0, 2)));
+msg->header.creationTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, 0, 3)));
 str2x(PQgetvalue(result, 0, 4), msg->header.showTime);
 str2x(PQgetvalue(result, 0, 5), msg->header.repeat);
 str2x(PQgetvalue(result, 0, 6), msg->header.repeatPeriod);
@@ -304,15 +297,6 @@ msg->text = PQgetvalue(result, 0, 7);
 
 PQclear(result);
 
-/*tuple >> msg->header.ver;
-tuple >> msg->header.type;
-tuple >> msg->header.lastSendTime;
-tuple >> msg->header.creationTime;
-tuple >> msg->header.showTime;
-tuple >> msg->header.repeat;
-tuple >> msg->header.repeatPeriod;
-tuple >> msg->text;*/
-
 if (CommitTransaction())
     {
     printfd(__FILE__, "POSTGRESQL_STORE::GetMessage(): 'Failed to commit transaction'\n");
@@ -322,7 +306,7 @@ if (CommitTransaction())
 return 0;
 }
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelMessage(uint64_t id, const string &) const
+int POSTGRESQL_STORE::DelMessage(uint64_t id, const std::string &) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -345,7 +329,7 @@ if (StartTransaction())
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "DELETE FROM tb_messages WHERE pk_message = " << id;
 
 result = PQexec(connection, query.str().c_str());
@@ -373,8 +357,8 @@ if (CommitTransaction())
 return 0;
 }
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList,
-                                   const string & login) const
+int POSTGRESQL_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList,
+                                   const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -409,7 +393,7 @@ if (EscapeString(elogin))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT pk_message, ver, msg_type, \
                  last_send_time, creation_time, show_time, \
                  repeat, repeat_period \
@@ -441,8 +425,8 @@ for (int i = 0; i < tuples; ++i)
     tuple << PQgetvalue(result, i, 0) << " ";
     tuple << PQgetvalue(result, i, 1) << " ";
     tuple << PQgetvalue(result, i, 2) << " ";
-    header.lastSendTime = TS2Int(PQgetvalue(result, i, 3));
-    header.creationTime = TS2Int(PQgetvalue(result, i, 4));
+    header.lastSendTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, i, 3)));
+    header.creationTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, i, 4)));
     tuple << PQgetvalue(result, i, 5) << " ";
     tuple << PQgetvalue(result, i, 6) << " ";
     tuple << PQgetvalue(result, i, 7) << " ";
index b509c0f0202b7fdb88621dc931f744f2385f7f09..825f798261410fec3da02be913c53cdc630adaf0 100644 (file)
@@ -37,7 +37,7 @@
 #include "stg/locker.h"
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetServicesList(vector<string> * servicesList) const
+int POSTGRESQL_STORE::GetServicesList(std::vector<std::string> * servicesList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -139,7 +139,7 @@ if (EscapeString(ecomment))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "UPDATE tb_services SET "
           << "comment = '" << ecomment << "', "
           << "cost = " << sc.cost << ", "
@@ -173,7 +173,7 @@ return 0;
 
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::RestoreService(SERVICE_CONF * sc,
-                                   const string & name) const
+                                   const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -208,7 +208,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT comment, cost, pay_day FROM tb_services WHERE name = '" << ename << "'";
 
 result = PQexec(connection, query.str().c_str());
@@ -260,7 +260,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddService(const string & name) const
+int POSTGRESQL_STORE::AddService(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -295,7 +295,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "INSERT INTO tb_services \
               (name, comment, cost, pay_day) \
           VALUES \
@@ -327,7 +327,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelService(const string & name) const
+int POSTGRESQL_STORE::DelService(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -362,7 +362,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "DELETE FROM tb_services WHERE name = '" << ename << "'";
 
 result = PQexec(connection, query.str().c_str());
index ffce284614452cf9f87a3d5cd77257aaf90daffc..c9cb7ccfe79f19968eb646c81b2f57652f16985d 100644 (file)
@@ -29,6 +29,7 @@
 #include <string>
 #include <vector>
 #include <sstream>
+#include <cmath>
 
 #include <libpq-fe.h>
 
@@ -36,7 +37,7 @@
 #include "stg/locker.h"
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetTariffsList(vector<string> * tariffsList) const
+int POSTGRESQL_STORE::GetTariffsList(std::vector<std::string> * tariffsList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -92,7 +93,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddTariff(const string & name) const
+int POSTGRESQL_STORE::AddTariff(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -127,7 +128,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT sp_add_tariff('" << ename << "', " << DIR_NUM << ")";
 
 result = PQexec(connection, query.str().c_str());
@@ -155,7 +156,7 @@ if (CommitTransaction())
 return 0;
 }
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelTariff(const string & name) const
+int POSTGRESQL_STORE::DelTariff(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -190,7 +191,7 @@ if (EscapeString(ename))
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "DELETE FROM tb_tariffs WHERE name = '" << ename << "'";
 
 result = PQexec(connection, query.str().c_str());
@@ -219,7 +220,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::SaveTariff(const TARIFF_DATA & td,
-                                 const string & tariffName) const
+                                 const std::string & tariffName) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -258,10 +259,12 @@ int32_t id, i;
 double pda, pdb, pna, pnb;
 int threshold;
 
-std::stringstream query;
-query << "SELECT pk_tariff FROM tb_tariffs WHERE name = '" << ename << "'";
+    {
+    std::ostringstream query;
+    query << "SELECT pk_tariff FROM tb_tariffs WHERE name = '" << ename << "'";
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -289,26 +292,30 @@ if (tuples != 1)
     return -1;
     }
 
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0);
+    {
+    std::stringstream tuple;
+    tuple << PQgetvalue(result, 0, 0);
 
-PQclear(result);
+    PQclear(result);
 
-tuple >> id;
+    tuple >> id;
+    }
 
-query.str("");
-query << "UPDATE tb_tariffs SET \
-              fee = " << td.tariffConf.fee << ", \
-              free = " << td.tariffConf.free << ", \
-              passive_cost = " << td.tariffConf.passiveCost << ", \
-              traff_type = " << td.tariffConf.traffType;
+    {
+    std::ostringstream query;
+    query << "UPDATE tb_tariffs SET \
+                  fee = " << td.tariffConf.fee << ", \
+                  free = " << td.tariffConf.free << ", \
+                  passive_cost = " << td.tariffConf.passiveCost << ", \
+                  traff_type = " << td.tariffConf.traffType;
 
-if (version > 6)
-    query << ", period = '" << TARIFF::PeriodToString(td.tariffConf.period) << "'";
+    if (version > 6)
+        query << ", period = '" << TARIFF::PeriodToString(td.tariffConf.period) << "'";
 
-query << " WHERE pk_tariff = " << id;
+    query << " WHERE pk_tariff = " << id;
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_COMMAND_OK)
     {
@@ -350,22 +357,24 @@ for(i = 0; i < DIR_NUM; i++)
         threshold = td.dirPrice[i].threshold;
         }
 
-    std::stringstream query;
-    query << "UPDATE tb_tariffs_params SET \
-                  price_day_a = " << pda << ", \
-                  price_day_b = " << pdb << ", \
-                  price_night_a = " << pna << ", \
-                  price_night_b = " << pnb << ", \
-                  threshold = " << threshold << ", \
-                  time_day_begins = CAST('" << td.dirPrice[i].hDay
-                                            << ":"
-                                            << td.dirPrice[i].mDay << "' AS TIME), \
-                  time_day_ends = CAST('" << td.dirPrice[i].hNight
-                                          << ":"
-                                          << td.dirPrice[i].mNight << "' AS TIME) \
-             WHERE fk_tariff = " << id << " AND dir_num = " << i;
-
-    result = PQexec(connection, query.str().c_str());
+        {
+        std::ostringstream query;
+        query << "UPDATE tb_tariffs_params SET \
+                      price_day_a = " << pda << ", \
+                      price_day_b = " << pdb << ", \
+                      price_night_a = " << pna << ", \
+                      price_night_b = " << pnb << ", \
+                      threshold = " << threshold << ", \
+                      time_day_begins = CAST('" << td.dirPrice[i].hDay
+                                                << ":"
+                                                << td.dirPrice[i].mDay << "' AS TIME), \
+                      time_day_ends = CAST('" << td.dirPrice[i].hNight
+                                              << ":"
+                                              << td.dirPrice[i].mNight << "' AS TIME) \
+                 WHERE fk_tariff = " << id << " AND dir_num = " << i;
+
+        result = PQexec(connection, query.str().c_str());
+        }
 
     if (PQresultStatus(result) != PGRES_COMMAND_OK)
         {
@@ -392,7 +401,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::RestoreTariff(TARIFF_DATA * td,
-                                  const string & tariffName) const
+                                  const std::string & tariffName) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -429,7 +438,7 @@ if (EscapeString(ename))
 
 td->tariffConf.name = tariffName;
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT pk_tariff, \
                  fee, \
                  free, \
@@ -469,19 +478,22 @@ if (tuples != 1)
     return -1;
     }
 
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0) << " ";
-tuple << PQgetvalue(result, 0, 1) << " ";
-tuple << PQgetvalue(result, 0, 2) << " ";
-tuple << PQgetvalue(result, 0, 3) << " ";
-tuple << PQgetvalue(result, 0, 4) << " ";
-
 int id;
-tuple >> id;
-tuple >> td->tariffConf.fee;
-tuple >> td->tariffConf.free;
-tuple >> td->tariffConf.passiveCost;
-tuple >> td->tariffConf.traffType;
+
+    {
+    std::stringstream tuple;
+    tuple << PQgetvalue(result, 0, 0) << " ";
+    tuple << PQgetvalue(result, 0, 1) << " ";
+    tuple << PQgetvalue(result, 0, 2) << " ";
+    tuple << PQgetvalue(result, 0, 3) << " ";
+    tuple << PQgetvalue(result, 0, 4) << " ";
+
+    tuple >> id;
+    tuple >> td->tariffConf.fee;
+    tuple >> td->tariffConf.free;
+    tuple >> td->tariffConf.passiveCost;
+    tuple >> td->tariffConf.traffType;
+    }
 
 if (version > 6)
     td->tariffConf.period = TARIFF::StringToPeriod(PQgetvalue(result, 0, 5));
@@ -525,37 +537,39 @@ if (tuples != DIR_NUM)
 
 for (int i = 0; i < std::min(tuples, DIR_NUM); ++i)
     {
-    std::stringstream tuple;
-    tuple << PQgetvalue(result, i, 0) << " ";
-    tuple << PQgetvalue(result, i, 1) << " ";
-    tuple << PQgetvalue(result, i, 2) << " ";
-    tuple << PQgetvalue(result, i, 3) << " ";
-    tuple << PQgetvalue(result, i, 4) << " ";
-    tuple << PQgetvalue(result, i, 5) << " ";
-    tuple << PQgetvalue(result, i, 6) << " ";
-    tuple << PQgetvalue(result, i, 7) << " ";
-    tuple << PQgetvalue(result, i, 8) << " ";
-    tuple << PQgetvalue(result, i, 9) << " ";
-
     int dir;
 
-    tuple >> dir;
-    tuple >> td->dirPrice[dir].priceDayA;
-    td->dirPrice[dir].priceDayA /= 1024 * 1024;
-    tuple >> td->dirPrice[dir].priceDayB;
-    td->dirPrice[dir].priceDayB /= 1024 * 1024;
-    tuple >> td->dirPrice[dir].priceNightA;
-    td->dirPrice[dir].priceNightA /= 1024 * 1024;
-    tuple >> td->dirPrice[dir].priceNightB;
-    td->dirPrice[dir].priceNightB /= 1024 * 1024;
-    tuple >> td->dirPrice[dir].threshold;
-    tuple >> td->dirPrice[dir].hDay;
-    tuple >> td->dirPrice[dir].mDay;
-    tuple >> td->dirPrice[dir].hNight;
-    tuple >> td->dirPrice[dir].mNight;
-
-    if (td->dirPrice[dir].priceDayA == td->dirPrice[dir].priceNightA &&
-        td->dirPrice[dir].priceDayB == td->dirPrice[dir].priceNightB)
+        {
+        std::stringstream tuple;
+        tuple << PQgetvalue(result, i, 0) << " ";
+        tuple << PQgetvalue(result, i, 1) << " ";
+        tuple << PQgetvalue(result, i, 2) << " ";
+        tuple << PQgetvalue(result, i, 3) << " ";
+        tuple << PQgetvalue(result, i, 4) << " ";
+        tuple << PQgetvalue(result, i, 5) << " ";
+        tuple << PQgetvalue(result, i, 6) << " ";
+        tuple << PQgetvalue(result, i, 7) << " ";
+        tuple << PQgetvalue(result, i, 8) << " ";
+        tuple << PQgetvalue(result, i, 9) << " ";
+
+        tuple >> dir;
+        tuple >> td->dirPrice[dir].priceDayA;
+        td->dirPrice[dir].priceDayA /= 1024 * 1024;
+        tuple >> td->dirPrice[dir].priceDayB;
+        td->dirPrice[dir].priceDayB /= 1024 * 1024;
+        tuple >> td->dirPrice[dir].priceNightA;
+        td->dirPrice[dir].priceNightA /= 1024 * 1024;
+        tuple >> td->dirPrice[dir].priceNightB;
+        td->dirPrice[dir].priceNightB /= 1024 * 1024;
+        tuple >> td->dirPrice[dir].threshold;
+        tuple >> td->dirPrice[dir].hDay;
+        tuple >> td->dirPrice[dir].mDay;
+        tuple >> td->dirPrice[dir].hNight;
+        tuple >> td->dirPrice[dir].mNight;
+        }
+
+    if (std::fabs(td->dirPrice[dir].priceDayA - td->dirPrice[dir].priceNightA) > 1.0e-3 &&
+        std::fabs(td->dirPrice[dir].priceDayB - td->dirPrice[dir].priceNightB) > 1.0e-3)
         {
         td->dirPrice[dir].singlePrice = true;
         }
index 11c757f263b13043bda75dc54280fda34b3618b8..3331a07d411692bfe957d6085b8e968afc903a75 100644 (file)
@@ -39,7 +39,7 @@
 #include "postgresql_store.h"
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetUsersList(vector<string> * usersList) const
+int POSTGRESQL_STORE::GetUsersList(std::vector<std::string> * usersList) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -70,9 +70,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     PQclear(result);
     printfd(__FILE__, "POSTGRESQL_STORE::GetUsersList(): '%s'\n", strError.c_str());
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::GetUsersList(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::GetUsersList(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -95,7 +95,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddUser(const string & name) const
+int POSTGRESQL_STORE::AddUser(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -124,13 +124,13 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT sp_add_user('" << elogin << "')";
 
 result = PQexec(connection, query.str().c_str());
@@ -141,9 +141,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     PQclear(result);
     printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): '%s'\n", strError.c_str());
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -159,7 +159,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelUser(const string & login) const
+int POSTGRESQL_STORE::DelUser(const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -188,13 +188,13 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "DELETE FROM tb_users WHERE name = '" << elogin << "'";
 
 result = PQexec(connection, query.str().c_str());
@@ -205,9 +205,9 @@ if (PQresultStatus(result) != PGRES_COMMAND_OK)
     PQclear(result);
     printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): '%s'\n", strError.c_str());
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -223,7 +223,7 @@ return 0;
 }
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::SaveUserStat(const USER_STAT & stat,
-                                   const string & login) const
+                                   const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -231,7 +231,7 @@ return SaveStat(stat, login);
 }
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::SaveStat(const USER_STAT & stat,
-                               const string & login,
+                               const std::string & login,
                                int year,
                                int month) const
 {
@@ -260,13 +260,13 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "UPDATE tb_users SET "
             "cash = " << stat.cash << ", "
             "free_mb = " << stat.freeMb << ", "
@@ -284,9 +284,9 @@ if (PQresultStatus(result) != PGRES_COMMAND_OK)
     PQclear(result);
     printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): '%s'\n", strError.c_str());
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -303,8 +303,8 @@ for (int dir = 0; dir < DIR_NUM; ++dir)
                 "'" << elogin << "', "
                 "CAST('" << date << "' AS DATE), "
                 "CAST(" << dir << " AS SMALLINT), "
-                "CAST(" << stat.up[dir] << " AS BIGINT), "
-                "CAST(" << stat.down[dir] << " AS BIGINT))";
+                "CAST(" << stat.monthUp[dir] << " AS BIGINT), "
+                "CAST(" << stat.monthDown[dir] << " AS BIGINT))";
 
     result = PQexec(connection, query.str().c_str());
 
@@ -334,7 +334,7 @@ return 0;
 
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::SaveUserConf(const USER_CONF & conf,
-                                 const string & login) const
+                                 const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -363,13 +363,13 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT pk_user FROM tb_users WHERE name = '" << elogin << "'";
 
 result = PQexec(connection, query.str().c_str());
@@ -380,9 +380,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     PQclear(result);
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): '%s'\n", strError.c_str());
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -394,20 +394,22 @@ if (tuples != 1)
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0);
+uint32_t uid;
 
-PQclear(result);
+    {
+    std::stringstream tuple;
+    tuple << PQgetvalue(result, 0, 0);
 
-uint32_t uid;
+    PQclear(result);
 
-tuple >> uid;
+    tuple >> uid;
+    }
 
 std::string eaddress = conf.address;
 std::string eemail = conf.email;
@@ -424,9 +426,9 @@ if (EscapeString(eaddress))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape address'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -434,9 +436,9 @@ if (EscapeString(eemail))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape email'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -444,9 +446,9 @@ if (EscapeString(egroup))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape group'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -454,9 +456,9 @@ if (EscapeString(enote))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape note'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -464,9 +466,9 @@ if (EscapeString(epassword))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape password'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -474,9 +476,9 @@ if (EscapeString(ephone))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape phone'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -484,9 +486,9 @@ if (EscapeString(erealname))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape real name'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -494,9 +496,9 @@ if (EscapeString(etariffname))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape tariff name'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -504,9 +506,9 @@ if (EscapeString(enexttariff))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape next tariff name'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -514,9 +516,9 @@ if (EscapeString(ecorporation))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape corporation name'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -554,9 +556,9 @@ if (PQresultStatus(result) != PGRES_COMMAND_OK)
     PQclear(result);
     printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): '%s'\n", strError.c_str());
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -603,7 +605,7 @@ return 0;
 
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::RestoreUserStat(USER_STAT * stat,
-                                    const string & login) const
+                                    const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -632,20 +634,22 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
-query << "SELECT cash, free_mb, "
-            "last_activity_time, last_cash_add, "
-            "last_cash_add_time, passive_time "
-         "FROM tb_users "
-         "WHERE name = '" << elogin << "'";
+    {
+    std::ostringstream query;
+    query << "SELECT cash, free_mb, "
+                "last_activity_time, last_cash_add, "
+                "last_cash_add_time, passive_time "
+             "FROM tb_users "
+             "WHERE name = '" << elogin << "'";
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -653,9 +657,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -667,35 +671,38 @@ if (tuples != 1)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0) << " ";
-tuple << PQgetvalue(result, 0, 1) << " ";
-stat->lastActivityTime = TS2Int(PQgetvalue(result, 0, 2));
-tuple << PQgetvalue(result, 0, 3) << " ";
-stat->lastCashAddTime = TS2Int(PQgetvalue(result, 0, 4));
-tuple << PQgetvalue(result, 0, 5) << " ";
-
-PQclear(result);
+    {
+    std::stringstream tuple;
+    tuple << PQgetvalue(result, 0, 0) << " ";
+    tuple << PQgetvalue(result, 0, 1) << " ";
+    stat->lastActivityTime = TS2Int(PQgetvalue(result, 0, 2));
+    tuple << PQgetvalue(result, 0, 3) << " ";
+    stat->lastCashAddTime = TS2Int(PQgetvalue(result, 0, 4));
+    tuple << PQgetvalue(result, 0, 5) << " ";
 
-tuple >> stat->cash
-      >> stat->freeMb
-      >> stat->lastCashAdd
-      >> stat->passiveTime;
+    PQclear(result);
 
-query.str("");
+    tuple >> stat->cash
+          >> stat->freeMb
+          >> stat->lastCashAdd
+          >> stat->passiveTime;
+    }
 
-query << "SELECT dir_num, upload, download "
-         "FROM tb_stats_traffic "
-         "WHERE fk_user IN (SELECT pk_user FROM tb_users WHERE name = '" << elogin << "') AND "
-               "DATE_TRUNC('month', stats_date) = DATE_TRUNC('month', CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP))";
+    {
+    std::ostringstream query;
+    query << "SELECT dir_num, upload, download "
+             "FROM tb_stats_traffic "
+             "WHERE fk_user IN (SELECT pk_user FROM tb_users WHERE name = '" << elogin << "') AND "
+                   "DATE_TRUNC('month', stats_date) = DATE_TRUNC('month', CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP))";
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -703,9 +710,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -721,8 +728,8 @@ for (int i = 0; i < tuples; ++i)
     int dir;
 
     tuple >> dir;
-    tuple >> stat->up[dir];
-    tuple >> stat->down[dir];
+    tuple >> stat->monthUp[dir];
+    tuple >> stat->monthDown[dir];
     }
 
 PQclear(result);
@@ -738,7 +745,7 @@ return 0;
 
 //-----------------------------------------------------------------------------
 int POSTGRESQL_STORE::RestoreUserConf(USER_CONF * conf,
-                                    const string & login) const
+                                    const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -767,27 +774,29 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
-       }
-    return -1;
-    }
-
-std::stringstream query;
-query << "SELECT tb_users.pk_user, tb_users.address, tb_users.always_online, "
-                "tb_users.credit, tb_users.credit_expire, tb_users.disabled, "
-                "tb_users.disabled_detail_stat, tb_users.email, tb_users.grp, "
-                "tb_users.note, tb_users.passive, tb_users.passwd, tb_users.phone, "
-                "tb_users.real_name, tf1.name, tf2.name, tb_corporations.name "
-         "FROM tb_users LEFT JOIN tb_tariffs AS tf1 "
-                            "ON tf1.pk_tariff = tb_users.fk_tariff "
-                       "LEFT JOIN tb_tariffs AS tf2 "
-                            "ON tf2.pk_tariff = tb_users.fk_tariff_change "
-                       "LEFT JOIN tb_corporations "
-                            "ON tb_corporations.pk_corporation = tb_users.fk_corporation "
-         "WHERE tb_users.name = '" << elogin << "'";
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+        }
+    return -1;
+    }
 
-result = PQexec(connection, query.str().c_str());
+    {
+    std::ostringstream query;
+    query << "SELECT tb_users.pk_user, tb_users.address, tb_users.always_online, "
+                    "tb_users.credit, tb_users.credit_expire, tb_users.disabled, "
+                    "tb_users.disabled_detail_stat, tb_users.email, tb_users.grp, "
+                    "tb_users.note, tb_users.passive, tb_users.passwd, tb_users.phone, "
+                    "tb_users.real_name, tf1.name, tf2.name, tb_corporations.name "
+             "FROM tb_users LEFT JOIN tb_tariffs AS tf1 "
+                                "ON tf1.pk_tariff = tb_users.fk_tariff "
+                           "LEFT JOIN tb_tariffs AS tf2 "
+                                "ON tf2.pk_tariff = tb_users.fk_tariff_change "
+                           "LEFT JOIN tb_corporations "
+                                "ON tb_corporations.pk_corporation = tb_users.fk_corporation "
+             "WHERE tb_users.name = '" << elogin << "'";
+
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -795,9 +804,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -809,51 +818,54 @@ if (tuples != 1)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
 uint32_t uid;
 
-std::stringstream tuple;
-
-tuple << PQgetvalue(result, 0, 0) << " ";               // uid
-conf->address = PQgetvalue(result, 0, 1);               // address
-conf->alwaysOnline = !strncmp(PQgetvalue(result, 0, 2), "t", 1);
-tuple << PQgetvalue(result, 0, 3) << " ";               // credit
-conf->creditExpire = TS2Int(PQgetvalue(result, 0, 4));  // creditExpire
-conf->disabled = !strncmp(PQgetvalue(result, 0, 5), "t", 1);
-conf->disabledDetailStat = !strncmp(PQgetvalue(result, 0, 6), "t", 1);
-conf->email = PQgetvalue(result, 0, 7);                 // email
-conf->group = PQgetvalue(result, 0, 8);                 // group
-conf->note = PQgetvalue(result, 0, 9);                  // note
-conf->passive = !strncmp(PQgetvalue(result, 0, 10), "t", 1);
-conf->password = PQgetvalue(result, 0, 11);             // password
-conf->phone = PQgetvalue(result, 0, 12);                // phone
-conf->realName = PQgetvalue(result, 0, 13);             // realName
-conf->tariffName = PQgetvalue(result, 0, 14);           // tariffName
-conf->nextTariff = PQgetvalue(result, 0, 15);           // nextTariff
-conf->corp = PQgetvalue(result, 0, 16);                 // corp
+    {
+    std::stringstream tuple;
+    tuple << PQgetvalue(result, 0, 0) << " ";               // uid
+    conf->address = PQgetvalue(result, 0, 1);               // address
+    conf->alwaysOnline = !strncmp(PQgetvalue(result, 0, 2), "t", 1);
+    tuple << PQgetvalue(result, 0, 3) << " ";               // credit
+    conf->creditExpire = TS2Int(PQgetvalue(result, 0, 4));  // creditExpire
+    conf->disabled = !strncmp(PQgetvalue(result, 0, 5), "t", 1);
+    conf->disabledDetailStat = !strncmp(PQgetvalue(result, 0, 6), "t", 1);
+    conf->email = PQgetvalue(result, 0, 7);                 // email
+    conf->group = PQgetvalue(result, 0, 8);                 // group
+    conf->note = PQgetvalue(result, 0, 9);                  // note
+    conf->passive = !strncmp(PQgetvalue(result, 0, 10), "t", 1);
+    conf->password = PQgetvalue(result, 0, 11);             // password
+    conf->phone = PQgetvalue(result, 0, 12);                // phone
+    conf->realName = PQgetvalue(result, 0, 13);             // realName
+    conf->tariffName = PQgetvalue(result, 0, 14);           // tariffName
+    conf->nextTariff = PQgetvalue(result, 0, 15);           // nextTariff
+    conf->corp = PQgetvalue(result, 0, 16);                 // corp
 
-PQclear(result);
+    PQclear(result);
 
-if (conf->tariffName == "")
-    conf->tariffName = NO_TARIFF_NAME;
-if (conf->corp == "")
-    conf->corp = NO_CORP_NAME;
+    if (conf->tariffName == "")
+        conf->tariffName = NO_TARIFF_NAME;
+    if (conf->corp == "")
+        conf->corp = NO_CORP_NAME;
 
-tuple >> uid
-      >> conf->credit;
+    tuple >> uid
+          >> conf->credit;
+    }
 
-query.str("");
-query << "SELECT name FROM tb_services "
-         "WHERE pk_service IN (SELECT fk_service "
-                              "FROM tb_users_services "
-                              "WHERE fk_user = " << uid << ")";
+    {
+    std::ostringstream query;
+    query << "SELECT name FROM tb_services "
+             "WHERE pk_service IN (SELECT fk_service "
+                                  "FROM tb_users_services "
+                                  "WHERE fk_user = " << uid << ")";
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -861,9 +873,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -876,12 +888,14 @@ for (int i = 0; i < tuples; ++i)
 
 PQclear(result);
 
-query.str("");
-query << "SELECT num, data "
-         "FROM tb_users_data "
-         "WHERE fk_user = " << uid;
+    {
+    std::ostringstream query;
+    query << "SELECT num, data "
+             "FROM tb_users_data "
+             "WHERE fk_user = " << uid;
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -889,9 +903,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -916,12 +930,14 @@ for (int i = 0; i < tuples; ++i)
 
 PQclear(result);
 
-query.str("");
-query << "SELECT host(ip), masklen(ip) "
-         "FROM tb_allowed_ip "
-         "WHERE fk_user = " << uid;
+    {
+    std::ostringstream query;
+    query << "SELECT host(ip), masklen(ip) "
+             "FROM tb_allowed_ip "
+             "WHERE fk_user = " << uid;
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -929,9 +945,9 @@ if (PQresultStatus(result) != PGRES_TUPLES_OK)
     printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -970,13 +986,13 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteUserChgLog(const string & login,
-                                    const string & admLogin,
+int POSTGRESQL_STORE::WriteUserChgLog(const std::string & login,
+                                    const std::string & admLogin,
                                     uint32_t admIP,
-                                    const string & paramName,
-                                    const string & oldValue,
-                                    const string & newValue,
-                                    const string & message = "") const
+                                    const std::string & paramName,
+                                    const std::string & oldValue,
+                                    const std::string & newValue,
+                                    const std::string & message = "") const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -1010,9 +1026,9 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1020,9 +1036,9 @@ if (EscapeString(eadminLogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape admin's login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1030,9 +1046,9 @@ if (EscapeString(eparam))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape param's name'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1040,9 +1056,9 @@ if (EscapeString(eold))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape old value'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1050,13 +1066,13 @@ if (EscapeString(enew))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape new value'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 query << "SELECT sp_add_param_log_entry("
             "'" << elogin << "', "
             "'" << eadminLogin << "', CAST('"
@@ -1093,7 +1109,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int POSTGRESQL_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -1122,13 +1138,13 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserConnect(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserConnect(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserConnect(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
+std::ostringstream query;
 if (version < 6)
     {
     query << "SELECT sp_add_session_log_entry("
@@ -1172,9 +1188,9 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteUserDisconnect(const string & login,
-                    const DIR_TRAFF & up,
-                    const DIR_TRAFF & down,
+int POSTGRESQL_STORE::WriteUserDisconnect(const std::string & login,
+                    const DIR_TRAFF & monthUp,
+                    const DIR_TRAFF & monthDown,
                     const DIR_TRAFF & sessionUp,
                     const DIR_TRAFF & sessionDown,
                     double cash,
@@ -1208,9 +1224,9 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1220,32 +1236,34 @@ if (EscapeString(ereason))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to escape reason'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-std::stringstream query;
-if (version < 6)
     {
-    // Old database version - no freeMb logging support
-    query << "SELECT sp_add_session_log_entry("
-                "'" << elogin << "', "
-                "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
-                "'d', CAST('0.0.0.0/0' AS INET), "
-                << cash << ")";
-    }
-else
-    {
-    query << "SELECT sp_add_session_log_entry("
-                "'" << elogin << "', "
-                "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
-                "'d', CAST('0.0.0.0/0' AS INET), "
-                << cash << ", " << freeMb << ", '" << ereason << "')";
-    }
+    std::ostringstream query;
+    if (version < 6)
+        {
+        // Old database version - no freeMb logging support
+        query << "SELECT sp_add_session_log_entry("
+                    "'" << elogin << "', "
+                    "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
+                    "'d', CAST('0.0.0.0/0' AS INET), "
+                    << cash << ")";
+        }
+    else
+        {
+        query << "SELECT sp_add_session_log_entry("
+                    "'" << elogin << "', "
+                    "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
+                    "'d', CAST('0.0.0.0/0' AS INET), "
+                    << cash << ", " << freeMb << ", '" << ereason << "')";
+        }
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_TUPLES_OK)
     {
@@ -1267,9 +1285,9 @@ if (tuples != 1)
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1281,9 +1299,9 @@ if (str2x(PQgetvalue(result, 0, 0), lid))
     printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): '%s'\n", strError.c_str());
     PQclear(result);
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
@@ -1291,7 +1309,7 @@ PQclear(result);
 
 for (int i = 0; i < DIR_NUM; ++i)
     {
-    std::stringstream query;
+    std::ostringstream query;
     query << "INSERT INTO tb_sessions_data "
                 "(fk_session_log, "
                  "dir_num, "
@@ -1304,8 +1322,8 @@ for (int i = 0; i < DIR_NUM; ++i)
                 << i << ", "
                 << sessionUp[i] << ", "
                 << sessionDown[i] << ", "
-                << up[i] << ", "
-                << down[i] << ")";
+                << monthUp[i] << ", "
+                << monthDown[i] << ")";
 
     result = PQexec(connection, query.str().c_str());
 
@@ -1334,9 +1352,9 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int POSTGRESQL_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
                                       time_t lastStat,
-                                      const string & login) const
+                                      const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -1365,18 +1383,18 @@ if (EscapeString(elogin))
     {
     printfd(__FILE__, "POSTGRESQL_STORE::WriteDetailedStat(): 'Failed to escape login'\n");
     if (RollbackTransaction())
-       {
-       printfd(__FILE__, "POSTGRESQL_STORE::WriteDetailedStat(): 'Failed to rollback transaction'\n");
-       }
+        {
+        printfd(__FILE__, "POSTGRESQL_STORE::WriteDetailedStat(): 'Failed to rollback transaction'\n");
+        }
     return -1;
     }
 
-map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
+std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
 time_t currTime = time(NULL);
 
 for (it = statTree.begin(); it != statTree.end(); ++it)
     {
-    std::stringstream query;
+    std::ostringstream query;
     query << "INSERT INTO tb_detail_stats "
                 "(till_time, from_time, fk_user, "
                  "dir_num, ip, download, upload, cost) "
@@ -1417,7 +1435,7 @@ return 0;
 }
 
 //-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
+int POSTGRESQL_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
@@ -1430,21 +1448,23 @@ int POSTGRESQL_STORE::SaveUserServices(uint32_t uid,
 {
 PGresult * result;
 
-std::stringstream query;
-query << "DELETE FROM tb_users_services WHERE fk_user = " << uid;
+    {
+    std::ostringstream query;
+    query << "DELETE FROM tb_users_services WHERE fk_user = " << uid;
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+
+    if (PQresultStatus(result) != PGRES_COMMAND_OK)
+        {
+        strError = PQresultErrorMessage(result);
+        PQclear(result);
+        printfd(__FILE__, "POSTGRESQL_STORE::SaveUserServices(): '%s'\n", strError.c_str());
+        return -1;
+        }
 
-if (PQresultStatus(result) != PGRES_COMMAND_OK)
-    {
-    strError = PQresultErrorMessage(result);
     PQclear(result);
-    printfd(__FILE__, "POSTGRESQL_STORE::SaveUserServices(): '%s'\n", strError.c_str());
-    return -1;
     }
 
-PQclear(result);
-
 std::vector<std::string>::const_iterator it;
 
 for (it = services.begin(); it != services.end(); ++it)
@@ -1457,7 +1477,7 @@ for (it = services.begin(); it != services.end(); ++it)
         return -1;
         }
 
-    std::stringstream query;
+    std::ostringstream query;
     query << "INSERT INTO tb_users_services "
                 "(fk_user, fk_service) "
              "VALUES "
@@ -1488,10 +1508,12 @@ int POSTGRESQL_STORE::SaveUserIPs(uint32_t uid,
 {
 PGresult * result;
 
-std::stringstream query;
-query << "DELETE FROM tb_allowed_ip WHERE fk_user = " << uid;
+    {
+    std::ostringstream query;
+    query << "DELETE FROM tb_allowed_ip WHERE fk_user = " << uid;
 
-result = PQexec(connection, query.str().c_str());
+    result = PQexec(connection, query.str().c_str());
+    }
 
 if (PQresultStatus(result) != PGRES_COMMAND_OK)
     {
@@ -1503,9 +1525,9 @@ if (PQresultStatus(result) != PGRES_COMMAND_OK)
 
 PQclear(result);
 
-for (int i = 0; i < ips.Count(); ++i)
+for (size_t i = 0; i < ips.Count(); ++i)
     {
-    std::stringstream query;
+    std::ostringstream query;
     query << "INSERT INTO tb_allowed_ip "
                 "(fk_user, ip) "
              "VALUES "
@@ -1545,7 +1567,7 @@ for (unsigned i = 0; i < data.size(); ++i)
 
     PGresult * result;
 
-    std::stringstream query;
+    std::ostringstream query;
     query << "SELECT sp_set_user_data("
                 << uid << ", "
                 << "CAST(" << i << " AS SMALLINT), "
index c36df0cd02efa1600ee39f032315f6c970585abe..ef70505389fc372eb2425398903256a805e4882f 100644 (file)
  *
  */
 
+#include "postgresql_store.h"
+
+#include "stg/common.h"
+
 #include <string>
 #include <ctime>
 
 #include <libpq-fe.h>
 
-#include "stg/common.h"
-#include "postgresql_store.h"
+extern volatile time_t stgTime;
 
 int POSTGRESQL_STORE::StartTransaction() const
 {
@@ -91,10 +94,10 @@ int error = 0;
 char * buf = new char[(value.length() << 1) + 1];
 
 PQescapeStringConn(connection,
-                  buf,
-                  value.c_str(),
-                  value.length(),
-                  &error);
+                   buf,
+                   value.c_str(),
+                   value.length(),
+                   &error);
 
 if (error)
     {
@@ -110,24 +113,23 @@ delete[] buf;
 return 0;
 }
 
-std::string POSTGRESQL_STORE::Int2TS(uint32_t ts) const
+std::string POSTGRESQL_STORE::Int2TS(time_t ts) const
 {
-char buf[32];
 struct tm brokenTime;
-time_t tt = ts;
 
 brokenTime.tm_wday = 0;
 brokenTime.tm_yday = 0;
 brokenTime.tm_isdst = 0;
 
-gmtime_r(&tt, &brokenTime);
+gmtime_r(&ts, &brokenTime);
 
+char buf[32];
 strftime(buf, 32, "%Y-%m-%d %H:%M:%S", &brokenTime);
 
 return buf;
 }
 
-uint32_t POSTGRESQL_STORE::TS2Int(const std::string & ts) const
+time_t POSTGRESQL_STORE::TS2Int(const std::string & ts) const
 {
 struct tm brokenTime;
 
@@ -159,8 +161,6 @@ if (year)
 else
     {
     time_t curTime = stgTime;
-    /*time(&curTime);*/
-
     localtime_r(&curTime, &brokenTime);
     }
 
@@ -172,4 +172,3 @@ strftime(buf, 32, "%Y-%m-%d", &brokenTime);
 
 date = buf;
 }
-
diff --git a/projects/stargazer/plugins/store/postgresql/postgresql_store_utils.h b/projects/stargazer/plugins/store/postgresql/postgresql_store_utils.h
deleted file mode 100644 (file)
index e09cccd..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-#ifndef POSTGRESQL_UTILS_STORE_H
-#define POSTGRESQL_UTILS_STORE_H
-
-#include <functional>
-
-struct ToLower : public std::unary_function<char, char>
-{
-char operator() (char c) const  { return std::tolower(c); }
-};
-
-#endif
index 85b0f4e51105f0cf01bea9dddcb7da40aa560626..832bf7e9ed54356313beb197670282481f3e67e6 100644 (file)
@@ -48,7 +48,7 @@ const PRIV * priv = admin->GetPriv();
 
 if (!priv->serviceChg)
     {
-    string s = admin->GetLogStr() + " Add service \'" + service.name + "\'. Access denied.";
+    std::string s = admin->GetLogStr() + " Add service \'" + service.name + "\'. Access denied.";
     strError = "Access denied.";
     WriteServLog(s.c_str());
     return -1;
@@ -79,14 +79,14 @@ WriteServLog("%s %s", admin->GetLogStr().c_str(), strError.c_str());
 return -1;
 }
 //-----------------------------------------------------------------------------
-int SERVICES_IMPL::Del(const string & name, const ADMIN * admin)
+int SERVICES_IMPL::Del(const std::string & name, const ADMIN * admin)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 const PRIV * priv = admin->GetPriv();
 
 if (!priv->serviceChg)
     {
-    string s = admin->GetLogStr() + " Delete service \'" + name + "\'. Access denied.";
+    std::string s = admin->GetLogStr() + " Delete service \'" + name + "\'. Access denied.";
     strError = "Access denied.";
     WriteServLog(s.c_str());
     return -1;
@@ -101,7 +101,7 @@ if (si == data.end())
     return -1;
     }
 
-map<int, const_srv_iter>::iterator csi;
+std::map<int, const_srv_iter>::iterator csi;
 csi = searchDescriptors.begin();
 while (csi != searchDescriptors.end())
     {
@@ -130,7 +130,7 @@ const PRIV * priv = admin->GetPriv();
 
 if (!priv->serviceChg)
     {
-    string s = admin->GetLogStr() + " Change service \'" + service.name + "\'. Access denied.";
+    std::string s = admin->GetLogStr() + " Change service \'" + service.name + "\'. Access denied.";
     strError = "Access denied.";
     WriteServLog(s.c_str());
     return -1;
@@ -162,7 +162,7 @@ return 0;
 bool SERVICES_IMPL::Read()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-vector<string> servicesList;
+std::vector<std::string> servicesList;
 if (store->GetServicesList(&servicesList) < 0)
     {
     WriteServLog(store->GetStrError().c_str());
@@ -184,7 +184,7 @@ for (size_t i = 0; i < servicesList.size(); i++)
 return false;
 }
 //-----------------------------------------------------------------------------
-bool SERVICES_IMPL::Find(const string & name, SERVICE_CONF * service)
+bool SERVICES_IMPL::Find(const std::string & name, SERVICE_CONF * service)
 {
 assert(service != NULL && "Pointer to service is not null");
 
@@ -203,7 +203,7 @@ if (si != data.end())
 return true;
 }
 //-----------------------------------------------------------------------------
-bool SERVICES_IMPL::Exists(const string & name) const
+bool SERVICES_IMPL::Exists(const std::string & name) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 if (data.empty())
index 2bb9c8797c44a8d00f5c5b536f37436053e84913..31aa72b2ed612e43e1bb8aeb383233d5bc873811 100644 (file)
@@ -58,8 +58,8 @@ private:
     SERVICES_IMPL(const SERVICES_IMPL & rvalue);
     SERVICES_IMPL & operator=(const SERVICES_IMPL & rvalue);
 
-    typedef list<SERVICE_CONF>::iterator       srv_iter;
-    typedef list<SERVICE_CONF>::const_iterator const_srv_iter;
+    typedef std::list<SERVICE_CONF>::iterator       srv_iter;
+    typedef std::list<SERVICE_CONF>::const_iterator const_srv_iter;
 
     bool Read();
 
index 2bf8d08271bf2b32bf718398d7c964d09744153e..92670cb5082a345768582a2173ce06803fa0d43f 100644 (file)
@@ -375,7 +375,7 @@ while (node)
 
     if (strcasecmp(node->getName(), "FeeChargeType") == 0)
         {
-        if (ParseUnsignedInRange(node->getValue(0), 0, 2, &feeChargeType) != 0)
+        if (ParseUnsignedInRange(node->getValue(0), 0, 3, &feeChargeType) != 0)
             {
             strError = "Incorrect FeeChargeType value: \'" + string(node->getValue(0)) + "\'";
             return -1;
@@ -457,6 +457,13 @@ while (node)
             }
         }
 
+    if (strcasecmp(node->getName(), "ScriptParams") == 0)
+        {
+        for (int i = 0; node->getValue(i) != NULL; ++i)
+            {
+            scriptParams.push_back(node->getValue(i));
+            }
+        }
     node = node->getNextNode();
     }
 
@@ -488,4 +495,4 @@ else if (detailStatPeriodStr == "1/6")
 
 return -1;
 }
-//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
\ No newline at end of file
index 739bbcc946cc273c9d85c9f54fcb0a4f7d77e0a6..7ba2708fd7ae6aace5260277b5421140918a2c4c 100644 (file)
@@ -85,7 +85,7 @@ public:
     bool                GetFreeMbAllowInet() const { return freeMbAllowInet; }
     bool                GetDayFeeIsLastDay() const { return dayFeeIsLastDay; }
     bool                GetWriteFreeMbTraffCost() const
-        { return writeFreeMbTraffCost; };
+        { return writeFreeMbTraffCost; }
     bool                GetShowFeeInCash() const { return showFeeInCash; }
     const std::string & GetMonitorDir() const { return monitorDir; }
     bool                GetMonitoring() const { return monitoring; }
@@ -98,6 +98,7 @@ public:
         { return storeModuleSettings; }
     const std::vector<MODULE_SETTINGS> & GetModulesSettings() const
         { return modulesSettings; }
+    const std::vector<std::string> & GetScriptParams() const { return scriptParams; }
 
 private:
 
@@ -117,6 +118,7 @@ private:
     std::string logFile;
     std::string pidFile;
     std::string monitorDir;
+    std::vector<std::string> scriptParams;
     bool        monitoring;
     unsigned    detailStatWritePeriod;
     unsigned    statWritePeriod;
@@ -136,7 +138,6 @@ private:
 
     std::vector<MODULE_SETTINGS> modulesSettings;
     MODULE_SETTINGS storeModuleSettings;
-
     STG_LOGGER & logger;
 };
 //-----------------------------------------------------------------------------
index 235c669e0df09dcea32c31d94e9b5347932b88ff..81128c7a776a867dcf5f8f0f7d2c7c8d1b0c0d8c 100644 (file)
@@ -6,6 +6,10 @@
 
 #include "stg/common.h"
 
+#include "stg_timer.h"
+
+void * StgTimer(void *);
+
 static int nonstop;
 static pthread_t thrStgTimer;
 static bool isTimerRunning = false;
@@ -88,7 +92,7 @@ static int a = 0;
 isTimerRunning = false;
 
 if (a == 0)
-    if (pthread_create(&thrStgTimer, NULL, StgTimer, NULL))
+    if (pthread_create(&thrStgTimer, NULL, &StgTimer, NULL))
         {
         isTimerRunning = false;
         return -1;
@@ -113,10 +117,10 @@ return isTimerRunning;
 int stgUsleep(unsigned long t)
 {
 #ifdef STG_TIMER_DEBUG
-struct timespec ts = {(t / TIME_SPEED) / 1000000, ((t / TIME_SPEED) % 1000000) * 1000};
+struct timespec ts = {static_cast<time_t>((t / TIME_SPEED) / 1000000), static_cast<long>(((t / TIME_SPEED) % 1000000) * 1000)};
 return nanosleep(&ts, NULL);
 #else
-struct timespec ts = {t / 1000000, (t % 1000000) * 1000};
+struct timespec ts = {static_cast<time_t>(t / 1000000), static_cast<long>((t % 1000000) * 1000)};
 return nanosleep(&ts, NULL);
 #endif
 }
index c57008e559cf816b669b24216e28700521a29925..75553b3eb95afda9f10ebe9f58f352102ca40ee0 100644 (file)
@@ -9,7 +9,7 @@
 
 #include <ctime>
 
-extern volatile const time_t stgTime;
+extern volatile time_t stgTime;
 int RunStgTimer();
 void StopStgTimer();
 void WaitTimer();
index c54bdb361cc2e0b0dfb9884ce1f080dcfa873fc3..d27c09023603f8745a02df66554d84cff694c862 100644 (file)
@@ -79,7 +79,7 @@ if (!handle)
 isLoaded = true;
 
 STORE * (*GetStore)();
-GetStore = (STORE * (*)())dlsym(handle, "GetStore");
+GetStore = reinterpret_cast<STORE * (*)()>(dlsym(handle, "GetStore"));
 if (!GetStore)
     {
     errorStr = std::string("GetStore() not found! ") + dlerror();
index bf272f3128a34f9939ba136fa29e68a95044964e..c6785cead85c26f71ea5e273014f0d71428a8d5f 100644 (file)
@@ -119,7 +119,7 @@ else
     }
 }
 //-----------------------------------------------------------------------------
-double TARIFF_IMPL::GetPriceWithoutFreeMb(int dir, int mb, time_t t) const
+double TARIFF_IMPL::GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const
 {
 int interval = Interval(dir, t);
 
@@ -143,45 +143,5 @@ else if (!sp && th)
     return tariffData.dirPrice[dir].priceNightA;
 else
     return tariffData.dirPrice[dir].priceDayA;
-
-/*if (tariffData.dirPrice[dir].noDiscount && tariffData.dirPrice[dir].singlePrice)
-    {
-    return tariffData.dirPrice[dir].priceDayA;
-    }
-else
-    {
-    if (tariffData.dirPrice[dir].noDiscount)
-        {
-        // Without threshold
-        if (interval == TARIFF_DAY)
-            return tariffData.dirPrice[dir].priceDayA;
-        else
-            return tariffData.dirPrice[dir].priceNightA;
-        }
-
-    if (tariffData.dirPrice[dir].singlePrice)
-        {
-        // Without day/night
-        if (mb < tariffData.dirPrice[dir].threshold)
-            return tariffData.dirPrice[dir].priceDayA;
-        else
-            return tariffData.dirPrice[dir].priceDayB;
-        }
-
-    if (mb < tariffData.dirPrice[dir].threshold)
-        {
-        if (interval == TARIFF_DAY)
-            return tariffData.dirPrice[dir].priceDayA;
-        else
-            return tariffData.dirPrice[dir].priceNightA;
-        }
-    else
-        {
-        if (interval == TARIFF_DAY)
-            return tariffData.dirPrice[dir].priceDayB;
-        else
-            return tariffData.dirPrice[dir].priceNightB;
-        }
-    }*/
 }
 //-----------------------------------------------------------------------------
index b471f0d04014e5c072dc7807c2ca6867c66302bd..f2f84d2630889f73432e9a191459c8174c37adf3 100644 (file)
@@ -48,20 +48,20 @@ public:
     TARIFF_IMPL()
         : TARIFF(),
           tariffData()
-    {};
+    {}
     TARIFF_IMPL(const std::string & name)
         : TARIFF(),
           tariffData(name)
-    {};
+    {}
     TARIFF_IMPL(const TARIFF_DATA & td)
         : TARIFF(),
           tariffData(td)
-    {};
+    {}
     TARIFF_IMPL(const TARIFF_IMPL & t)
         : TARIFF(),
           tariffData(t.tariffData)
-    {};
-    virtual ~TARIFF_IMPL() {};
+    {}
+    virtual ~TARIFF_IMPL() {}
 
     double  GetPriceWithTraffType(uint64_t up,
                                   uint64_t down,
@@ -91,7 +91,7 @@ public:
 private:
     TARIFF_DATA     tariffData;
 
-    double  GetPriceWithoutFreeMb(int dir, int mb, time_t t) const;
+    double  GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const;
     int     Interval(int dir, time_t t) const;
 };
 
index ab3d970fa38f650edd5aa4e9ff5d320c745fa0cb..dbd3d2e397934e442e8dd980716c588b8159ef76 100644 (file)
@@ -72,9 +72,9 @@ if (store->GetTariffsList(&tariffsList))
     WriteServLog("%s", store->GetStrError().c_str());
     }
 
-int tariffsNum = tariffsList.size();
+Tariffs::size_type tariffsNum = tariffsList.size();
 
-for (int i = 0; i < tariffsNum; i++)
+for (Tariffs::size_type i = 0; i < tariffsNum; i++)
     {
     TARIFF_DATA td;
     if (store->RestoreTariff(&td, tariffsList[i]))
@@ -258,7 +258,7 @@ void TARIFFS_IMPL::GetTariffsData(std::list<TARIFF_DATA> * tdl)
 assert(tdl != NULL && "Tariffs data list is not null");
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-std::list<TARIFF_IMPL>::const_iterator it = tariffs.begin();
+Tariffs::const_iterator it = tariffs.begin();
 for (; it != tariffs.end(); ++it)
     {
     tdl->push_back(it->GetTariffData());
index caeb811d954bdafe9d277f44a0077987e1d6a005..37c76fc4070ff812e12886c70cffeec2a51f9195 100644 (file)
@@ -45,15 +45,17 @@ class ADMIN;
 
 class TARIFFS_IMPL : public TARIFFS {
 public:
+    typedef std::list<TARIFF_IMPL> Tariffs;
+
     TARIFFS_IMPL(STORE * store);
     virtual ~TARIFFS_IMPL();
-    int     ReadTariffs ();
+    int ReadTariffs ();
     const TARIFF * FindByName(const std::string & name) const;
-    const TARIFF * GetNoTariff() const { return &noTariff; };
-    size_t  Count() const;
-    int     Del(const std::string & name, const ADMIN * admin);
-    int     Add(const std::string & name, const ADMIN * admin);
-    int     Chg(const TARIFF_DATA & td, const ADMIN * admin);
+    const TARIFF * GetNoTariff() const { return &noTariff; }
+    size_t Count() const;
+    int Del(const std::string & name, const ADMIN * admin);
+    int Add(const std::string & name, const ADMIN * admin);
+    int Chg(const TARIFF_DATA & td, const ADMIN * admin);
 
     void AddNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * notifier);
     void DelNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * notifier);
@@ -61,7 +63,7 @@ public:
     void AddNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier);
     void DelNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier);
 
-    void    GetTariffsData(std::list<TARIFF_DATA> * tdl);
+    void GetTariffsData(std::list<TARIFF_DATA> * tdl);
 
     const std::string & GetStrError() const { return strError; }
 
@@ -69,7 +71,7 @@ private:
     TARIFFS_IMPL(const TARIFFS_IMPL & rvalue);
     TARIFFS_IMPL & operator=(const TARIFFS_IMPL & rvalue);
 
-    std::list<TARIFF_IMPL>  tariffs;
+    Tariffs                 tariffs;
     STORE *                 store;
     STG_LOGGER &            WriteServLog;
     mutable pthread_mutex_t mutex;
index c2088e0f2009cc210b6b0c1e514b163921c5ca6a..fce475952537b598d5f39864d6975fe863d3be67 100644 (file)
@@ -41,6 +41,7 @@
 
 #include "stg/common.h"
 #include "stg/locker.h"
+#include "stg/const.h" // MONITOR_TIME_DELAY_SEC
 #include "traffcounter_impl.h"
 #include "stg_timer.h"
 #include "users_impl.h"
@@ -67,6 +68,7 @@ TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
       rulesFileName(fn),
       monitorDir(),
       monitoring(false),
+      touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
       users(u),
       running(false),
       stopped(true),
@@ -202,13 +204,11 @@ void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
 if (!running)
     return;
 
-static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
-
-if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
+if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
     {
-    static std::string monFile = monitorDir + "/traffcounter_p";
+    std::string monFile = monitorDir + "/traffcounter_p";
     printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
-    touchTime = stgTime;
+    touchTimeP = stgTime;
     TouchFile(monFile.c_str());
     }
 
@@ -292,12 +292,12 @@ void TRAFFCOUNTER_IMPL::FlushAndRemove()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-int oldPacketsSize = packets.size();
-int oldIp2packetsSize = ip2packets.size();
+Packets::size_type oldPacketsSize = packets.size();
+Index::size_type oldIp2packetsSize = ip2packets.size();
 
 pp_iter pi;
 pi = packets.begin();
-std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
+Packets newPackets;
 ip2packets.erase(ip2packets.begin(), ip2packets.end());
 while (pi != packets.end())
     {
@@ -673,13 +673,13 @@ while (fgets(str, 1023, f))
     rul.proto = 0xff;
     rul.dir = 0xff;
 
-    for (size_t i = 0; i < PROTOMAX; i++)
+    for (uint8_t i = 0; i < PROTOMAX; i++)
         {
         if (strcasecmp(tp, protoName[i]) == 0)
             rul.proto = i;
         }
 
-    for (size_t i = 0; i < DIR_NUM + 1; i++)
+    for (uint32_t i = 0; i < DIR_NUM + 1; i++)
         {
         if (td == dirName[i])
             rul.dir = i;
@@ -738,8 +738,8 @@ if (ReadRules(true))
 
 FreeRules();
 ReadRules();
-printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reload rules successfull.\n");
-WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
+printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reloaded rules successfully.\n");
+WriteServLog("TRAFFCOUNTER: Reloaded rules successfully.");
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -747,9 +747,9 @@ bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
 {
 char addr[50], mask[20], port1[20], port2[20], ports[40];
 
-int len = strlen(ta);
+size_t len = strlen(ta);
 char n = 0;
-int i, p;
+size_t i, p;
 memset(addr, 0, sizeof(addr));
 for (i = 0; i < len; i++)
     {
@@ -829,15 +829,15 @@ uint16_t prt1, prt2, msk;
 struct in_addr ipaddr;
 char *res;
 
-msk = strtol(mask, &res, 10);
+msk = static_cast<uint16_t>(strtol(mask, &res, 10));
 if (*res != 0)
     return true;
 
-prt1 = strtol(port1, &res, 10);
+prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
 if (*res != 0)
     return true;
 
-prt2 = strtol(port2, &res, 10);
+prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
 if (*res != 0)
     return true;
 
@@ -902,9 +902,9 @@ switch (rule.proto)
 printf("dir=%u \n", static_cast<unsigned>(rule.dir));
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
+void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir)
 {
-TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
-monitoring = (monitorDir != "");
+monitorDir = dir;
+monitoring = !monitorDir.empty();
 }
 //-----------------------------------------------------------------------------
index 2a9fca5a61590dddb0bd4bb716a028e20f989fd8..7e552f82c186e2eab2c179c72ecb2d0d972a43ca 100644 (file)
@@ -221,15 +221,18 @@ private:
     void        UnSetUserNotifiers(USER_IMPL * user);
 
     typedef std::list<RULE>::iterator rule_iter;
-    typedef std::map<RAW_PACKET, PACKET_EXTRA_DATA>::iterator pp_iter;
-    typedef std::multimap<uint32_t, pp_iter>::iterator ip2p_iter;
-    typedef std::multimap<uint32_t, pp_iter>::const_iterator ip2p_citer;
 
     std::list<RULE>          rules;
 
-    std::map<RAW_PACKET, PACKET_EXTRA_DATA> packets; // Packets tree
+    typedef std::map<RAW_PACKET, PACKET_EXTRA_DATA> Packets;
+    typedef Packets::iterator pp_iter;
+    typedef std::multimap<uint32_t, pp_iter> Index;
+    typedef Index::iterator ip2p_iter;
+    typedef Index::const_iterator ip2p_citer;
 
-    std::multimap<uint32_t, pp_iter> ip2packets; // IP-to-Packet index
+    Packets packets; // Packets tree
+
+    Index ip2packets; // IP-to-Packet index
 
     std::string              dirName[DIR_NUM + 1];
 
@@ -238,6 +241,7 @@ private:
 
     std::string              monitorDir;
     bool                     monitoring;
+    time_t                   touchTimeP;
 
     USERS_IMPL *             users;
 
index 42650effed158034cd7e30569df661bf0763f376..3b2489ad319bc1d660d089f4f5a0b2bf4264e93f 100644 (file)
 #define _GNU_SOURCE
 #endif
 
-#include <pthread.h>
-#include <unistd.h> // access
-
-#include <cassert>
-#include <cstdlib>
+#include "user_impl.h"
+#include "settings_impl.h"
+#include "stg_timer.h"
 
 #include "stg/users.h"
 #include "stg/common.h"
 #include "stg/tariff.h"
 #include "stg/tariffs.h"
 #include "stg/admin.h"
-#include "user_impl.h"
-#include "settings_impl.h"
-#include "stg_timer.h"
+
+#include <algorithm>
+#include <functional>
+
+#include <cassert>
+#include <cstdlib>
+#include <cmath>
+
+#include <pthread.h>
+#include <unistd.h> // access
 
 #ifdef USE_ABSTRACT_SETTINGS
 USER_IMPL::USER_IMPL(const SETTINGS * s,
@@ -59,12 +64,9 @@ USER_IMPL::USER_IMPL(const SETTINGS * s,
       property(s->GetScriptsDir()),
       WriteServLog(GetStgLogger()),
       lastScanMessages(0),
-      login(),
       id(0),
       __connected(0),
       connected(__connected),
-      enabledDirs(),
-      userIDGenerator(),
       __currIP(0),
       currIP(__currIP),
       lastIPForDisconnect(0),
@@ -73,11 +75,8 @@ USER_IMPL::USER_IMPL(const SETTINGS * s,
       store(st),
       tariffs(t),
       tariff(NULL),
-      traffStat(),
-      traffStatSaved(),
       settings(s),
-      authorizedBy(),
-      messages(),
+      authorizedModificationTime(0),
       deleted(false),
       lastWriteStat(0),
       lastWriteDetailedStat(0),
@@ -115,14 +114,10 @@ USER_IMPL::USER_IMPL(const SETTINGS * s,
       userdata7(property.userdata7),
       userdata8(property.userdata8),
       userdata9(property.userdata9),
-      sessionUpload(),
-      sessionDownload(),
       passiveNotifier(this),
       tariffNotifier(this),
       cashNotifier(this),
-      ipNotifier(this),
-      mutex(),
-      errorStr()
+      ipNotifier(this)
 {
 password = "*_EMPTY_PASSWORD_*";
 tariffName = NO_TARIFF_NAME;
@@ -132,6 +127,7 @@ lastWriteDetailedStat = stgTime;
 
 property.tariffName.AddBeforeNotifier(&tariffNotifier);
 property.passive.AddBeforeNotifier(&passiveNotifier);
+property.disabled.AddAfterNotifier(&disabledNotifier);
 property.cash.AddBeforeNotifier(&cashNotifier);
 ips.AddAfterNotifier(&ipNotifier);
 
@@ -151,12 +147,9 @@ USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s,
       property(s->GetScriptsDir()),
       WriteServLog(GetStgLogger()),
       lastScanMessages(0),
-      login(),
       id(0),
       __connected(0),
       connected(__connected),
-      enabledDirs(),
-      userIDGenerator(),
       __currIP(0),
       currIP(__currIP),
       lastIPForDisconnect(0),
@@ -165,11 +158,8 @@ USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s,
       store(st),
       tariffs(t),
       tariff(NULL),
-      traffStat(),
-      traffStatSaved(),
       settings(s),
-      authorizedBy(),
-      messages(),
+      authorizedModificationTime(0),
       deleted(false),
       lastWriteStat(0),
       lastWriteDetailedStat(0),
@@ -207,14 +197,11 @@ USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s,
       userdata7(property.userdata7),
       userdata8(property.userdata8),
       userdata9(property.userdata9),
-      sessionUpload(),
-      sessionDownload(),
       passiveNotifier(this),
+      disabledNotifier(this),
       tariffNotifier(this),
       cashNotifier(this),
-      ipNotifier(this),
-      mutex(),
-      errorStr()
+      ipNotifier(this)
 {
 password = "*_EMPTY_PASSWORD_*";
 tariffName = NO_TARIFF_NAME;
@@ -224,6 +211,7 @@ lastWriteDetailedStat = stgTime;
 
 property.tariffName.AddBeforeNotifier(&tariffNotifier);
 property.passive.AddBeforeNotifier(&passiveNotifier);
+property.disabled.AddAfterNotifier(&disabledNotifier);
 property.cash.AddBeforeNotifier(&cashNotifier);
 ips.AddAfterNotifier(&ipNotifier);
 
@@ -244,7 +232,6 @@ USER_IMPL::USER_IMPL(const USER_IMPL & u)
       id(u.id),
       __connected(0),
       connected(__connected),
-      enabledDirs(),
       userIDGenerator(u.userIDGenerator),
       __currIP(u.__currIP),
       currIP(__currIP),
@@ -257,7 +244,7 @@ USER_IMPL::USER_IMPL(const USER_IMPL & u)
       traffStat(u.traffStat),
       traffStatSaved(u.traffStatSaved),
       settings(u.settings),
-      authorizedBy(),
+      authorizedModificationTime(u.authorizedModificationTime),
       messages(u.messages),
       deleted(u.deleted),
       lastWriteStat(u.lastWriteStat),
@@ -299,17 +286,17 @@ USER_IMPL::USER_IMPL(const USER_IMPL & u)
       sessionUpload(),
       sessionDownload(),
       passiveNotifier(this),
+      disabledNotifier(this),
       tariffNotifier(this),
       cashNotifier(this),
-      ipNotifier(this),
-      mutex(),
-      errorStr()
+      ipNotifier(this)
 {
 if (&u == this)
     return;
 
 property.tariffName.AddBeforeNotifier(&tariffNotifier);
 property.passive.AddBeforeNotifier(&passiveNotifier);
+property.disabled.AddAfterNotifier(&disabledNotifier);
 property.cash.AddBeforeNotifier(&cashNotifier);
 ips.AddAfterNotifier(&ipNotifier);
 
@@ -323,12 +310,14 @@ pthread_mutex_init(&mutex, &attr);
 //-----------------------------------------------------------------------------
 USER_IMPL::~USER_IMPL()
 {
-property.passive.DelBeforeNotifier(&passiveNotifier);
 property.tariffName.DelBeforeNotifier(&tariffNotifier);
+property.passive.DelBeforeNotifier(&passiveNotifier);
+property.disabled.DelAfterNotifier(&disabledNotifier);
+property.cash.DelBeforeNotifier(&cashNotifier);
 pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::SetLogin(string const & l)
+void USER_IMPL::SetLogin(const std::string & l)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 assert(login.empty() && "Login is already set");
@@ -527,6 +516,8 @@ else
         }
     }
 
+if (authorizedBy.empty())
+    authorizedModificationTime = stgTime;
 authorizedBy.insert(auth);
 
 ScanMessage();
@@ -534,7 +525,7 @@ ScanMessage();
 return 0;
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::Unauthorize(const AUTH * auth)
+void USER_IMPL::Unauthorize(const AUTH * auth, const std::string & reason)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 /*
@@ -545,6 +536,8 @@ if (!authorizedBy.erase(auth))
 
 if (authorizedBy.empty())
     {
+    authorizedModificationTime = stgTime;
+    lastDisconnectReason = reason;
     lastIPForDisconnect = currIP;
     currIP = 0; // DelUser in traffcounter
     return;
@@ -558,6 +551,13 @@ STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 return authorizedBy.find(auth) != authorizedBy.end();
 }
 //-----------------------------------------------------------------------------
+std::vector<std::string> USER_IMPL::GetAuthorizers() const
+{
+    std::vector<std::string> list;
+    std::transform(authorizedBy.begin(), authorizedBy.end(), std::back_inserter(list), std::mem_fun(&AUTH::GetVersion));
+    return list;
+}
+//-----------------------------------------------------------------------------
 void USER_IMPL::Connect(bool fakeConnect)
 {
 /*
@@ -568,7 +568,7 @@ STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 if (!fakeConnect)
     {
-    string scriptOnConnect = settings->GetScriptsDir() + "/OnConnect";
+    std::string scriptOnConnect = settings->GetScriptsDir() + "/OnConnect";
 
     if (access(scriptOnConnect.c_str(), X_OK) == 0)
         {
@@ -579,16 +579,24 @@ if (!fakeConnect)
             dirsStr[i] = enabledDirs[i] ? '1' : '0';
             }
 
-        string scriptOnConnectParams;
+        std::string scriptOnConnectParams;
+
         strprintf(&scriptOnConnectParams,
                 "%s \"%s\" \"%s\" \"%f\" \"%d\" \"%s\"",
                 scriptOnConnect.c_str(),
                 login.c_str(),
                 inet_ntostring(currIP).c_str(),
-                (double)cash,
+                cash.ConstData(),
                 id,
                 dirsStr);
 
+        std::vector<std::string>::const_iterator it(settings->GetScriptParams().begin());
+        while (it != settings->GetScriptParams().end())
+            {
+            scriptOnConnectParams += " \"" + GetParamValue(it->c_str()) + "\"";
+            ++it;
+            }
+
         ScriptExec(scriptOnConnectParams.c_str());
         }
     else
@@ -625,7 +633,8 @@ if (!lastIPForDisconnect)
 
 if (!fakeDisconnect)
     {
-    string scriptOnDisonnect = settings->GetScriptsDir() + "/OnDisconnect";
+    lastDisconnectReason = reason;
+    std::string scriptOnDisonnect = settings->GetScriptsDir() + "/OnDisconnect";
 
     if (access(scriptOnDisonnect.c_str(), X_OK) == 0)
         {
@@ -636,16 +645,23 @@ if (!fakeDisconnect)
             dirsStr[i] = enabledDirs[i] ? '1' : '0';
             }
 
-        string scriptOnDisonnectParams;
+        std::string scriptOnDisonnectParams;
         strprintf(&scriptOnDisonnectParams,
                 "%s \"%s\" \"%s\" \"%f\" \"%d\" \"%s\"",
                 scriptOnDisonnect.c_str(),
                 login.c_str(),
                 inet_ntostring(lastIPForDisconnect).c_str(),
-                (double)cash,
+                cash.ConstData(),
                 id,
                 dirsStr);
 
+        std::vector<std::string>::const_iterator it(settings->GetScriptParams().begin());
+        while (it != settings->GetScriptParams().end())
+            {
+            scriptOnDisonnectParams += " \"" + GetParamValue(it->c_str()) + "\"";
+            ++it;
+            }
+
         ScriptExec(scriptOnDisonnectParams.c_str());
         }
     else
@@ -656,7 +672,12 @@ if (!fakeDisconnect)
     connected = false;
     }
 
-if (store->WriteUserDisconnect(login, up, down, sessionUpload, sessionDownload, cash, freeMb, reason))
+std::string reasonMessage(reason);
+if (!lastDisconnectReason.empty())
+    reasonMessage += ": " + lastDisconnectReason;
+
+if (store->WriteUserDisconnect(login, up, down, sessionUpload, sessionDownload,
+                               cash, freeMb, reasonMessage))
     {
     WriteServLog("Cannot write disconnect for user %s.", login.c_str());
     WriteServLog("%s", store->GetStrError().c_str());
@@ -675,37 +696,37 @@ void USER_IMPL::PrintUser() const
 {
 //return;
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-cout << "============================================================" << endl;
-cout << "id=" << id << endl;
-cout << "login=" << login << endl;
-cout << "password=" << password << endl;
-cout << "passive=" << passive << endl;
-cout << "disabled=" << disabled << endl;
-cout << "disabledDetailStat=" << disabledDetailStat << endl;
-cout << "alwaysOnline=" << alwaysOnline << endl;
-cout << "tariffName=" << tariffName << endl;
-cout << "address=" << address << endl;
-cout << "phone=" << phone << endl;
-cout << "email=" << email << endl;
-cout << "note=" << note << endl;
-cout << "realName=" <<realName << endl;
-cout << "group=" << group << endl;
-cout << "credit=" << credit << endl;
-cout << "nextTariff=" << nextTariff << endl;
-cout << "userdata0" << userdata0 << endl;
-cout << "userdata1" << userdata1 << endl;
-cout << "creditExpire=" << creditExpire << endl;
-cout << "ips=" << ips << endl;
-cout << "------------------------" << endl;
-cout << "up=" << up << endl;
-cout << "down=" << down << endl;
-cout << "cash=" << cash << endl;
-cout << "freeMb=" << freeMb << endl;
-cout << "lastCashAdd=" << lastCashAdd << endl;
-cout << "lastCashAddTime=" << lastCashAddTime << endl;
-cout << "passiveTime=" << passiveTime << endl;
-cout << "lastActivityTime=" << lastActivityTime << endl;
-cout << "============================================================" << endl;
+std::cout << "============================================================" << std::endl;
+std::cout << "id=" << id << std::endl;
+std::cout << "login=" << login << std::endl;
+std::cout << "password=" << password << std::endl;
+std::cout << "passive=" << passive << std::endl;
+std::cout << "disabled=" << disabled << std::endl;
+std::cout << "disabledDetailStat=" << disabledDetailStat << std::endl;
+std::cout << "alwaysOnline=" << alwaysOnline << std::endl;
+std::cout << "tariffName=" << tariffName << std::endl;
+std::cout << "address=" << address << std::endl;
+std::cout << "phone=" << phone << std::endl;
+std::cout << "email=" << email << std::endl;
+std::cout << "note=" << note << std::endl;
+std::cout << "realName=" <<realName << std::endl;
+std::cout << "group=" << group << std::endl;
+std::cout << "credit=" << credit << std::endl;
+std::cout << "nextTariff=" << nextTariff << std::endl;
+std::cout << "userdata0" << userdata0 << std::endl;
+std::cout << "userdata1" << userdata1 << std::endl;
+std::cout << "creditExpire=" << creditExpire << std::endl;
+std::cout << "ips=" << ips << std::endl;
+std::cout << "------------------------" << std::endl;
+std::cout << "up=" << up << std::endl;
+std::cout << "down=" << down << std::endl;
+std::cout << "cash=" << cash << std::endl;
+std::cout << "freeMb=" << freeMb << std::endl;
+std::cout << "lastCashAdd=" << lastCashAdd << std::endl;
+std::cout << "lastCashAddTime=" << lastCashAddTime << std::endl;
+std::cout << "passiveTime=" << passiveTime << std::endl;
+std::cout << "lastActivityTime=" << lastActivityTime << std::endl;
+std::cout << "============================================================" << std::endl;
 }
 //-----------------------------------------------------------------------------
 void USER_IMPL::Run()
@@ -800,11 +821,11 @@ if (settings->GetShowFeeInCash() || tariff == NULL)
 return (cash - tariff->GetFee() >= -credit);
 }
 //-----------------------------------------------------------------------------
-string USER_IMPL::GetEnabledDirs()
+std::string USER_IMPL::GetEnabledDirs()
 {
 //STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-string dirs = "";
+std::string dirs = "";
 for(int i = 0; i < DIR_NUM; i++)
     dirs += enabledDirs[i] ? "1" : "0";
 return dirs;
@@ -887,13 +908,13 @@ IP_DIR_PAIR idp(ip, dir, port);
 IP_DIR_PAIR idp(ip, dir);
 #endif
 
-map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
+std::map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
 lb = traffStat.lower_bound(idp);
 if (lb == traffStat.end() || lb->first != idp)
     {
     traffStat.insert(lb,
-                     pair<IP_DIR_PAIR, STAT_NODE>(idp,
-                                                  STAT_NODE(len, 0, cost)));
+                     std::make_pair(idp,
+                                    STAT_NODE(len, 0, cost)));
     }
 else
     {
@@ -978,13 +999,13 @@ IP_DIR_PAIR idp(ip, dir, port);
 IP_DIR_PAIR idp(ip, dir);
 #endif
 
-map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
+std::map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
 lb = traffStat.lower_bound(idp);
 if (lb == traffStat.end() || lb->first != idp)
     {
     traffStat.insert(lb,
-                     pair<IP_DIR_PAIR, STAT_NODE>(idp,
-                                                  STAT_NODE(0, len, cost)));
+                     std::make_pair(idp,
+                                    STAT_NODE(0, len, cost)));
     }
 else
     {
@@ -993,63 +1014,63 @@ else
     }
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * n)
+void USER_IMPL::AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-currIP.AddBeforeNotifier(n);
+currIP.AddBeforeNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * n)
+void USER_IMPL::DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-currIP.DelBeforeNotifier(n);
+currIP.DelBeforeNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * n)
+void USER_IMPL::AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-currIP.AddAfterNotifier(n);
+currIP.AddAfterNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * n)
+void USER_IMPL::DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-currIP.DelAfterNotifier(n);
+currIP.DelAfterNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> * n)
+void USER_IMPL::AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-connected.AddBeforeNotifier(n);
+connected.AddBeforeNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> * n)
+void USER_IMPL::DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-connected.DelBeforeNotifier(n);
+connected.DelBeforeNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> * n)
+void USER_IMPL::AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-connected.AddAfterNotifier(n);
+connected.AddAfterNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
-void USER_IMPL::DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> * n)
+void USER_IMPL::DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-connected.DelAfterNotifier(n);
+connected.DelAfterNotifier(notifier);
 }
 //-----------------------------------------------------------------------------
 void USER_IMPL::OnAdd()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-string scriptOnAdd = settings->GetScriptsDir() + "/OnUserAdd";
+std::string scriptOnAdd = settings->GetScriptsDir() + "/OnUserAdd";
 
 if (access(scriptOnAdd.c_str(), X_OK) == 0)
     {
-    string scriptOnAddParams;
+    std::string scriptOnAddParams;
     strprintf(&scriptOnAddParams,
             "%s \"%s\"",
             scriptOnAdd.c_str(),
@@ -1067,11 +1088,11 @@ void USER_IMPL::OnDelete()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-string scriptOnDel = settings->GetScriptsDir() + "/OnUserDel";
+std::string scriptOnDel = settings->GetScriptsDir() + "/OnUserDel";
 
 if (access(scriptOnDel.c_str(), X_OK) == 0)
     {
-    string scriptOnDelParams;
+    std::string scriptOnDelParams;
     strprintf(&scriptOnDelParams,
             "%s \"%s\"",
             scriptOnDel.c_str(),
@@ -1152,12 +1173,12 @@ if (tms.tm_year % 4 == 0 && tms.tm_mon == 1)
     secMonth += 24 * 3600;
     }
 
-int dt = secMonth - passiveTime;
+time_t dt = secMonth - passiveTime;
 
 if (dt < 0)
     dt = 0;
 
-return double(dt) / (secMonth);
+return static_cast<double>(dt) / secMonth;
 }
 //-----------------------------------------------------------------------------
 void USER_IMPL::SetPassiveTimeAsNewUser()
@@ -1168,9 +1189,10 @@ time_t t = stgTime;
 struct tm tm;
 localtime_r(&t, &tm);
 int daysCurrMon = DaysInCurrentMonth();
-double pt = (tm.tm_mday - 1) / (double)daysCurrMon;
+double pt = tm.tm_mday - 1;
+pt /= daysCurrMon;
 
-passiveTime = (time_t)(pt * 24 * 3600 * daysCurrMon);
+passiveTime = static_cast<time_t>(pt * 24 * 3600 * daysCurrMon);
 }
 //-----------------------------------------------------------------------------
 void USER_IMPL::MidnightResetSessionStat()
@@ -1236,7 +1258,7 @@ if (tariff->GetPeriod() != TARIFF::MONTH)
 
 double fee = tariff->GetFee() / DaysInCurrentMonth();
 
-if (fee == 0.0)
+if (std::fabs(fee) < 1.0e-3)
     return;
 
 double c = cash;
@@ -1253,6 +1275,10 @@ switch (settings->GetFeeChargeType())
         if (c + credit >= fee)
             property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge");
         break;
+    case 3:
+        if (c >= 0)
+            property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge");
+        break;
     }
 ResetPassiveTime();
 }
@@ -1284,7 +1310,7 @@ double fee = tariff->GetFee() * passiveTimePart;
 
 ResetPassiveTime();
 
-if (fee == 0.0)
+if (std::fabs(fee) < 1.0e-3)
     {
     SetPrepaidTraff();
     return;
@@ -1318,6 +1344,13 @@ switch (settings->GetFeeChargeType())
             SetPrepaidTraff();
             }
         break;
+    case 3:
+        if (c >= 0)
+            {
+            property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge");
+            SetPrepaidTraff();
+            }
+        break;
     }
 }
 //-----------------------------------------------------------------------------
@@ -1382,9 +1415,9 @@ else
         msg->header.repeat--;
         #ifndef DEBUG
         //TODO: gcc v. 4.x generate ICE on x86_64
-        msg->header.lastSendTime = time(NULL);
+        msg->header.lastSendTime = static_cast<int>(time(NULL));
         #else
-        msg->header.lastSendTime = stgTime;
+        msg->header.lastSendTime = static_cast<int>(stgTime);
         #endif
         if (store->AddMessage(msg, login))
             {
@@ -1403,7 +1436,7 @@ int USER_IMPL::SendMessage(STG_MSG & msg) const
 {
 // No lock `cause we are already locked from caller
 int ret = -1;
-set<const AUTH*>::iterator it(authorizedBy.begin());
+std::set<const AUTH*>::iterator it(authorizedBy.begin());
 while (it != authorizedBy.end())
     {
     if (!(*it++)->SendMessage(msg, currIP))
@@ -1413,9 +1446,9 @@ if (!ret)
     {
 #ifndef DEBUG
     //TODO: gcc v. 4.x generate ICE on x86_64
-    msg.header.lastSendTime = time(NULL);
+    msg.header.lastSendTime = static_cast<int>(time(NULL));
 #else
-    msg.header.lastSendTime = stgTime;
+    msg.header.lastSendTime = static_cast<int>(stgTime);
 #endif
     msg.header.repeat--;
     }
@@ -1476,6 +1509,43 @@ while (it != messages.end())
     }
 }
 //-----------------------------------------------------------------------------
+std::string USER_IMPL::GetParamValue(const std::string & name) const
+{
+if (name == "freeMb")       return property.freeMb.ToString();
+if (name == "passive")      return property.passive.ToString();
+if (name == "disabled")     return property.disabled.ToString();
+if (name == "alwaysOnline") return property.alwaysOnline.ToString();
+if (name == "tariffName")   return property.tariffName;
+if (name == "nextTariff")   return property.nextTariff;
+if (name == "address")      return property.address;
+if (name == "note")         return property.note;
+if (name == "group")        return property.group;
+if (name == "email")        return property.email;
+if (name == "phone")        return property.phone;
+if (name == "realName")     return property.realName;
+if (name == "credit")       return property.credit.ToString();
+if (name == "userdata0")    return property.userdata0;
+if (name == "userdata1")    return property.userdata1;
+if (name == "userdata2")    return property.userdata2;
+if (name == "userdata3")    return property.userdata3;
+if (name == "userdata4")    return property.userdata4;
+if (name == "userdata5")    return property.userdata5;
+if (name == "userdata6")    return property.userdata6;
+if (name == "userdata7")    return property.userdata7;
+if (name == "userdata8")    return property.userdata8;
+if (name == "userdata9")    return property.userdata9;
+if (name == "cash")         return property.cash.ToString();
+if (name == "id")
+    {
+    std::stringstream stream;
+    stream << id;
+    return stream.str();;
+    }
+if (name == "login")        return login;
+if (name == "ip")           return currIP.ToString();
+return "";
+}
+//-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 void CHG_PASSIVE_NOTIFIER::Notify(const int & oldPassive, const int & newPassive)
@@ -1488,7 +1558,20 @@ if (newPassive && !oldPassive && user->tariff != NULL)
                             "Freeze");
 }
 //-----------------------------------------------------------------------------
-void CHG_TARIFF_NOTIFIER::Notify(const string &, const string & newTariff)
+void CHG_DISABLED_NOTIFIER::Notify(const int & oldValue, const int & newValue)
+{
+if (oldValue && !newValue && user->GetConnected())
+    {
+    user->Disconnect(false, "disabled");
+    }
+else if (!oldValue && newValue && user->IsInetable())
+    {
+    user->Connect(false);
+    }
+
+}
+//-----------------------------------------------------------------------------
+void CHG_TARIFF_NOTIFIER::Notify(const std::string &, const std::string & newTariff)
 {
 if (user->settings->GetReconnectOnTariffChange() && user->connected)
     user->Disconnect(false, "Change tariff");
index 17623294548d208ab31452f19c7db131c5d53c33..90ae01b96669043dfd2a1facf3afa9e0f88668d7 100644 (file)
 #ifndef USER_IMPL_H
 #define USER_IMPL_H
 
-#include <ctime>
-#include <list>
-#include <string>
-#include <set>
-
 #include "stg/user.h"
-#include "stg/os_int.h"
-#include "stg/const.h"
 #include "stg/user_stat.h"
 #include "stg/user_conf.h"
 #include "stg/user_ips.h"
 #include "stg/auth.h"
 #include "stg/message.h"
 #include "stg/noncopyable.h"
+#include "stg/os_int.h"
+#include "stg/const.h"
+
+#include <list>
+#include <vector>
+#include <string>
+#include <set>
+
+#include <ctime>
 
 //-----------------------------------------------------------------------------
 class TARIFF;
@@ -68,9 +70,16 @@ public:
     void Notify(const int & oldPassive, const int & newPassive);
 
 private:
-    CHG_PASSIVE_NOTIFIER(const CHG_PASSIVE_NOTIFIER & rvalue);
-    CHG_PASSIVE_NOTIFIER & operator=(const CHG_PASSIVE_NOTIFIER & rvalue);
+    USER_IMPL * user;
+};
+//-----------------------------------------------------------------------------
+class CHG_DISABLED_NOTIFIER : public PROPERTY_NOTIFIER_BASE<int>,
+                             private NONCOPYABLE {
+public:
+    CHG_DISABLED_NOTIFIER(USER_IMPL * u) : user(u) {}
+    void Notify(const int & oldValue, const int & newValue);
 
+private:
     USER_IMPL * user;
 };
 //-----------------------------------------------------------------------------
@@ -81,9 +90,6 @@ public:
     void Notify(const std::string & oldTariff, const std::string & newTariff);
 
 private:
-    CHG_TARIFF_NOTIFIER(const CHG_TARIFF_NOTIFIER & rvalue);
-    CHG_TARIFF_NOTIFIER & operator=(const CHG_TARIFF_NOTIFIER & rvalue);
-
     USER_IMPL * user;
 };
 //-----------------------------------------------------------------------------
@@ -94,18 +100,12 @@ public:
     void Notify(const double & oldCash, const double & newCash);
 
 private:
-    CHG_CASH_NOTIFIER(const CHG_CASH_NOTIFIER & rvalue);
-    CHG_CASH_NOTIFIER & operator=(const CHG_CASH_NOTIFIER & rvalue);
-
     USER_IMPL * user;
 };
 //-----------------------------------------------------------------------------
 class CHG_IPS_NOTIFIER : public PROPERTY_NOTIFIER_BASE<USER_IPS>,
                          private NONCOPYABLE {
 public:
-    CHG_IPS_NOTIFIER(const CHG_IPS_NOTIFIER & rvalue);
-    CHG_IPS_NOTIFIER & operator=(const CHG_IPS_NOTIFIER & rvalue);
-
     CHG_IPS_NOTIFIER(USER_IMPL * u) : user(u) {}
     void Notify(const USER_IPS & oldIPs, const USER_IPS & newIPs);
 
@@ -115,6 +115,7 @@ private:
 //-----------------------------------------------------------------------------
 class USER_IMPL : public USER {
 friend class CHG_PASSIVE_NOTIFIER;
+friend class CHG_DISABLED_NOTIFIER;
 friend class CHG_TARIFF_NOTIFIER;
 friend class CHG_CASH_NOTIFIER;
 friend class CHG_IPS_NOTIFIER;
@@ -147,17 +148,17 @@ public:
     uint32_t        GetCurrIP() const { return currIP; }
     time_t          GetCurrIPModificationTime() const { return currIP.ModificationTime(); }
 
-    void            AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
-    void            DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
+    void            AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier);
+    void            DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier);
 
-    void            AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
-    void            DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
+    void            AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier);
+    void            DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier);
 
-    void            AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
-    void            DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
+    void            AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier);
+    void            DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier);
 
-    void            AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
-    void            DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
+    void            AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier);
+    void            DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier);
 
     int             GetID() const { return id; }
 
@@ -183,10 +184,14 @@ public:
 
     bool            GetConnected() const { return connected; }
     time_t          GetConnectedModificationTime() const { return connected.ModificationTime(); }
-    int             GetAuthorized() const { return authorizedBy.size(); }
+    const std::string & GetLastDisconnectReason() const { return lastDisconnectReason; }
+    int             GetAuthorized() const { return static_cast<int>(authorizedBy.size()); }
+    time_t          GetAuthorizedModificationTime() const { return authorizedModificationTime; }
     int             Authorize(uint32_t ip, uint32_t enabledDirs, const AUTH * auth);
-    void            Unauthorize(const AUTH * auth);
+    void            Unauthorize(const AUTH * auth,
+                                const std::string & reason = std::string());
     bool            IsAuthorizedBy(const AUTH * auth) const;
+    std::vector<std::string> GetAuthorizers() const;
 
     int             AddMessage(STG_MSG * msg);
 
@@ -198,8 +203,8 @@ public:
 
     const std::string & GetStrError() const { return errorStr; }
 
-    USER_PROPERTIES & GetProperty() { return property; };
-    const USER_PROPERTIES & GetProperty() const { return property; };
+    USER_PROPERTIES & GetProperty() { return property; }
+    const USER_PROPERTIES & GetProperty() const { return property; }
 
     void            SetDeleted() { deleted = true; }
     bool            GetDeleted() const { return deleted; }
@@ -218,6 +223,8 @@ public:
     void            OnAdd();
     void            OnDelete();
 
+    virtual std::string GetParamValue(const std::string & name) const;
+
 private:
     USER_IMPL & operator=(const USER_IMPL & rvalue);
 
@@ -240,6 +247,7 @@ private:
     int             id;
     bool            __connected;
     USER_PROPERTY<bool> connected;
+    std::string     lastDisconnectReason;
 
     bool            enabledDirs[DIR_NUM];
 
@@ -249,6 +257,7 @@ private:
     USER_PROPERTY<uint32_t> currIP;
 
     uint32_t        lastIPForDisconnect; // User's ip after unauth but before disconnect
+    std::string     lastDisconnectReason;
 
     time_t          pingTime;
 
@@ -268,6 +277,7 @@ private:
 #endif
 
     std::set<const AUTH *> authorizedBy;
+    time_t          authorizedModificationTime;
 
     std::list<STG_MSG> messages;
 
@@ -318,6 +328,7 @@ private:
     DIR_TRAFF                sessionDownload;
 
     CHG_PASSIVE_NOTIFIER     passiveNotifier;
+    CHG_DISABLED_NOTIFIER    disabledNotifier;
     CHG_TARIFF_NOTIFIER      tariffNotifier;
     CHG_CASH_NOTIFIER        cashNotifier;
     CHG_IPS_NOTIFIER         ipNotifier;
index 5af05a467f9674a4614a6afbe4b3ac5fcb566240..f5f5eeeacbec868cae7f2c5be6ed5289893a77e6 100644 (file)
@@ -4,8 +4,8 @@ USER_PROPERTIES::USER_PROPERTIES(const std::string & sd)
     : stat(),
       conf(),
       cash            (stat.cash,             "cash",             false, true, GetStgLogger(), sd),
-      up              (stat.up,               "upload",           false, true, GetStgLogger(), sd),
-      down            (stat.down,             "download",         false, true, GetStgLogger(), sd),
+      up              (stat.monthUp,          "upload",           false, true, GetStgLogger(), sd),
+      down            (stat.monthDown,        "download",         false, true, GetStgLogger(), sd),
       lastCashAdd     (stat.lastCashAdd,      "lastCashAdd",      false, true, GetStgLogger(), sd),
       passiveTime     (stat.passiveTime,      "passiveTime",      false, true, GetStgLogger(), sd),
       lastCashAddTime (stat.lastCashAddTime,  "lastCashAddTime",  false, true, GetStgLogger(), sd),
index dfcc556fbf87726ae1e1a20986e7b4d601b68928..f4b4dea0b800420259afb1caef46753936398332 100644 (file)
@@ -46,9 +46,7 @@
 #include "users_impl.h"
 #include "stg_timer.h"
 
-using namespace std;
-
-extern const volatile time_t stgTime;
+extern volatile time_t stgTime;
 
 //#define USERS_DEBUG 1
 
@@ -88,34 +86,50 @@ USERS_IMPL::~USERS_IMPL()
 pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
-int USERS_IMPL::FindByNameNonLock(const string & login, user_iter * user)
+int USERS_IMPL::FindByNameNonLock(const std::string & login, user_iter * user)
 {
-map<string, user_iter>::iterator iter;
-iter = loginIndex.find(login);
-if (iter != loginIndex.end())
-    {
-    if (user)
-        *user = iter->second;
-    return 0;
-    }
-return -1;
+const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
+if (iter == loginIndex.end())
+    return -1;
+if (user)
+    *user = iter->second;
+return 0;
+}
+//-----------------------------------------------------------------------------
+int USERS_IMPL::FindByNameNonLock(const std::string & login, const_user_iter * user) const
+{
+const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
+if (iter == loginIndex.end())
+    return -1;
+if (user)
+    *user = iter->second;
+return 0;
 }
 //-----------------------------------------------------------------------------
-int USERS_IMPL::FindByName(const string & login, USER_PTR * user)
+int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 user_iter u;
-int res = FindByNameNonLock(login, &u);
-if (res)
+if (FindByNameNonLock(login, &u))
+    return -1;
+*user = &(*u);
+return 0;
+}
+//-----------------------------------------------------------------------------
+int USERS_IMPL::FindByName(const std::string & login, CONST_USER_PTR * user) const
+{
+STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+const_user_iter u;
+if (FindByNameNonLock(login, &u))
     return -1;
 *user = &(*u);
 return 0;
 }
 //-----------------------------------------------------------------------------
-bool USERS_IMPL::TariffInUse(const string & tariffName) const
+bool USERS_IMPL::TariffInUse(const std::string & tariffName) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-list<USER_IMPL>::const_iterator iter;
+std::list<USER_IMPL>::const_iterator iter;
 iter = users.begin();
 while (iter != users.end())
     {
@@ -126,7 +140,7 @@ while (iter != users.end())
 return false;
 }
 //-----------------------------------------------------------------------------
-int USERS_IMPL::Add(const string & login, const ADMIN * admin)
+int USERS_IMPL::Add(const std::string & login, const ADMIN * admin)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 const PRIV * priv = admin->GetPriv();
@@ -184,7 +198,7 @@ AddUserIntoIndexes(users.begin());
 
     {
     // Fire all "on add" notifiers
-    set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
+    std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
     while (ni != onAddNotifiers.end())
         {
         (*ni)->Notify(&users.front());
@@ -194,7 +208,7 @@ AddUserIntoIndexes(users.begin());
 
     {
     // Fire all "on add" implementation notifiers
-    set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
+    std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
     while (ni != onAddNotifiersImpl.end())
         {
         (*ni)->Notify(&users.front());
@@ -205,7 +219,7 @@ AddUserIntoIndexes(users.begin());
 return 0;
 }
 //-----------------------------------------------------------------------------
-void USERS_IMPL::Del(const string & login, const ADMIN * admin)
+void USERS_IMPL::Del(const std::string & login, const ADMIN * admin)
 {
 const PRIV * priv = admin->GetPriv();
 user_iter u;
@@ -233,7 +247,7 @@ if (!priv->userAddDel)
     }
 
     {
-    set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
+    std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
     while (ni != onDelNotifiers.end())
         {
         (*ni)->Notify(&(*u));
@@ -242,7 +256,7 @@ if (!priv->userAddDel)
     }
 
     {
-    set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
+    std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
     while (ni != onDelNotifiersImpl.end())
         {
         (*ni)->Notify(&(*u));
@@ -300,7 +314,9 @@ AddToIPIdx(iter);
 return true;
 }
 //-----------------------------------------------------------------------------
-bool USERS_IMPL::Unauthorize(const std::string & login, const AUTH * auth)
+bool USERS_IMPL::Unauthorize(const std::string & login,
+                             const AUTH * auth,
+                             const std::string & reason)
 {
 user_iter iter;
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
@@ -312,7 +328,7 @@ if (FindByNameNonLock(login, &iter))
 
 uint32_t ip = iter->GetCurrIP();
 
-iter->Unauthorize(auth);
+iter->Unauthorize(auth, reason);
 
 if (!iter->GetAuthorized())
     DelFromIPIdx(ip);
@@ -322,7 +338,7 @@ return true;
 //-----------------------------------------------------------------------------
 int USERS_IMPL::ReadUsers()
 {
-vector<string> usersList;
+std::vector<std::string> usersList;
 usersList.clear();
 if (store->GetUsersList(&usersList) < 0)
     {
@@ -371,7 +387,7 @@ int day = t.tm_mday;
 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
 
 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
-string monFile = us->settings->GetMonitorDir() + "/users_r";
+std::string monFile = us->settings->GetMonitorDir() + "/users_r";
 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
 
 us->isRunning = true;
@@ -380,7 +396,7 @@ while (us->nonstop)
     //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
     //printfd(__FILE__,"New Day.    old = %2d current = %2d\n", day, t->tm_mday);
 
-    for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
+    for_each(us->users.begin(), us->users.end(), std::mem_fun_ref(&USER_IMPL::Run));
 
     tt = stgTime;
     localtime_r(&tt, &t);
@@ -419,7 +435,7 @@ while (ui != us->users.end())
     ++ui;
     }
 
-list<USER_TO_DEL>::iterator iter;
+std::list<USER_TO_DEL>::iterator iter;
 iter = us->usersToDelete.begin();
 while (iter != us->usersToDelete.end())
     {
@@ -439,7 +455,7 @@ void USERS_IMPL::NewMinute(const struct tm & t)
 if (t.tm_hour == 23 && t.tm_min == 59)
     {
     printfd(__FILE__,"MidnightResetSessionStat\n");
-    for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
+    for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
     }
 
 if (TimeToWriteDetailStat(t))
@@ -448,14 +464,14 @@ if (TimeToWriteDetailStat(t))
     int usersCnt = 0;
 
     // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
-    list<USER_IMPL>::iterator usr = users.begin();
+    std::list<USER_IMPL>::iterator usr = users.begin();
     while (usr != users.end())
         {
         usersCnt++;
         usr->WriteDetailStat();
         ++usr;
         if (usersCnt % 10 == 0)
-            for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
+            for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
         }
     }
 
@@ -486,14 +502,14 @@ if (!settings->GetDayFeeIsLastDay())
 if (settings->GetSpreadFee())
     {
     printfd(__FILE__, "Spread DayFee\n");
-    for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
+    for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
     }
 else
     {
     if (t.tm_mday == dayFee)
         {
         printfd(__FILE__, "DayFee\n");
-        for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
+        for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFee));
         }
     }
 
@@ -514,7 +530,7 @@ if (dayResetTraff == 0)
 if (t1.tm_mday == dayResetTraff)
     {
     printfd(__FILE__, "ResetTraff\n");
-    for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
+    for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
     //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
     }
 }
@@ -573,15 +589,15 @@ if (isRunning)
     }
 
 printfd(__FILE__, "Before USERS::Run()\n");
-for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
+for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
 
 // 'cause bind2st accepts only constant first param
-for (list<USER_IMPL>::iterator it = users.begin();
+for (std::list<USER_IMPL>::iterator it = users.begin();
      it != users.end();
      ++it)
     it->WriteDetailStat(true);
 
-for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
+for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
 
 printfd(__FILE__, "USERS::Stop()\n");
@@ -594,7 +610,7 @@ STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
 
-list<USER_TO_DEL>::iterator iter;
+std::list<USER_TO_DEL>::iterator iter;
 iter = usersToDelete.begin();
 while (iter != usersToDelete.end())
     {
@@ -627,7 +643,7 @@ if (!ip)
 
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-const map<uint32_t, user_iter>::iterator it(
+const std::map<uint32_t, user_iter>::iterator it(
         ipIndex.lower_bound(ip)
 );
 
@@ -643,7 +659,7 @@ assert(ip && "User has non-null ip");
 
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-const map<uint32_t, user_iter>::iterator it(
+const std::map<uint32_t, user_iter>::iterator it(
         ipIndex.find(ip)
 );
 
@@ -655,7 +671,7 @@ ipIndex.erase(it);
 //-----------------------------------------------------------------------------
 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
 {
-map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
+std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
 if (it == ipIndex.end())
     return false;
 iter = it->second;
@@ -694,11 +710,31 @@ bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
 
-map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
+std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
 
 return it != ipIndex.end();
 }
 //-----------------------------------------------------------------------------
+bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
+{
+STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::list<USER_IMPL>::const_iterator iter;
+iter = users.begin();
+while (iter != users.end())
+    {
+    if (iter->GetLogin() != login &&
+        !iter->GetProperty().ips.Get().IsAnyIP() &&
+        iter->GetProperty().ips.Get().IsIPInIPS(ip))
+        {
+        if (user != NULL)
+            *user = &(*iter);
+        return true;
+        }
+    ++iter;
+    }
+return false;
+}
+//-----------------------------------------------------------------------------
 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
index 69f3fbae8d9aca286e1aa9d1ae9f3ac0c9cc04c6..43065bdeb18753f3ab9bbeeb1c68491892cc2b48 100644 (file)
@@ -75,6 +75,7 @@ public:
     virtual ~USERS_IMPL();
 
     int             FindByName(const std::string & login, USER_PTR * user);
+    int             FindByName(const std::string & login, CONST_USER_PTR * user) const;
 
     bool            TariffInUse(const std::string & tariffName) const;
 
@@ -95,7 +96,9 @@ public:
 
     bool            Authorize(const std::string & login, uint32_t ip,
                               uint32_t enabledDirs, const AUTH * auth);
-    bool            Unauthorize(const std::string & login, const AUTH * auth);
+    bool            Unauthorize(const std::string & login,
+                                const AUTH * auth,
+                                const std::string & reason = std::string());
 
     int             ReadUsers();
     size_t          Count() const { return users.size(); }
@@ -103,6 +106,7 @@ public:
     int             FindByIPIdx(uint32_t ip, USER_PTR * user) const;
     int             FindByIPIdx(uint32_t ip, USER_IMPL ** user) const;
     bool            IsIPInIndex(uint32_t ip) const;
+    bool            IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const;
 
     int             OpenSearch();
     int             SearchNext(int handler, USER_PTR * user);
@@ -121,6 +125,7 @@ private:
     bool            FindByIPIdx(uint32_t ip, user_iter & iter) const;
 
     int             FindByNameNonLock(const std::string & login, user_iter * user);
+    int             FindByNameNonLock(const std::string & login, const_user_iter * user) const;
 
     void            RealDelUser();
     void            ProcessActions();
index 912be63debeb836291c7b4b6fe34904288502d56..6b9fbe4023b727919647aba2f08954a63a1b87c5 100644 (file)
@@ -7,9 +7,9 @@ include ../Makefile.conf
 .PHONY: all $(STG_LIBS)
 .PHONY: clean install uninstall includes
 all: $(STG_LIBS)
-
-$(STG_LIBS):
-       $(MAKE) $(MAKECMDGOALS) -C $@
+       for LIB in $(STG_LIBS); do\
+           $(MAKE) $(MAKECMDGOALS) -C $$LIB;\
+       done
 
 includes: all
 
index a3184974bae4326ee007f527486f63904ec6ec4f..b5d1195c422ee9918c5a24eaa57244d5ca936d83 100644 (file)
@@ -35,8 +35,11 @@ clean:
        rm -f deps $(PROG) *.o *.a *.so tags *.*~ 
 
 install: $(PROG)
-       mkdir -m $(DIR_MODE) -p $(PREFIX)/usr/lib/stg
-       install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+ifeq ($(DEBUG), yes)
+       install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+else
+       install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+endif
        mkdir -m $(DIR_MODE) -p $(PREFIX)/usr/include/stg
        install -m $(DATA_MODE) -o $(OWNER) $(addprefix include/stg/,$(INCS)) $(PREFIX)/usr/include/stg/
 
index 2ea32c2b7060f0017c5298931e829ff7674af154..15547b49122e4fa0ade9d6d98ab000e1c56cda14 100644 (file)
 #   define INET_ADDRSTRLEN 16
 #endif
 
-using namespace std;
+namespace
+{
+//---------------------------------------------------------------------------
+unsigned char koi2win[] = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+        0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
+        0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
+        0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
+        0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
+        0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
+        0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
+        0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
+        0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
+        0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
+        0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
+        0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
+        0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
+        0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
+        0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+        0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
+        0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
+        0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
+        0xA0, 0xA1, 0xA2, 0xB8, 0xBA, 0xA5, 0xB3, 0xBF,
+        0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xB4, 0xAE, 0xAF,
+        0xB0, 0xB1, 0xB2, 0xA8, 0xAA, 0xB5, 0xB2, 0xAF,
+        0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xA5, 0xBE, 0xBF,
+        0xFE, 0xE0, 0xE1, 0xF6, 0xE4, 0xE5, 0xF4, 0xE3,
+        0xF5, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE,
+        0xEF, 0xFF, 0xF0, 0xF1, 0xF2, 0xF3, 0xE6, 0xE2,
+        0xFC, 0xFB, 0xE7, 0xF8, 0xFD, 0xF9, 0xF7, 0xFA,
+        0xDE, 0xC0, 0xC1, 0xD6, 0xC4, 0xC5, 0xD4, 0xC3,
+        0xD5, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE,
+        0xCF, 0xDF, 0xD0, 0xD1, 0xD2, 0xD3, 0xC6, 0xC2,
+        0xDC, 0xDB, 0xC7, 0xD8, 0xDD, 0xD9, 0xD7, 0xDA};
+
+
+unsigned char win2koi[] = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+        0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
+        0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
+        0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
+        0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
+        0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
+        0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
+        0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
+        0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
+        0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
+        0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
+        0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
+        0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
+        0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
+        0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+        0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
+        0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
+        0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
+        0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xBD, 0xA6, 0xA7,
+        0xB3, 0xA9, 0xB4, 0xAB, 0xAC, 0xAD, 0xAE, 0xB7,
+        0xB0, 0xB1, 0xB6, 0xA6, 0xAD, 0xB5, 0xB6, 0xB7,
+        0xA3, 0xB9, 0xA4, 0xBB, 0xBC, 0xBD, 0xBE, 0xA7,
+        0xE1, 0xE2, 0xF7, 0xE7, 0xE4, 0xE5, 0xF6, 0xFA,
+        0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0,
+        0xF2, 0xF3, 0xF4, 0xF5, 0xE6, 0xE8, 0xE3, 0xFE,
+        0xFB, 0xFD, 0xFF, 0xF9, 0xF8, 0xFC, 0xE0, 0xF1,
+        0xC1, 0xC2, 0xD7, 0xC7, 0xC4, 0xC5, 0xD6, 0xDA,
+        0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,
+        0xD2, 0xD3, 0xD4, 0xD5, 0xC6, 0xC8, 0xC3, 0xDE,
+        0xDB, 0xDD, 0xDF, 0xD9, 0xD8, 0xDC, 0xC0, 0xD1};
+}
 
 #ifdef WIN32
 //-----------------------------------------------------------------------------
@@ -136,7 +207,7 @@ printf("%s", buff);
 return 0;
 }
 //-----------------------------------------------------------------------------
-int strprintf(string * str, const char * fmt, ...)
+int strprintf(std::string * str, const char * fmt, ...)
 {
 char buff[1024];
 
@@ -150,11 +221,13 @@ buff[1023] = 0;
 return n;
 }
 //-----------------------------------------------------------------------------
-const char *IntToKMG(long long a, int stat)
+const char *IntToKMG(int64_t a, int stat)
 {
-static int64_t M = 1024*1024;
-static int64_t G = 1024*1024*1024;
+static const double K = 1024;
+static const double M = 1024 * 1024;
+static const double G = 1024 * 1024 * 1024;
 static char str[30];
+double value = a;
 
 switch (stat)
     {
@@ -166,108 +239,39 @@ switch (stat)
         #endif
         break;
     case ST_KB:
-        sprintf(str, "%.2f kb", double(a)/1024.0);
+        sprintf(str, "%.2f kb", value / K);
         break;
     case ST_MB:
-        sprintf(str, "%.2f Mb", double(a)/(1024.0*1024.0));
+        sprintf(str, "%.2f Mb", value / M);
         break;
     default:
         if (a > G)
             {
-            sprintf(str, "%.2f Gb", double(a)/double(G));
+            sprintf(str, "%.2f Gb", value / G);
             return &str[0];
             }
         if (a < -G)
             {
-            sprintf(str, "%.2f Gb", double(a)/double(G));
+            sprintf(str, "%.2f Gb", value / G);
             return &str[0];
             }
         if (a > M)
             {
-            sprintf(str, "%.2f Mb", double(a)/double(M));
+            sprintf(str, "%.2f Mb", value / M);
             return &str[0];
             }
         if (a < -M)
             {
-            sprintf(str, "%.2f Mb", double(a)/double(M));
+            sprintf(str, "%.2f Mb", value / M);
             return &str[0];
             }
 
-        sprintf(str, "%.2f kb", double(a)/1024.0);
+        sprintf(str, "%.2f kb", value / K);
         break;
     }
 return str;
 }
 //---------------------------------------------------------------------------
-unsigned char koi2win[] = {
-        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
-        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
-        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
-        0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
-        0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
-        0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
-        0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
-        0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
-        0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
-        0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
-        0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
-        0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
-        0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
-        0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
-        0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
-        0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
-        0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
-        0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
-        0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
-        0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
-        0xA0, 0xA1, 0xA2, 0xB8, 0xBA, 0xA5, 0xB3, 0xBF,
-        0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xB4, 0xAE, 0xAF,
-        0xB0, 0xB1, 0xB2, 0xA8, 0xAA, 0xB5, 0xB2, 0xAF,
-        0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xA5, 0xBE, 0xBF,
-        0xFE, 0xE0, 0xE1, 0xF6, 0xE4, 0xE5, 0xF4, 0xE3,
-        0xF5, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE,
-        0xEF, 0xFF, 0xF0, 0xF1, 0xF2, 0xF3, 0xE6, 0xE2,
-        0xFC, 0xFB, 0xE7, 0xF8, 0xFD, 0xF9, 0xF7, 0xFA,
-        0xDE, 0xC0, 0xC1, 0xD6, 0xC4, 0xC5, 0xD4, 0xC3,
-        0xD5, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE,
-        0xCF, 0xDF, 0xD0, 0xD1, 0xD2, 0xD3, 0xC6, 0xC2,
-        0xDC, 0xDB, 0xC7, 0xD8, 0xDD, 0xD9, 0xD7, 0xDA};
-
-
-unsigned char win2koi[] = {
-        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
-        0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
-        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
-        0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
-        0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
-        0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
-        0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
-        0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
-        0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
-        0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
-        0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
-        0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
-        0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
-        0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
-        0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
-        0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
-        0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
-        0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
-        0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
-        0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
-        0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xBD, 0xA6, 0xA7,
-        0xB3, 0xA9, 0xB4, 0xAB, 0xAC, 0xAD, 0xAE, 0xB7,
-        0xB0, 0xB1, 0xB6, 0xA6, 0xAD, 0xB5, 0xB6, 0xB7,
-        0xA3, 0xB9, 0xA4, 0xBB, 0xBC, 0xBD, 0xBE, 0xA7,
-        0xE1, 0xE2, 0xF7, 0xE7, 0xE4, 0xE5, 0xF6, 0xFA,
-        0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0,
-        0xF2, 0xF3, 0xF4, 0xF5, 0xE6, 0xE8, 0xE3, 0xFE,
-        0xFB, 0xFD, 0xFF, 0xF9, 0xF8, 0xFC, 0xE0, 0xF1,
-        0xC1, 0xC2, 0xD7, 0xC7, 0xC4, 0xC5, 0xD6, 0xDA,
-        0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,
-        0xD2, 0xD3, 0xD4, 0xD5, 0xC6, 0xC8, 0xC3, 0xDE,
-        0xDB, 0xDD, 0xDF, 0xD9, 0xD8, 0xDC, 0xC0, 0xD1};
-//---------------------------------------------------------------------------
 void KOIToWin(const char * s1, char * s2, int l)
 {
 unsigned char t;
@@ -294,7 +298,7 @@ for (int j = 0; j < l; j++)
     }
 }
 //---------------------------------------------------------------------------
-void KOIToWin(const string & s1, string * s2)
+void KOIToWin(const std::string & s1, std::string * s2)
 {
 s2->erase(s2->begin(), s2->end());
 unsigned char t;
@@ -306,7 +310,7 @@ for (int j = 0; j < (int)s1.length(); j++)
     }
 }
 //---------------------------------------------------------------------------
-void WinToKOI(const string & s1, string * s2)
+void WinToKOI(const std::string & s1, std::string * s2)
 {
 s2->erase(s2->begin(), s2->end());
 unsigned char t;
@@ -318,7 +322,7 @@ for (int j = 0; j < (int)s1.length(); j++)
     }
 }
 //---------------------------------------------------------------------------
-void Encode12str(string & dst, const string & src)
+void Encode12str(std::string & dst, const std::string & src)
 {
 dst.erase(dst.begin(), dst.end());
 for (size_t i = 0; i < src.length(); i++)
@@ -339,10 +343,24 @@ for (size_t i = 0; i < src.length() / 2; i++)
     c1 -= 'a';
     c2 -= 'a';
 
-    dst.push_back(c1 + (c2 << 4));
+    dst.push_back(static_cast<char>(c1 + (c2 << 4)));
     }
 }
 //---------------------------------------------------------------------------
+std::string Encode12str(const std::string & src)
+{
+std::string res;
+Encode12str(res, src);
+return res;
+}
+//---------------------------------------------------------------------------
+std::string Decode21str(const std::string & src)
+{
+std::string res;
+Decode21str(res, src);
+return res;
+}
+//---------------------------------------------------------------------------
 void Encode12(char * dst, const char * src, size_t srcLen)
 {
 for (size_t i = 0; i <= srcLen; i++)
@@ -372,7 +390,7 @@ for (size_t i = 0; ; i++)
     c1 -= 'a';
     c2 -= 'a';
 
-    dst[i] = c1 + (c2 << 4);
+    dst[i] = static_cast<char>(c1 + (c2 << 4));
     }
 dst[strlen(src) / 2] = 0;
 }
@@ -610,7 +628,7 @@ if (msk == 0) return 0;
 return htonl(0xFFffFFff << (32 - msk));
 }
 //---------------------------------------------------------------------------
-void TouchFile(const string & fileName)
+void TouchFile(const std::string & fileName)
 {
 FILE * f = fopen(fileName.c_str(), "w");
 if (f)
@@ -689,28 +707,28 @@ strcpy(str, strdc);
 #endif //WIN32
 void SwapBytes(uint16_t & value)
 {
-    value = (value >> 8) |
-            (value << 8);
+    value = static_cast<uint16_t>((value >> 8) |
+                                  (value << 8));
 }
 //---------------------------------------------------------------------------
 void SwapBytes(uint32_t & value)
 {
-    value = (value >> 24) |
-            ((value << 8) &  0x00FF0000L)|
-            ((value >> 8) &  0x0000FF00L)|
-            (value << 24);
+    value = static_cast<uint32_t>((value >> 24) |
+                                  ((value << 8) &  0x00FF0000L) |
+                                  ((value >> 8) &  0x0000FF00L) |
+                                  (value << 24));
 }
 //---------------------------------------------------------------------------
 void SwapBytes(uint64_t & value)
 {
-    value = (value >> 56) |
-            ((value << 40) & 0x00FF000000000000LL) |
-            ((value << 24) & 0x0000FF0000000000LL) |
-            ((value << 8)  & 0x000000FF00000000LL) |
-            ((value >> 8)  & 0x00000000FF000000LL) |
-            ((value >> 24) & 0x0000000000FF0000LL) |
-            ((value >> 40) & 0x000000000000FF00LL) |
-            (value << 56);
+    value = static_cast<uint64_t>((value >> 56) |
+                                  ((value << 40) & 0x00FF000000000000LL) |
+                                  ((value << 24) & 0x0000FF0000000000LL) |
+                                  ((value << 8)  & 0x000000FF00000000LL) |
+                                  ((value >> 8)  & 0x00000000FF000000LL) |
+                                  ((value >> 24) & 0x0000000000FF0000LL) |
+                                  ((value >> 40) & 0x000000000000FF00LL) |
+                                  (value << 56));
 }
 //---------------------------------------------------------------------------
 void SwapBytes(int16_t & value)
@@ -734,9 +752,9 @@ void SwapBytes(int64_t & value)
     value = temp;
 }
 //---------------------------------------------------------------------------
-int str2x(const std::string & str, int & x)
+int str2x(const std::string & str, int32_t & x)
 {
-x = strtol(str.c_str(), NULL, 10);
+x = static_cast<int32_t>(strtol(str.c_str(), NULL, 10));
 
 if (errno == ERANGE)
     return -1;
@@ -744,29 +762,9 @@ if (errno == ERANGE)
 return 0;
 }
 //---------------------------------------------------------------------------
-int str2x(const std::string & str, unsigned & x)
+int str2x(const std::string & str, uint32_t & x)
 {
-x = strtoul(str.c_str(), NULL, 10);
-
-if (errno == ERANGE)
-    return -1;
-
-return 0;
-}
-//---------------------------------------------------------------------------
-int str2x(const std::string & str, long & x)
-{
-x = strtol(str.c_str(), NULL, 10);
-
-if (errno == ERANGE)
-    return -1;
-
-return 0;
-}
-//---------------------------------------------------------------------------
-int str2x(const std::string & str, unsigned long & x)
-{
-x = strtoul(str.c_str(), NULL, 10);
+x = static_cast<uint32_t>(strtoul(str.c_str(), NULL, 10));
 
 if (errno == ERANGE)
     return -1;
@@ -775,7 +773,7 @@ return 0;
 }
 #ifndef WIN32
 //---------------------------------------------------------------------------
-int str2x(const std::string & str, long long & x)
+int str2x(const std::string & str, int64_t & x)
 {
 x = strtoll(str.c_str(), NULL, 10);
 
@@ -785,7 +783,7 @@ if (errno == ERANGE)
 return 0;
 }
 //---------------------------------------------------------------------------
-int str2x(const std::string & str, unsigned long long & x)
+int str2x(const std::string & str, uint64_t & x)
 {
 x = strtoull(str.c_str(), NULL, 10);
 
@@ -796,19 +794,21 @@ return 0;
 }
 #endif
 //---------------------------------------------------------------------------
-const std::string & x2str(unsigned x, std::string & s)
+const std::string & x2str(uint32_t x, std::string & s)
 {
 return unsigned2str(x, s);
 }
 //---------------------------------------------------------------------------
-const std::string & x2str(unsigned long x, std::string & s)
+const std::string & x2str(uint64_t x, std::string & s)
 {
 return unsigned2str(x, s);
 }
 //---------------------------------------------------------------------------
-const std::string & x2str(unsigned long long x, std::string & s)
+const std::string & x2str(double x, std::string & s)
 {
-return unsigned2str(x, s);
+char buf[256];
+s = snprintf(buf, sizeof(buf), "%f", x);
+return s;
 }
 //---------------------------------------------------------------------------
 std::string & TrimL(std::string & val)
@@ -840,6 +840,22 @@ std::string & Trim(std::string & val)
 return TrimR(TrimL(val));
 }
 //---------------------------------------------------------------------------
+std::string ToLower(const std::string & value)
+{
+    std::string res;
+    for (std::string::size_type pos = 0; pos < value.length(); ++pos)
+        res += tolower(value[pos]);
+    return res;
+}
+//---------------------------------------------------------------------------
+std::string ToUpper(const std::string & value)
+{
+    std::string res;
+    for (std::string::size_type pos = 0; pos < value.length(); ++pos)
+        res += toupper(value[pos]);
+    return res;
+}
+//---------------------------------------------------------------------------
 #ifdef WIN32
 static int is_leap(unsigned y)
 {
@@ -982,14 +998,14 @@ if (str2x<int>(str, *val))
 return 0;
 }
 
-int ParseUnsigned(const string & str, unsigned * val)
+int ParseUnsigned(const std::string & str, unsigned * val)
 {
 if (str2x<unsigned>(str, *val))
     return -1;
 return 0;
 }
 
-int ParseIntInRange(const string & str, int min, int max, int * val)
+int ParseIntInRange(const std::string & str, int min, int max, int * val)
 {
 if (ParseInt(str, val) != 0)
     return -1;
@@ -1000,7 +1016,7 @@ if (*val < min || *val > max)
 return 0;
 }
 
-int ParseUnsignedInRange(const string & str, unsigned min,
+int ParseUnsignedInRange(const std::string & str, unsigned min,
                          unsigned max, unsigned * val)
 {
 if (ParseUnsigned(str, val) != 0)
index df93815215e4f32a8fd85e5882967f218116c555..b4b53530d512a94cc4021ce954892218eba7c886 100644 (file)
 #define ST_MB   3
 
 //-----------------------------------------------------------------------------
-const char    * IntToKMG(long long a, int statType = ST_F);
+const char    * IntToKMG(int64_t a, int statType = ST_F);
 const char    * LogDate(time_t t);
 int             ParesTimeStat(const char * str);
 int             IsTimeStat(struct tm * t, int statTime);
-/*bool            IsDigit(char c);
-bool            IsAlpha(char c);*/
-int             strtodouble2(const char * s, double &a);
+int             strtodouble2(const char * str, double & value);
+inline int      strtodouble2(const std::string & str, double & value) { return strtodouble2(str.c_str(), value); }
 int             printfd(const char * __file__, const char * fmt, ...);
 void            Encode12(char * dst, const char * src, size_t srcLen);
 void            Decode21(char * dst, const char * src);
 
 void            Encode12str(std::string & dst, const std::string & src);
 void            Decode21str(std::string & dst, const std::string & src);
+std::string     Encode12str(const std::string & src);
+std::string     Decode21str(const std::string & src);
 
 int             ParseIPString(const char * str, uint32_t * ips, int maxIP);
 void            KOIToWin(const char * s1, char * s2, int l);
@@ -74,7 +75,6 @@ void            WinToKOI(const std::string & s1, std::string * s2);
 int             DaysInMonth(unsigned year, unsigned mon);
 int             DaysInCurrentMonth();
 int             Min8(int a);
-//char          * inet_ntostr(unsigned long);
 std::string     inet_ntostring(uint32_t);
 uint32_t        inet_strington(const std::string & value);
 int             strprintf(std::string * str, const char * fmt, ...);
@@ -96,6 +96,9 @@ std::string &   TrimL(std::string & val);
 std::string &   TrimR(std::string & val);
 std::string &   Trim(std::string & val);
 
+std::string     ToLower(const std::string & value);
+std::string     ToUpper(const std::string & value);
+
 std::string     IconvString(const std::string & source, const std::string & from, const std::string & to);
 
 int ParseInt(const std::string & str, int * val);
@@ -107,12 +110,30 @@ int ParseYesNo(const std::string & str, bool * val);
 
 bool WaitPackets(int sd);
 
+//-----------------------------------------------------------------------------
+int str2x(const std::string & str, int32_t & x);
+int str2x(const std::string & str, uint32_t & x);
+#ifndef WIN32
+int str2x(const std::string & str, int64_t & x);
+int str2x(const std::string & str, uint64_t & x);
+#endif
+//-----------------------------------------------------------------------------
+const std::string & x2str(uint32_t x, std::string & s);
+const std::string & x2str(uint64_t x, std::string & s);
+//-----------------------------------------------------------------------------
+const std::string & x2str(double x, std::string & s);
+//-----------------------------------------------------------------------------
+
 template <typename varT>
 int str2x(const std::string & str, varT & x);
 template <typename varT>
 const std::string & x2str(varT x, std::string & s);
 template <typename varT>
+std::string x2str(varT x) { std::string s; return x2str(x, s); }
+template <typename varT>
 const std::string & unsigned2str(varT x, std::string & s);
+template <typename varT>
+std::string unsigned2str(varT x) { std::string s; return unsigned2str(x, s); }
 
 //-----------------------------------------------------------------------------
 template <typename varT>
@@ -148,7 +169,7 @@ int str2x(const std::string & str, varT & x)
         x += str[i] - '0';
     }
 
-    x*= minus;
+    x *= minus;
 
     return 0;
 }
@@ -236,19 +257,6 @@ const std::string & unsigned2str(varT x, std::string & s)
     return s;
 }
 //-----------------------------------------------------------------------------
-int str2x(const std::string & str, int & x);
-int str2x(const std::string & str, unsigned & x);
-int str2x(const std::string & str, long & x);
-int str2x(const std::string & str, unsigned long & x);
-#ifndef WIN32
-int str2x(const std::string & str, long long & x);
-int str2x(const std::string & str, unsigned long long & x);
-#endif
-//-----------------------------------------------------------------------------
-const std::string & x2str(unsigned x, std::string & s);
-const std::string & x2str(unsigned long x, std::string & s);
-const std::string & x2str(unsigned long long x, std::string & s);
-//-----------------------------------------------------------------------------
 char * stg_strptime(const char *, const char *, struct tm *);
 time_t stg_timegm(struct tm *);
 
index 0e1fde27e177c118f9716bc53c3b5071cde235e6..38b86b47fd9398d68f8554eb529bbc764b3b8524 100644 (file)
@@ -10,6 +10,8 @@
 #define _XOPEN_SOURCE
 #include <time.h>
 
+#include "stg/common.h"
+
 char * stg_strptime(const char * a, const char * b, struct tm * tm)
 {
 return strptime(a, b, tm);
index 263c9933daa156add001ef7b611927fe7a5b9938..302c365194ddd0cd6d08de0f4521a786c762c5ed 100644 (file)
 
 #include "stg/conffiles.h"
 
-using namespace std;
+namespace
+{
+//---------------------------------------------------------------------------
+std::string TrimL(std::string val)
+{
+size_t pos = val.find_first_not_of(" \t");
+if (pos == std::string::npos)
+    {
+    val.erase(val.begin(), val.end());
+    }
+else
+    {
+    val.erase(0, pos);
+    }
+return val;
+}
+//---------------------------------------------------------------------------
+std::string TrimR(std::string val)
+{
+size_t pos = val.find_last_not_of(" \t");
+if (pos != std::string::npos)
+    {
+    val.erase(pos + 1);
+    }
+return val;
+}
+//---------------------------------------------------------------------------
+std::string Trim(std::string val)
+{
+return TrimR(TrimL(val));
+}
+//---------------------------------------------------------------------------
+} // namespace anonymous
 
 //---------------------------------------------------------------------------
-bool StringCaseCmp(const string & str1, const string & str2)
+bool StringCaseCmp(const std::string & str1, const std::string & str2)
 {
 return (strcasecmp(str1.c_str(), str2.c_str()) < 0);
 }
 //---------------------------------------------------------------------------
-CONFIGFILE::CONFIGFILE(const string & fn, bool nook)
+CONFIGFILE::CONFIGFILE(const std::string & fn, bool nook)
     : param_val(StringCaseCmp),
       fileName(fn),
       error(0),
       changed(false)
 {
-ifstream f(fileName.c_str());
+std::ifstream f(fileName.c_str());
 
 if (!f)
     {
@@ -65,25 +97,25 @@ if (!f)
     return;
     }
 
-string line;
+std::string line;
 while (getline(f, line))
     {
     size_t pos = line.find('#');
-    if (pos != string::npos)
+    if (pos != std::string::npos)
         line.resize(pos);
 
-    if (line.find_first_not_of(" \t\r") == string::npos)
+    if (line.find_first_not_of(" \t\r") == std::string::npos)
         continue;
 
     pos = line.find_first_of('=');
-    if (pos == string::npos)
+    if (pos == std::string::npos)
         {
         error = -1;
         return;
         }
 
-    string parameter = line.substr(0, pos);
-    string value = line.substr(pos + 1);
+    std::string parameter = Trim(line.substr(0, pos));
+    std::string value = Trim(line.substr(pos + 1));
     param_val[parameter] = value;
     }
 }
@@ -93,7 +125,7 @@ CONFIGFILE::~CONFIGFILE()
 Flush();
 }
 //---------------------------------------------------------------------------
-const string & CONFIGFILE::GetFileName() const
+const std::string & CONFIGFILE::GetFileName() const
 {
 return fileName;
 }
@@ -105,9 +137,9 @@ error = 0;
 return e;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadString(const string & param, string * val, const string & defaultVal) const
+int CONFIGFILE::ReadString(const std::string & param, std::string * val, const std::string & defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -119,15 +151,15 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-void CONFIGFILE::WriteString(const string & param, const string &val)
+void CONFIGFILE::WriteString(const std::string & param, const std::string &val)
 {
 param_val[param] = val;
 changed = true;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadTime(const string & param, time_t * val, time_t defaultVal) const
+int CONFIGFILE::ReadTime(const std::string & param, time_t * val, time_t defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -145,14 +177,14 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadInt(const string & param, int * val, int defaultVal) const
+int CONFIGFILE::ReadInt(const std::string & param, int * val, int defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
     char *res;
-    *val = strtol(it->second.c_str(), &res, 10);
+    *val = static_cast<int>(strtol(it->second.c_str(), &res, 10));
     if (*res != 0)
         {
         *val = defaultVal; //Error!
@@ -165,14 +197,14 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadUInt(const string & param, unsigned int * val, unsigned int defaultVal) const
+int CONFIGFILE::ReadUInt(const std::string & param, unsigned int * val, unsigned int defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
     char *res;
-    *val = strtoul(it->second.c_str(), &res, 10);
+    *val = static_cast<unsigned int>(strtoul(it->second.c_str(), &res, 10));
     if (*res != 0)
         {
         *val = defaultVal; //Error!
@@ -185,9 +217,9 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadLongInt(const string & param, long int * val, long int defaultVal) const
+int CONFIGFILE::ReadLongInt(const std::string & param, long int * val, long int defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -205,9 +237,9 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadULongInt(const string & param, unsigned long int * val, unsigned long int defaultVal) const
+int CONFIGFILE::ReadULongInt(const std::string & param, unsigned long int * val, unsigned long int defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -225,9 +257,9 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadLongLongInt(const string & param, int64_t * val, int64_t defaultVal) const
+int CONFIGFILE::ReadLongLongInt(const std::string & param, int64_t * val, int64_t defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -245,9 +277,9 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadULongLongInt(const string & param, uint64_t * val, uint64_t defaultVal) const
+int CONFIGFILE::ReadULongLongInt(const std::string & param, uint64_t * val, uint64_t defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -265,9 +297,9 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadShortInt(const string & param, short int * val, short int defaultVal) const
+int CONFIGFILE::ReadShortInt(const std::string & param, short int * val, short int defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -285,9 +317,9 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadUShortInt(const string & param, unsigned short int * val, unsigned short int defaultVal) const
+int CONFIGFILE::ReadUShortInt(const std::string & param, unsigned short int * val, unsigned short int defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -305,7 +337,7 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-void CONFIGFILE::WriteInt(const string & param, int64_t val)
+void CONFIGFILE::WriteInt(const std::string & param, int64_t val)
 {
 char buf[32];
 snprintf(buf, sizeof(buf), "%lld", static_cast<long long int>(val));
@@ -313,9 +345,9 @@ param_val[param] = buf;
 changed = true;
 }
 //---------------------------------------------------------------------------
-int CONFIGFILE::ReadDouble(const string & param, double * val, double defaultVal) const
+int CONFIGFILE::ReadDouble(const std::string & param, double * val, double defaultVal) const
 {
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
 
 if (it != param_val.end())
     {
@@ -333,7 +365,7 @@ if (it != param_val.end())
 return -1;
 }
 //---------------------------------------------------------------------------
-void CONFIGFILE::WriteDouble(const string & param, double val)
+void CONFIGFILE::WriteDouble(const std::string & param, double val)
 {
 char s[30];
 snprintf(s, 30, "%f", val);
@@ -343,14 +375,14 @@ changed = true;
 //---------------------------------------------------------------------------
 int CONFIGFILE::Flush(const std::string & path) const
 {
-ofstream f(path.c_str());
+std::ofstream f(path.c_str());
 if (!f.is_open())
     {
     error = EIO;
     return EIO;
     }
 
-map<string, string>::const_iterator it = param_val.begin();
+std::map<std::string, std::string>::const_iterator it = param_val.begin();
 while (it != param_val.end())
     {
     f << it->first << "=" << it->second << "\n";
index 6909c6c91290c5d9e1eeff79d5f5814d161ecdc9..48e07b6282bd2be594b35deee7d5f69a206d4779 100644 (file)
 
 #include "stg/os_int.h"
 
-using namespace std;
 //---------------------------------------------------------------------------
 
-typedef bool (*StringCaseCmp_t)(const string & str1, const string & str2);
+typedef bool (*StringCaseCmp_t)(const std::string & str1, const std::string & str2);
 
 class CONFIGFILE
 {
 public:
-    CONFIGFILE(const string & fn, bool nook = false);
+    CONFIGFILE(const std::string & fn, bool nook = false);
     ~CONFIGFILE();
-    const string & GetFileName() const;
+    const std::string & GetFileName() const;
 
     // æÕÎËÃÉÉ Read* ×ÏÚ×ÒÁÝÁÀÔ 0 ÐÒÉ ÕÓÐÅÛÎÏÍ ÓÞÉÔÙ×ÁÎÉÉ
     // É EINVAL ÐÒÉ ÏÔÓÕÔÓ×ÉÉ ÐÁÒÁÍÅÔÒÁ É ×ÙÓÔÁ×ÌÑÀÔ defaulValue
-    //int ReadString(const string & param, char * val, int * maxLen, const char * defaultVal) const;
-    int ReadString(const string & param, string * val, const string & defaultVal) const;
-    int ReadTime(const string & param, time_t *, time_t) const;
-    int ReadShortInt(const string & param, short int *, short int) const;
-    int ReadInt(const string & param, int *, int) const;
-    int ReadLongInt(const string & param, long int *, long int) const;
-    int ReadLongLongInt(const string & param, int64_t *, int64_t) const;
-    int ReadUShortInt(const string & param, unsigned short int *, unsigned short int) const;
-    int ReadUInt(const string & param, unsigned int *, unsigned int) const;
-    int ReadULongInt(const string & param, unsigned long int *, unsigned long int) const;
-    int ReadULongLongInt(const string & param, uint64_t *, uint64_t) const;
-    int ReadDouble(const string & param, double * val, double defaultVal) const;
+    //int ReadString(const std::string & param, char * val, int * maxLen, const char * defaultVal) const;
+    int ReadString(const std::string & param, std::string * val, const std::string & defaultVal) const;
+    int ReadTime(const std::string & param, time_t *, time_t) const;
+    int ReadShortInt(const std::string & param, short int *, short int) const;
+    int ReadInt(const std::string & param, int *, int) const;
+    int ReadLongInt(const std::string & param, long int *, long int) const;
+    int ReadLongLongInt(const std::string & param, int64_t *, int64_t) const;
+    int ReadUShortInt(const std::string & param, unsigned short int *, unsigned short int) const;
+    int ReadUInt(const std::string & param, unsigned int *, unsigned int) const;
+    int ReadULongInt(const std::string & param, unsigned long int *, unsigned long int) const;
+    int ReadULongLongInt(const std::string & param, uint64_t *, uint64_t) const;
+    int ReadDouble(const std::string & param, double * val, double defaultVal) const;
 
-    void WriteString(const string & param, const char * val) { return WriteString(param, std::string(val)); }
-    void WriteString(const string & param, const string & val);
-    void WriteInt(const string & param, int64_t val);
-    void WriteDouble(const string & param, double val);
+    void WriteString(const std::string & param, const char * val) { return WriteString(param, std::string(val)); }
+    void WriteString(const std::string & param, const std::string& val);
+    void WriteInt(const std::string & param, int64_t val);
+    void WriteDouble(const std::string & param, double val);
 
     int Error() const;
     int Flush() const;
 
 private:
-    map<string, string, StringCaseCmp_t> param_val;
-    string fileName;
+    std::map<std::string, std::string, StringCaseCmp_t> param_val;
+    std::string fileName;
     mutable int error;
     mutable bool changed;
 
index a8800d7533201b6fe8ac195bd43d7d612544f362..c99833403e23d893ed32c8920ec4d226f6775afb 100644 (file)
 #define MAXKEYBYTES 56          /* 448 bits */
 
 #ifdef __cplusplus
+#include <cstddef> // size_t
 extern "C" {
+#else
+#include <stddef.h> // size_t
 #endif
 
 typedef struct {
index 8c2a82ade7fe9c55cc76d51daf89d9896a594046..930750135ac6bb9fbb84a0421335fd6dd05a64b7 100644 (file)
@@ -110,7 +110,7 @@ public:
     DOTCONFDocument(CaseSensitive caseSensitivity = CASESENSITIVE);
     virtual ~DOTCONFDocument();
 
-    void setErrorCallback(DOTCONFCallback _callback, void * _data) { errorCallback = _callback; errorCallbackData = _data; };
+    void setErrorCallback(DOTCONFCallback _callback, void * _data) { errorCallback = _callback; errorCallbackData = _data; }
 
     int setContent(const char * _fileName);
 
index d6cb09ef22e4bbd1d49b78836f6e12c4961278d1..aa12a012424426f2c6e48d6c8e40ccf2259bedcd 100644 (file)
@@ -108,10 +108,36 @@ return 0;
 }
 //---------------------------------------------------------------------------
 #endif
+
+namespace
+{
+
+bool HostNameToIP(const std::string & hostName, uint32_t & ip)
+{
+ip = inet_addr(hostName.c_str());
+if (ip == INADDR_NONE)
+    {
+    hostent * phe = gethostbyname(hostName.c_str());
+    if (phe)
+        {
+        ip = *((uint32_t *)phe->h_addr_list[0]);
+        }
+    else
+        {
+        return false;
+        }
+    }
+
+return true;
+}
+
+}
+
 //---------------------------------------------------------------------------
 //---------------------------------------------------------------------------
 //---------------------------------------------------------------------------
-IA_CLIENT_PROT::IA_CLIENT_PROT(const string & sn, unsigned short p, uint16_t localPort)
+IA_CLIENT_PROT::IA_CLIENT_PROT(const std::string & sn, unsigned short p,
+                               const std::string & ln, uint16_t lp)
     : action(IA_NONE),
       phase(1),
       phaseTime(0),
@@ -122,7 +148,8 @@ IA_CLIENT_PROT::IA_CLIENT_PROT(const string & sn, unsigned short p, uint16_t loc
       serverName(sn),
       port(p),
       ip(0),
-      localPort(localPort),
+      localName(ln),
+      localPort(lp),
       firstConnect(true),
       reconnect(0),
       sockr(0),
@@ -190,7 +217,7 @@ servAddr.sin_addr.s_addr = ip;
 //---------------------------------------------------------------------------
 void IA_CLIENT_PROT::PrepareNet()
 {
-struct hostent * phe;
+/*struct hostent * phe;
 unsigned long ip;
 
 ip = inet_addr(serverName.c_str());
@@ -208,6 +235,16 @@ if (ip == INADDR_NONE)
         if (pErrorCb != NULL)
             pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData);
         }
+    }*/
+
+if (!HostNameToIP(serverName, ip))
+    {
+    ip = 0;
+    strError = std::string("Unknown host ") + "\'" + serverName + "\'";
+    codeError = IA_GETHOSTBYNAME_ERROR;
+    if (pErrorCb != NULL)
+        pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData);
+    return;
     }
 
 #ifndef WIN32
@@ -225,7 +262,24 @@ if (localPort)
     localAddrR.sin_port = htons(localPort);
 else
     localAddrR.sin_port = htons(port);
-localAddrR.sin_addr.s_addr = inet_addr("0.0.0.0");
+
+if (!localName.empty())
+    {
+    if (!HostNameToIP(localName, localIP))
+        {
+        strError = std::string("Unknown host ") + "\'" + serverName + "\'";
+        codeError = IA_GETHOSTBYNAME_ERROR;
+        if (pErrorCb != NULL)
+            pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData);
+        localIP = INADDR_ANY;
+        }
+    }
+else
+    {
+    localIP = INADDR_ANY;
+    }
+
+localAddrR.sin_addr.s_addr = localIP;
 
 servAddr.sin_family = AF_INET;
 servAddr.sin_port = htons(port);
@@ -268,7 +322,7 @@ WSACleanup();
 //---------------------------------------------------------------------------
 int IA_CLIENT_PROT::DeterminatePacketType(const char * buffer)
 {
-map<string, int>::iterator pi;
+std::map<std::string, int>::iterator pi;
 pi = packetTypes.find(buffer);
 if (pi == packetTypes.end())
     {
@@ -543,19 +597,19 @@ void IA_CLIENT_PROT::GetStat(LOADSTAT * ls)
 memcpy(ls, &stat, sizeof(stat));
 }
 //---------------------------------------------------------------------------
-void IA_CLIENT_PROT::SetServer(const string & sn, unsigned short p)
+void IA_CLIENT_PROT::SetServer(const std::string & sn, unsigned short p)
 {
 serverName = sn;
 port = p;
 PrepareNet();
 }
 //---------------------------------------------------------------------------
-void IA_CLIENT_PROT::SetLogin(const string & l)
+void IA_CLIENT_PROT::SetLogin(const std::string & l)
 {
 login = l;
 }
 //---------------------------------------------------------------------------
-void IA_CLIENT_PROT::SetPassword(const string & p)
+void IA_CLIENT_PROT::SetPassword(const std::string & p)
 {
 password = p;
 
@@ -583,7 +637,7 @@ action = IA_DISCONNECT;
 return 0;
 }
 //---------------------------------------------------------------------------
-int IA_CLIENT_PROT::GetStrError(string * error) const
+int IA_CLIENT_PROT::GetStrError(std::string * error) const
 {
 int ret = codeError;
 *error = strError;
@@ -594,7 +648,7 @@ return ret;
 //---------------------------------------------------------------------------
 int IA_CLIENT_PROT::Process_CONN_SYN_ACK_8(const char * buffer)
 {
-vector<string> dirNames;
+std::vector<std::string> dirNames;
 connSynAck8 = (CONN_SYN_ACK_8*)buffer;
 
 #ifdef ARCH_BE
index 9c8ea37f560293d9f16b0e5645b436938bb114e1..c37f4394a6aa67190990fb5c762b6eabc7ef68b3 100644 (file)
 #define IA_PROTO_VER            (8)
 #define IA_PROTO_PROXY_VER      (101)
 
-using namespace std;
-
 typedef void (*tpStatusChangedCb)(int status, void * data);
 typedef void (*tpStatChangedCb)(const LOADSTAT & stat, void * data);
-typedef void (*tpCallBackInfoFn)(const string & message, int infoType, int showTime, int sendTime, void * data);
-typedef void (*tpCallBackErrorFn)(const string & message, int netError, void * data);
-typedef void (*tpCallBackDirNameFn)(const vector<string> & dirName, void * data);
+typedef void (*tpCallBackInfoFn)(const std::string & message, int infoType, int showTime, int sendTime, void * data);
+typedef void (*tpCallBackErrorFn)(const std::string & message, int netError, void * data);
+typedef void (*tpCallBackDirNameFn)(const std::vector<std::string> & dirName, void * data);
 
 //---------------------------------------------------------------------------
 class IA_CLIENT_PROT
@@ -69,16 +67,16 @@ friend void * RunL(void * data);
 #endif
 
 public:
-    IA_CLIENT_PROT(const string & sn, uint16_t p, uint16_t localPort = 0);
+    IA_CLIENT_PROT(const std::string & sn, uint16_t p, const std::string & localName = "", uint16_t localPort = 0);
     ~IA_CLIENT_PROT();
 
     void        Start();
     void        Stop();
     void        GetStat(LOADSTAT * ls);
 
-    void        SetServer(const string & sn, unsigned short port);
-    void        SetLogin(const string & login);
-    void        SetPassword(const string & password);
+    void        SetServer(const std::string & sn, unsigned short port);
+    void        SetLogin(const std::string & login);
+    void        SetPassword(const std::string & password);
     void        SetEnabledDirs(const bool * selectedDirs);
 
     void        SetStatusChangedCb(tpStatusChangedCb p, void * data);
@@ -95,9 +93,9 @@ public:
     int         GetReconnect() const { return reconnect; };
     void        SetReconnect(int r) { reconnect = r; };
     char        GetProtoVer() const { return proxyMode ? IA_PROTO_PROXY_VER : IA_PROTO_VER; };
-    void        GetMessageText(string * text) const { *text = messageText; };
-    void        GetInfoText(string * text) const { *text = infoText; };
-    int         GetStrError(string * error) const;
+    void        GetMessageText(std::string * text) const { *text = messageText; };
+    void        GetInfoText(std::string * text) const { *text = infoText; };
+    int         GetStrError(std::string * error) const;
 
     void        SetProxyMode(bool on) { proxyMode = on; };
     bool        GetProxyMode() const { return proxyMode; };
@@ -134,9 +132,9 @@ private:
     int             action;
     int             phase;
     int             phaseTime;
-    string          messageText;
-    string          infoText;
-    mutable string  strError;
+    std::string     messageText;
+    std::string     infoText;
+    mutable std::string strError;
     mutable int     codeError;
     bool            nonstop;
     bool            isNetPrepared;
@@ -147,8 +145,8 @@ private:
 
     bool            selectedDirs[DIR_NUM];
 
-    string          password;
-    string          login;
+    std::string     password;
+    std::string     login;
 
     #ifdef WIN32
     WSADATA wsaData;
@@ -156,9 +154,11 @@ private:
     pthread_t thread;
     #endif
 
-    string          serverName;
+    std::string     serverName;
     uint16_t        port;
     uint32_t        ip;
+    std::string     localName;
+    uint32_t        localIP;
     uint32_t        localPort;
 
     struct sockaddr_in  servAddr;
@@ -183,7 +183,7 @@ private:
     void              * errorCbData;
     void              * dirNameCbData;
 
-    map<string, int>    packetTypes;
+    std::map<std::string, int> packetTypes;
 
     CONN_SYN_8        * connSyn8;
     CONN_SYN_ACK_8    * connSynAck8;
index 8284fe9b141cdf5d96fbf952dc6fdf63c4408f1e..27d368af977fddf9fa6bd8d439de854d4e6b6199 100644 (file)
@@ -465,7 +465,7 @@ struct GDS
 #ifdef IBPP_WINDOWS\r
                mHandle = 0;\r
 #endif\r
-       };\r
+       }\r
 };\r
 \r
 extern GDS gds;\r
index cfdd61fe339c9c7806dfa185da75302cee81a311..298fe70613218655dc47317464cab19f881dcaee 100644 (file)
@@ -118,7 +118,7 @@ int BlobImpl::Read(void* buffer, int size)
 \r
        IBS status;\r
        unsigned short bytesread;\r
-       int result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle, &bytesread,\r
+       ISC_STATUS result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle, &bytesread,\r
                                        (unsigned short)size, (char*)buffer);\r
        if (result == isc_segstr_eof) return 0; // Fin du blob\r
        if (result != isc_segment && status.Errors())\r
@@ -230,7 +230,7 @@ void BlobImpl::Load(std::string& data)
        {\r
                status.Reset();\r
                unsigned short bytesread;\r
-               int result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle,\r
+               ISC_STATUS result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle,\r
                                                &bytesread, (unsigned short)blklen,\r
                                                        const_cast<char*>(data.data()+pos));\r
                if (result == isc_segstr_eof) break;    // End of blob\r
index c108aaceb021b51f2220f03b021b6bf201cfa518..9c43ba2020abce852cba3e8f1598020aa5c3d447 100644 (file)
@@ -104,8 +104,10 @@ typedef unsigned __int64   ISC_UINT64;
 #ifdef  ISC_INT64_DEFINED\r
 #undef  ISC_INT64_DEFINED\r
 #else\r
-typedef long long int                  ISC_INT64;\r
-typedef unsigned long long int ISC_UINT64;\r
+//typedef long long int                        ISC_INT64;\r
+//typedef unsigned long long int       ISC_UINT64;\r
+typedef int64_t        ISC_INT64;\r
+typedef uint64_t       ISC_UINT64;\r
 #endif\r
 \r
 // Nickolay: it is easier to assume that integer is at least 32-bit.\r
index 37a19add995f52bf2c52e635b63d9ce6bfc89994..0029094eef1167f070c883b683e08cc2ce9a9c22 100644 (file)
@@ -223,7 +223,7 @@ namespace IBPP
                int mDate;      // The date : 1 == 1 Jan 1900\r
 \r
        public:\r
-               void Clear()    { mDate = MinDate - 1; };\r
+               void Clear()    { mDate = MinDate - 1; }\r
                void Today();\r
                void SetDate(int year, int month, int day);\r
                void SetDate(int dt);\r
@@ -236,7 +236,7 @@ namespace IBPP
                void StartOfMonth();\r
                void EndOfMonth();\r
        \r
-               Date()                  { Clear(); };\r
+               Date()                  { Clear(); }\r
                Date(int dt)    { SetDate(dt); }\r
                Date(int year, int month, int day);\r
                Date(const Date&);                                                      // Copy Constructor\r
@@ -248,7 +248,7 @@ namespace IBPP
                bool operator<(const Date& rv) const { return mDate < rv.GetDate(); }\r
                bool operator>(const Date& rv) const { return mDate > rv.GetDate(); }\r
 \r
-               virtual ~Date() { };\r
+               virtual ~Date() { }\r
        };\r
 \r
        /* Class Time represent purely a Time. It is usefull in interactions\r
@@ -283,7 +283,7 @@ namespace IBPP
                bool operator<(const Time& rv) const { return mTime < rv.GetTime(); }\r
                bool operator>(const Time& rv) const { return mTime > rv.GetTime(); }\r
 \r
-               virtual ~Time() { };\r
+               virtual ~Time() { }\r
        };\r
 \r
        /* Class Timestamp represent a date AND a time. It is usefull in\r
@@ -386,7 +386,7 @@ namespace IBPP
                User& operator=(const User& r)  { copyfrom(r); return *this; }\r
                User(const User& r)                             { copyfrom(r); }\r
                User() : userid(0), groupid(0)  { }\r
-               ~User() { };\r
+               ~User() { }\r
        };\r
 \r
        //      Interface Wrapper\r
@@ -480,7 +480,7 @@ namespace IBPP
                virtual IBlob* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-               virtual ~IBlob() { };\r
+               virtual ~IBlob() { }\r
        };\r
 \r
        /*      IArray is the interface to the array capabilities of IBPP. Array is the\r
@@ -506,7 +506,7 @@ namespace IBPP
                virtual IArray* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-               virtual ~IArray() { };\r
+               virtual ~IArray() { }\r
        };\r
 \r
        /* IService is the interface to the service capabilities of IBPP. Service is\r
@@ -551,7 +551,7 @@ namespace IBPP
                virtual IService* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-               virtual ~IService() { };\r
+               virtual ~IService() { }\r
        };\r
 \r
        /*      IDatabase is the interface to the database connections in IBPP. Database\r
@@ -591,7 +591,7 @@ namespace IBPP
                virtual IDatabase* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-           virtual ~IDatabase() { };\r
+           virtual ~IDatabase() { }\r
        };\r
 \r
        /* ITransaction is the interface to the transaction connections in IBPP.\r
@@ -621,7 +621,7 @@ namespace IBPP
                virtual ITransaction* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-           virtual ~ITransaction() { };\r
+           virtual ~ITransaction() { }\r
        };\r
 \r
        /*\r
@@ -700,7 +700,7 @@ namespace IBPP
                virtual IRow* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-           virtual ~IRow() {};\r
+           virtual ~IRow() {}\r
        };\r
 \r
        /* IStatement is the interface to the statements execution in IBPP.\r
@@ -799,7 +799,7 @@ namespace IBPP
                virtual IStatement* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-           virtual ~IStatement() { };\r
+           virtual ~IStatement() { }\r
 \r
                // DEPRECATED METHODS (WON'T BE AVAILABLE IN VERSIONS 3.x)\r
                virtual bool Get(int, char*) = 0;                                       // DEPRECATED\r
@@ -832,7 +832,7 @@ namespace IBPP
                virtual IEvents* AddRef() = 0;\r
                virtual void Release() = 0;\r
 \r
-           virtual ~IEvents() { };\r
+           virtual ~IEvents() { }\r
        };\r
        \r
        /* Class EventInterface is merely a pure interface.\r
@@ -844,7 +844,7 @@ namespace IBPP
        {\r
        public:\r
                virtual void ibppEventHandler(Events, const std::string&, int) = 0;\r
-               virtual ~EventInterface() { };\r
+               virtual ~EventInterface() { }\r
        };\r
 \r
        //      --- Factories ---\r
index 1a3031fe80943e7f88a34f2544bab57d1b38a429..e2271cf4b544011cc471d67af06e21bac4207568 100644 (file)
@@ -422,7 +422,7 @@ bool StatementImpl::Fetch()
                        _("No statement has been executed or no result set available."));\r
 \r
        IBS status;\r
-       int code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1, mOutRow->Self());\r
+       ISC_STATUS code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1, mOutRow->Self());\r
        if (code == 100)        // This special code means "no more rows"\r
        {\r
                mResultSetAvailable = false;\r
@@ -452,7 +452,7 @@ bool StatementImpl::Fetch(IBPP::Row& row)
        row = rowimpl;\r
 \r
        IBS status;\r
-       int code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1,\r
+       ISC_STATUS code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1,\r
                                        rowimpl->Self());\r
        if (code == 100)        // This special code means "no more rows"\r
        {\r
index c9a38774a25507de990d2af4f8ebaa73f885b07d..47eb61c7b94ecc5c47af89a2324e2d6e46d7b203 100644 (file)
@@ -103,9 +103,9 @@ void TransactionImpl::AddReservation(IBPP::Database db,
                                        tpb->Insert(table);\r
                                        tpb->Insert(isc_tpb_protected);\r
                                        break;\r
-                       default :\r
+                       /*default :\r
                                        throw LogicExceptionImpl("Transaction::AddReservation",\r
-                                               _("Illegal TTR value detected."));\r
+                                               _("Illegal TTR value detected."));*/\r
                }\r
        }\r
        else throw LogicExceptionImpl("Transaction::AddReservation",\r
@@ -306,7 +306,7 @@ void TransactionImpl::AttachDatabaseImpl(DatabaseImpl* dbi,
                                                                tpb->Insert(isc_tpb_rec_version); break;\r
                case IBPP::ilReadCommitted :    tpb->Insert(isc_tpb_read_committed);\r
                                                                                tpb->Insert(isc_tpb_no_rec_version); break;\r
-               default :                                               tpb->Insert(isc_tpb_concurrency); break;\r
+                case IBPP::ilConcurrency :                                             tpb->Insert(isc_tpb_concurrency); break;\r
        }\r
 \r
     if (lr == IBPP::lrNoWait) tpb->Insert(isc_tpb_nowait);\r
index 7a8d0b8d30113a80431a1ab1ccd2f1519fcdddbd..51ceb738e53253cfec1a2e9dd54605a20cf997a9 100644 (file)
@@ -67,7 +67,7 @@ public:
         pthread_mutex_unlock(&lockerMutex);
         #endif
         pthread_mutex_lock(mutex);
-        };
+        }
 
     ~STG_LOCKER()
         {
@@ -77,7 +77,7 @@ public:
         std::cout << "Unlock: " << lockID << " " << file << ":" << line << " " << mutex << " " << pthread_self() << std::endl;
         pthread_mutex_unlock(&lockerMutex);
         #endif
-        };
+        }
 private:
     STG_LOCKER(const STG_LOCKER & rvalue);
     STG_LOCKER & operator=(const STG_LOCKER & rvalue);
index 9fe1487842188e29699d3e0deaab8c01e7730b17..c55801ac2a32570fb41348b2f74a2d604332122b 100644 (file)
@@ -5,16 +5,14 @@
 
 #include <string>
 
-const char * LogDate(time_t t);
-//-----------------------------------------------------------------------------
 class STG_LOGGER;
 STG_LOGGER & GetStgLogger();
 //-----------------------------------------------------------------------------
 class STG_LOGGER_LOCKER
 {
 public:
-    STG_LOGGER_LOCKER(pthread_mutex_t * m) : mutex(m) { pthread_mutex_lock(mutex); };
-    ~STG_LOGGER_LOCKER() { pthread_mutex_unlock(mutex); };
+    STG_LOGGER_LOCKER(pthread_mutex_t * m) : mutex(m) { pthread_mutex_lock(mutex); }
+    ~STG_LOGGER_LOCKER() { pthread_mutex_unlock(mutex); }
 
 private:
     STG_LOGGER_LOCKER(const STG_LOGGER_LOCKER & rvalue);
@@ -26,22 +24,37 @@ private:
 class STG_LOGGER
 {
 friend STG_LOGGER & GetStgLogger();
+friend class PLUGIN_LOGGER;
 
 public:
     ~STG_LOGGER();
     void SetLogFileName(const std::string & fn);
-    void operator()(const char * fmt, ...);
+    void operator()(const char * fmt, ...) const;
 
 private:
     STG_LOGGER();
     STG_LOGGER(const STG_LOGGER & rvalue);
     STG_LOGGER & operator=(const STG_LOGGER & rvalue);
 
-    const char * LogDate(time_t t);
+    const char * LogDate(time_t t) const;
 
     std::string fileName;
-    pthread_mutex_t mutex;
+    mutable pthread_mutex_t mutex;
 };
 //-----------------------------------------------------------------------------
+class PLUGIN_LOGGER : private STG_LOGGER
+{
+friend PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName);
+
+public:
+    PLUGIN_LOGGER(const PLUGIN_LOGGER & rhs);
+    void operator()(const char * fmt, ...) const;
+
+private:
+    PLUGIN_LOGGER(const STG_LOGGER & logger, const std::string & pn);
+    std::string pluginName;
+};
+
+PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName);
 
 #endif //STG_LOGGER_H
index d85581991b0c5cfea7da97c2f52fb59a7890adf0..14c09591f0394147c3527a1ec253ad746e59c865 100644 (file)
@@ -32,7 +32,7 @@ STG_LOGGER_LOCKER lock(&mutex);
 fileName = fn;
 }
 //-----------------------------------------------------------------------------
-void STG_LOGGER::operator()(const char * fmt, ...)
+void STG_LOGGER::operator()(const char * fmt, ...) const
 {
 STG_LOGGER_LOCKER lock(&mutex);
 
@@ -74,7 +74,7 @@ else
     }
 }
 //-----------------------------------------------------------------------------
-const char * STG_LOGGER::LogDate(time_t t)
+const char * STG_LOGGER::LogDate(time_t t) const
 {
 static char s[32];
 if (t == 0)
@@ -93,3 +93,34 @@ snprintf(s, 32, "%d-%s%d-%s%d %s%d:%s%d:%s%d",
 return s;
 }
 //-----------------------------------------------------------------------------
+PLUGIN_LOGGER::PLUGIN_LOGGER(const STG_LOGGER & logger, const std::string & pn)
+    : STG_LOGGER(),
+      pluginName(pn)
+{
+    SetLogFileName(logger.fileName);
+}
+//-----------------------------------------------------------------------------
+PLUGIN_LOGGER::PLUGIN_LOGGER(const PLUGIN_LOGGER & rhs)
+    : STG_LOGGER(),
+      pluginName(rhs.pluginName)
+{
+    SetLogFileName(fileName);
+}
+//-----------------------------------------------------------------------------
+void PLUGIN_LOGGER::operator()(const char * fmt, ...) const
+{
+char buff[2029];
+
+va_list vl;
+va_start(vl, fmt);
+vsnprintf(buff, sizeof(buff), fmt, vl);
+va_end(vl);
+
+STG_LOGGER::operator()("[%s] %s", pluginName.c_str(), buff);
+}
+//-----------------------------------------------------------------------------
+PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName)
+{
+return PLUGIN_LOGGER(logger, pluginName);
+}
+//-----------------------------------------------------------------------------
index b1b777813fc617f0710ae51799a76b3c80a2f804..91608dbbc2b38c8341943635f6e8dc8878967bcf 100644 (file)
@@ -18,7 +18,7 @@
 #include <netinet/ip_icmp.h>
 #endif
 
-#if defined (FREE_BSD) || defined (FREE_BSD5)
+#if defined (FREE_BSD) || defined (FREE_BSD5) || defined(DARWIN)
 #include <netinet/in.h>
 #include <netinet/in_systm.h>
 #include <netinet/ip.h>
@@ -84,6 +84,9 @@ struct PING_MESSAGE
 class STG_PINGER
 {
 public:
+    typedef std::multimap<uint32_t, time_t> PingIPs;
+    typedef PingIPs::size_type SizeType;
+
             STG_PINGER(time_t delay = 15);
             ~STG_PINGER();
 
@@ -91,7 +94,7 @@ public:
     int     Stop();
     void    AddIP(uint32_t ip);
     void    DelIP(uint32_t ip);
-    int     GetPingIPNum() const;
+    SizeType GetPingIPNum() const { return pingIP.size(); }
     void    PrintAllIP();
     int     GetIPTime(uint32_t ip, time_t * t) const;
     void    SetDelayTime(time_t d) { delay = d; }
@@ -108,7 +111,7 @@ private:
     static void * RunSendPing(void * d);
     static void * RunRecvPing(void * d);
 
-    int         delay;
+    time_t      delay;
     bool        nonstop;
     bool        isRunningRecver;
     bool        isRunningSender;
index 664367e897e6c0d7fc084d9efabd59f32ef14171..edc8c174c7fb06a831707aba2d9e5876e7b23955 100644 (file)
@@ -165,11 +165,6 @@ while (iter != ipToDel.end())
 ipToDel.erase(ipToDel.begin(), ipToDel.end());
 }
 //-----------------------------------------------------------------------------
-int STG_PINGER::GetPingIPNum() const
-{
-return pingIP.size();
-}
-//-----------------------------------------------------------------------------
 void STG_PINGER::PrintAllIP()
 {
 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
@@ -202,20 +197,20 @@ return 0;
 //-----------------------------------------------------------------------------
 uint16_t STG_PINGER::PingCheckSum(void * data, int len)
 {
-unsigned short * buf = (unsigned short *)data;
-unsigned int sum = 0;
-unsigned short result;
+uint16_t * buf = static_cast<uint16_t *>(data);
+uint32_t sum = 0;
+uint32_t result;
 
 for ( sum = 0; len > 1; len -= 2 )
     sum += *buf++;
 
 if ( len == 1 )
-    sum += *(unsigned char*)buf;
+    sum += *reinterpret_cast<uint8_t*>(buf);
 
 sum = (sum >> 16) + (sum & 0xFFFF);
 sum += (sum >> 16);
 result = ~sum;
-return result;
+return static_cast<uint16_t>(result);
 }
 //-----------------------------------------------------------------------------
 int STG_PINGER::SendPing(uint32_t ip)
@@ -228,7 +223,7 @@ addr.sin_addr.s_addr = ip;
 
 memset(&pmSend, 0, sizeof(pmSend));
 pmSend.hdr.type = ICMP_ECHO;
-pmSend.hdr.un.echo.id = pid;
+pmSend.hdr.un.echo.id = static_cast<uint16_t>(pid);
 memcpy(pmSend.msg, &ip, sizeof(ip));
 
 pmSend.hdr.checksum = PingCheckSum(&pmSend, sizeof(pmSend));
@@ -250,19 +245,17 @@ uint32_t ipAddr = 0;
 
 char buf[128];
 memset(buf, 0, sizeof(buf));
-int bytes;
 socklen_t len = sizeof(addr);
 
-bytes = recvfrom(recvSocket, &buf, sizeof(buf), 0, (struct sockaddr*)&addr, &len);
-if (bytes > 0)
+if (recvfrom(recvSocket, &buf, sizeof(buf), 0, reinterpret_cast<struct sockaddr*>(&addr), &len))
     {
-    struct IP_HDR * ip = (struct IP_HDR *)buf;
-    struct ICMP_HDR *icmp = (struct ICMP_HDR *)(buf + ip->ihl * 4);
+    struct IP_HDR * ip = static_cast<struct IP_HDR *>(static_cast<void *>(buf));
+    struct ICMP_HDR *icmp = static_cast<struct ICMP_HDR *>(static_cast<void *>(buf + ip->ihl * 4));
 
     if (icmp->un.echo.id != pid)
         return 0;
 
-    ipAddr = *(uint32_t*)(buf + sizeof(ICMP_HDR) + ip->ihl * 4);
+    ipAddr = *static_cast<uint32_t*>(static_cast<void *>(buf + sizeof(ICMP_HDR) + ip->ihl * 4));
     }
 
 return ipAddr;
index 41b02a2fdf8927bd57e9a959253af4e56b20f21a..947669c785b433f0bd9874e4010ba98b3e1efecc 100644 (file)
@@ -6,7 +6,7 @@ extern "C" {
 #endif
 
 int ScriptExec(const char * str);
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
 void Executer(int msgID, pid_t pid, char * procName);
 #else
 void Executer(int msgID, pid_t pid);
index bf45105a8332652d31df6b850d9eefc05afe1afd..728082ae350ba079e5404f4b6a3168eb0e805002 100644 (file)
@@ -40,7 +40,7 @@ if (msgsnd(msgid, (void *)&sd, MAX_SCRIPT_LEN, 0) < 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
 void Executer(int msgID, pid_t pid, char * procName)
 #else
 void Executer(int msgID, pid_t pid)
@@ -56,7 +56,7 @@ if (pid)
     return;
 nonstop = 1;
 
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
 memset(procName, 0, strlen(procName));
 strcpy(procName, "stg-exec");
 #else
index e3bfa76219fdab686afac6203e6a76186be74e83..d7bc80c01390fdb372f611ff9a11880b4a9b07a4 100644 (file)
@@ -8,14 +8,28 @@ STGLIBS = -lstgcommon \
           -lstgcrypto
 LIBS = -lexpat
 
-SRCS =         netunit.cpp \
-        parser.cpp \
+SRCS =  parsers/property.cpp \
+        parsers/simple.cpp \
+        parsers/server_info.cpp \
+        parsers/get_admin.cpp \
+        parsers/chg_admin.cpp \
+        parsers/get_tariff.cpp \
+        parsers/chg_tariff.cpp \
+        parsers/auth_by.cpp \
+        parsers/get_user.cpp \
+        parsers/chg_user.cpp \
+        parsers/get_service.cpp \
+        parsers/chg_service.cpp \
+        parsers/get_corp.cpp \
+        parsers/chg_corp.cpp \
+        netunit.cpp \
         servconf.cpp
 
+
 INCS = servconf.h \
        netunit.h
 
 LIB_INCS = -I ../common.lib/include \
-          -I ../crypto.lib/include
+           -I ../crypto.lib/include
 
 include ../Makefile.in
diff --git a/stglibs/srvconf.lib/include/stg/netunit.h b/stglibs/srvconf.lib/include/stg/netunit.h
deleted file mode 100644 (file)
index e288df8..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
- /*
- $Revision: 1.6 $
- $Date: 2010/02/11 12:32:53 $
- $Author: faust $
- */
-
-#ifndef NetUnitH
-#define NetUnitH
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-
-#include <list>
-#include <string>
-
-#include "stg/blowfish.h"
-
-#define  STG_HEADER     "SG04"
-#define  OK_HEADER      "OKHD"
-#define  ERR_HEADER     "ERHD"
-#define  OK_LOGIN       "OKLG"
-#define  ERR_LOGIN      "ERLG"
-#define  OK_LOGINS      "OKLS"
-#define  ERR_LOGINS     "ERLS"
-
-// äÌÉÎÎÁ ÛÉÆÒÕÅÍÏÇÏ É ÐÅÒÅÄÁ×ÁÅÍÏÇ ÚÁ ÏÄÉΠÒÁÚ ÂÌÏËÁ ÉÎÆÏÒÍÁÃÉÉ
-#define  ENC_MSG_LEN    (8)
-
-#define MAX_ERR_STR_LEN (64)
-
-typedef int(*RxCallback_t)(void *, std::list<std::string> *);
-
-enum status
-{
-st_ok = 0,
-st_conn_fail,
-st_send_fail,
-st_recv_fail,
-st_header_err,
-st_login_err,
-st_logins_err,
-st_data_err,
-st_unknown_err,
-st_dns_err,
-st_xml_parse_error,
-st_data_error
-};
-
-enum CONF_STATE
-{
-confHdr = 0,
-confLogin,
-confLoginCipher,
-confData
-};
-//---------------------------------------------------------------------------
-class NETTRANSACT
-{
-public:
-    NETTRANSACT();
-    int     Transact(const char * data);
-    const std::string & GetError() const;
-
-    void    SetRxCallback(void * data, RxCallback_t);
-
-    void    SetServer(const char * serverName);
-    void    SetServerPort(short unsigned p);
-
-    void    SetLogin(const char * l);
-    void    SetPassword(const char * p);
-    ////////////////////////////////////////////
-    int     Connect();
-    int     Disconnect();
-    void    Reset();
-private:
-    int     TxHeader();
-    int     RxHeaderAnswer();
-
-    int     TxLogin();
-    int     RxLoginAnswer();
-
-    int     TxLoginS();
-    int     RxLoginSAnswer();
-
-    int     TxData(const char * text);
-    int     TxData(char * data);
-    int     RxDataAnswer();
-
-    void Encrypt(char * d, const char * s, BLOWFISH_CTX *ctx);
-    void EnDecryptInit(const char * passwd, int passwdLen, BLOWFISH_CTX *ctx);
-    void Decrypt(char * d, const char * s, BLOWFISH_CTX *ctx);
-
-    std::string server;
-    short unsigned  port;
-    std::string login;
-    std::string password;
-    int     outerSocket;
-    std::list<std::string>   answerList;
-    RxCallback_t RxCallBack;
-    void *  dataRxCallBack;
-    std::string errorMsg;
-};
-//---------------------------------------------------------------------------
-#endif
index 67c2f248dbae85c49b08fb1cf7f4eaa0189170e2..2a2dbcaac0a13af69badfc3143eb3fd023c6fbb5 100644 (file)
 
 /*
  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
  */
 
- /*
- $Revision: 1.10 $
- $Date: 2009/03/17 09:52:35 $
- $Author: faust $
- */
-
-#ifndef SERVCONF_H
-#define SERVCONF_H
+#ifndef __STG_STGLIBS_SERVCONF_H__
+#define __STG_STGLIBS_SERVCONF_H__
 
-#include <expat.h>
-
-#include <list>
-#include <string>
+#include "stg/servconf_types.h"
 
+#include "stg/admin_conf.h"
 #include "stg/os_int.h"
-#include "stg/const.h"
-#include "netunit.h"
 
-void Start(void *data, const char *el, const char **attr);
-void End(void *data, const char *el);
+#include <string>
 
-#define MAX_ERR_STR_LEN (64)
-#define IP_STRING_LEN   (255)
-#define UNAME_LEN       (256)
-#define SERV_VER_LEN    (64)
-#define DIRNAME_LEN     (16)
+struct USER_CONF_RES;
+struct USER_STAT_RES;
+struct TARIFF_DATA_RES;
+struct SERVICE_CONF_RES;
+struct CORP_CONF_RES;
 
-//-----------------------------------------------------------------------------
-struct STAT
-{
-    long long   su[DIR_NUM];
-    long long   sd[DIR_NUM];
-    long long   mu[DIR_NUM];
-    long long   md[DIR_NUM];
-    double      freeMb;
-};
-//-----------------------------------------------------------------------------
-struct SERVERINFO
-{
-    std::string version;
-    int         tariffNum;
-    int         tariffType;
-    int         usersNum;
-    std::string uname;
-    int         dirNum;
-    std::string dirName[DIR_NUM];
-};
-//-----------------------------------------------------------------------------
-struct USERDATA
-{
-    std::string     login;
-    std::string     password;
-    double          cash;
-    double          credit;
-    time_t          creditExpire;
-    double          lastCash;
-    double          prepaidTraff;
-    int             down;
-    int             passive;
-    int             disableDetailStat;
-    int             connected;
-    int             alwaysOnline;
-    uint32_t        ip;
-    std::string     ips;
-    std::string     tariff;
-    std::string     iface;
-    std::string     group;
-    std::string     note;
-    std::string     email;
-    std::string     name;
-    std::string     address;
-    std::string     phone;
-    STAT            stat;
-    std::string     userData[USERDATA_NUM];
-
-    struct USERDATA * next;
-};
-//-----------------------------------------------------------------------------
-typedef void(*RecvUserDataCb_t)(USERDATA * ud, void * data);
-typedef void(*RecvServerInfoDataCb_t)(SERVERINFO * si, void * data);
-typedef int(*RecvChgUserCb_t)(const char * asnwer, void * data);
-typedef int(*RecvCheckUserCb_t)(const char * answer, void * data);
-typedef int(*RecvSendMessageCb_t)(const char * answer, void * data);
-//-----------------------------------------------------------------------------
-struct ADMINDATA
-{
-    char login[ADM_LOGIN_LEN];
-};
-//-----------------------------------------------------------------------------
-class PARSER
-{
-public:
-    PARSER() {}
-    virtual ~PARSER() {}
-    virtual int ParseStart(const char *el, const char **attr) = 0;
-    virtual void ParseEnd(const char *el) = 0;
-};
-//-----------------------------------------------------------------------------
-class PARSER_CHG_USER: public PARSER
-{
-public:
-    PARSER_CHG_USER();
-    int  ParseStart(const char *el, const char **attr);
-    void ParseEnd(const char *el);
-    void ParseAnswer(const char *el, const char **attr);
-    void SetChgUserRecvCb(RecvChgUserCb_t, void * data);
-private:
-    RecvChgUserCb_t RecvChgUserCb;
-    void * chgUserCbData;
-    int depth;
-    bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_CHECK_USER: public PARSER
-{
-public:
-    PARSER_CHECK_USER();
-    int  ParseStart(const char *el, const char **attr);
-    void ParseEnd(const char *el);
-    void ParseAnswer(const char *el, const char **attr);
-    void SetCheckUserRecvCb(RecvCheckUserCb_t, void * data);
-private:
-    RecvCheckUserCb_t RecvCheckUserCb;
-    void * checkUserCbData;
-    int depth;
-    bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_GET_USERS: public PARSER
+namespace STG
 {
-public:
-    PARSER_GET_USERS();
-    int  ParseStart(const char *el, const char **attr);
-    void ParseEnd(const char *el);
-    void ParseUsers(const char *el, const char **attr);
-    void ParseUser(const char *el, const char **attr);
-    void ParseUserParams(const char *el, const char **attr);
-    void ParseUserLoadStat(const char * el, const char ** attr);
-    void SetUserDataRecvCb(RecvUserDataCb_t, void * data);
-private:
-    RecvUserDataCb_t RecvUserDataCb;
-    void * userDataCb;
-    USERDATA user;
-    int depth;
-    bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_GET_USER: public PARSER
-{
-public:
-    PARSER_GET_USER();
-    int  ParseStart(const char *el, const char **attr);
-    void ParseEnd(const char *el);
-    void ParseUsers(const char *el, const char **attr);
-    void ParseUser(const char *el, const char **attr);
-    void ParseUserParams(const char *el, const char **attr);
-    void ParseUserLoadStat(const char * el, const char ** attr);
-    void SetUserDataRecvCb(RecvUserDataCb_t, void * data);
-private:
-    RecvUserDataCb_t RecvUserDataCb;
-    void * userDataCb;
-    USERDATA user;
-    int depth;
-    bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_GET_SERVER_INFO: public PARSER
-{
-public:
-    PARSER_GET_SERVER_INFO();
-    int  ParseStart(const char *el, const char **attr);
-    void ParseEnd(const char *el);
-    void ParseServerInfo(const char *el, const char **attr);
-    bool GetError();
-    void SetServerInfoRecvCb(RecvServerInfoDataCb_t, void * data);
-private:
-    void ParseUname(const char ** attr);
-    void ParseServerVersion(const char ** attr);
-    void ParseUsersNum(const char ** attr);
-    void ParseTariffsNum(const char ** attr);
-    void ParseTariffType(const char ** attr);
-    void ParseDirNum(const char **attr);
-    void ParseDirName(const char **attr, int d);
 
-    RecvServerInfoDataCb_t RecvServerInfoDataCb;
-    void * serverInfoDataCb;
-    int depth;
-    bool error;
-    SERVERINFO serverInfo;
-};
-//-----------------------------------------------------------------------------
-class PARSER_SEND_MESSAGE: public PARSER
-{
-public:
-    PARSER_SEND_MESSAGE();
-    int  ParseStart(const char *el, const char **attr);
-    void ParseEnd(const char *el);
-    void ParseAnswer(const char *el, const char **attr);
-    void SetSendMessageRecvCb(RecvSendMessageCb_t, void * data);
-private:
-    RecvSendMessageCb_t RecvSendMessageCb;
-    void * sendMessageCbData;
-    int depth;
-    bool error;
-};
-//-----------------------------------------------------------------------------
 class SERVCONF
 {
 public:
-    SERVCONF();
-    void SetServer(const char * server);
-    void SetPort(uint16_t port);
-
-    void SetAdmLogin(const char * login);
-    void SetAdmPassword(const char * password);
-
-    void SetUserDataRecvCb(RecvUserDataCb_t, void * data);
-    void SetServerInfoRecvCb(RecvServerInfoDataCb_t, void * data);
-    void SetChgUserCb(RecvChgUserCb_t, void * data);
-    void SetCheckUserCb(RecvCheckUserCb_t, void * data);
-    void SetGetUserDataRecvCb(RecvUserDataCb_t, void * data);
-    void SetSendMessageCb(RecvSendMessageCb_t, void * data);
-
-    int GetUsers();
-    int GetUser(const char * login);
-    int ChgUser(const char * request);
-    // TODO: Remove this shit!
-    int MsgUser(const char * request);
-    int SendMessage(const char * login, const char * message, int prio);
-    int GetServerInfo();
-    int CheckUser(const char * login, const char * password);
+    SERVCONF(const std::string & server, uint16_t port,
+             const std::string & login, const std::string & password);
+    ~SERVCONF();
+
+    int ServerInfo(SERVER_INFO::CALLBACK f, void * data);
+
+    int RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data);
+
+    int GetAdmins(GET_CONTAINER::CALLBACK<GET_ADMIN::INFO>::TYPE f, void * data);
+    int GetAdmin(const std::string & login, GET_ADMIN::CALLBACK f, void * data);
+    int ChgAdmin(const ADMIN_CONF_RES & conf, SIMPLE::CALLBACK f, void * data);
+    int AddAdmin(const std::string & login,
+                 const ADMIN_CONF_RES & conf,
+                 SIMPLE::CALLBACK f, void * data);
+    int DelAdmin(const std::string & login, SIMPLE::CALLBACK f, void * data);
+
+    int GetTariffs(GET_CONTAINER::CALLBACK<GET_TARIFF::INFO>::TYPE f, void * data);
+    int GetTariff(const std::string & name, GET_TARIFF::CALLBACK f, void * data);
+    int ChgTariff(const TARIFF_DATA_RES & conf, SIMPLE::CALLBACK f, void * data);
+    int AddTariff(const std::string & name,
+                  const TARIFF_DATA_RES & conf,
+                  SIMPLE::CALLBACK f, void * data);
+    int DelTariff(const std::string & name, SIMPLE::CALLBACK f, void * data);
+
+    int GetUsers(GET_CONTAINER::CALLBACK<GET_USER::INFO>::TYPE f, void * data);
+    int GetUser(const std::string & login, GET_USER::CALLBACK f, void * data);
+    int ChgUser(const std::string & login,
+                const USER_CONF_RES & conf,
+                const USER_STAT_RES & stat,
+                SIMPLE::CALLBACK f, void * data);
+    int DelUser(const std::string & login, SIMPLE::CALLBACK f, void * data);
+    int AddUser(const std::string & login, SIMPLE::CALLBACK f, void * data);
+    int AuthBy(const std::string & login, AUTH_BY::CALLBACK f, void * data);
+    int SendMessage(const std::string & login, const std::string & text, SIMPLE::CALLBACK f, void * data);
+    int CheckUser(const std::string & login, const std::string & password, SIMPLE::CALLBACK f, void * data);
+
+    int GetServices(GET_CONTAINER::CALLBACK<GET_SERVICE::INFO>::TYPE f, void * data);
+    int GetService(const std::string & name, GET_SERVICE::CALLBACK f, void * data);
+    int ChgService(const SERVICE_CONF_RES & conf, SIMPLE::CALLBACK f, void * data);
+    int AddService(const std::string & name,
+                   const SERVICE_CONF_RES & conf,
+                   SIMPLE::CALLBACK f, void * data);
+    int DelService(const std::string & name, SIMPLE::CALLBACK f, void * data);
+
+    int GetCorporations(GET_CONTAINER::CALLBACK<GET_CORP::INFO>::TYPE f, void * data);
+    int GetCorp(const std::string & name, GET_CORP::CALLBACK f, void * data);
+    int ChgCorp(const CORP_CONF_RES & conf, SIMPLE::CALLBACK f, void * data);
+    int AddCorp(const std::string & name,
+                const CORP_CONF_RES & conf,
+                SIMPLE::CALLBACK f, void * data);
+    int DelCorp(const std::string & name, SIMPLE::CALLBACK f, void * data);
 
     const std::string & GetStrError() const;
-    int GetError();
-    int Start(const char *el, const char **attr);
-    void End(const char *el);
 
 private:
-    PARSER * currParser;
-
-    PARSER_GET_USERS parserGetUsers;
-    PARSER_GET_USER parserGetUser;
-    PARSER_GET_SERVER_INFO  parserServerInfo;
-    PARSER_CHG_USER parserChgUser;
-    PARSER_CHECK_USER parserCheckUser;
-    PARSER_SEND_MESSAGE parserSendMessage;
-
-    NETTRANSACT nt;
-    int parseDepth;
-
-    std::string errorMsg;
-    int error;
-    XML_Parser parser;
-
-    RecvUserDataCb_t RecvUserDataCb;
-    RecvUserDataCb_t RecvGetUserDataCb;
-    RecvServerInfoDataCb_t RecvServerInfoDataCb;
-    RecvChgUserCb_t RecvChgUserCb;
-    RecvCheckUserCb_t RecvCheckUserCb;
-    RecvSendMessageCb_t RecvSendMessageCb;
-
-    void * getUserDataDataCb;
-    void * getUsersDataDataCb;
-    void * getServerInfoDataCb;
-    void * chgUserDataCb;
-    void * checkUserDataCb;
-    void * sendMessageDataCb;
-
-    friend int AnsRecv(void * data, std::list<std::string> * list);
+    class IMPL;
+    IMPL * pImpl;
 };
-//-----------------------------------------------------------------------------
 
-#endif  /* _SERVCONF_H_ */
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/include/stg/servconf_types.h b/stglibs/srvconf.lib/include/stg/servconf_types.h
new file mode 100644 (file)
index 0000000..f323e99
--- /dev/null
@@ -0,0 +1,200 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_TYPES_H__
+#define __STG_STGLIBS_SRVCONF_TYPES_H__
+
+#include "stg/const.h" // DIR_NUM
+#include "stg/os_int.h" // uint32_t, etc...
+
+#include <string>
+#include <vector>
+#include <ctime>
+
+#define  STG_HEADER     "SG04"
+#define  OK_HEADER      "OKHD"
+#define  ERR_HEADER     "ERHD"
+#define  OK_LOGIN       "OKLG"
+#define  ERR_LOGIN      "ERLG"
+#define  OK_LOGINS      "OKLS"
+#define  ERR_LOGINS     "ERLS"
+
+#define  ENC_MSG_LEN    (8)
+
+struct ADMIN_CONF;
+struct TARIFF_DATA;
+struct SERVICE_CONF;
+struct CORP_CONF;
+
+namespace STG
+{
+
+enum status
+{
+st_ok = 0,
+st_conn_fail,
+st_send_fail,
+st_recv_fail,
+st_header_err,
+st_login_err,
+st_logins_err,
+st_data_err,
+st_unknown_err,
+st_dns_err,
+st_xml_parse_error,
+st_data_error
+};
+
+enum CONF_STATE
+{
+confHdr = 0,
+confLogin,
+confLoginCipher,
+confData
+};
+
+namespace SIMPLE
+{
+
+typedef void (* CALLBACK)(bool result, const std::string & reason, void * data);
+
+} // namespace SIMPLE
+
+namespace GET_CONTAINER
+{
+
+template <typename INFO>
+struct CALLBACK
+{
+typedef void (* TYPE)(bool result, const std::string & reason, const std::vector<INFO> & info, void * data);
+};
+
+}
+
+namespace AUTH_BY
+{
+
+typedef std::vector<std::string> INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+} // namespace AUTH_BY
+
+namespace SERVER_INFO
+{
+
+struct INFO
+{
+    std::string version;
+    int         tariffNum;
+    int         tariffType;
+    int         usersNum;
+    std::string uname;
+    int         dirNum;
+    std::string dirName[DIR_NUM];
+};
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+} // namespace SERVER_INFO
+
+namespace RAW_XML
+{
+
+typedef void (* CALLBACK)(bool result, const std::string & reason, const std::string & response, void * data);
+
+}
+
+namespace GET_USER
+{
+
+struct STAT
+{
+    long long  su[DIR_NUM];
+    long long  sd[DIR_NUM];
+    long long  mu[DIR_NUM];
+    long long  md[DIR_NUM];
+    double     freeMb;
+};
+
+struct INFO
+{
+    std::string login;
+    std::string password;
+    double      cash;
+    double      credit;
+    time_t      creditExpire;
+    double      lastCash;
+    double      prepaidTraff;
+    int         down;
+    int         passive;
+    int         disableDetailStat;
+    int         connected;
+    int         alwaysOnline;
+    uint32_t    ip;
+    std::string ips;
+    std::string tariff;
+    std::string group;
+    std::string note;
+    std::string email;
+    std::string name;
+    std::string address;
+    std::string phone;
+    STAT        stat;
+    std::string userData[USERDATA_NUM];
+};
+
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+} // namespace GET_USER
+
+namespace GET_ADMIN
+{
+
+typedef ADMIN_CONF INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+namespace GET_TARIFF
+{
+
+typedef TARIFF_DATA INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+namespace GET_SERVICE
+{
+
+typedef SERVICE_CONF INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+namespace GET_CORP
+{
+
+typedef CORP_CONF INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+} // namespace STG
+
+#endif
index 9a653d5bf5e76621be46b3b6367a1463dccdf771..164823d8395d42d41f81f11a728dfdba5c34c958 100644 (file)
  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
  */
 
- /*
- $Revision: 1.6 $
- $Date: 2009/02/06 10:25:54 $
- $Author: faust $
- */
+#include "netunit.h"
+
+#include "stg/servconf_types.h"
+#include "stg/common.h"
+#include "stg/blowfish.h"
+
+#include <algorithm> // std::min
+
+#include <cstdio>
+#include <cerrno>
+#include <cstring>
 
-//---------------------------------------------------------------------------
 #include <netdb.h>
 #include <arpa/inet.h>
 #include <unistd.h>
 
-#include <cstdio>
-#include <cstring>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
 
-#include "stg/netunit.h"
-#include "stg/common.h"
+using namespace STG;
+
+namespace
+{
+
+const std::string::size_type MAX_XML_CHUNK_LENGTH = 2048;
+
+}
 
 //---------------------------------------------------------------------------
 
 #define RECV_HEADER_ANSWER_ERROR    "Recv header answer error!"
 
 //---------------------------------------------------------------------------
-NETTRANSACT::NETTRANSACT()
-    : port(0),
-      outerSocket(-1),
-      RxCallBack(NULL),
-      dataRxCallBack(NULL)
-{
-}
-//-----------------------------------------------------------------------------
-void NETTRANSACT::EnDecryptInit(const char * passwd, int, BLOWFISH_CTX *ctx)
+NETTRANSACT::NETTRANSACT(const std::string & s, uint16_t p,
+                         const std::string & l, const std::string & pwd)
+    : server(s),
+      port(p),
+      login(l),
+      password(pwd),
+      outerSocket(-1)
 {
-unsigned char * keyL = NULL;
-
-keyL = new unsigned char[PASSWD_LEN];
-
-memset(keyL, 0, PASSWD_LEN);
-
-strncpy((char *)keyL, passwd, PASSWD_LEN);
-
-Blowfish_Init(ctx, keyL, PASSWD_LEN);
-
-delete[] keyL;
-}
-//-----------------------------------------------------------------------------
-void NETTRANSACT::Encrypt(char * d, const char * s, BLOWFISH_CTX *ctx)
-{
-EncodeString(d, s, ctx);
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::Decrypt(char * d, const char * s, BLOWFISH_CTX *ctx)
-{
-DecodeString(d, s, ctx);
 }
 //---------------------------------------------------------------------------
 int NETTRANSACT::Connect()
 {
-int ret;
-
 outerSocket = socket(PF_INET, SOCK_STREAM, 0);
 if (outerSocket < 0)
     {
@@ -98,46 +85,42 @@ if (outerSocket < 0)
 struct sockaddr_in outerAddr;
 memset(&outerAddr, 0, sizeof(outerAddr));
 
-struct hostent he;
-struct hostent * phe;
-
-unsigned long ip;
-ip = inet_addr(server.c_str());
+unsigned long ip = inet_addr(server.c_str());
 
 if (ip == INADDR_NONE)
     {
-    phe = gethostbyname(server.c_str());
+    struct hostent * phe = gethostbyname(server.c_str());
     if (phe == NULL)
         {
         errorMsg = "DNS error.\nCan not reslove " + server;
         return st_dns_err;
         }
 
+    struct hostent he;
     memcpy(&he, phe, sizeof(he));
-    ip = *((long*)he.h_addr_list[0]);
+    ip = *((long *)he.h_addr_list[0]);
     }
+
 outerAddr.sin_family = AF_INET;
 outerAddr.sin_port = htons(port);
 outerAddr.sin_addr.s_addr = ip;
 
-ret = connect(outerSocket, (struct sockaddr*)&outerAddr, sizeof(outerAddr));
-
-if (ret < 0)
+if (connect(outerSocket, (struct sockaddr *)&outerAddr, sizeof(outerAddr)) < 0)
     {
     errorMsg = CONNECT_FAILED;
     close(outerSocket);
     return st_conn_fail;
     }
+
 return st_ok;
 }
 //---------------------------------------------------------------------------
-int NETTRANSACT::Disconnect()
+void NETTRANSACT::Disconnect()
 {
 close(outerSocket);
-return 0;
 }
 //---------------------------------------------------------------------------
-int NETTRANSACT::Transact(const char * data)
+int NETTRANSACT::Transact(const std::string & request, CALLBACK callback, void * data)
 {
 int ret;
 if ((ret = TxHeader()) != st_ok)
@@ -176,13 +159,13 @@ if ((ret = RxLoginSAnswer()) != st_ok)
     return ret;
     }
 
-if ((ret = TxData(data)) != st_ok)
+if ((ret = TxData(request)) != st_ok)
     {
     Disconnect();
     return ret;
     }
 
-if ((ret = RxDataAnswer()) != st_ok)
+if ((ret = RxDataAnswer(callback, data)) != st_ok)
     {
     Disconnect();
     return ret;
@@ -193,9 +176,7 @@ return st_ok;
 //---------------------------------------------------------------------------
 int NETTRANSACT::TxHeader()
 {
-int ret;
-ret = send(outerSocket, STG_HEADER, strlen(STG_HEADER), 0);
-if (ret <= 0)
+if (send(outerSocket, STG_HEADER, strlen(STG_HEADER), 0) <= 0)
     {
     errorMsg = SEND_HEADER_ERROR;
     return st_send_fail;
@@ -206,12 +187,11 @@ return st_ok;
 //---------------------------------------------------------------------------
 int NETTRANSACT::RxHeaderAnswer()
 {
-char buffer[sizeof(STG_HEADER)+1];
-int ret;
+char buffer[sizeof(STG_HEADER) + 1];
 
-ret = recv(outerSocket, buffer, strlen(OK_HEADER), 0);
-if (ret <= 0)
+if (recv(outerSocket, buffer, strlen(OK_HEADER), 0) <= 0)
     {
+    printf("Receive header answer error: '%s'\n", strerror(errno));
     errorMsg = RECV_HEADER_ANSWER_ERROR;
     return st_recv_fail;
     }
@@ -238,13 +218,10 @@ else
 int NETTRANSACT::TxLogin()
 {
 char loginZ[ADM_LOGIN_LEN];
-int ret;
-
 memset(loginZ, 0, ADM_LOGIN_LEN);
 strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN);
-ret = send(outerSocket, loginZ, ADM_LOGIN_LEN, 0);
 
-if (ret <= 0)
+if (send(outerSocket, loginZ, ADM_LOGIN_LEN, 0) <= 0)
     {
     errorMsg = SEND_LOGIN_ERROR;
     return st_send_fail;
@@ -255,12 +232,11 @@ return st_ok;
 //---------------------------------------------------------------------------
 int NETTRANSACT::RxLoginAnswer()
 {
-char buffer[sizeof(OK_LOGIN)+1];
-int ret;
+char buffer[sizeof(OK_LOGIN) + 1];
 
-ret = recv(outerSocket, buffer, strlen(OK_LOGIN), 0);
-if (ret <= 0)
+if (recv(outerSocket, buffer, strlen(OK_LOGIN), 0) <= 0)
     {
+    printf("Receive login answer error: '%s'\n", strerror(errno));
     errorMsg = RECV_LOGIN_ANSWER_ERROR;
     return st_recv_fail;
     }
@@ -287,20 +263,17 @@ else
 int NETTRANSACT::TxLoginS()
 {
 char loginZ[ADM_LOGIN_LEN];
-char ct[ENC_MSG_LEN];
-int ret;
-
 memset(loginZ, 0, ADM_LOGIN_LEN);
 strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN);
 
 BLOWFISH_CTX ctx;
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
+EnDecodeInit(password.c_str(), PASSWD_LEN, &ctx);
 
 for (int j = 0; j < ADM_LOGIN_LEN / ENC_MSG_LEN; j++)
     {
-    Encrypt(ct, loginZ + j*ENC_MSG_LEN, &ctx);
-    ret = send(outerSocket, ct, ENC_MSG_LEN, 0);
-    if (ret <= 0)
+    char ct[ENC_MSG_LEN];
+    EncodeString(ct, loginZ + j * ENC_MSG_LEN, &ctx);
+    if (send(outerSocket, ct, ENC_MSG_LEN, 0) <= 0)
         {
         errorMsg = SEND_LOGIN_ERROR;
         return st_send_fail;
@@ -312,12 +285,11 @@ return st_ok;
 //---------------------------------------------------------------------------
 int NETTRANSACT::RxLoginSAnswer()
 {
-char buffer[sizeof(OK_LOGINS)+1];
-int ret;
+char buffer[sizeof(OK_LOGINS) + 1];
 
-ret = recv(outerSocket, buffer, strlen(OK_LOGINS), 0);
-if (ret <= 0)
+if (recv(outerSocket, buffer, strlen(OK_LOGINS), 0) <= 0)
     {
+    printf("Receive secret login answer error: '%s'\n", strerror(errno));
     errorMsg = RECV_LOGIN_ANSWER_ERROR;
     return st_recv_fail;
     }
@@ -341,152 +313,75 @@ else
     }
 }
 //---------------------------------------------------------------------------
-int NETTRANSACT::TxData(const char * text)
+int NETTRANSACT::TxData(const std::string & text)
 {
-char textZ[ENC_MSG_LEN];
-char ct[ENC_MSG_LEN];
-int ret;
-int j;
-
-int n = strlen(text) / ENC_MSG_LEN;
-int r = strlen(text) % ENC_MSG_LEN;
-
 BLOWFISH_CTX ctx;
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
+EnDecodeInit(password.c_str(), PASSWD_LEN, &ctx);
 
-for (j = 0; j < n; j++)
+size_t pos = 0;
+while (pos < text.size())
     {
-    strncpy(textZ, text + j*ENC_MSG_LEN, ENC_MSG_LEN);
-    Encrypt(ct, textZ, &ctx);
-    ret = send(outerSocket, ct, ENC_MSG_LEN, 0);
-    if (ret <= 0)
+    char textZ[ENC_MSG_LEN];
+    if (text.size() - pos < ENC_MSG_LEN)
+        memset(textZ, 0, ENC_MSG_LEN);
+    strncpy(textZ, text.c_str() + pos, std::min(ENC_MSG_LEN, (int)(text.size() - pos)));
+    char ct[ENC_MSG_LEN];
+    EncodeString(ct, textZ, &ctx);
+    if (send(outerSocket, ct, ENC_MSG_LEN, 0) <= 0)
         {
         errorMsg = SEND_DATA_ERROR;
         return st_send_fail;
         }
-    }
-
-memset(textZ, 0, ENC_MSG_LEN);
-if (r)
-    strncpy(textZ, text + j*ENC_MSG_LEN, ENC_MSG_LEN);
-
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
-
-Encrypt(ct, textZ, &ctx);
-ret = send(outerSocket, ct, ENC_MSG_LEN, 0);
-if (ret <= 0)
-    {
-    errorMsg = SEND_DATA_ERROR;
-    return st_send_fail;
+    pos += ENC_MSG_LEN;
     }
 
 return st_ok;
 }
 //---------------------------------------------------------------------------
-int NETTRANSACT::TxData(char * data)
-{
-char buff[ENC_MSG_LEN];
-char buffS[ENC_MSG_LEN];
-char passwd[ADM_PASSWD_LEN];
-
-memset(passwd, 0, ADM_PASSWD_LEN);
-strncpy(passwd, password.c_str(), ADM_PASSWD_LEN);
-memset(buff, 0, ENC_MSG_LEN);
-
-int l = strlen(data)/ENC_MSG_LEN;
-if (strlen(data)%ENC_MSG_LEN)
-    l++;
-
-BLOWFISH_CTX ctx;
-EnDecryptInit(passwd, PASSWD_LEN, &ctx);
-
-for (int j = 0; j < l; j++)
-    {
-    strncpy(buff, &data[j*ENC_MSG_LEN], ENC_MSG_LEN);
-    Encrypt(buffS, buff, &ctx);
-    send(outerSocket, buffS, ENC_MSG_LEN, 0);
-    }
-
-return 0;
-}
-//---------------------------------------------------------------------------
-int NETTRANSACT::RxDataAnswer()
+int NETTRANSACT::RxDataAnswer(CALLBACK callback, void * data)
 {
-int n = 0;
-int ret;
-char bufferS[ENC_MSG_LEN];
-char buffer[ENC_MSG_LEN + 1];
-
 BLOWFISH_CTX ctx;
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
+EnDecodeInit(password.c_str(), PASSWD_LEN, &ctx);
 
-while (1)
+std::string chunk;
+while (true)
     {
-    ret = recv(outerSocket, &bufferS[n++], 1, 0);
-    if (ret <= 0)
+    char bufferS[ENC_MSG_LEN];
+    size_t toRead = ENC_MSG_LEN;
+    while (toRead > 0)
         {
-        close(outerSocket);
-        errorMsg = RECV_DATA_ANSWER_ERROR;
-        return st_recv_fail;
+        int ret = recv(outerSocket, &bufferS[ENC_MSG_LEN - toRead], toRead, 0);
+        if (ret <= 0)
+            {
+            printf("Receive data error: '%s'\n", strerror(errno));
+            close(outerSocket);
+            errorMsg = RECV_DATA_ANSWER_ERROR;
+            return st_recv_fail;
+            }
+        toRead -= ret;
         }
 
-    if (n == ENC_MSG_LEN)
-        {
-        n = 0;
-        Decrypt(buffer, bufferS, &ctx);
-        buffer[ENC_MSG_LEN] = 0;
+    char buffer[ENC_MSG_LEN];
+    DecodeString(buffer, bufferS, &ctx);
 
-        answerList.push_back(buffer);
+    bool final = false;
+    size_t pos = 0;
+    for (; pos < ENC_MSG_LEN && buffer[pos] != 0; pos++) ;
+    if (pos < ENC_MSG_LEN && buffer[pos] == 0)
+        final = true;
 
-        for (int j = 0; j < ENC_MSG_LEN; j++)
-            {
-            if (buffer[j] == 0)
-                {
-                if (RxCallBack)
-                    if (st_ok != RxCallBack(dataRxCallBack, &answerList))
-                        {
-                        return st_xml_parse_error;
-                        }
-                return st_ok;
-                }
-            }
+    if (pos > 0)
+        chunk.append(&buffer[0], &buffer[pos]);
+
+    if (chunk.length() > MAX_XML_CHUNK_LENGTH || final)
+        {
+        if (callback)
+            if (!callback(chunk, final, data))
+                return st_xml_parse_error;
+        chunk.clear();
         }
+
+    if (final)
+        return st_ok;
     }
 }
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetLogin(const char * l)
-{
-login = l;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetPassword(const char * p)
-{
-password = p;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetServer(const char * serverName)
-{
-server = serverName;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetServerPort(short unsigned p)
-{
-port = p;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetRxCallback(void * data, RxCallback_t cb)
-{
-RxCallBack = cb;
-dataRxCallBack = data;
-}
-//---------------------------------------------------------------------------
-const std::string & NETTRANSACT::GetError() const
-{
-return errorMsg;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::Reset()
-{
-answerList.clear();
-}
-//---------------------------------------------------------------------------
diff --git a/stglibs/srvconf.lib/netunit.h b/stglibs/srvconf.lib/netunit.h
new file mode 100644 (file)
index 0000000..f87fb3a
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ */
+
+#ifndef NetUnitH
+#define NetUnitH
+
+#include "stg/os_int.h"
+
+#include <string>
+
+class NETTRANSACT
+{
+public:
+    typedef bool (* CALLBACK)(const std::string &, bool, void *);
+
+    NETTRANSACT(const std::string & server, uint16_t port,
+                const std::string & login, const std::string & password);
+    int Transact(const std::string & request, CALLBACK f, void * data);
+    const std::string & GetError() const { return errorMsg; }
+
+    int  Connect();
+    void Disconnect();
+private:
+    int  TxHeader();
+    int  RxHeaderAnswer();
+
+    int  TxLogin();
+    int  RxLoginAnswer();
+
+    int  TxLoginS();
+    int  RxLoginSAnswer();
+
+    int  TxData(const std::string & text);
+    int  RxDataAnswer(CALLBACK f, void * data);
+
+    std::string server;
+    uint16_t  port;
+    std::string login;
+    std::string password;
+    int outerSocket;
+    std::string errorMsg;
+};
+
+#endif
diff --git a/stglibs/srvconf.lib/parser.cpp b/stglibs/srvconf.lib/parser.cpp
deleted file mode 100644 (file)
index a87266e..0000000
+++ /dev/null
@@ -1,955 +0,0 @@
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
- /*
- $Revision: 1.18 $
- $Date: 2010/08/04 00:40:00 $
- $Author: faust $
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <string>
-
-#include "stg/common.h"
-#include "stg/const.h"
-#include "stg/servconf.h"
-
-using namespace std;
-
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_GET_USERS::PARSER_GET_USERS()
-    : RecvUserDataCb(NULL),
-      userDataCb(NULL),
-      user(),
-      depth(0),
-      error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_GET_USERS::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
-    {
-    ParseUsers(el, attr);
-    }
-
-if (depth == 2)
-    {
-    ParseUser(el, attr);
-    }
-
-if (depth == 3)
-    {
-    ParseUserParams(el, attr);
-    }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseEnd(const char *)
-{
-depth--;
-if (depth == 1)
-    {
-    if (RecvUserDataCb)
-        {
-        RecvUserDataCb(&user, userDataCb);
-        }
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUsers(const char * el, const char ** attr)
-{
-if (strcasecmp(el, "users") == 0)
-    {
-    if (*attr != NULL)
-        return;
-    return;
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUser(const char * el, const char ** attr)
-{
-if (el && attr[0])
-    {
-    if (strcasecmp(el, "user") != 0)
-        {
-        return;
-        }
-
-    if (strcasecmp(attr[0], "login") != 0)
-        {
-        return;
-        }
-    user.login = attr[1];
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUserParams(const char * el, const char ** attr)
-{
-if (strcasecmp(el, "cash") == 0)
-    {
-    if (strtodouble2(attr[1], user.cash) < 0)
-        {
-        return;
-        }
-    }
-
-/*if (strcasecmp(el, "LastCash") == 0)
-    {
-    if (strtodouble2(attr[1], user.lastCash) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }*/
-
-/*if (strcasecmp(el, "LastActivityTime") == 0)
-    {
-    if (strtol(attr[1], user.lastActivityTime) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }*/
-
-
-/*if (strcasecmp(el, "LastTimeCash") == 0)
-    {
-    if (strtol(attr[1], user.lastTimeCash) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }*/
-
-/*if (strcasecmp(el, "CashExpire") == 0)
-    {
-    if (strtol(attr[1], user.cashExpire) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }*/
-
-if (strcasecmp(el, "credit") == 0)
-    {
-    if (strtodouble2(attr[1], user.credit) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "creditExpire") == 0)
-    {
-    if (str2x(attr[1], user.creditExpire) < 0)
-        {
-        return;
-        }
-    }
-
-/*if (strcasecmp(el, "freemb") == 0)
-    {
-    if (strtodouble2(attr[1], user.freeMb) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }*/
-
-if (strcasecmp(el, "down") == 0)
-    {
-    if (str2x(attr[1], user.down) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "passive") == 0)
-    {
-    if (str2x(attr[1], user.passive) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "disableDetailStat") == 0)
-    {
-    if (str2x(attr[1], user.disableDetailStat) < 0)
-        {
-        return;
-        }
-    }
-
-
-if (strcasecmp(el, "status") == 0)
-    {
-    if (str2x(attr[1], user.connected) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "aonline") == 0)
-    {
-    if (str2x(attr[1], user.alwaysOnline) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "currip") == 0)
-    {
-    user.ip = inet_addr(attr[1]);
-    }
-
-if (strcasecmp(el, "ip") == 0)
-    {
-    user.ips = attr[1];
-    }
-
-
-if (strcasecmp(el, "tariff") == 0)
-    {
-    //KOIToWin(user.tariff, *(attr+1), TARIFF_LEN);
-    user.tariff = attr[1];
-    return;
-    }
-
-if (strcasecmp(el, "password") == 0)
-    {
-    user.password = *(attr+1);
-    return;
-    }
-
-if (strcasecmp(el, "iface") == 0)
-    {
-    user.iface = attr[1];
-    return;
-    }
-
-/*if (strcasecmp(el, "name") == 0)
-    {
-    / *char nameEnc[REALNM_LEN * 2 + 1];
-    char name[REALNM_LEN];
-    strncpy(nameEnc, attr[1], REALNM_LEN * 2 + 1);
-    Decode21(name, nameEnc);
-    KOIToWin(user.realName, name, REALNM_LEN);* /
-    Decode21str(user.realName, attr[1]);
-    return;
-    }*/
-
-if (strcasecmp(el, "address") == 0)
-    {
-    /*char addressEnc[ADDR_LEN * 2 + 1];
-    char address[ADDR_LEN];
-    strncpy(addressEnc, attr[1], ADDR_LEN * 2 + 1);
-    Decode21(address, addressEnc);
-    KOIToWin(user.address, address, ADDR_LEN);*/
-    Decode21str(user.address, attr[1]);
-    return;
-    }
-
-if (strcasecmp(el, "phone") == 0)
-    {
-    /*char phoneEnc[PHONE_LEN * 2 + 1];
-    char phone[PHONE_LEN];
-    strncpy(phoneEnc, attr[1], PHONE_LEN * 2 + 1);
-    Decode21(phone, phoneEnc);
-    KOIToWin(user.phone, phone, PHONE_LEN);*/
-    Decode21str(user.phone, attr[1]);
-    return;
-    }
-
-if (strcasecmp(el, "note") == 0)
-    {
-    /*char noteEnc[NOTE_LEN * 2 + 1];
-    char note[NOTE_LEN];
-    strncpy(noteEnc, attr[1], NOTE_LEN * 2 + 1);*/
-    //KOIToWin(user.note, note, NOTE_LEN);
-    //user.note = note;
-    Decode21str(user.note, attr[1]);
-    return;
-    }
-
-if (strcasecmp(el, "email") == 0)
-    {
-    /*char emailEnc[EMAIL_LEN * 2 + 1];
-    char email[EMAIL_LEN];
-    strncpy(emailEnc, attr[1], EMAIL_LEN * 2 + 1);
-    Decode21(email, emailEnc);
-    //KOIToWin(user.email, email, EMAIL_LEN);
-    user.email = email;*/
-    Decode21str(user.email, attr[1]);
-    return;
-    }
-
-if (strcasecmp(el, "group") == 0)
-    {
-    /*char groupEnc[GROUP_LEN * 2 + 1];
-    char group[GROUP_LEN];
-    strncpy(groupEnc, attr[1], GROUP_LEN * 2 + 1);
-    Decode21(group, groupEnc);
-    //KOIToWin(user.group, group, GROUP_LEN);
-    user.group = group;*/
-    Decode21str(user.group, attr[1]);
-    return;
-    }
-
-if (strcasecmp(el, "traff") == 0)
-    {
-    ParseUserLoadStat(el, attr);
-    return;
-    }
-
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUserLoadStat(const char *, const char ** attr)
-{
-int i = 0;
-char dir[6];
-while (attr[i])
-    {
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "MU%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.mu[j]);
-            break;
-            }
-        }
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "MD%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.md[j]);
-            break;
-            }
-        }
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "SU%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.su[j]);
-            break;
-            }
-        }
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "SD%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.sd[j]);
-            break;
-            }
-        }
-    i+=2;
-    }
-return;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::SetUserDataRecvCb(RecvUserDataCb_t f, void * data)
-{
-RecvUserDataCb = f;
-userDataCb = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_GET_USER::PARSER_GET_USER()
-    : RecvUserDataCb(NULL),
-      userDataCb(NULL),
-      user(),
-      depth(0),
-      error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_GET_USER::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
-    {
-    ParseUser(el, attr);
-    }
-
-if (depth == 2)
-    {
-    ParseUserParams(el, attr);
-    }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseEnd(const char *)
-{
-depth--;
-if (depth == 0)
-    {
-    if (RecvUserDataCb)
-        {
-        RecvUserDataCb(&user, userDataCb);
-        }
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseUser(const char * el, const char ** attr)
-{
-if (strcasecmp(el, "user") == 0)
-    {
-    if (strcasecmp(attr[1], "error") == 0)
-        user.login = "";
-    return;
-    }
-}
-//-----------------------------------------------------------------------------
-struct ParsedStringParams
-{
-string    * param;
-string      paramName;
-};
-//-----------------------------------------------------------------------------
-struct ParsedDoubleParams
-{
-double    * param;
-string      paramName;
-};
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseUserParams(const char * el, const char ** attr)
-{
-//printf("PARSER_GET_USER::ParseUserParams el=%s attr[1]=%s\n", el, attr[1]);
-
-if (strcasecmp(el, "login") == 0)
-    {
-    user.login = attr[1];
-    }
-
-
-/*if (strcasecmp(el, "LastActivityTime") == 0)
-    {
-    if (strtol(attr[1], user.lastActivityTime) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }
-
-
-if (strcasecmp(el, "LastTimeCash") == 0)
-    {
-    if (strtol(attr[1], user.lastTimeCash) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }
-
-if (strcasecmp(el, "CashExpire") == 0)
-    {
-    if (strtol(attr[1], user.cashExpire) < 0)
-        {
-        MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
-        return 0;
-        }
-    }
-*/
-
-if (strcasecmp(el, "down") == 0)
-    {
-    if (str2x(attr[1], user.down) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "passive") == 0)
-    {
-    if (str2x(attr[1], user.passive) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "disableDetailStat") == 0)
-    {
-    if (str2x(attr[1], user.disableDetailStat) < 0)
-        {
-        return;
-        }
-    }
-
-
-if (strcasecmp(el, "status") == 0)
-    {
-    if (str2x(attr[1], user.connected) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "aonline") == 0)
-    {
-    if (str2x(attr[1], user.alwaysOnline) < 0)
-        {
-        return;
-        }
-    }
-
-if (strcasecmp(el, "currip") == 0)
-    {
-    user.ip = inet_addr(attr[1]);
-    }
-
-if (strcasecmp(el, "creditExpire") == 0)
-    {
-    if (str2x(attr[1], user.creditExpire) < 0)
-        {
-        return;
-        }
-    }
-
-for (int i = 0; i < USERDATA_NUM; i++)
-    {
-    string num;
-    x2str(i, num);
-    string udName = "UserData" + num;
-    if (strcasecmp(el, udName.c_str()) == 0)
-        {
-        Decode21str(user.userData[i], attr[1]);
-        return;
-        }
-    }
-
-ParsedStringParams psp[] =
-{
-    {&user.ips,         "ip"},
-    {&user.tariff,      "tariff"},
-    {&user.password,    "password"},
-    {&user.iface,       "iface"},
-};
-
-for (unsigned i = 0; i < sizeof(psp)/sizeof(ParsedStringParams); i++)
-    {
-    if (strcasecmp(el, psp[i].paramName.c_str()) == 0)
-        {
-        *psp[i].param = attr[1];
-        return;
-        }
-    }
-
-ParsedStringParams pspEnc[] =
-{
-    {&user.note,    "note"},
-    {&user.email,   "email"},
-    {&user.group,   "group"},
-    {&user.name,    "name"},
-    {&user.address, "address"},
-    {&user.phone,   "phone"}
-};
-
-for (unsigned i = 0; i < sizeof(pspEnc)/sizeof(ParsedStringParams); i++)
-    {
-    if (strcasecmp(el, pspEnc[i].paramName.c_str()) == 0)
-        {
-        Decode21str(*pspEnc[i].param, attr[1]);
-        return;
-        }
-    }
-
-ParsedDoubleParams pdp[] =
-{
-    {&user.cash,            "cash"},
-    {&user.credit,          "credit"},
-    {&user.lastCash,        "lastCash"},
-    {&user.prepaidTraff,    "freemb"},
-};
-
-for (unsigned i = 0; i < sizeof(pdp)/sizeof(ParsedDoubleParams); i++)
-    {
-    if (strcasecmp(el, pdp[i].paramName.c_str()) == 0)
-        {
-        strtodouble2(attr[1], *pdp[i].param);
-        return;
-        }
-    }
-
-if (strcasecmp(el, "traff") == 0)
-    {
-    ParseUserLoadStat(el, attr);
-    return;
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseUserLoadStat(const char *, const char ** attr)
-{
-int i = 0;
-char dir[6];
-while (attr[i])
-    {
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "MU%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.mu[j]);
-            break;
-            }
-        }
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "MD%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.md[j]);
-            break;
-            }
-        }
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "SU%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.su[j]);
-            break;
-            }
-        }
-    for (int j = 0; j < DIR_NUM; j++)
-        {
-        sprintf(dir, "SD%d", j);
-        if (strcasecmp(dir, attr[i]) == 0)
-            {
-            str2x(attr[i+1], user.stat.sd[j]);
-            break;
-            }
-        }
-    i+=2;
-    }
-return;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::SetUserDataRecvCb(RecvUserDataCb_t f, void * data)
-{
-RecvUserDataCb = f;
-userDataCb = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_GET_SERVER_INFO::PARSER_GET_SERVER_INFO()
-    : RecvServerInfoDataCb(NULL),
-      serverInfoDataCb(NULL),
-      depth(0),
-      error(false),
-      serverInfo()
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_GET_SERVER_INFO::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
-    {
-    if (strcasecmp(el, "ServerInfo") != 0)
-        {
-        //printf("%s\n", el);
-        }
-    }
-else
-    {
-    if (depth == 2)
-        {
-        if (strcasecmp(el, "uname") == 0)
-            {
-            ParseUname(attr);
-            return 0;
-            }
-        if (strcasecmp(el, "version") == 0)
-            {
-            ParseServerVersion(attr);
-            return 0;
-            }
-        if (strcasecmp(el, "tariff") == 0)
-            {
-            ParseTariffType(attr);
-            return 0;
-            }
-        if (strcasecmp(el, "dir_num") == 0)
-            {
-            ParseDirNum(attr);
-            return 0;
-            }
-        if (strcasecmp(el, "users_num") == 0)
-            {
-            ParseUsersNum(attr);
-            return 0;
-            }
-        if (strcasecmp(el, "tariff_num") == 0)
-            {
-            ParseTariffsNum(attr);
-            return 0;
-            }
-
-        for (int j = 0; j < DIR_NUM; j++)
-            {
-            char str[16];
-            sprintf(str, "dir_name_%d", j);
-            if (strcasecmp(el, str) == 0)
-                {
-                ParseDirName(attr, j);
-                }
-            }
-
-        }
-    }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseEnd(const char *)
-{
-depth--;
-if (depth == 0)
-    {
-    RecvServerInfoDataCb(&serverInfo, serverInfoDataCb);
-    }
-}
-//-----------------------------------------------------------------------------
-/*void PARSER_GET_SERVER_INFO::ParseServerInfo(const char * el, const char ** attr)
-    {
-    }*/
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::SetServerInfoRecvCb(RecvServerInfoDataCb_t f, void * data)
-{
-RecvServerInfoDataCb = f;
-serverInfoDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseUname(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
-    serverInfo.uname = attr[1];
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseServerVersion(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
-    serverInfo.version = attr[1];
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseUsersNum(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
-    {
-    if (str2x(attr[1], serverInfo.usersNum) < 0)
-        {
-        serverInfo.usersNum = -1;
-        return;
-        }
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseTariffsNum(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
-    {
-    if (str2x(attr[1], serverInfo.tariffNum) < 0)
-        {
-        serverInfo.tariffNum = -1;
-        return;
-        }
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseTariffType(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
-    {
-    if (str2x(attr[1], serverInfo.tariffType) < 0)
-        {
-        serverInfo.tariffType = -1;
-        return;
-        }
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseDirNum(const char **attr)
-{
-if (strcasecmp(*attr, "value") == 0)
-    {
-    if (str2x(attr[1], serverInfo.dirNum) < 0)
-        {
-        serverInfo.dirNum = -1;
-        return;
-        }
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseDirName(const char **attr, int d)
-{
-if (strcmp(attr[0], "value") == 0)
-    {
-    char str[2*DIRNAME_LEN + 1];
-    Decode21(str, attr[1]);
-    serverInfo.dirName[d] = str;
-    }
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_CHG_USER::PARSER_CHG_USER()
-    : RecvChgUserCb(NULL),
-      chgUserCbData(NULL),
-      depth(0),
-      error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_CHG_USER::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
-    {
-    if (strcasecmp(el, "SetUser") == 0)
-        {
-        ParseAnswer(el, attr);
-        }
-    else if (strcasecmp(el, "DelUser") == 0)
-        {
-        ParseAnswer(el, attr);
-        }
-    else if (strcasecmp(el, "AddUser") == 0)
-        {
-        ParseAnswer(el, attr);
-        }
-    }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHG_USER::ParseEnd(const char *)
-{
-depth--;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHG_USER::ParseAnswer(const char *, const char **attr)
-{
-if (RecvChgUserCb)
-    {
-    RecvChgUserCb(attr[1], chgUserCbData);
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHG_USER::SetChgUserRecvCb(RecvChgUserCb_t f, void * data)
-{
-RecvChgUserCb = f;
-chgUserCbData = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_CHECK_USER::PARSER_CHECK_USER()
-    : RecvCheckUserCb(NULL),
-      checkUserCbData(NULL),
-      depth(0),
-      error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_CHECK_USER::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
-    {
-    if (strcasecmp(el, "CheckUser") == 0)
-        {
-        //printf("el=%s attr[0]=%s attr[1]=%s\n", el, attr[0], attr[1]);
-        ParseAnswer(el, attr);
-        }
-    }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::ParseEnd(const char *)
-{
-depth--;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::ParseAnswer(const char *, const char **attr)
-{
-if (RecvCheckUserCb)
-    {
-    RecvCheckUserCb(attr[1], checkUserCbData);
-    }
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::SetCheckUserRecvCb(RecvCheckUserCb_t f, void * data)
-{
-RecvCheckUserCb = f;
-checkUserCbData = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_SEND_MESSAGE::PARSER_SEND_MESSAGE()
-    : RecvSendMessageCb(NULL),
-      sendMessageCbData(NULL),
-      depth(0),
-      error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int  PARSER_SEND_MESSAGE::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
-    {
-    if (strcasecmp(el, "SendMessageResult") == 0)
-        {
-        ParseAnswer(el, attr);
-        }
-    }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_SEND_MESSAGE::ParseEnd(const char *)
-{
-depth--;
-}
-//-----------------------------------------------------------------------------
-void PARSER_SEND_MESSAGE::ParseAnswer(const char *, const char **attr)
-{
-if (RecvSendMessageCb)
-    RecvSendMessageCb(attr[1], sendMessageCbData);
-}
-//-----------------------------------------------------------------------------
-void PARSER_SEND_MESSAGE::SetSendMessageRecvCb(RecvSendMessageCb_t f, void * data)
-{
-RecvSendMessageCb = f;
-sendMessageCbData = data;
-}
-//-----------------------------------------------------------------------------
diff --git a/stglibs/srvconf.lib/parsers/auth_by.cpp b/stglibs/srvconf.lib/parsers/auth_by.cpp
new file mode 100644 (file)
index 0000000..61f590b
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "auth_by.h"
+
+#include <strings.h> // strcasecmp
+
+using namespace STG;
+
+AUTH_BY::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+}
+//-----------------------------------------------------------------------------
+int AUTH_BY::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+    {
+    if (strcasecmp(el, "AuthorizedBy") == 0)
+        if (attr && attr[0] && attr[1])
+            {
+            if (strcasecmp(attr[1], "error") == 0)
+                {
+                if (attr[2] && attr[3])
+                    error = attr[3];
+                else
+                    error = "User not found.";
+                }
+            else
+                parsingAnswer = true;
+            }
+    }
+else
+    {
+    if (depth == 2)
+        {
+        if (parsingAnswer && strcasecmp(el, "Auth") == 0)
+            {
+            if (attr && attr[0] && attr[1] && strcasecmp(attr[0], "name") == 0)
+                info.push_back(attr[1]);
+            return 0;
+            }
+        }
+    }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void AUTH_BY::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    info.clear();
+    error.clear();
+    }
+}
diff --git a/stglibs/srvconf.lib/parsers/auth_by.h b/stglibs/srvconf.lib/parsers/auth_by.h
new file mode 100644 (file)
index 0000000..f285d2b
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace AUTH_BY
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    PARSER(CALLBACK f, void * data);
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    CALLBACK callback;
+    void * data;
+    int depth;
+    bool parsingAnswer;
+    INFO info;
+    std::string error;
+};
+
+} // namespace AUTH_BY
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/base.h b/stglibs/srvconf.lib/parsers/base.h
new file mode 100644 (file)
index 0000000..8d695a3
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_H__
+
+namespace STG
+{
+
+class PARSER
+{
+public:
+    virtual ~PARSER() {}
+    virtual int ParseStart(const char *el, const char **attr) = 0;
+    virtual void ParseEnd(const char *el) = 0;
+};
+
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/chg_admin.cpp b/stglibs/srvconf.lib/parsers/chg_admin.cpp
new file mode 100644 (file)
index 0000000..a4265ef
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_admin.h"
+
+#include "stg/admin_conf.h"
+#include "stg/common.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+std::string CHG_ADMIN::Serialize(const ADMIN_CONF_RES & conf)
+{
+std::string params;
+if (!conf.login.empty())
+    params += " login=\"" + conf.login.data() + "\"";
+if (!conf.password.empty())
+    params += " password=\"" + conf.password.data() + "\"";
+if (!conf.priv.empty())
+    params += " priv=\"" + unsigned2str(conf.priv.data().ToInt()) + "\"";
+return params;
+}
diff --git a/stglibs/srvconf.lib/parsers/chg_admin.h b/stglibs/srvconf.lib/parsers/chg_admin.h
new file mode 100644 (file)
index 0000000..c10332c
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct ADMIN_CONF_RES;
+
+namespace STG
+{
+namespace CHG_ADMIN
+{
+
+std::string Serialize(const ADMIN_CONF_RES & conf);
+
+} // namespace CHG_ADMIN
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/chg_corp.cpp b/stglibs/srvconf.lib/parsers/chg_corp.cpp
new file mode 100644 (file)
index 0000000..dc88422
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_corp.h"
+
+#include "resetable_utils.h"
+
+#include "stg/corp_conf.h"
+#include "stg/common.h"
+
+#include <sstream>
+
+using namespace STG;
+
+std::string CHG_CORP::Serialize(const CORP_CONF_RES & conf)
+{
+std::ostringstream stream;
+
+appendResetable(stream, "name", conf.name);
+appendResetable(stream, "cash", conf.cash);
+
+return stream.str();
+}
diff --git a/stglibs/srvconf.lib/parsers/chg_corp.h b/stglibs/srvconf.lib/parsers/chg_corp.h
new file mode 100644 (file)
index 0000000..8b75fbd
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct CORP_CONF_RES;
+
+namespace STG
+{
+namespace CHG_CORP
+{
+
+std::string Serialize(const CORP_CONF_RES & conf);
+
+} // namespace CHG_CORP
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/chg_service.cpp b/stglibs/srvconf.lib/parsers/chg_service.cpp
new file mode 100644 (file)
index 0000000..f862761
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_service.h"
+
+#include "resetable_utils.h"
+
+#include "stg/service_conf.h"
+#include "stg/common.h"
+
+#include <sstream>
+
+using namespace STG;
+
+std::string CHG_SERVICE::Serialize(const SERVICE_CONF_RES & conf)
+{
+std::ostringstream stream;
+
+appendResetable(stream, "name", conf.name);
+appendResetable(stream, "comment", conf.comment);
+appendResetable(stream, "cost", conf.cost);
+appendResetable(stream, "payDay", conf.payDay);
+
+return stream.str();
+}
diff --git a/stglibs/srvconf.lib/parsers/chg_service.h b/stglibs/srvconf.lib/parsers/chg_service.h
new file mode 100644 (file)
index 0000000..10fbf6f
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct SERVICE_CONF_RES;
+
+namespace STG
+{
+namespace CHG_SERVICE
+{
+
+std::string Serialize(const SERVICE_CONF_RES & conf);
+
+} // namespace CHG_SERVICE
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/chg_tariff.cpp b/stglibs/srvconf.lib/parsers/chg_tariff.cpp
new file mode 100644 (file)
index 0000000..cb7d947
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_tariff.h"
+
+#include "resetable_utils.h"
+
+#include "stg/tariff_conf.h"
+#include "stg/common.h"
+
+#include <sstream>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace
+{
+
+template <typename A, typename T>
+void appendSlashedResetable(std::ostream & stream, const std::string & name, const A & array, T A::value_type:: * field)
+{
+std::string res;
+for (typename A::size_type i = 0; i < array.size(); ++i)
+    {
+    if ((array[i].*field).empty()) // All values must be set
+        return;
+    if (!res.empty())
+        res += "/";
+    res += x2str((array[i].*field).data());
+    }
+stream << "<" << name << " value=\"" << res << "\"/>";
+}
+
+} // namespace anonymous
+
+std::string CHG_TARIFF::Serialize(const TARIFF_DATA_RES & data)
+{
+std::ostringstream stream;
+
+appendResetable(stream, "fee", data.tariffConf.fee);
+appendResetable(stream, "passiveCost", data.tariffConf.passiveCost);
+appendResetable(stream, "free", data.tariffConf.free);
+
+if (!data.tariffConf.traffType.empty())
+    switch (data.tariffConf.traffType.data())
+        {
+        case TRAFF_UP: stream << "<traffType value=\"up\"/>"; break;
+        case TRAFF_DOWN: stream << "<traffType value=\"down\"/>"; break;
+        case TRAFF_UP_DOWN: stream << "<traffType value=\"up+down\"/>"; break;
+        case TRAFF_MAX: stream << "<traffType value=\"max\"/>"; break;
+        }
+
+for (size_t i = 0; i < DIR_NUM; ++i)
+    if (!data.dirPrice[i].hDay.empty() &&
+        !data.dirPrice[i].mDay.empty() &&
+        !data.dirPrice[i].hNight.empty() &&
+        !data.dirPrice[i].mNight.empty())
+        stream << "<time" << i << " value=\"" << data.dirPrice[i].hDay.data() << ":"
+                                              << data.dirPrice[i].mDay.data() << "-"
+                                              << data.dirPrice[i].hNight.data() << ":"
+                                              << data.dirPrice[i].mNight.data() << "\"/>";
+
+appendSlashedResetable(stream, "priceDayA", data.dirPrice, &DIRPRICE_DATA_RES::priceDayA);
+appendSlashedResetable(stream, "priceDayB", data.dirPrice, &DIRPRICE_DATA_RES::priceDayB);
+appendSlashedResetable(stream, "priceNightA", data.dirPrice, &DIRPRICE_DATA_RES::priceNightA);
+appendSlashedResetable(stream, "priceNightB", data.dirPrice, &DIRPRICE_DATA_RES::priceNightB);
+appendSlashedResetable(stream, "singlePrice", data.dirPrice, &DIRPRICE_DATA_RES::singlePrice);
+appendSlashedResetable(stream, "noDiscount", data.dirPrice, &DIRPRICE_DATA_RES::noDiscount);
+appendSlashedResetable(stream, "threshold", data.dirPrice, &DIRPRICE_DATA_RES::threshold);
+
+return stream.str();
+}
diff --git a/stglibs/srvconf.lib/parsers/chg_tariff.h b/stglibs/srvconf.lib/parsers/chg_tariff.h
new file mode 100644 (file)
index 0000000..c5cc0f0
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct TARIFF_DATA_RES;
+
+namespace STG
+{
+namespace CHG_TARIFF
+{
+
+std::string Serialize(const TARIFF_DATA_RES & data);
+
+} // namespace CHG_TARIFF
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/chg_user.cpp b/stglibs/srvconf.lib/parsers/chg_user.cpp
new file mode 100644 (file)
index 0000000..ed2002b
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_user.h"
+
+#include "resetable_utils.h"
+
+#include "stg/user_conf.h"
+#include "stg/user_stat.h"
+
+#include <sstream>
+
+#include <strings.h>
+
+using namespace STG;
+
+CHG_USER::PARSER::PARSER(SIMPLE::CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0)
+{
+}
+//-----------------------------------------------------------------------------
+int CHG_USER::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+    {
+    if (strcasecmp(el, "SetUser") == 0)
+        ParseAnswer(el, attr);
+    else if (strcasecmp(el, "DelUser") == 0)
+        ParseAnswer(el, attr);
+    else if (strcasecmp(el, "AddUser") == 0)
+        ParseAnswer(el, attr);
+    }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void CHG_USER::PARSER::ParseEnd(const char *)
+{
+depth--;
+}
+//-----------------------------------------------------------------------------
+void CHG_USER::PARSER::ParseAnswer(const char * /*el*/, const char ** attr)
+{
+if (!callback)
+    return;
+if (attr && attr[0] && attr[1])
+    callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : "", data);
+else
+    callback(false, "Invalid response.", data);
+}
+
+std::string CHG_USER::Serialize(const USER_CONF_RES & conf, const USER_STAT_RES & stat)
+{
+std::ostringstream stream;
+
+// Conf
+
+appendResetable(stream, "credit", conf.credit);
+appendResetable(stream, "creditExpire", conf.creditExpire);
+appendResetable(stream, "password", conf.password);
+appendResetable(stream, "down", conf.disabled); // TODO: down -> disabled
+appendResetable(stream, "passive", conf.passive);
+appendResetable(stream, "disableDetailStat", conf.disabledDetailStat); // TODO: disable -> disabled
+appendResetable(stream, "aonline", conf.alwaysOnline); // TODO: aonline -> alwaysOnline
+appendResetable(stream, "ip", conf.ips); // TODO: ip -> ips
+
+if (!conf.nextTariff.empty())
+    stream << "<tariff delayed=\"" << conf.nextTariff.data() << "\"/>";
+else if (!conf.tariffName.empty())
+    stream << "<tariff now=\"" << conf.nextTariff.data() << "\"/>";
+
+appendResetable(stream, "note", conf.note);
+appendResetable(stream, "name", conf.realName); // TODO: name -> realName
+appendResetable(stream, "address", conf.address);
+appendResetable(stream, "email", conf.email);
+appendResetable(stream, "phone", conf.phone);
+appendResetable(stream, "group", conf.group);
+
+for (size_t i = 0; i < conf.userdata.size(); ++i)
+    appendResetable(stream, "userdata", i, conf.userdata[i]);
+
+// Stat
+
+if (!stat.cashAdd.empty())
+    stream << "<cash add=\"" << stat.cashAdd.data().first << "\" msg=\"" << stat.cashAdd.data().second << "\"/>";
+else if (!stat.cashSet.empty())
+    stream << "<cash set=\"" << stat.cashAdd.data().first << "\" msg=\"" << stat.cashAdd.data().second << "\"/>";
+
+appendResetable(stream, "freeMb", stat.freeMb);
+
+std::ostringstream traff;
+for (size_t i = 0; i < stat.sessionUp.size(); ++i)
+    if (!stat.sessionUp[i].empty())
+        traff << " SU" << i << "=\"" << stat.sessionUp[i].data() << "\"";
+for (size_t i = 0; i < stat.sessionDown.size(); ++i)
+    if (!stat.sessionDown[i].empty())
+        traff << " SD" << i << "=\"" << stat.sessionDown[i].data() << "\"";
+for (size_t i = 0; i < stat.monthUp.size(); ++i)
+    if (!stat.monthUp[i].empty())
+        traff << " MU" << i << "=\"" << stat.monthUp[i].data() << "\"";
+for (size_t i = 0; i < stat.monthDown.size(); ++i)
+    if (!stat.monthDown[i].empty())
+        traff << " MD" << i << "=\"" << stat.monthDown[i].data() << "\"";
+
+std::string traffData = traff.str();
+if (!traffData.empty())
+    stream << "<traff" << traffData << "/>";
+
+return stream.str();
+}
diff --git a/stglibs/srvconf.lib/parsers/chg_user.h b/stglibs/srvconf.lib/parsers/chg_user.h
new file mode 100644 (file)
index 0000000..9f8e6b0
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_USER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_USER_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+struct USER_CONF_RES;
+struct USER_STAT_RES;
+
+namespace STG
+{
+namespace CHG_USER
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    PARSER(SIMPLE::CALLBACK f, void * data);
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    SIMPLE::CALLBACK callback;
+    void * data;
+    int depth;
+
+    void ParseAnswer(const char * el, const char ** attr);
+};
+
+std::string Serialize(const USER_CONF_RES & conf, const USER_STAT_RES & stat);
+
+} // namespace CHG_USER
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/get_admin.cpp b/stglibs/srvconf.lib/parsers/get_admin.cpp
new file mode 100644 (file)
index 0000000..41217df
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_admin.h"
+
+#include "stg/common.h"
+
+#include <map>
+#include <utility>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace STG
+{
+
+template <>
+inline
+bool GetValue<PRIV>(const char ** attr, PRIV & value)
+{
+uint32_t priv;
+if (!GetValue(attr, priv))
+    return false;
+value = priv;
+return true;
+}
+
+} // namespace STG
+
+GET_ADMIN::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+    AddParser(propertyParsers, "login", info.login);
+    AddParser(propertyParsers, "password", info.password);
+    AddParser(propertyParsers, "priv", info.priv);
+}
+//-----------------------------------------------------------------------------
+GET_ADMIN::PARSER::~PARSER()
+{
+    PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+    while (it != propertyParsers.end())
+        delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_ADMIN::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+    ParseAdmin(el, attr);
+
+if (depth == 2 && parsingAnswer)
+    ParseAdminParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_ADMIN::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    error.clear();
+    parsingAnswer = false;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_ADMIN::PARSER::ParseAdmin(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "admin") == 0)
+    {
+    if (attr && attr[0] && attr[1])
+        {
+        if (strcasecmp(attr[1], "error") == 0)
+            {
+            if (attr[2] && attr[3])
+                error = attr[3];
+            else
+                error = "Admin not found.";
+            }
+        else
+            parsingAnswer = true;
+        }
+    else
+        parsingAnswer = true;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_ADMIN::PARSER::ParseAdminParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+    error = "Invalid parameter.";
+}
diff --git a/stglibs/srvconf.lib/parsers/get_admin.h b/stglibs/srvconf.lib/parsers/get_admin.h
new file mode 100644 (file)
index 0000000..d8e2fe9
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/admin_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_ADMIN
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    typedef GET_ADMIN::INFO INFO;
+
+    PARSER(CALLBACK f, void * data);
+    virtual ~PARSER();
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    PROPERTY_PARSERS propertyParsers;
+    CALLBACK callback;
+    void * data;
+    INFO info;
+    int depth;
+    bool parsingAnswer;
+    std::string error;
+
+    void ParseAdmin(const char * el, const char ** attr);
+    void ParseAdminParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_ADMIN
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/get_container.h b/stglibs/srvconf.lib/parsers/get_container.h
new file mode 100644 (file)
index 0000000..31bb425
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__
+
+#include "base.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_CONTAINER
+{
+
+template <typename ELEMENT_PARSER>
+class PARSER: public STG::PARSER
+{
+public:
+    typedef std::vector<typename ELEMENT_PARSER::INFO> INFO;
+    typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+    PARSER(const std::string & t, CALLBACK f, void * d)
+        : tag(t), callback(f), data(d),
+          elementParser(&PARSER<ELEMENT_PARSER>::ElementCallback, this),
+          depth(0), parsingAnswer(false)
+    {}
+    int  ParseStart(const char * el, const char ** attr)
+    {
+    depth++;
+    if (depth == 1 && strcasecmp(el, tag.c_str()) == 0)
+        parsingAnswer = true;
+
+    if (depth > 1 && parsingAnswer)
+        elementParser.ParseStart(el, attr);
+
+    return 0;
+    }
+    void ParseEnd(const char * el)
+    {
+    depth--;
+    if (depth > 0 && parsingAnswer)
+        elementParser.ParseEnd(el);
+
+    if (depth == 0 && parsingAnswer)
+        {
+        if (callback)
+            callback(error.empty(), error, info, data);
+        error.clear();
+        info.clear();
+        parsingAnswer = false;
+        }
+    }
+
+private:
+    std::string tag;
+    CALLBACK callback;
+    void * data;
+    ELEMENT_PARSER elementParser;
+    INFO info;
+    int depth;
+    bool parsingAnswer;
+    std::string error;
+
+    void AddElement(const typename ELEMENT_PARSER::INFO & elementInfo)
+    {
+    info.push_back(elementInfo);
+    }
+    void SetError(const std::string & e) { error = e; }
+
+    static void ElementCallback(bool result, const std::string& reason, const typename ELEMENT_PARSER::INFO & info, void * data)
+    {
+    PARSER<ELEMENT_PARSER> * parser = static_cast<PARSER<ELEMENT_PARSER> *>(data);
+    if (!result)
+        parser->SetError(reason);
+    else
+        parser->AddElement(info);
+    }
+};
+
+} // namespace GET_CONTAINER
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/get_corp.cpp b/stglibs/srvconf.lib/parsers/get_corp.cpp
new file mode 100644 (file)
index 0000000..339d1eb
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_corp.h"
+
+#include "parsers/property.h"
+
+#include "stg/common.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+GET_CORP::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+    AddParser(propertyParsers, "name", info.name);
+    AddParser(propertyParsers, "cash", info.cash);
+}
+//-----------------------------------------------------------------------------
+GET_CORP::PARSER::~PARSER()
+{
+    PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+    while (it != propertyParsers.end())
+        delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_CORP::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+    ParseCorp(el, attr);
+
+if (depth == 2 && parsingAnswer)
+    ParseCorpParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_CORP::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    error.clear();
+    parsingAnswer = false;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_CORP::PARSER::ParseCorp(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "corp") == 0)
+    {
+    if (attr && attr[0] && attr[1])
+        {
+        if (strcasecmp(attr[1], "error") == 0)
+            {
+            if (attr[2] && attr[3])
+                error = attr[3];
+            else
+                error = "Corp not found.";
+            }
+        else
+            parsingAnswer = true;
+        }
+    else
+        parsingAnswer = true;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_CORP::PARSER::ParseCorpParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+    error = "Invalid parameter.";
+}
diff --git a/stglibs/srvconf.lib/parsers/get_corp.h b/stglibs/srvconf.lib/parsers/get_corp.h
new file mode 100644 (file)
index 0000000..a01fe26
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/corp_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_CORP
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    typedef GET_CORP::INFO INFO;
+
+    PARSER(CALLBACK f, void * data);
+    virtual ~PARSER();
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    PROPERTY_PARSERS propertyParsers;
+    CALLBACK callback;
+    void * data;
+    INFO info;
+    int depth;
+    bool parsingAnswer;
+    std::string error;
+
+    void ParseCorp(const char * el, const char ** attr);
+    void ParseCorpParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_CORP
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/get_service.cpp b/stglibs/srvconf.lib/parsers/get_service.cpp
new file mode 100644 (file)
index 0000000..105b739
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_service.h"
+
+#include "parsers/property.h"
+
+#include "stg/common.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+GET_SERVICE::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+    AddParser(propertyParsers, "name", info.name);
+    AddParser(propertyParsers, "comment", info.comment);
+    AddParser(propertyParsers, "cost", info.cost);
+    AddParser(propertyParsers, "payDay", info.payDay);
+}
+//-----------------------------------------------------------------------------
+GET_SERVICE::PARSER::~PARSER()
+{
+    PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+    while (it != propertyParsers.end())
+        delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_SERVICE::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+    ParseService(el, attr);
+
+if (depth == 2 && parsingAnswer)
+    ParseServiceParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_SERVICE::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    error.clear();
+    parsingAnswer = false;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_SERVICE::PARSER::ParseService(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "service") == 0)
+    {
+    if (attr && attr[0] && attr[1])
+        {
+        if (strcasecmp(attr[1], "error") == 0)
+            {
+            if (attr[2] && attr[3])
+                error = attr[3];
+            else
+                error = "Service not found.";
+            }
+        else
+            parsingAnswer = true;
+        }
+    else
+        parsingAnswer = true;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_SERVICE::PARSER::ParseServiceParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+    error = "Invalid parameter.";
+}
diff --git a/stglibs/srvconf.lib/parsers/get_service.h b/stglibs/srvconf.lib/parsers/get_service.h
new file mode 100644 (file)
index 0000000..847d8bf
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/service_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_SERVICE
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    typedef GET_SERVICE::INFO INFO;
+    PARSER(CALLBACK f, void * data);
+    virtual ~PARSER();
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    PROPERTY_PARSERS propertyParsers;
+    CALLBACK callback;
+    void * data;
+    INFO info;
+    int depth;
+    bool parsingAnswer;
+    std::string error;
+
+    void ParseService(const char * el, const char ** attr);
+    void ParseServiceParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_SERVICE
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/get_tariff.cpp b/stglibs/srvconf.lib/parsers/get_tariff.cpp
new file mode 100644 (file)
index 0000000..e861843
--- /dev/null
@@ -0,0 +1,192 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_tariff.h"
+
+#include "parsers/property.h"
+
+#include "stg/common.h"
+
+#include <utility>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace
+{
+
+template <typename A, typename T>
+class AOS_PARSER : public BASE_PROPERTY_PARSER
+{
+    public:
+        typedef bool (* FUNC)(const char **, A &, T A::value_type:: *);
+        AOS_PARSER(A & a, T A::value_type:: * fld, FUNC f) : array(a), field(fld), func(f) {}
+        virtual bool Parse(const char ** attr) { return func(attr, array, field); }
+    private:
+        A & array;
+        T A::value_type:: * field;
+        FUNC func;
+};
+
+template <typename A, typename T>
+inline
+void AddAOSParser(PROPERTY_PARSERS & parsers, const std::string & name, A & array, T A::value_type:: * field, const typename AOS_PARSER<A, T>::FUNC & func)
+{
+    parsers.insert(std::make_pair(ToLower(name), new AOS_PARSER<A, T>(array, field, func)));
+}
+
+bool GetTimeSpan(const char ** attr, DIRPRICE_DATA & value)
+{
+int hb = 0;
+int mb = 0;
+int he = 0;
+int me = 0;
+if (CheckValue(attr))
+    if (ParseTariffTimeStr(attr[1], hb, mb, he, me) == 0)
+        {
+        value.hDay = hb;
+        value.mDay = mb;
+        value.hNight = he;
+        value.mNight = me;
+        return true;
+        }
+return false;
+}
+
+template <typename T>
+bool GetTraffType(const char ** attr, T & value)
+{
+if (!CheckValue(attr))
+    return false;
+std::string type(attr[1]);
+if (type == "up")
+    value = TRAFF_UP;
+else if (type == "down")
+    value = TRAFF_DOWN;
+else if (type == "up+down")
+    value = TRAFF_UP_DOWN;
+else if (type == "max")
+    value = TRAFF_MAX;
+else
+    return false;
+return true;
+}
+
+template <typename A, typename T>
+bool GetSlashedValue(const char ** attr, A & array, T A::value_type:: * field)
+{
+if (!CheckValue(attr))
+    return false;
+const char * start = attr[1];
+size_t item = 0;
+const char * pos = NULL;
+while ((pos = strchr(start, '/')) && item < array.size())
+    {
+    if (str2x(std::string(start, pos), array[item++].*field))
+            return false;
+    start = pos + 1;
+    }
+if (item < array.size())
+    if (str2x(start, array[item].*field))
+        return false;
+return true;
+}
+
+} // namespace anonymous
+
+GET_TARIFF::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+    AddParser(propertyParsers, "fee", info.tariffConf.fee);
+    AddParser(propertyParsers, "passiveCost", info.tariffConf.passiveCost);
+    AddParser(propertyParsers, "free", info.tariffConf.free);
+    AddParser(propertyParsers, "traffType", info.tariffConf.traffType, GetTraffType);
+    for (size_t i = 0; i < DIR_NUM; ++i)
+        AddParser(propertyParsers, "time" + unsigned2str(i), info.dirPrice[i], GetTimeSpan);
+    AddAOSParser(propertyParsers, "priceDayA", info.dirPrice, &DIRPRICE_DATA::priceDayA, GetSlashedValue);
+    AddAOSParser(propertyParsers, "priceDayB", info.dirPrice, &DIRPRICE_DATA::priceDayB, GetSlashedValue);
+    AddAOSParser(propertyParsers, "priceNightA", info.dirPrice, &DIRPRICE_DATA::priceNightA, GetSlashedValue);
+    AddAOSParser(propertyParsers, "priceNightB", info.dirPrice, &DIRPRICE_DATA::priceNightB, GetSlashedValue);
+    AddAOSParser(propertyParsers, "singlePrice", info.dirPrice, &DIRPRICE_DATA::singlePrice, GetSlashedValue);
+    AddAOSParser(propertyParsers, "noDiscount", info.dirPrice, &DIRPRICE_DATA::noDiscount, GetSlashedValue);
+    AddAOSParser(propertyParsers, "threshold", info.dirPrice, &DIRPRICE_DATA::threshold, GetSlashedValue);
+}
+//-----------------------------------------------------------------------------
+GET_TARIFF::PARSER::~PARSER()
+{
+    PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+    while (it != propertyParsers.end())
+        delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_TARIFF::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+    ParseTariff(el, attr);
+
+if (depth == 2 && parsingAnswer)
+    ParseTariffParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_TARIFF::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    error.clear();
+    parsingAnswer = false;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_TARIFF::PARSER::ParseTariff(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "tariff") == 0)
+    {
+    if (attr && attr[0] && attr[1])
+        {
+        if (strcasecmp(attr[1], "error") == 0)
+            {
+            if (attr[2] && attr[3])
+                error = attr[3];
+            else
+                error = "Tariff not found.";
+            }
+        else
+            parsingAnswer = true;
+        }
+    else
+        parsingAnswer = true;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_TARIFF::PARSER::ParseTariffParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+    error = "Invalid parameter.";
+}
diff --git a/stglibs/srvconf.lib/parsers/get_tariff.h b/stglibs/srvconf.lib/parsers/get_tariff.h
new file mode 100644 (file)
index 0000000..e655825
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/tariff_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_TARIFF
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    typedef GET_TARIFF::INFO INFO;
+
+    PARSER(CALLBACK f, void * data);
+    virtual ~PARSER();
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    PROPERTY_PARSERS propertyParsers;
+    CALLBACK callback;
+    void * data;
+    INFO info;
+    int depth;
+    bool parsingAnswer;
+    std::string error;
+
+    void ParseTariff(const char * el, const char ** attr);
+    void ParseTariffParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_TARIFF
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/get_user.cpp b/stglibs/srvconf.lib/parsers/get_user.cpp
new file mode 100644 (file)
index 0000000..54cfc0f
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_user.h"
+
+#include "stg/common.h"
+
+#include <map>
+#include <utility>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace STG
+{
+
+template <>
+bool GetValue<GET_USER::STAT>(const char ** attr, GET_USER::STAT & value)
+{
+if (!attr)
+    return false;
+std::map<std::string, long long *> props;
+for (size_t i = 0; i < DIR_NUM; ++i)
+    {
+    props.insert(std::pair<std::string, long long *>("su" + unsigned2str(i), &value.su[i]));
+    props.insert(std::pair<std::string, long long *>("sd" + unsigned2str(i), &value.sd[i]));
+    props.insert(std::pair<std::string, long long *>("mu" + unsigned2str(i), &value.mu[i]));
+    props.insert(std::pair<std::string, long long *>("md" + unsigned2str(i), &value.md[i]));
+    }
+size_t pos = 0;
+while (attr[pos])
+    {
+        std::string name(ToLower(attr[pos++]));
+        std::map<std::string, long long *>::iterator it(props.find(name));
+        if (it != props.end())
+            if (str2x(attr[pos++], *it->second) < 0)
+                return false;
+    }
+return true;
+}
+
+}
+
+GET_USER::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+    AddParser(propertyParsers, "login", info.login);
+    AddParser(propertyParsers, "password", info.password);
+    AddParser(propertyParsers, "cash", info.cash);
+    AddParser(propertyParsers, "credit", info.credit);
+    AddParser(propertyParsers, "creditExpire", info.creditExpire);
+    AddParser(propertyParsers, "lastCash", info.lastCash);
+    AddParser(propertyParsers, "prepaidTraff", info.prepaidTraff);
+    AddParser(propertyParsers, "down", info.down);
+    AddParser(propertyParsers, "passive", info.passive);
+    AddParser(propertyParsers, "disableDetailStat", info.disableDetailStat);
+    AddParser(propertyParsers, "connected", info.connected);
+    AddParser(propertyParsers, "aonline", info.alwaysOnline);
+    AddParser(propertyParsers, "currIP", info.ip, GetIPValue);
+    AddParser(propertyParsers, "ip", info.ips);
+    AddParser(propertyParsers, "tariff", info.tariff);
+    AddParser(propertyParsers, "group", info.group, GetEncodedValue);
+    AddParser(propertyParsers, "note", info.note, GetEncodedValue);
+    AddParser(propertyParsers, "email", info.email, GetEncodedValue);
+    AddParser(propertyParsers, "name", info.name, GetEncodedValue);
+    AddParser(propertyParsers, "address", info.address, GetEncodedValue);
+    AddParser(propertyParsers, "phone", info.phone, GetEncodedValue);
+    AddParser(propertyParsers, "traff", info.stat);
+
+    for (size_t i = 0; i < USERDATA_NUM; ++i)
+        AddParser(propertyParsers, "userData" + unsigned2str(i), info.userData[i], GetEncodedValue);
+}
+//-----------------------------------------------------------------------------
+GET_USER::PARSER::~PARSER()
+{
+    PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+    while (it != propertyParsers.end())
+        delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_USER::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+    ParseUser(el, attr);
+
+if (depth == 2 && parsingAnswer)
+    ParseUserParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_USER::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    error.clear();
+    parsingAnswer = false;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_USER::PARSER::ParseUser(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "user") == 0)
+    {
+    if (attr && attr[0] && attr[1])
+        {
+        if (strcasecmp(attr[1], "error") == 0)
+            {
+            if (attr[2] && attr[3])
+                error = attr[3];
+            else
+                error = "User not found.";
+            }
+        else
+            parsingAnswer = true;
+        }
+    else
+        parsingAnswer = true;
+    }
+}
+//-----------------------------------------------------------------------------
+void GET_USER::PARSER::ParseUserParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+    error = "Invalid parameter.";
+}
diff --git a/stglibs/srvconf.lib/parsers/get_user.h b/stglibs/srvconf.lib/parsers/get_user.h
new file mode 100644 (file)
index 0000000..519d67b
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_USER
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    typedef GET_USER::INFO INFO;
+
+    PARSER(CALLBACK f, void * data);
+    virtual ~PARSER();
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    PROPERTY_PARSERS propertyParsers;
+    CALLBACK callback;
+    void * data;
+    INFO info;
+    int depth;
+    bool parsingAnswer;
+    std::string error;
+
+    void ParseUser(const char * el, const char ** attr);
+    void ParseUserParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_USER
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/property.cpp b/stglibs/srvconf.lib/parsers/property.cpp
new file mode 100644 (file)
index 0000000..8a78fe7
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "property.h"
+
+#include <strings.h>
+
+bool STG::CheckValue(const char ** attr)
+{
+return attr && attr[0] && attr[1] && strcasecmp(attr[0], "value") == 0;
+}
+
+bool STG::GetEncodedValue(const char ** attr, std::string & value)
+{
+if (!CheckValue(attr))
+    return false;
+Decode21str(value, attr[1]);
+return true;
+}
+
+bool STG::GetIPValue(const char ** attr, uint32_t & value)
+{
+if (!CheckValue(attr))
+    return false;
+std::string ip(attr[1]);
+value = inet_strington(attr[1]);
+if (value == 0 && ip != "0.0.0.0")
+    return false;
+return true;
+}
+
+bool STG::TryParse(PROPERTY_PARSERS & parsers, const std::string & name, const char ** attr)
+{
+    PROPERTY_PARSERS::iterator it(parsers.find(name));
+    if (it != parsers.end())
+        return it->second->Parse(attr);
+    return true; // Assume that non-existing params are ok.
+}
diff --git a/stglibs/srvconf.lib/parsers/property.h b/stglibs/srvconf.lib/parsers/property.h
new file mode 100644 (file)
index 0000000..3469b98
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__
+#define __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__
+
+#include "stg/common.h"
+
+#include <map>
+#include <string>
+
+namespace STG
+{
+
+class BASE_PROPERTY_PARSER
+{
+    public:
+        virtual ~BASE_PROPERTY_PARSER() {}
+        virtual bool Parse(const char ** attr) = 0;
+};
+
+template <typename T>
+class PROPERTY_PARSER : public BASE_PROPERTY_PARSER
+{
+    public:
+        typedef bool (* FUNC)(const char **, T &);
+        PROPERTY_PARSER(T & v, FUNC f) : value(v), func(f) {}
+        virtual bool Parse(const char ** attr) { return func(attr, value); }
+    private:
+        T & value;
+        FUNC func;
+};
+
+typedef std::map<std::string, BASE_PROPERTY_PARSER *> PROPERTY_PARSERS;
+
+bool CheckValue(const char ** attr);
+
+template <typename T>
+inline
+bool GetValue(const char ** attr, T & value)
+{
+if (CheckValue(attr))
+    if (str2x(attr[1], value) < 0)
+        return false;
+return true;
+}
+
+template <>
+inline
+bool GetValue<std::string>(const char ** attr, std::string & value)
+{
+if (!CheckValue(attr))
+    return false;
+value = attr[1];
+return true;
+}
+
+template <>
+inline
+bool GetValue<double>(const char ** attr, double & value)
+{
+if (CheckValue(attr))
+    if (strtodouble2(attr[1], value))
+        return false;
+return true;
+}
+
+bool GetEncodedValue(const char ** attr, std::string & value);
+
+bool GetIPValue(const char ** attr, uint32_t& value);
+
+template <typename T>
+void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const typename PROPERTY_PARSER<T>::FUNC & func = GetValue<T>);
+
+template <typename T>
+inline
+void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const typename PROPERTY_PARSER<T>::FUNC & func)
+{
+    parsers.insert(std::make_pair(ToLower(name), new PROPERTY_PARSER<T>(value, func)));
+}
+
+bool TryParse(PROPERTY_PARSERS & parsers, const std::string & name, const char ** attr);
+
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/resetable_utils.h b/stglibs/srvconf.lib/parsers/resetable_utils.h
new file mode 100644 (file)
index 0000000..ed1cd30
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__
+#define __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__
+
+#include "stg/resetable.h"
+
+#include <string>
+#include <ostream>
+
+namespace STG
+{
+
+template <typename T>
+void appendResetable(std::ostream & stream, const std::string & name, const T & value)
+{
+if (!value.empty())
+    stream << "<" << name << " value=\"" << value.data() << "\"/>";
+}
+
+template <typename T>
+void appendResetable(std::ostream & stream, const std::string & name, size_t suffix, const T & value)
+{
+if (!value.empty())
+    stream << "<" << name << suffix << " value=\"" << value.data() << "\"/>";
+}
+
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/server_info.cpp b/stglibs/srvconf.lib/parsers/server_info.cpp
new file mode 100644 (file)
index 0000000..fbefb2d
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "server_info.h"
+
+#include "stg/common.h"
+
+#include <cstdio> // sprintf
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace
+{
+
+const size_t UNAME_LEN    = 256;
+const size_t SERV_VER_LEN = 64;
+const size_t DIRNAME_LEN  = 16;
+
+}
+
+SERVER_INFO::PARSER::PARSER(CALLBACK f, void * d)
+    : callback(f),
+      data(d),
+      depth(0),
+      parsingAnswer(false)
+{
+    AddParser(propertyParsers, "uname", info.uname);
+    AddParser(propertyParsers, "version", info.version);
+    AddParser(propertyParsers, "tariff", info.tariffType);
+    AddParser(propertyParsers, "dir_num", info.dirNum);
+    AddParser(propertyParsers, "users_num", info.usersNum);
+    AddParser(propertyParsers, "tariff_num", info.tariffNum);
+
+    for (size_t i = 0; i < DIR_NUM; i++)
+        AddParser(propertyParsers, "dir_name_" + unsigned2str(i), info.dirName[i], GetEncodedValue);
+}
+//-----------------------------------------------------------------------------
+int SERVER_INFO::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+    {
+    if (strcasecmp(el, "ServerInfo") == 0)
+        parsingAnswer = true;
+    }
+else
+    {
+    if (depth == 2 && parsingAnswer)
+        if (!TryParse(propertyParsers, ToLower(el), attr))
+            error = "Invalid parameter.";
+    }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void SERVER_INFO::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+    {
+    if (callback)
+        callback(error.empty(), error, info, data);
+    error.clear();
+    parsingAnswer = false;
+    }
+}
diff --git a/stglibs/srvconf.lib/parsers/server_info.h b/stglibs/srvconf.lib/parsers/server_info.h
new file mode 100644 (file)
index 0000000..7f5b8e9
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace SERVER_INFO
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    PARSER(CALLBACK f, void * data);
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    PROPERTY_PARSERS propertyParsers;
+    CALLBACK callback;
+    void * data;
+    int depth;
+    bool parsingAnswer;
+    INFO info;
+    std::string error;
+};
+
+} // namespace SERVER_INFO
+} // namespace STG
+
+#endif
diff --git a/stglibs/srvconf.lib/parsers/simple.cpp b/stglibs/srvconf.lib/parsers/simple.cpp
new file mode 100644 (file)
index 0000000..89537f2
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "simple.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+SIMPLE::PARSER::PARSER(const std::string & t, CALLBACK f, void * d)
+    : tag(t),
+      callback(f),
+      data(d),
+      depth(0)
+{
+}
+//-----------------------------------------------------------------------------
+int SIMPLE::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+    if (strcasecmp(el, tag.c_str()) == 0)
+        ParseAnswer(el, attr);
+return 0;
+}
+//-----------------------------------------------------------------------------
+void SIMPLE::PARSER::ParseEnd(const char *)
+{
+depth--;
+}
+//-----------------------------------------------------------------------------
+void SIMPLE::PARSER::ParseAnswer(const char * /*el*/, const char ** attr)
+{
+if (!callback)
+    return;
+if (attr && attr[0] && attr[1])
+    callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : attr[1], data);
+else
+    callback(false, "Invalid response.", data);
+}
diff --git a/stglibs/srvconf.lib/parsers/simple.h b/stglibs/srvconf.lib/parsers/simple.h
new file mode 100644 (file)
index 0000000..03c950b
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ *    This program is free software; you can redistribute it and/or modify
+ *    it under the terms of the GNU General Public License as published by
+ *    the Free Software Foundation; either version 2 of the License, or
+ *    (at your option) any later version.
+ *
+ *    This program is distributed in the hope that it will be useful,
+ *    but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *    GNU General Public License for more details.
+ *
+ *    You should have received a copy of the GNU General Public License
+ *    along with this program; if not, write to the Free Software
+ *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+/*
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace SIMPLE
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+    PARSER(const std::string & tag, CALLBACK f, void * data);
+    int  ParseStart(const char * el, const char ** attr);
+    void ParseEnd(const char * el);
+
+private:
+    std::string tag;
+    CALLBACK callback;
+    void * data;
+    int depth;
+
+    void ParseAnswer(const char * el, const char ** attr);
+};
+
+} // namespace SIMPLE
+} // namespace STG
+
+#endif
index ab386cf753dfab06b631806d5faea58d63776050..430de3c146d20d430a564201cd592c02e5a75eea 100644 (file)
 
 /*
  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
  */
 
- /*
- $Revision: 1.8 $
- $Date: 2010/08/04 00:40:38 $
- $Author: faust $
- */
+#include "stg/servconf.h"
+
+#include "netunit.h"
+
+#include "parsers/simple.h"
+#include "parsers/get_container.h"
+
+#include "parsers/server_info.h"
+
+#include "parsers/get_admin.h"
+#include "parsers/chg_admin.h"
+
+#include "parsers/get_tariff.h"
+#include "parsers/chg_tariff.h"
+
+#include "parsers/auth_by.h"
+#include "parsers/get_user.h"
+#include "parsers/chg_user.h"
+
+#include "parsers/get_service.h"
+#include "parsers/chg_service.h"
+
+#include "parsers/get_corp.h"
+#include "parsers/chg_corp.h"
+
+#include "parsers/base.h"
+
+#include "stg/common.h"
 
 #include <cstdio>
 #include <cstring>
 
-#include "stg/common.h"
-#include "stg/servconf.h"
+#include <expat.h>
 
-using namespace std;
+using namespace STG;
 
-//-----------------------------------------------------------------------------
-int AnsRecv(void * data, list<string> * list1)
+class SERVCONF::IMPL
 {
-//NODE * node;
-SERVCONF * sc;
-char ans[ENC_MSG_LEN + 1];
-int len, done = 0;
-
-sc = (SERVCONF*)data;
+public:
+    IMPL(const std::string & server, uint16_t port,
+         const std::string & login, const std::string & password);
 
-XML_ParserReset(sc->parser, NULL);
-XML_SetElementHandler(sc->parser, Start, End);
-XML_SetUserData(sc->parser, data);
+    const std::string & GetStrError() const;
+    static void Start(void * data, const char * el, const char ** attr);
+    static void End(void * data, const char * el);
 
-//loop parsing
-list<string>::iterator node;
-node = list1->begin();
+    int RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data);
 
-if (node == list1->end())
+    template <class P, typename C>
+    int Exec(const std::string & request, C callback, void * data)
     {
-    return st_ok;
+        P cp(callback, data);
+        return ExecImpl(request, cp);
     }
 
-while (node != list1->end())
+    template <class P, typename C>
+    int Exec(const std::string & tag, const std::string & request, C callback, void * data)
     {
-    strncpy(ans, node->c_str(), ENC_MSG_LEN);
-    ans[ENC_MSG_LEN] = 0;
-       //printf("---> %s\n", ans);
-    len = strlen(ans);
-
-    if (XML_Parse(sc->parser, ans, len, done) == XML_STATUS_ERROR)
-        {
-        strprintf(&sc->errorMsg, "XML parse error at line %d: %s",
-                  static_cast<int>(XML_GetCurrentLineNumber(sc->parser)),
-                  XML_ErrorString(XML_GetErrorCode(sc->parser)));
-        return st_xml_parse_error;
-        }
-    ++node;
+        P cp(tag, callback, data);
+        return ExecImpl(request, cp);
+    }
+
+private:
+    NETTRANSACT nt;
+
+    std::string errorMsg;
+    XML_Parser parser;
+
+    static bool ParserRecv(const std::string & chunk, bool final, void * data);
+    static bool SimpleRecv(const std::string & chunk, bool final, void * data);
+    int ExecImpl(const std::string & request, PARSER & cp);
+};
+
+bool SERVCONF::IMPL::ParserRecv(const std::string & chunk, bool final, void * data)
+{
+SERVCONF::IMPL * sc = static_cast<SERVCONF::IMPL *>(data);
 
+if (XML_Parse(sc->parser, chunk.c_str(), chunk.length(), final) == XML_STATUS_ERROR)
+    {
+    strprintf(&sc->errorMsg, "XML parse error at line %d: %s",
+              static_cast<int>(XML_GetCurrentLineNumber(sc->parser)),
+              XML_ErrorString(XML_GetErrorCode(sc->parser)));
+    printf("%s\n", sc->errorMsg.c_str());
+    return false;
     }
 
-return 0;
+return true;
 }
-//-----------------------------------------------------------------------------
-void Start(void *data, const char *el, const char **attr)
+
+bool SERVCONF::IMPL::SimpleRecv(const std::string & chunk, bool /*final*/, void * data)
 {
-SERVCONF * sc;
-sc = (SERVCONF*)data;
-sc->Start(el, attr);
+*static_cast<std::string *>(data) += chunk;
+return true;
 }
-//-----------------------------------------------------------------------------
-void End(void *data, const char *el)
+
+SERVCONF::SERVCONF(const std::string & server, uint16_t port,
+                   const std::string & login, const std::string & password)
+    : pImpl(new IMPL(server, port, login, password))
 {
-SERVCONF * sc;
-sc = (SERVCONF*)data;
-sc->End(el);
 }
-//-----------------------------------------------------------------------------
-SERVCONF::SERVCONF()
-    : currParser(NULL),
-      parseDepth(0),
-      error(0),
-      RecvUserDataCb(NULL),
-      RecvGetUserDataCb(NULL),
-      RecvServerInfoDataCb(NULL),
-      RecvChgUserCb(NULL),
-      RecvCheckUserCb(NULL),
-      RecvSendMessageCb(NULL),
-      getUserDataDataCb(NULL),
-      getUsersDataDataCb(NULL),
-      getServerInfoDataCb(NULL),
-      chgUserDataCb(NULL),
-      checkUserDataCb(NULL),
-      sendMessageDataCb(NULL)
+
+SERVCONF::~SERVCONF()
 {
-parser = XML_ParserCreate(NULL);
+delete pImpl;
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetServer(const char * server)
+
+int SERVCONF::ServerInfo(SERVER_INFO::CALLBACK f, void * data)
 {
-nt.SetServer(server);
+return pImpl->Exec<SERVER_INFO::PARSER>("<GetServerInfo/>", f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetPort(uint16_t port)
+
+int SERVCONF::RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data)
 {
-nt.SetServerPort(port);
+return pImpl->RawXML(request, f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetAdmLogin(const char * login)
+
+// -- Admins --
+
+int SERVCONF::GetAdmins(GET_CONTAINER::CALLBACK<GET_ADMIN::INFO>::TYPE f, void * data)
 {
-nt.SetLogin(login);
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_ADMIN::PARSER> >("admins", "<GetAdmins/>", f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetAdmPassword(const char * password)
+
+int SERVCONF::GetAdmin(const std::string & login, GET_ADMIN::CALLBACK f, void * data)
 {
-nt.SetPassword(password);
+return pImpl->Exec<GET_ADMIN::PARSER>("<GetAdmin login=\"" + login + "\"/>", f, data);
 }
-//-----------------------------------------------------------------------------
-int SERVCONF::GetUser(const char * l)
-{
-char request[255];
-snprintf(request, 255, "<GetUser login=\"%s\"/>", l);
-int ret;
-
-currParser = &parserGetUser;
-((PARSER_GET_USER*)currParser)->SetUserDataRecvCb(RecvGetUserDataCb, getUserDataDataCb);
-
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
-
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
 
-return st_ok;
-}
-//-----------------------------------------------------------------------------
-int SERVCONF::GetUsers()
+int SERVCONF::ChgAdmin(const ADMIN_CONF_RES & conf, SIMPLE::CALLBACK f, void * data)
 {
-char request[] = "<GetUsers/>";
-int ret;
-
-currParser = &parserGetUsers;
-((PARSER_GET_USERS*)currParser)->SetUserDataRecvCb(RecvUserDataCb, getUsersDataDataCb);
-
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
-
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
+return pImpl->Exec<SIMPLE::PARSER>("ChgAdmin", "<ChgAdmin" + CHG_ADMIN::Serialize(conf) + "/>", f, data);
+}
 
-return st_ok;
+int SERVCONF::AddAdmin(const std::string & login,
+                       const ADMIN_CONF_RES & conf,
+                       SIMPLE::CALLBACK f, void * data)
+{
+int res = pImpl->Exec<SIMPLE::PARSER>("AddAdmin", "<AddAdmin login=\"" + login + "\"/>", f, data);
+if (res != st_ok)
+    return res;
+return pImpl->Exec<SIMPLE::PARSER>("ChgAdmin", "<ChgAdmin" + CHG_ADMIN::Serialize(conf) + "/>", f, data);
 }
-//-----------------------------------------------------------------------------
-int SERVCONF::SendMessage(const char * login, const char * message, int prio)
+
+int SERVCONF::DelAdmin(const std::string & login, SIMPLE::CALLBACK f, void * data)
 {
-char request[1000];
-char msg[500];
-Encode12(msg, message, strlen(message));
-snprintf(request, 1000, "<Message login=\"%s\" priority=\"%d\" text=\"%s\"/>", login, prio, msg);
-int ret;
+return pImpl->Exec<SIMPLE::PARSER>("DelAdmin", "<DelAdmin login=\"" + login + "\"/>", f, data);
+}
 
-currParser = &parserSendMessage;
-parserSendMessage.SetSendMessageRecvCb(RecvSendMessageCb, sendMessageDataCb);
+// -- Tariffs --
 
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::GetTariffs(GET_CONTAINER::CALLBACK<GET_TARIFF::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_TARIFF::PARSER> >("tariffs", "<GetTariffs/>", f, data);
+}
 
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
+int SERVCONF::GetTariff(const std::string & name, GET_TARIFF::CALLBACK f, void * data)
+{
+return pImpl->Exec<GET_TARIFF::PARSER>("<GetTariff name=\"" + name + "\"/>", f, data);
+}
 
-return st_ok;
+int SERVCONF::ChgTariff(const TARIFF_DATA_RES & tariffData, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("SetTariff", "<SetTariff name=\"" + tariffData.tariffConf.name.data() + "\">" + CHG_TARIFF::Serialize(tariffData) + "</SetTariff>", f, data);
 }
-//-----------------------------------------------------------------------------
-int SERVCONF::GetServerInfo()
+
+int SERVCONF::AddTariff(const std::string & name,
+                       const TARIFF_DATA_RES & tariffData,
+                       SIMPLE::CALLBACK f, void * data)
 {
-char request[] = "<GetServerInfo/>";
-int ret;
+int res = pImpl->Exec<SIMPLE::PARSER>("AddTariff", "<AddTariff name=\"" + name + "\"/>", f, data);
+if (res != st_ok)
+    return res;
+return pImpl->Exec<SIMPLE::PARSER>("SetTariff", "<SetTariff name=\"" + name + "\">" + CHG_TARIFF::Serialize(tariffData) + "</SetTariff>", f, data);
+}
 
-currParser = &parserServerInfo;
-((PARSER_GET_SERVER_INFO*)currParser)->SetServerInfoRecvCb(RecvServerInfoDataCb, getServerInfoDataCb);
+int SERVCONF::DelTariff(const std::string & name, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelTariff", "<DelTariff name=\"" + name + "\"/>", f, data);
+}
 
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+// -- Users --
 
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-
-return st_ok;
+int SERVCONF::GetUsers(GET_CONTAINER::CALLBACK<GET_USER::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_USER::PARSER> >("users", "<GetUsers/>", f, data);
 }
-//-----------------------------------------------------------------------------
-int SERVCONF::ChgUser(const char * request)
+
+int SERVCONF::GetUser(const std::string & login, GET_USER::CALLBACK f, void * data)
 {
-int ret;
+return pImpl->Exec<GET_USER::PARSER>("<GetUser login=\"" + login + "\"/>", f, data);
+}
 
-currParser = &parserChgUser;
-((PARSER_CHG_USER*)currParser)->SetChgUserRecvCb(RecvChgUserCb, chgUserDataCb);
+int SERVCONF::ChgUser(const std::string & login,
+                      const USER_CONF_RES & conf,
+                      const USER_STAT_RES & stat,
+                      SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<CHG_USER::PARSER>("<SetUser><Login value=\"" + login + "\"/>" + CHG_USER::Serialize(conf, stat) + "</SetUser>", f, data);
+}
 
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::DelUser(const std::string & login, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelUser", "<DelUser login=\"" + login + "\"/>", f, data);
+}
 
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
+int SERVCONF::AddUser(const std::string & login, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("AddUser", "<AddUser><Login value=\"" + login + "\"/></AddUser>", f, data);
+}
 
-return st_ok;
+int SERVCONF::AuthBy(const std::string & login, AUTH_BY::CALLBACK f, void * data)
+{
+return pImpl->Exec<AUTH_BY::PARSER>("<GetUserAuthBy login=\"" + login + "\"/>", f, data);
 }
-//-----------------------------------------------------------------------------
-//  TODO: remove this shit!
-//-----------------------------------------------------------------------------
-int SERVCONF::MsgUser(const char * request)
+
+int SERVCONF::SendMessage(const std::string & login, const std::string & text, SIMPLE::CALLBACK f, void * data)
 {
-int ret;
+return pImpl->Exec<SIMPLE::PARSER>("SendMessage", "<Message login=\"" + login + "\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"" + Encode12str(text) + "\"/>", f, data);
+}
 
-currParser = &parserSendMessage;
-parserSendMessage.SetSendMessageRecvCb(RecvSendMessageCb, sendMessageDataCb);
+int SERVCONF::CheckUser(const std::string & login, const std::string & password, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("CheckUser", "<CheckUser login=\"" + login + "\" password=\"" + password + "\"/>", f, data);
+}
 
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+// -- Services --
 
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
+int SERVCONF::GetServices(GET_CONTAINER::CALLBACK<GET_SERVICE::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_SERVICE::PARSER> >("services", "<GetServices/>", f, data);
+}
 
-return st_ok;
+int SERVCONF::GetService(const std::string & name, GET_SERVICE::CALLBACK f, void * data)
+{
+return pImpl->Exec<GET_SERVICE::PARSER>("<GetService name=\"" + name + "\"/>", f, data);
 }
-//-----------------------------------------------------------------------------
-int SERVCONF::CheckUser(const char * login, const char * password)
+
+int SERVCONF::ChgService(const SERVICE_CONF_RES & conf, SIMPLE::CALLBACK f, void * data)
 {
-char request[255];
-snprintf(request, 255, "<CheckUser login=\"%s\" password=\"%s\"/>", login, password);
-int ret;
+return pImpl->Exec<SIMPLE::PARSER>("SetService", "<SetService name=\"" + conf.name.data() + "\">" + CHG_SERVICE::Serialize(conf) + "</SetService>", f, data);
+}
 
-currParser = &parserCheckUser;
-((PARSER_CHECK_USER*)currParser)->SetCheckUserRecvCb(RecvCheckUserCb, checkUserDataCb);
+int SERVCONF::AddService(const std::string & name,
+                         const SERVICE_CONF_RES & conf,
+                         SIMPLE::CALLBACK f, void * data)
+{
+int res = pImpl->Exec<SIMPLE::PARSER>("AddService", "<AddService name=\"" + name + "\"/>", f, data);
+if (res != st_ok)
+    return res;
+return pImpl->Exec<SIMPLE::PARSER>("SetService", "<SetService name=\"" + name + "\">" + CHG_SERVICE::Serialize(conf) + "</SetService>", f, data);
+}
 
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::DelService(const std::string & name, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelService", "<DelService name=\"" + name + "\"/>", f, data);
+}
 
-if ((ret = nt.Connect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Transact(request)) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
-if ((ret = nt.Disconnect()) != st_ok)
-    {
-    errorMsg = nt.GetError();
-    return ret;
-    }
+// -- Corporations --
 
-return st_ok;
+int SERVCONF::GetCorporations(GET_CONTAINER::CALLBACK<GET_CORP::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_CORP::PARSER> >("corporations", "<GetCorporations/>", f, data);
 }
-//-----------------------------------------------------------------------------
-int SERVCONF::Start(const char *el, const char **attr)
+
+int SERVCONF::GetCorp(const std::string & name, GET_CORP::CALLBACK f, void * data)
 {
-currParser->ParseStart(el, attr);
-return 0;
+return pImpl->Exec<GET_CORP::PARSER>("<GetCorp name=\"" + name + "\"/>", f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::End(const char *el)
+
+int SERVCONF::ChgCorp(const CORP_CONF_RES & conf, SIMPLE::CALLBACK f, void * data)
 {
-currParser->ParseEnd(el);
+return pImpl->Exec<SIMPLE::PARSER>("SetCorp", "<SetCorp name=\"" + conf.name.data() + "\">" + CHG_CORP::Serialize(conf) + "</SetCorp>", f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetUserDataRecvCb(RecvUserDataCb_t f, void * data)
+
+int SERVCONF::AddCorp(const std::string & name,
+                      const CORP_CONF_RES & conf,
+                      SIMPLE::CALLBACK f, void * data)
 {
-RecvUserDataCb = f;
-getUsersDataDataCb = data;
+int res = pImpl->Exec<SIMPLE::PARSER>("AddCorp", "<AddCorp name=\"" + name + "\"/>", f, data);
+if (res != st_ok)
+    return res;
+return pImpl->Exec<SIMPLE::PARSER>("SetCorp", "<SetCorp name=\"" + name + "\">" + CHG_CORP::Serialize(conf) + "</SetCorp>", f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetGetUserDataRecvCb(RecvUserDataCb_t f, void * data)
+
+int SERVCONF::DelCorp(const std::string & name, SIMPLE::CALLBACK f, void * data)
 {
-RecvGetUserDataCb = f;            //GET_USER
-getUserDataDataCb = data;
+return pImpl->Exec<SIMPLE::PARSER>("DelCorp", "<DelCorp name=\"" + name + "\"/>", f, data);
 }
-//-----------------------------------------------------------------------------
-void SERVCONF::SetServerInfoRecvCb(RecvServerInfoDataCb_t f, void * data)
+
+const std::string & SERVCONF::GetStrError() const
 {
-RecvServerInfoDataCb = f;
-getServerInfoDataCb = data;
+return pImpl->GetStrError();
 }
+
 //-----------------------------------------------------------------------------
-void SERVCONF::SetChgUserCb(RecvChgUserCb_t f, void * data)
+SERVCONF::IMPL::IMPL(const std::string & server, uint16_t port,
+                     const std::string & login, const std::string & password)
+    : nt( server, port, login, password )
 {
-RecvChgUserCb = f;
-chgUserDataCb = data;
+parser = XML_ParserCreate(NULL);
 }
 //-----------------------------------------------------------------------------
-void SERVCONF::SetCheckUserCb(RecvCheckUserCb_t f, void * data)
+void SERVCONF::IMPL::Start(void * data, const char * el, const char ** attr)
 {
-RecvCheckUserCb = f;
-checkUserDataCb = data;
+PARSER * currParser = static_cast<PARSER *>(data);
+currParser->ParseStart(el, attr);
 }
 //-----------------------------------------------------------------------------
-void SERVCONF::SetSendMessageCb(RecvSendMessageCb_t f, void * data)
+void SERVCONF::IMPL::End(void * data, const char * el)
 {
-RecvSendMessageCb = f;
-sendMessageDataCb = data;
+PARSER * currParser = static_cast<PARSER *>(data);
+currParser->ParseEnd(el);
 }
 //-----------------------------------------------------------------------------
-const std::string & SERVCONF::GetStrError() const
+const std::string & SERVCONF::IMPL::GetStrError() const
 {
 return errorMsg;
 }
 //-----------------------------------------------------------------------------
-int SERVCONF::GetError()
+int SERVCONF::IMPL::ExecImpl(const std::string & request, PARSER & cp)
 {
-int e = error;
-error = 0;
-return e;
+XML_ParserReset(parser, NULL);
+XML_SetElementHandler(parser, Start, End);
+XML_SetUserData(parser, &cp);
+
+int ret = 0;
+if ((ret = nt.Connect()) != st_ok)
+    {
+    errorMsg = nt.GetError();
+    return ret;
+    }
+if ((ret = nt.Transact(request, ParserRecv, this)) != st_ok)
+    {
+    errorMsg = nt.GetError();
+    return ret;
+    }
+
+nt.Disconnect();
+return st_ok;
+}
+
+int SERVCONF::IMPL::RawXML(const std::string & request, RAW_XML::CALLBACK callback, void * data)
+{
+int ret = 0;
+if ((ret = nt.Connect()) != st_ok)
+    {
+    errorMsg = nt.GetError();
+    callback(false, errorMsg, "", data);
+    return ret;
+    }
+std::string response;
+if ((ret = nt.Transact(request, SimpleRecv, &response)) != st_ok)
+    {
+    errorMsg = nt.GetError();
+    callback(false, errorMsg, "", data);
+    return ret;
+    }
+
+nt.Disconnect();
+callback(true, "", response, data);
+return st_ok;
 }
-//-----------------------------------------------------------------------------
diff --git a/stglibs/srvconf.lib/servconf.vpj b/stglibs/srvconf.lib/servconf.vpj
deleted file mode 100644 (file)
index c5f9b3c..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-<!DOCTYPE Project SYSTEM "http://www.slickedit.com/dtd/vse/10.0/vpj.dtd">
-<Project
-       Version="10.0"
-       VendorName="SlickEdit"
-       WorkingDir="."
-       BuildSystem="automakefile"
-       BuildMakeFile="makefile">
-       <Config
-               Name="Debug"
-               Type="gnuc"
-               DebugCallbackName="gdb"
-               OutputFile="%bdservconf.a">
-               <Menu>
-                       <Target
-                               Name="Compile"
-                               MenuCaption="&amp;Compile"
-                               OutputExts="*.o"
-                               Dialog="_gnuc_options_form Compile"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               SaveOption="SaveCurrent"
-                               Deletable="0">
-                               <Exec CmdLine='g++ -c %xup -pipe -g -Wall -ggdb -o "%bd%n%oe" %i "%f"'/>
-                       </Target>
-                       <Target
-                               Name="Link"
-                               MenuCaption="&amp;Link"
-                               ShowOnMenu="Never"
-                               Dialog="_gnuc_options_form Link"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               SaveOption="SaveCurrent"
-                               Deletable="0">
-                               <Exec CmdLine='g++ %xup -pipe -g -Wall -o "%o" %f %libs'/>
-                       </Target>
-                       <Target
-                               Name="Build"
-                               MenuCaption="&amp;Build"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               SaveOption="SaveWorkspaceFiles"
-                               Deletable="0">
-                               <Exec CmdLine="gmake -fMakefile"/>
-                       </Target>
-                       <Target
-                               Name="Rebuild"
-                               MenuCaption="&amp;Rebuild"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               Deletable="0">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="Debug"
-                               MenuCaption="&amp;Debug"
-                               RunFromDir="%rw"
-                               Deletable="0">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="Execute"
-                               MenuCaption="E&amp;xecute"
-                               RunFromDir="%rw"
-                               Deletable="0">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="dash"
-                               MenuCaption="-"
-                               RunFromDir="%rw">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="GNU C Options"
-                               MenuCaption="GNU C &amp;Options..."
-                               ShowOnMenu="HideIfNoCmdLine"
-                               Deletable="0">
-                               <Exec
-                                       CmdLine="gnucoptions"
-                                       Type="Slick-C"/>
-                       </Target>
-               </Menu>
-               <Libs>
-                       <Lib File="/usr/lib/libexpat.a"/>
-               </Libs>
-       </Config>
-       <Config
-               Name="Release"
-               Type="gnuc"
-               DebugCallbackName="gdb"
-               OutputFile="%bdservconf.a">
-               <Menu>
-                       <Target
-                               Name="Compile"
-                               MenuCaption="&amp;Compile"
-                               OutputExts="*.o"
-                               Dialog="_gnuc_options_form Compile"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               SaveOption="SaveCurrent"
-                               Deletable="0">
-                               <Exec CmdLine='g++ -c %xup -pipe -Wall -o "%bd%n%oe" %i "%f"'/>
-                       </Target>
-                       <Target
-                               Name="Link"
-                               MenuCaption="&amp;Link"
-                               ShowOnMenu="Never"
-                               Dialog="_gnuc_options_form Link"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               SaveOption="SaveCurrent"
-                               Deletable="0">
-                               <Exec CmdLine='g++ %xup -pipe -Wall -o "%o" %f %libs'/>
-                       </Target>
-                       <Target
-                               Name="Build"
-                               MenuCaption="&amp;Build"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               SaveOption="SaveWorkspaceFiles"
-                               Deletable="0">
-                               <Exec CmdLine="gmake -fMakefile"/>
-                       </Target>
-                       <Target
-                               Name="Rebuild"
-                               MenuCaption="&amp;Rebuild"
-                               RunFromDir="%rw"
-                               CaptureOutputWith="ProcessBuffer"
-                               Deletable="0">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="Debug"
-                               MenuCaption="&amp;Debug"
-                               RunFromDir="%rw"
-                               Deletable="0">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="Execute"
-                               MenuCaption="E&amp;xecute"
-                               RunFromDir="%rw"
-                               Deletable="0">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="dash"
-                               MenuCaption="-"
-                               RunFromDir="%rw">
-                               <Exec/>
-                       </Target>
-                       <Target
-                               Name="GNU C Options"
-                               MenuCaption="GNU C &amp;Options..."
-                               ShowOnMenu="HideIfNoCmdLine"
-                               Deletable="0">
-                               <Exec
-                                       CmdLine="gnucoptions"
-                                       Type="Slick-C"/>
-                       </Target>
-               </Menu>
-               <Libs>
-                       <Lib File="/usr/lib/libexpat.a"/>
-               </Libs>
-       </Config>
-       <Files>
-               <Folder
-                       Name="Source Files"
-                       Filters="*.c;*.cc;*.cpp;*.cp;*.cxx;*.prg;*.pas;*.dpr;*.asm;*.s;*.bas;*.java;*.sc;*.e;*.cob;*.html;*.rc;*.tcl;*.py;*.pl">
-                       <F N="netunit.cpp"/>
-                       <F N="parser.cpp"/>
-                       <F N="servconf.cpp"/>
-                       <F N="test.cpp"/>
-               </Folder>
-               <Folder
-                       Name="Header Files"
-                       Filters="*.h;*.hh;*.hpp;*.hxx;*.inc;*.sh;*.cpy;*.if">
-                       <F N="netunit.h"/>
-                       <F N="servconf.h"/>
-               </Folder>
-               <Folder
-                       Name="Resource Files"
-                       Filters="*.ico;*.cur;*.dlg"/>
-               <Folder
-                       Name="Bitmaps"
-                       Filters="*.bmp;*.xpm;*.xbm"/>
-               <Folder
-                       Name="Other Files"
-                       Filters=""/>
-       </Files>
-</Project>
diff --git a/stglibs/srvconf.lib/servconf.vpw b/stglibs/srvconf.lib/servconf.vpw
deleted file mode 100644 (file)
index 96ebe79..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-[Global]
-Version=8
-[ProjectFiles]
-servconf.vpj